Programs & Examples On #Jvm hotspot

HotSpot is the standard Java virtual machine used by both the Oracle and OpenJDK Java runtime environments.

How do I write a correct micro-benchmark in Java?

If you are trying to compare two algorithms, do at least two benchmarks for each, alternating the order. i.e.:

for(i=1..n)
  alg1();
for(i=1..n)
  alg2();
for(i=1..n)
  alg2();
for(i=1..n)
  alg1();

I have found some noticeable differences (5-10% sometimes) in the runtime of the same algorithm in different passes..

Also, make sure that n is very large, so that the runtime of each loop is at the very least 10 seconds or so. The more iterations, the more significant figures in your benchmark time and the more reliable that data is.

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

Well, after some struggling, what worked for me was completely removing the current JDK, as described here:

sudo rm -rf /Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk
sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/LaunchAgents/com.oracle.java.Java-Updater.plist
sudo rm -rf /Library/PrivilegedHelperTools/com.oracle.java.JavaUpdateHelper
sudo rm -rf /Library/LaunchDaemons/com.oracle.java.JavaUpdateHelper.plist
sudo rm -rf /Library/Preferences/com.oracle.java.Helper-Tool.plist

Then installed 1.7.0_21, which was downloaded from here.

Now java -version prompts:

java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b12)
Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)

-XX:MaxPermSize with or without -XX:PermSize

By playing with parameters as -XX:PermSize and -Xms you can tune the performance of - for example - the startup of your application. I haven't looked at it recently, but a few years back the default value of -Xms was something like 32MB (I think), if your application required a lot more than that it would trigger a number of cycles of fill memory - full garbage collect - increase memory etc until it had loaded everything it needed. This cycle can be detrimental for startup performance, so immediately assigning the number required could improve startup.

A similar cycle is applied to the permanent generation. So tuning these parameters can improve startup (amongst others).

WARNING The JVM has a lot of optimization and intelligence when it comes to allocating memory, dividing eden space and older generations etc, so don't do things like making -Xms equal to -Xmx or -XX:PermSize equal to -XX:MaxPermSize as it will remove some of the optimizations the JVM can apply to its allocation strategies and therefor reduce your application performance instead of improving it.

As always: make non-trivial measurements to prove your changes actually improve performance overall (for example improving startup time could be disastrous for performance during use of the application)

Real differences between "java -server" and "java -client"?

Last time I had a look at this, (and admittedly it was a while back) the biggest difference I noticed was in the garbage collection.

IIRC:

  • The server heap VM has a differnt number of generations than the Client VM, and a different garbage collection algorithm. This may not be true anymore
  • The server VM will allocate memory and not release it to the OS
  • The server VM will use more sophisticated optimisation algorithms, and hence have bigger time and memory requirements for optimisation

If you can compare two java VMs, one client, one server using the jvisualvm tool, you should see a difference in the frequency and effect of the garbage collection, as well as in the number of generations.

I had a pair of screenshots that showed the difference really well, but I can't reproduce as I have a 64 bit JVM which only implements the server VM. (And I can't be bothered to download and wrangle the 32 bit version on my system as well.)

This doesn't seem to be the case anymore, having tried running some code on windows with both server and client VMs, I seem to get the same generation model for both...

Can I try/catch a warning?

I would only recommend using @ to suppress warnings when it's a straight forward operation (e.g. $prop = @($high/($width - $depth)); to skip division by zero warnings). However in most cases it's better to handle.

Why maven? What are the benefits?

Figuring out package dependencies is really not that hard. You rarely do it anyway. Probably once during project setup and few more during upgrades. With maven you'll end up fixing mismatched dependencies, badly written poms, and doing package exclusions anyway.

Not that hard... for toy projects. But the projects I work on have many, really many, of them, and I'm very glad to get them transitively, to have a standardized naming scheme for them. Managing all this manually by hand would be a nightmare.

And yes, sometimes you have to work on the convergence of dependencies. But think about it twice, this is not inherent to Maven, this is inherent to any system using dependencies (and I am talking about Java dependencies in general here).

So with Ant, you have to do the same work except that you have to do everything manually: grabbing some version of project A and its dependencies, grabbing some version of project B and its dependencies, figuring out yourself what exact versions they use, checking that they don't overlap, checking that they are not incompatible, etc. Welcome to hell.

On the other hand, Maven supports dependency management and will retrieve them transitively for me and gives me the tooling I need to manage the complexity inherent to dependency management: I can analyze a dependency tree, control the versions used in transitive dependencies, exclude some of them if required, control the converge across modules, etc. There is no magic. But at least you have support.

And don't forget that dependency management is only a small part of what Maven offers, there is much more (not even mentioning the other tools that integrates nicely with Maven, e.g. Sonar).

Slow FIX-COMPILE-DEPLOY-DEBUG cycle, which kills productivity. This is my main gripe. You make a change, the you have to wait for maven build to kick in and wait for it to deploy. No hot deployment whatsoever.

First, why do you use Maven like this? I don't. I use my IDE to write tests, code until they pass, refactor, deploy, hot deploy and run a local Maven build when I'm done, before to commit, to make sure I will not break the continuous build.

Second, I'm not sure using Ant would make things much better. And to my experience, modular Maven builds using binary dependencies gives me faster build time than typical monolithic Ant builds. Anyway, have a look at Maven Shell for a ready to (re)use Maven environment (which is awesome by the way).

So at end, and I'm sorry to say so, it's not really Maven that is killing your productivity, it's you misusing your tools. And if you're not happy with it, well, what can I say, don't use it. Personally, I'm using Maven since 2003 and I never looked back.

How to get request URL in Spring Boot RestController

You may try adding an additional argument of type HttpServletRequest to the getUrlValue() method:

@RequestMapping(value ="/",produces = "application/json")
public String getURLValue(HttpServletRequest request){
    String test = request.getRequestURI();
    return test;
}

Send data from javascript to a mysql database

The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.

So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net

If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.

http://api.jquery.com/jQuery.ajax/

Getting Python error "from: can't read /var/mail/Bio"

I ran into a similar error

"from: can't read /var/mail/django.test.utils"

when trying to run a command

>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()

in the tutorial at https://docs.djangoproject.com/en/1.8/intro/tutorial05/

after reading the answer by Tamás I realized I was not trying this command in the python shell but in the termnial (this can happen to those new to linux)

solution was to first enter in the python shell with the command python and when you get these >>> then run any python commands

ASP.NET custom error page - Server.GetLastError() is null

I think you have a couple of options here.

you could store the last Exception in the Session and retrieve it from your custom error page; or you could just redirect to your custom error page within the Application_error event. If you choose the latter, you want to make sure you use the Server.Transfer method.

How to hide the keyboard when I press return key in a UITextField?

Try this in Swift,

Step 1: Set delegate as self to your textField

textField.delegate = self

Step 2: Add this UITextFieldDelegate below your class declaration,

extension YourClassName: UITextFieldDelegate {
    func textFieldShouldReturn(textField: UITextField) -> Bool {
         textField.resignFirstResponder()
        return true
    }
}

Calling a PHP function from an HTML form in the same file

Take a look at this example:

<!DOCTYPE HTML> 
<html>
<head>
</head>
<body> 

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $name = test_input($_POST["name"]);
   $email = test_input($_POST["email"]);
   $website = test_input($_POST["website"]);
   $comment = test_input($_POST["comment"]);
   $gender = test_input($_POST["gender"]);
}

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
   Name: <input type="text" name="name">
   <br><br>
   E-mail: <input type="text" name="email">
   <br><br>
   Website: <input type="text" name="website">
   <br><br>
   Comment: <textarea name="comment" rows="5" cols="40"></textarea>
   <br><br>
   Gender:
   <input type="radio" name="gender" value="female">Female
   <input type="radio" name="gender" value="male">Male
   <br><br>
   <input type="submit" name="submit" value="Submit"> 
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

How can I monitor the thread count of a process on linux?

JStack is quite inexpensive - one option would be to pipe the output through grep to find active threads and then pipe through wc -l.

More graphically is JConsole, which displays the thread count for a given process.

How does the FetchMode work in Spring Data JPA

The fetch mode will only work when selecting the object by id i.e. using entityManager.find(). Since Spring Data will always create a query, the fetch mode configuration will have no use to you. You can either use dedicated queries with fetch joins or use entity graphs.

When you want best performance, you should select only the subset of the data you really need. To do this, it is generally recommended to use a DTO approach to avoid unnecessary data to be fetched, but that usually results in quite a lot of error prone boilerplate code, since you need define a dedicated query that constructs your DTO model via a JPQL constructor expression.

Spring Data projections can help here, but at some point you will need a solution like Blaze-Persistence Entity Views which makes this pretty easy and has a lot more features in it's sleeve that will come in handy! You just create a DTO interface per entity where the getters represent the subset of data you need. A solution to your problem could look like this

@EntityView(Identified.class)
public interface IdentifiedView {
    @IdMapping
    Integer getId();
}

@EntityView(Identified.class)
public interface UserView extends IdentifiedView {
    String getName();
}

@EntityView(Identified.class)
public interface StateView extends IdentifiedView {
    String getName();
}

@EntityView(Place.class)
public interface PlaceView extends IdentifiedView {
    UserView getAuthor();
    CityView getCity();
}

@EntityView(City.class)
public interface CityView extends IdentifiedView {
    StateView getState();
}

public interface PlaceRepository extends JpaRepository<Place, Long>, PlaceRepositoryCustom {
    PlaceView findById(int id);
}

public interface UserRepository extends JpaRepository<User, Long> {
    List<UserView> findAllByOrderByIdAsc();
    UserView findById(int id);
}

public interface CityRepository extends JpaRepository<City, Long>, CityRepositoryCustom {    
    CityView findById(int id);
}

Disclaimer, I'm the author of Blaze-Persistence, so I might be biased.

XML Carriage return encoding

To insert a CR into XML, you need to use its character entity &#13;.

This is because compliant XML parsers must, before parsing, translate CRLF and any CR not followed by a LF to a single LF. This behavior is defined in the End-of-Line handling section of the XML 1.0 specification.

SQL Count for each date

You can use:

Select
     count(created_date) as counted_leads,
     created_date as count_date
from
     table
group by
     created_date

Pass a data.frame column name to a function

If you are trying to build this function within an R package or simply want to reduce complexity, you can do the following:

test_func <- function(df, column) {
  if (column %in% colnames(df)) {
    return(max(df[, column, with=FALSE])) 
  } else {
    stop(cat(column, "not in data.frame columns."))
  }
}

The argument with=FALSE "disables the ability to refer to columns as if they are variables, thereby restoring the “data.frame mode” (per CRAN documentation). The if statement is a quick way to catch if the column name provided is within the data.frame. Could also use tryCatch error handling here.

Get values from label using jQuery

While this question is rather old, and has been answered, I thought I'd take the time to offer a couple of options that are, as yet, not addressed in other answers.

Given the corrected HTML (camelCasing the id attribute-value) of:

<label year="2010" month="6" id="currentMonth"> June &nbsp;2010</label>

You could use regular expressions to extract the month-name, and year:

// gets the eleent with an id equal to 'currentMonth',
// retrieves its text-content,
// uses String.prototype.trim() to remove leading and trailing white-space:
var labelText = $('#currentMonth').text().trim(),
    // finds the sequence of one, or more, letters (a-z, inclusive)
    // at the start (^) of the string, and retrieves the first match from
    // the array returned by the match() method:
    month = labelText.match(/^[a-z]+/i)[0],
    // finds the sequence of numbers (\d) of length 2-4 ({2,4}) characters,
    // at the end ($) of the string:
    year = labelText.match(/\d{2,4}$/)[0];

_x000D_
_x000D_
var labelText = $('#currentMonth').text().trim(),_x000D_
    month = labelText.match(/^[a-z]+/i)[0],_x000D_
    year = labelText.match(/\d{2,4}$/)[0];_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label year="2010" month="6" id="currentMonth"> June &nbsp;2010</label>
_x000D_
_x000D_
_x000D_

Rather than regular expressions, though, you could instead use custom data-* attributes (which work in HTML 4.x, despite being invalid under the doctype, but are valid under HTML 5):

_x000D_
_x000D_
var label = $('#currentMonth'),_x000D_
    month = label.data('month'),_x000D_
    year = label.data('year');_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label data-year="2010" data-month="6" id="currentMonth"> June &nbsp;2010</label>
_x000D_
_x000D_
_x000D_

Note that this will output 6 (for the data-month), rather than 'June' as in the previous example, though if you use an array to tie numbers to month-names, that can be solved easily:

_x000D_
_x000D_
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],_x000D_
    label = $('#currentMonth'),_x000D_
    month = monthNames[+label.data('month') - 1],_x000D_
    year = label.data('year');_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label data-year="2010" data-month="6" id="currentMonth"> June &nbsp;2010</label>
_x000D_
_x000D_
_x000D_

Similarly, the above could be easily transcribed to the native DOM (in compliant browsers):

_x000D_
_x000D_
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],_x000D_
    label = document.getElementById('currentMonth'),_x000D_
    month = monthNames[+label.dataset.month - 1],_x000D_
    year = label.dataset.year;_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label data-year="2010" data-month="6" id="currentMonth"> June &nbsp;2010</label>
_x000D_
_x000D_
_x000D_

References:

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

Convert double to Int, rounded down

I think I had a better output, especially for a double datatype sorting.

Though this question has been marked answered, perhaps this will help someone else;

Arrays.sort(newTag, new Comparator<String[]>() {
         @Override
         public int compare(final String[] entry1, final String[] entry2) {
              final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
              final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
              return time1.compareTo(time2);
         }
    });

ASP.NET 4.5 has not been registered on the Web server

tl;dr; Clicking OK is the workaround, everything will work fine after that.

I also received this error message.

Configuring Web http://localhost:xxxxx/ for ASP.NET 4.5 failed. You must manually configure this site for ASP.NET 4.5 in order for the site to run correctly. ASP.NET 4.0 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly.

Environment: Windows 10, IIS8, VS 2012 Web.

After finding this page, along with several seemingly invasive solutions, I read through the hotfix option at https://support.microsoft.com/en-us/help/3002339/unexpected-dialog-box-appears-when-you-open-projects-in-visual-studio as suggested here.

Please avoid doing anything too drastic, and note the section of that page marked "Workaround" as shown below:

Workaround


To work around this issue, click OK when the dialog box appears after you either create a new project or open an existing Web Site Project or Windows Azure project. After you do this, the project works as expected.

In other words, click OK on the dialog box one time, and the message is gone forever. The project will work just fine.

npm global path prefix

If you have linked the node packages using sudo command

Then go to the folder where node_modules are installed globally.

On Unix systems they are normally placed in /usr/local/lib/node or /usr/local/lib/node_modules when installed globally. If you set the NODE_PATH environment variable to this path, the modules can be found by node.

Windows XP - %USERPROFILE%\Application Data\npm\node_modules Windows 7 - %AppData%\npm\node_modules

and then run the command

ls -l

This will give the list of all global node_modules and you can easily see the linked node modules.

How can I load the contents of a text file into a batch file variable?

for /f "delims=" %%i in (count.txt) do set c=%%i
echo %c%
pause

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

How to use Chrome's network debugger with redirects

Another great solution to debug the Network calls before redirecting to other pages is to select the beforeunload event break point

This way you assure to break the flow right before it redirecting it to another page, this way all network calls, network data and console logs are still there.

This solution is best when you want to check what is the response of the calls

Chrome beforeunload event break point

P.S: You can also use XHR break points if you want to stop right before a specific call or any call (see image example) XHR break point

How to add MVC5 to Visual Studio 2013?

Also, while installing Visual Studio 2013, ensure that you have checked "Web Developer Tools"

Switch case on type c#

Update C# 7

Yes: Source

switch(shape)
{
    case Circle c:
        WriteLine($"circle with radius {c.Radius}");
        break;
    case Rectangle s when (s.Length == s.Height):
        WriteLine($"{s.Length} x {s.Height} square");
        break;
    case Rectangle r:
        WriteLine($"{r.Length} x {r.Height} rectangle");
        break;
    default:
        WriteLine("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}

Prior to C# 7

No.

http://blogs.msdn.com/b/peterhal/archive/2005/07/05/435760.aspx

We get a lot of requests for addditions to the C# language and today I'm going to talk about one of the more common ones - switch on type. Switch on type looks like a pretty useful and straightforward feature: Add a switch-like construct which switches on the type of the expression, rather than the value. This might look something like this:

switch typeof(e) { 
        case int:    ... break; 
        case string: ... break; 
        case double: ... break; 
        default:     ... break; 
}

This kind of statement would be extremely useful for adding virtual method like dispatch over a disjoint type hierarchy, or over a type hierarchy containing types that you don't own. Seeing an example like this, you could easily conclude that the feature would be straightforward and useful. It might even get you thinking "Why don't those #*&%$ lazy C# language designers just make my life easier and add this simple, timesaving language feature?"

Unfortunately, like many 'simple' language features, type switch is not as simple as it first appears. The troubles start when you look at a more significant, and no less important, example like this:

class C {}
interface I {}
class D : C, I {}

switch typeof(e) {
case C: … break;
case I: … break;
default: … break;
}

Link: https://blogs.msdn.microsoft.com/peterhal/2005/07/05/many-questions-switch-on-type/

Can I call methods in constructor in Java?

Can I put my method readConfig() into constructor?

Invoking a not overridable method in a constructor is an acceptable approach.
While if the method is only used by the constructor you may wonder if extracting it into a method (even private) is really required.

If you choose to extract some logic done by the constructor into a method, as for any method you have to choose a access modifier that fits to the method requirement but in this specific case it matters further as protecting the method against the overriding of the method has to be done at risk of making the super class constructor inconsistent.

So it should be private if it is used only by the constructor(s) (and instance methods) of the class.
Otherwise it should be both package-private and final if the method is reused inside the package or in the subclasses.

which would give me benefit of one time calling or is there another mechanism to do that ?

You don't have any benefit or drawback to use this way.
I don't encourage to perform much logic in constructors but in some cases it may make sense to init multiple things in a constructor.
For example the copy constructor may perform a lot of things.
Multiple JDK classes illustrate that.
Take for example the HashMap copy constructor that constructs a new HashMap with the same mappings as the specified Map parameter :

public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        if (table == null) { // pre-size
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
            resize();
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
            K key = e.getKey();
            V value = e.getValue();
            putVal(hash(key), key, value, false, evict);
        }
    }
}

Extracting the logic of the map populating in putMapEntries() is a good thing because it allows :

  • reusing the method in other contexts. For example clone() and putAll() use it too
  • (minor but interesting) giving a meaningful name that conveys the performed logic

How to do INSERT into a table records extracted from another table

inserting data form one table to another table in different DATABASE

insert into DocTypeGroup 
    Select DocGrp_Id,DocGrp_SubId,DocGrp_GroupName,DocGrp_PM,DocGrp_DocType 
    from Opendatasource( 'SQLOLEDB','Data Source=10.132.20.19;UserID=sa;Password=gchaturthi').dbIPFMCI.dbo.DocTypeGroup

Sorting an array of objects by property values

This could have been achieved through a simple one line valueof() sort function. Run code snippet below to see demo.

_x000D_
_x000D_
var homes = [_x000D_
    {_x000D_
        "h_id": "3",_x000D_
        "city": "Dallas",_x000D_
        "state": "TX",_x000D_
        "zip": "75201",_x000D_
        "price": "162500"_x000D_
    }, {_x000D_
        "h_id": "4",_x000D_
        "city": "Bevery Hills",_x000D_
        "state": "CA",_x000D_
        "zip": "90210",_x000D_
        "price": "319250"_x000D_
    }, {_x000D_
        "h_id": "5",_x000D_
        "city": "New York",_x000D_
        "state": "NY",_x000D_
        "zip": "00010",_x000D_
        "price": "962500"_x000D_
    }_x000D_
];_x000D_
_x000D_
console.log("To sort descending/highest first, use operator '<'");_x000D_
_x000D_
homes.sort(function(a,b) { return a.price.valueOf() < b.price.valueOf();});_x000D_
_x000D_
console.log(homes);_x000D_
_x000D_
console.log("To sort ascending/lowest first, use operator '>'");_x000D_
_x000D_
homes.sort(function(a,b) { return a.price.valueOf() > b.price.valueOf();});_x000D_
_x000D_
console.log(homes);
_x000D_
_x000D_
_x000D_

how to list all sub directories in a directory

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

namespace TRIAL
{
    public class Class1
    {
        static void Main(string[] args)
        {
           string[] fileArray = Directory.GetDirectories("YOUR PATH");
           for (int i = 0; i < fileArray.Length; i++)
           {

               Console.WriteLine(fileArray[i]);
           }
            Console.ReadLine();
        }
    }
}

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Download numpy-1.9.2+mkl-cp27-none-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy .

Copy the file to C:\Python27\Scripts

Run cmd from the above location and type

pip install numpy-1.9.2+mkl-cp27-none-win32.whl

You will hopefully get the below output:

Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2

Hope that works for you.

EDIT 1
Adding @oneleggedmule 's suggestion:

You can also run the following command in the cmd:

pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl

Basically, writing pip alone also works perfectly (as in the original answer). Writing the version 2.7 can also be done for the sake of clarity or specification.

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

How can I exclude multiple folders using Get-ChildItem -exclude?

My KISS approach to skip some folders is chaining Get-ChildItem calls. This excludes root level folders but not deeper level folders if that is what you want.

Get-ChildItem -Exclude folder1,folder2 | Get-ChildItem -Recurse | ...
  • Start excluding folders you don't want
  • Then do the recursive search with non desired folders excluded.

What I like from this approach is that it is simple and easy to remember. If you don't want to mix folders and files in the first search a filter would be needed.

List all tables in postgresql information_schema

You should be able to just run select * from information_schema.tables to get a listing of every table being managed by Postgres for a particular database.

You can also add a where table_schema = 'information_schema' to see just the tables in the information schema.

How to change current Theme at runtime in Android

recreate() (as mentioned by TPReal) will only restart current activity, but the previous activities will still be in back stack and theme will not be applied to them.

So, another solution for this problem is to recreate the task stack completely, like this:

    TaskStackBuilder.create(getActivity())
            .addNextIntent(new Intent(getActivity(), MainActivity.class))
            .addNextIntent(getActivity().getIntent())
            .startActivities();

EDIT:

Just put the code above after you perform changing of theme on the UI or somewhere else. All your activities should have method setTheme() called before onCreate(), probably in some parent activity. It is also a normal approach to store the theme chosen in SharedPreferences, read it and then set using setTheme() method.

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

You're confusing PATH and PYTHONPATH. You need to do this:

export PATH=$PATH:/home/randy/lib/python 

PYTHONPATH is used by the python interpreter to determine which modules to load.

PATH is used by the shell to determine which executables to run.

JSON datetime between Python and JavaScript

For the Python to JavaScript date conversion, the date object needs to be in specific ISO format, i.e. ISO format or UNIX number. If the ISO format lacks some info, then you can convert to the Unix number with Date.parse first. Moreover, Date.parse works with React as well while new Date might trigger an exception.

In case you have a DateTime object without milliseconds, the following needs to be considered. :

  var unixDate = Date.parse('2016-01-08T19:00:00') 
  var desiredDate = new Date(unixDate).toLocaleDateString();

The example date could equally be a variable in the result.data object after an API call.

For options to display the date in the desired format (e.g. to display long weekdays) check out the MDN doc.

How to clear cache in Yarn?

Run yarn cache clean.


Run yarn help cache in your bash, and you will see:

Usage: yarn cache [ls|clean] [flags]

Options: -h, --help output usage information -V, --version output the version number --offline
--prefer-offline
--strict-semver
--json
--global-folder [path]
--modules-folder [path] rather than installing modules into the node_modules folder relative to the cwd, output them here
--packages-root [path] rather than storing modules into a global packages root, store them here
--mutex [type][:specifier] use a mutex to ensure only one yarn instance is executing

Visit http://yarnpkg.com/en/docs/cli/cache for documentation about this command.

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

ImportError: Couldn't import Django

Looks like you have not activated your virtualenv when using the runserver command.

Windows: <virtualenv dir>\Scripts\activate.bat

Linux: source <virtualenv dir>\bin\activate

You should see (name of virtualenv) as a prefix to your current directory:

(virtualenv) E:\video course\Python\code\web_worker\MxOnline>python manage.py runserver

How Does Modulus Divison Work

Modulus division gives you the remainder of a division, rather than the quotient.

round value to 2 decimals javascript

Just multiply the number by 100, round, and divide the resulting number by 100.

How to include js and CSS in JSP with spring MVC

You cant directly access anything under the WEB-INF foldere. When browsers request your CSS file, they can not see inside the WEB-INF folder.

Try putting your files css/css folder under WebContent.

And add the following in dispatcher servlet to grant access ,

<mvc:resources mapping="/css/**" location="/css/" />

similarly for your js files . A Nice example here on this

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try details: use any option..

    MessageBox.Show("your message",
    "window title", 
    MessageBoxButtons.OK, 
    MessageBoxIcon.Warning // for Warning  
    //MessageBoxIcon.Error // for Error 
    //MessageBoxIcon.Information  // for Information
    //MessageBoxIcon.Question // for Question
   );

What is the best way to implement constants in Java?

That's the right way to go.

Generally constants are not kept in separate "Constants" classes because they're not discoverable. If the constant is relevant to the current class, keeping them there helps the next developer.

Best C++ IDE or Editor for Windows

notepad++ or codeblocks for large projects

how to load url into div tag

Try the load() function.

$('#content').load("http://vnexpress.net");

Please not that for this to work, the URL to be loaded must either be on the same domain as the page that's calling it, or enable cross-origin HTTP requests ("Cross-Origin Resource Sharing", short CORS) on the server. This involves sending an additional HTTP header, in its most basic form:

Access-Control-Allow-Origin:*

to allow requests from everywhere.

Plot inline or a separate window using Matplotlib in Spyder IDE

Magic commands such as

%matplotlib qt  

work in the iPython console and Notebook, but do not work within a script.

In that case, after importing:

from IPython import get_ipython

use:

get_ipython().run_line_magic('matplotlib', 'inline')

for inline plotting of the following code, and

get_ipython().run_line_magic('matplotlib', 'qt')

for plotting in an external window.

Edit: solution above does not always work, depending on your OS/Spyder version Anaconda issue on GitHub. Setting the Graphics Backend to Automatic (as indicated in another answer: Tools >> Preferences >> IPython console >> Graphics --> Automatic) solves the problem for me.

Then, after a Console restart, one can switch between Inline and External plot windows using the get_ipython() command, without having to restart the console.

How do I close an open port from the terminal on the Mac?

You can also use this first command to kill a process that owns a particular port:

sudo netstat -ap | grep :<port_number>

For example, say this process holds port 8000 TCP, then running the command:

sudo netstat -ap | grep :8000

will output the line corresponding to the process holding port 8000, for example:

tcp  0  0 *:8000   *:* LISTEN  4683/procHoldingPort

In this case, procHoldingPort is the name of the process that opened the port, 4683 is its pid, and 8000 (note that it is TCP) is the port number it holds (which you wish to close).

Then kill the process, following the above example:

kill  4683

As others mentioned here out, if that doesn't work (you can try using kill with -9 as an argument):

kill -9 4683

Again, in general, it's better to avoid sending SIGKILL (-9) if you can.

How to preventDefault on anchor tags?

if you never want to go to href... you should change your markup and use a button not an anchor tag because semantically it's not an anchor or a link. Inversely if you have a button that does some checks and then redirects it should be a link / anchor tag and not a button... for SEO purposes as well testing [insert test suite here].

for links that you only want to redirect conditionally like prompting to save changes, or acknowledge dirty state... you should use ng-click="someFunction($event)" and in someFunction on your validationError preventDefault and or stopPropagation.

also just because you can doesn't mean you should. javascript:void(0) worked well back in the day... but because of the nefarious hackers/crackers browsers flag apps/sites that use javascript within an href... see no reason to ducktype above..

it's 2016 since 2010 should be no reason anywhere to use links that act like buttons... if you still have to support IE8 and below you need to re-evaluate your place of business.

How to make a simple image upload using Javascript/HTML

<img id="output_image" height=50px width=50px\
<input type="file" accept="image/*" onchange="preview_image(event)">

<script type"text/javascript">
  function preview_image(event) {
    var reader = new FileReader();
    reader.onload = function(){
      var output = document.getElementById('output_image');
      output.src = reader.result;
    }
    reader.readAsDataURL(event.target.files[0]);
  }
</script>

Only using @JsonIgnore during serialization, but not deserialization

Exactly how to do this depends on the version of Jackson that you're using. This changed around version 1.9, before that, you could do this by adding @JsonIgnore to the getter.

Which you've tried:

Add @JsonIgnore on the getter method only

Do this, and also add a specific @JsonProperty annotation for your JSON "password" field name to the setter method for the password on your object.

More recent versions of Jackson have added READ_ONLY and WRITE_ONLY annotation arguments for JsonProperty. So you could also do something like:

@JsonProperty(access = Access.WRITE_ONLY)
private String password;

Docs can be found here.

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

public class AndroidWalkthroughApp1 extends Activity implements View.OnClickListener {

    final int TOP_ID = 3;
    final int BOTTOM_ID = 4;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // create two layouts to hold buttons
        RelativeLayout top = new RelativeLayout(this);
        top.setId(TOP_ID);
        RelativeLayout bottom = new RelativeLayout(this);
        bottom.setId(BOTTOM_ID);

        // create buttons in a loop
        for (int i = 0; i < 2; i++) {
            Button button = new Button(this);
            button.setText("Button " + i);
            // R.id won't be generated for us, so we need to create one
            button.setId(i);

            // add our event handler (less memory than an anonymous inner class)
            button.setOnClickListener(this);

            // add generated button to view
            if (i == 0) {
                top.addView(button);
            }
            else {
                bottom.addView(button);
            }
        }

        RelativeLayout root = (RelativeLayout) findViewById(R.id.root_layout);

        // add generated layouts to root layout view
       // LinearLayout root = (LinearLayout)this.findViewById(R.id.root_layout);

        root.addView(top);
        root.addView(bottom);
    }

    @Override
    public void onClick(View v) {
        // show a message with the button's ID
        Toast toast = Toast.makeText(AndroidWalkthroughApp1.this, "You clicked button " + v.getId(), Toast.LENGTH_LONG);
        toast.show();

        // get the parent layout and remove the clicked button
        RelativeLayout parentLayout = (RelativeLayout)v.getParent();
        parentLayout.removeView(v);



    }
}

Emulate a 403 error page

I have read all the answers here and none of them was complete answer for my situation (which is exactly the same in this question) so here is how I gathered some parts of the suggested answers and come up with the exact solution:

  1. Land on your server's real 403 page. (Go to a forbidden URL on your server, or go to any 403 page you like)
  2. Right-click and select 'view source'. Select all the source and save it to file on your domain like: http://domain.com/403.html
  3. now go to your real forbidden page (or a forbidden situation in some part of your php) example: http://domain.com/members/this_is_forbidden.php
  4. echo this code below before any HTML output or header! (even a whitespace will cause PHP to send HTML/TEXT HTTP Header and it won't work) The code below should be your first line!

        <?php header('HTTP/1.0 403 Forbidden');
        $contents = file_get_contents('/home/your_account/public_html/domain.com/403.html', TRUE);
        exit($contents);
    

Now you have the exact solution. I checked and verified with CPANEL Latest Visitors and it is registered as exact 403 event.

Write / add data in JSON file using Node.js

For formatting jsonfile gives spaces option which you can pass as a parameter:

   jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
         console.error(err);
   })

Or use jsonfile.spaces = 4. Read details here.

I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.

var jsonfile = require('jsonfile');
var obj={
     'table':[]
    };

for (i=0; i <11 ; i++){
       obj.table.push({"id":i,"square":i*i});
}
jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
      console.log(err);
});

how to set imageview src?

To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.

If you have image in the form of bitmap then use

imageview.setImageBitmap(bm);

If you have image in the form of drawable then use

imageview.setImageDrawable(drawable);

If you have image in your resource example if image is present in drawable folder then use

imageview.setImageResource(R.drawable.image);

If you have path of image then use

imageview.setImageURI(Uri.parse("pathofimage"));

Hashing a dictionary?

If your dictionary is not nested, you could make a frozenset with the dict's items and use hash():

hash(frozenset(my_dict.items()))

This is much less computationally intensive than generating the JSON string or representation of the dictionary.

UPDATE: Please see the comments below, why this approach might not produce a stable result.

MySQL JOIN the most recent row only?

I know this question is old, but it's got a lot of attention over the years and I think it's missing a concept which may help someone in a similar case. I'm adding it here for completeness sake.

If you cannot modify your original database schema, then a lot of good answers have been provided and solve the problem just fine.

If you can, however, modify your schema, I would advise to add a field in your customer table that holds the id of the latest customer_data record for this customer:

CREATE TABLE customer (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  current_data_id INT UNSIGNED NULL DEFAULT NULL
);

CREATE TABLE customer_data (
   id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
   customer_id INT UNSIGNED NOT NULL, 
   title VARCHAR(10) NOT NULL,
   forename VARCHAR(10) NOT NULL,
   surname VARCHAR(10) NOT NULL
);

Querying customers

Querying is as easy and fast as it can be:

SELECT c.*, d.title, d.forename, d.surname
FROM customer c
INNER JOIN customer_data d on d.id = c.current_data_id
WHERE ...;

The drawback is the extra complexity when creating or updating a customer.

Updating a customer

Whenever you want to update a customer, you insert a new record in the customer_data table, and update the customer record.

INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(2, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = 2;

Creating a customer

Creating a customer is just a matter of inserting the customer entry, then running the same statements:

INSERT INTO customer () VALUES ();

SET @customer_id = LAST_INSERT_ID();
INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(@customer_id, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = @customer_id;

Wrapping up

The extra complexity for creating/updating a customer might be fearsome, but it can easily be automated with triggers.

Finally, if you're using an ORM, this can be really easy to manage. The ORM can take care of inserting the values, updating the ids, and joining the two tables automatically for you.

Here is how your mutable Customer model would look like:

class Customer
{
    private int id;
    private CustomerData currentData;

    public Customer(String title, String forename, String surname)
    {
        this.update(title, forename, surname);
    }

    public void update(String title, String forename, String surname)
    {
        this.currentData = new CustomerData(this, title, forename, surname);
    }

    public String getTitle()
    {
        return this.currentData.getTitle();
    }

    public String getForename()
    {
        return this.currentData.getForename();
    }

    public String getSurname()
    {
        return this.currentData.getSurname();
    }
}

And your immutable CustomerData model, that contains only getters:

class CustomerData
{
    private int id;
    private Customer customer;
    private String title;
    private String forename;
    private String surname;

    public CustomerData(Customer customer, String title, String forename, String surname)
    {
        this.customer = customer;
        this.title    = title;
        this.forename = forename;
        this.surname  = surname;
    }

    public String getTitle()
    {
        return this.title;
    }

    public String getForename()
    {
        return this.forename;
    }

    public String getSurname()
    {
        return this.surname;
    }
}

What does -> mean in Python function definitions?

def function(arg)->123:

It's simply a return type, integer in this case doesn't matter which number you write.

like Java :

public int function(int args){...}

But for Python (how Jim Fasarakis Hilliard said) the return type it's just an hint, so it's suggest the return but allow anyway to return other type like a string..

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

Dont go crazy I just clean , then rebuild project and error was gone

Removing spaces from string

String  input = EditTextinput.getText().toString();
input = input.replace(" ", "");

Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim:

input = input.trim();

How to launch an EXE from Web page (asp.net)

if the applications are C#, you can use ClickOnce deployment, which is a good option if you can't guarentee the user will have the app, however you'll have to re-build the apps with deployment options and grab some boilerplate code from each project.

You can also use Javascript.

Or you can register an application to handle a new web protocol you can define. This could also be an "app selection" protocol, so each time an app is clicked it would link to a page on your new protocol, all handling of this protocol is then passed to your "selection app" which uses arguments to find and launch an app on the clients PC.

HTH

Get data from file input in JQuery

input element, of type file

<input id="fileInput" type="file" />

On your input change use the FileReader object and read your input file property:

$('#fileInput').on('change', function () {
    var fileReader = new FileReader();
    fileReader.onload = function () {
      var data = fileReader.result;  // data <-- in this var you have the file data in Base64 format
    };
    fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});

FileReader will load your file and in fileReader.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)

Margin on child element moves parent element

Using top instead of margin-top is another possible solution, if appropriate.

How do you create a dropdownlist from an enum in ASP.NET MVC?

Html.DropDownListFor only requires an IEnumerable, so an alternative to Prise's solution is as follows. This will allow you to simply write:

@Html.DropDownListFor(m => m.SelectedItemType, Model.SelectedItemType.ToSelectList())

[Where SelectedItemType is a field on your model of type ItemTypes, and your model is non-null]

Also, you don't really need to genericize the extension method as you can use enumValue.GetType() rather than typeof(T).

EDIT: Integrated Simon's solution here as well, and included ToDescription extension method.

public static class EnumExtensions
{
    public static IEnumerable<SelectListItem> ToSelectList(this Enum enumValue)
    {
        return from Enum e in Enum.GetValues(enumValue.GetType())
               select new SelectListItem
               {
                   Selected = e.Equals(enumValue),
                   Text = e.ToDescription(),
                   Value = e.ToString()
               };
    }

    public static string ToDescription(this Enum value)
    {
        var attributes = (DescriptionAttribute[])value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
        return attributes.Length > 0 ? attributes[0].Description : value.ToString();
    }
}

How to set image to fit width of the page using jsPDF?

The API changed since this commit, using version 1.4.1 it's now

var width = pdf.internal.pageSize.getWidth();
var height = pdf.internal.pageSize.getHeight();

In Gradle, is there a better way to get Environment Variables?

Well; this works as well:

home = "$System.env.HOME"

It's not clear what you're aiming for.

How to get all privileges back to the root user in MySQL?

This worked for me on Ubuntu:

Stop MySQL server:

/etc/init.d/mysql stop

Start MySQL from the commandline:

/usr/sbin/mysqld

In another terminal enter mysql and issue:

grant all privileges on *.* to 'root'@'%' with grant option;

You may also want to add

grant all privileges on *.* to 'root'@'localhost' with grant option;

and optionally use a password as well.

flush privileges;

and then exit your MySQL prompt and then kill the mysqld server running in the foreground. Restart with

/etc/init.d/mysql start  

Convert string to datetime

I have had success with:

require 'time'
t = Time.parse(some_string)

Git diff says subproject is dirty

I ended up removing the submodule directory and initializing it once again

cd my-submodule
git push
cd ../
rm -rf my-submodule
git submodule init
git submodule update

Apache Spark: map vs mapPartitions?

Imp. TIP :

Whenever you have heavyweight initialization that should be done once for many RDD elements rather than once per RDD element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), use mapPartitions() instead of map(). mapPartitions() provides for the initialization to be done once per worker task/thread/partition instead of once per RDD data element for example : see below.

val newRd = myRdd.mapPartitions(partition => {
  val connection = new DbConnection /*creates a db connection per partition*/

  val newPartition = partition.map(record => {
    readMatchingFromDB(record, connection)
  }).toList // consumes the iterator, thus calls readMatchingFromDB 

  connection.close() // close dbconnection here
  newPartition.iterator // create a new iterator
})

Q2. does flatMap behave like map or like mapPartitions?

Yes. please see example 2 of flatmap.. its self explanatory.

Q1. What's the difference between an RDD's map and mapPartitions

map works the function being utilized at a per element level while mapPartitions exercises the function at the partition level.

Example Scenario : if we have 100K elements in a particular RDD partition then we will fire off the function being used by the mapping transformation 100K times when we use map.

Conversely, if we use mapPartitions then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.

There will be performance gain since map works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions).

map

Applies a transformation function on each item of the RDD and returns the result as a new RDD.

Listing Variants

def map[U: ClassTag](f: T => U): RDD[U]

Example :

val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
 val b = a.map(_.length)
 val c = a.zip(b)
 c.collect
 res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8)) 

mapPartitions

This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.

preservesPartitioning indicates whether the input function preserves the partitioner, which should be false unless this is a pair RDD and the input function doesn't modify the keys.

Listing Variants

def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]

Example 1

val a = sc.parallelize(1 to 9, 3)
 def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
   var res = List[(T, T)]()
   var pre = iter.next
   while (iter.hasNext)
   {
     val cur = iter.next;
     res .::= (pre, cur)
     pre = cur;
   }
   res.iterator
 }
 a.mapPartitions(myfunc).collect
 res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8)) 

Example 2

val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
 def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
   var res = List[Int]()
   while (iter.hasNext) {
     val cur = iter.next;
     res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
   }
   res.iterator
 }
 x.mapPartitions(myfunc).collect
 // some of the number are not outputted at all. This is because the random number generated for it is zero.
 res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10) 

The above program can also be written using flatMap as follows.

Example 2 using flatmap

val x  = sc.parallelize(1 to 10, 3)
 x.flatMap(List.fill(scala.util.Random.nextInt(10))(_)).collect

 res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10) 

Conclusion :

mapPartitions transformation is faster than map since it calls your function once/partition, not once/element..

Further reading : foreach Vs foreachPartitions When to use What?

What is the proper way to check and uncheck a checkbox in HTML5?

you can use autocomplete="off" on parent form, so if you reload your page, checkboxes will not be checked automatically

How to know installed Oracle Client is 32 bit or 64 bit?

None of the links above about lib and lib32 folder worked for me with Oracle Client 11.2.0 But I found this on the OTN community:

As far as inspecting a client install to try to tell if it's 32 bit or 64 bit, you can check the registry, a 32 bit home will be located in HKLM>Software>WOW6432Node>Oracle, whereas a 64 bit home will be in HKLM>Software>Oracle.

Installing Homebrew on OS X

How To Set Up Your Mac for Homebrew

Step 1

Check you have already Install the Xcode. Run the below command in your terminal

/usr/bin/xcodebuild -version

It will print the below sample output:

Xcode 12.3 Build version 12C33

Step 2

Now Open Xcode:

  1. Select preferences
  2. Select location tab
  3. Now in command Line Tool select your Xcode version from dropdown menu

Step 3

In terminal run below command:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Note : if you have M1 Chip Mac run the below command, close terminal and open the terminal again

echo "export PATH=/opt/homebrew/bin:$PATH" >> ~/.zshrc

Context.startForegroundService() did not then call Service.startForeground()

Your app will crash if you call Context.startForegroundService(...) and then call Context.stopService(...) before Service.startForeground(...) is called.

I have a clear repro here ForegroundServiceAPI26

I have opened a bug on this at : Google issue tracker

Several bugs on this have been opened and closed Won't Fix.

Hopefully mine with clear repro steps will make the cut.

Information provided by google team

Google issue tracker Comment 36

This is not a framework bug; it's intentional. If the app starts a service instance with startForegroundService(), it must transition that service instance to the foreground state and show the notification. If the service instance is stopped before startForeground() is called on it, that promise is unfulfilled: this is a bug in the app.

Re #31, publishing a Service that other apps can start directly is fundamentally unsafe. You can mitigate that a bit by treating all start actions of that service as requiring startForeground(), though obviously that may not be what you had in mind.

Google issue tracker Comment 56

There are a couple of different scenarios that lead to the same outcome here.

The outright semantic issue, that it's simply an error to kick something off with startForegroundService() but neglect to actually transition it to foreground via startForeground(), is just that: a semantic issue. That's treated as an app bug, intentionally. Stopping the service before transitioning it to foreground is an app error. That was the crux of the OP, and is why this issue has been marked "working as intended."

However, there are also questions about spurious detection of this problem. That's is being treated as a genuine problem, though it's being tracked separately from this particular bug tracker issue. We aren't deaf to the complaint.

Creating a class object in c++

1) What is the difference between both the way of creating class objects.

a) pointer

Example* example=new Example();
// you get a pointer, and when you finish it use, you have to delete it:

delete example;

b) Simple declaration

Example example;

you get a variable, not a pointer, and it will be destroyed out of scope it was declared.

2) Singleton C++

This SO question may helps you

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

Aside from other great responses, I just had to give NTFS permissions to the Oracle installation folder. (I gave read access)

Using lodash to compare jagged arrays (items existence without order)

Edit: I missed the multi-dimensional aspect of this question, so I'm leaving this here in case it helps people compare one-dimensional arrays

It's an old question, but I was having issues with the speed of using .sort() or sortBy(), so I used this instead:

function arraysContainSameStrings(array1: string[], array2: string[]): boolean {
  return (
    array1.length === array2.length &&
    array1.every((str) => array2.includes(str)) &&
    array2.every((str) => array1.includes(str))
  )
}

It was intended to fail fast, and for my purposes works fine.

How do I bottom-align grid elements in bootstrap fluid layout

.align-bottom {
    position: absolute;
    bottom: 10px;
    right: 10px;
}

Can I use jQuery to check whether at least one checkbox is checked?

$('#frmTest').submit(function(){
    if(!$('#frmTest input[type="checkbox"]').is(':checked')){
      alert("Please check at least one.");
      return false;
    }
});

is(':checked') will return true if at least one or more of the checkboxes are checked.

Build a basic Python iterator

This is an iterable function without yield. It make use of the iter function and a closure which keeps it's state in a mutable (list) in the enclosing scope for python 2.

def count(low, high):
    counter = [0]
    def tmp():
        val = low + counter[0]
        if val < high:
            counter[0] += 1
            return val
        return None
    return iter(tmp, None)

For Python 3, closure state is kept in an immutable in the enclosing scope and nonlocal is used in local scope to update the state variable.

def count(low, high):
    counter = 0
    def tmp():
        nonlocal counter
        val = low + counter
        if val < high:
            counter += 1
            return val
        return None
    return iter(tmp, None)  

Test;

for i in count(1,10):
    print(i)
1
2
3
4
5
6
7
8
9

" app-release.apk" how to change this default generated apk name

My solution may also be of help to someone.

Tested and Works on IntelliJ 2017.3.2 with Gradle 4.4

Scenario:

I have 2 flavours in my application, and so I wanted each release to be named appropriately according to each flavor.

The code below will be placed into your module gradle build file found in:

{app-root}/app/build.gradle

Gradle code to be added to android{ } block:

android {
    // ...

    defaultConfig {
        versionCode 10
        versionName "1.2.3_build5"
    }

    buildTypes {
        // ...

        release {
            // ...

            applicationVariants.all { 
                variant.outputs.each { output ->
                    output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace(output.outputFile.name, variant.flavorName + "-" + defaultConfig.versionName + "_v" + defaultConfig.versionCode + ".apk"))
                }
            }

        }
    }

    productFlavors {
        myspicyflavor {
            applicationIdSuffix ".MySpicyFlavor"
            signingConfig signingConfigs.debug
        }

        mystandardflavor {
            applicationIdSuffix ".MyStandardFlavor"
            signingConfig signingConfigs.config
        }
    }
}

The above provides the following APKs found in {app-root}/app/:

myspicyflavor-release-1.2.3_build5_v10.apk
mystandardflavor-release-1.2.3_build5_v10.apk

Hope it can be of use to someone.

For more info, see other answers mentioned in the question

How to skip the OPTIONS preflight request?

I think best way is check if request is of type "OPTIONS" return 200 from middle ware. It worked for me.

express.use('*',(req,res,next) =>{
      if (req.method == "OPTIONS") {
        res.status(200);
        res.send();
      }else{
        next();
      }
    });

How to use variables in SQL statement in Python?

Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

or (e.g. with sqlite3 from the Python standard library):

cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3))

or others yet (after VALUES you could have (:1, :2, :3) , or "named styles" (:fee, :fie, :fo) or (%(fee)s, %(fie)s, %(fo)s) where you pass a dict instead of a map as the second argument to execute). Check the paramstyle string constant in the DB API module you're using, and look for paramstyle at http://www.python.org/dev/peps/pep-0249/ to see what all the parameter-passing styles are!

Using StringWriter for XML Serialization

One problem with StringWriter is that by default it doesn't let you set the encoding which it advertises - so you can end up with an XML document advertising its encoding as UTF-16, which means you need to encode it as UTF-16 if you write it to a file. I have a small class to help with that though:

public sealed class StringWriterWithEncoding : StringWriter
{
    public override Encoding Encoding { get; }

    public StringWriterWithEncoding (Encoding encoding)
    {
        Encoding = encoding;
    }    
}

Or if you only need UTF-8 (which is all I often need):

public sealed class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

As for why you couldn't save your XML to the database - you'll have to give us more details about what happened when you tried, if you want us to be able to diagnose/fix it.

how to permit an array with strong parameters

If you want to permit an array of hashes(or an array of objects from the perspective of JSON)

params.permit(:foo, array: [:key1, :key2])

2 points to notice here:

  1. array should be the last argument of the permit method.
  2. you should specify keys of the hash in the array, otherwise you will get an error Unpermitted parameter: array, which is very difficult to debug in this case.

How to use ADB to send touch events to device using sendevent command?

In order to do a particular action (for example to open the web browser), you need to first figure out where to tap. To do that, you can first run:

adb shell getevent -l

Once you press on the device, at the location that you want, you will see this output:

<...>
/dev/input/event3: EV_KEY       BTN_TOUCH            DOWN
/dev/input/event3: EV_ABS       ABS_MT_POSITION_X    000002f5
/dev/input/event3: EV_ABS       ABS_MT_POSITION_Y    0000069e

adb is telling you that a key was pressed (button down) at position 2f5, 69e in hex which is 757 and 1694 in decimal.

If you now want to generate the same event, you can use the input tap command at the same position:

adb shell input tap 757 1694

More info can be found at:

https://source.android.com/devices/input/touch-devices.html http://source.android.com/devices/input/getevent.html

How to count certain elements in array?

Here is an ES2017+ way to get the counts for all array items in O(N):

const arr = [1, 2, 3, 5, 2, 8, 9, 2];
const counts = {};

arr.forEach((el) => {
  counts[el] = counts[el] ? (counts[el] += 1) : 1;
});

You can also optionally sort the output:

const countsSorted = Object.entries(counts).sort(([_, a], [__, b]) => a - b);

console.log(countsSorted) for your example array:

[
  [ '2', 3 ],
  [ '1', 1 ],
  [ '3', 1 ],
  [ '5', 1 ],
  [ '8', 1 ],
  [ '9', 1 ]
]

How to JOIN three tables in Codeigniter

Try as follows:

public function funcname($id)
{
    $this->db->select('*');
    $this->db->from('Album a'); 
    $this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
    $this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
    $this->db->where('c.album_id',$id);
    $this->db->order_by('c.track_title','asc');         
    $query = $this->db->get(); 
    return $query->result_array();
}

If no result found CI returns false otherwise true

How to change port for jenkins window service when 8080 is being used

Use Default Port

If the default port 8080 has been bind with other process, Then kill that process.

DOS> netstat -a -o -n

Find the process id (PID) XXXX of the process which occupied 8080.

DOS> taskkill /F /PID XXXX

Now, start Jenkins (on default port)

DOS> Java -jar jenkins.war

Use Custom Port

DOS> Java -jar jenkins.war --httpPort=8008

How do I convert from BLOB to TEXT in MySQL?

You can do it very easily.

ALTER TABLE `table_name` CHANGE COLUMN `column_name` `column_name` LONGTEXT NULL DEFAULT NULL ;

The above query worked for me. I hope it helps you too.

How can I get the URL of the current tab from a Google Chrome extension?

You have to check on this.

HTML

<button id="saveActionId"> Save </button>

manifest.json

  "permissions": [
    "activeTab",
    "tabs"
   ]

JavaScript
The below code will save all the urls of active window into JSON object as part of button click.

var saveActionButton = document.getElementById('saveActionId');
saveActionButton.addEventListener('click', function() {
    myArray = [];
    chrome.tabs.query({"currentWindow": true},  //{"windowId": targetWindow.id, "index": tabPosition});
    function (array_of_Tabs) {  //Tab tab
        arrayLength = array_of_Tabs.length;
        //alert(arrayLength);
        for (var i = 0; i < arrayLength; i++) {
            myArray.push(array_of_Tabs[i].url);
        }
        obj = JSON.parse(JSON.stringify(myArray));
    });
}, false);

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

I was seeing this error reported once in a while from some of my apps, and here's what solved it for me:

if(!((Activity) context).isFinishing())
{
    //show dialog
}

All the other answers out there seem to be doing weird things like iterating through the list of running activities, but this is much simpler and seems to do the trick.

.NET Core vs Mono

Necromancing.
Providing an actual answer.

What is the difference between .Net Core and Mono?

.NET Core now officially is the future of .NET. It started for most part with a re-write of the ASP.NET MVC framework and console applications, which of course includes server applications. (Since it's Turing-complete and supports interop with C dlls, you could, if you absolutely wanted to, also write your own desktop applications with it, for example through 3rd-party libraries like Avalonia, which were a bit very basic at the time I first wrote this, which meant you were pretty much limited to web or server stuff.) Over time, many APIs have been added to .NET Core, so much so that after version 3.1, .NET Core will jump to version 5.0, be known as .NET 5.0 without the "Core", and that then will be the future of the .NET Framework. What used to be the full .NET Framework will linger around in maintenance mode as Full .NET Framework 4.8.x for a few decades, until it will die (maybe there are still going to be some upgrades, but I doubt it). In other words, .NET Core is the future of .NET, and Full .NET Framework will go the way of the Dodo/Silverlight/WindowsPhone.

The main point of .NET Core, apart from multi-platform support, is to improve performance, and to enable "native compilation"/self-contained-deployment (so you don't need .NET framework/VM installed on the target machine.
On the one hand, this means docker.io support on Linux, and on the other, self-contained deployment is useful in "cloud-computing", since then you can just use whatever version of the dotnet-CORE framework you like, and you don't have to worry about which version(s) of the .NET framework the sysadmin has actually installed.

While the .NET Core runtime supports multiple operating systems and processors, the SDK is a different story. And while the SDK supports multiple OS, ARM support for the SDK is/was still work in progress. .NET Core is supported by Microsoft. Dotnet-Core did not come with WinForms or WPF or anything like that.

  • As of version 3.0, WinForms and WPF is also supported by .NET Core, but only on Windows, and only by C#. Not by VB.NET (VB.NET support planned for v5 in 2020). And there is no Forms Designer in .NET Core: it's being shipped with a Visual Studio update later, at an unspecified time.
  • WebForms are still not supported by .NET Core, and there are no plans to support them, ever (Blazor is the new kid in town for that).
  • .NET Core also comes with System.Runtime, which replaces mscorelib.
  • Oftentimes, .NET Core is mixed up with NetStandard, which is a bit of a wrapper around System.Runtime/mscorelib (and some others), that allows you to write libraries that target .NET Core, Full .NET Framework and Xamarin (iOS/Android), all at the same time.
  • the .NET Core SDK does not/did not work on ARM, at least not last time I checked.

"The Mono Project" is much older than .NET Core.
Mono is Spanish and means Monkey, and as a side-remark, the name has nothing to do with mononucleosis (hint: you could get a list of staff under http://primates.ximian.com/).
Mono was started in 2005 by Miguel de Icaza (the guy that started GNOME - and a few others) as an implementation of the .NET Framework for Linux (Ximian/SuSe/Novell). Mono includes Web-Forms, Winforms, MVC, Olive, and an IDE called MonoDevelop (also knows as Xamarin Studio or Visual Studio Mac). Basically the equivalent of (OpenJDK) JVM and (OpenJDK) JDK/JRE (as opposed to SUN/Oracle JDK). You can use it to get ASP.NET-WebForms + WinForms + ASP.NET-MVC applications to work on Linux.

Mono is supported by Xamarin (the new company name of what used to be Ximian, when they focused on the Mobile market, instead of the Linux market), and not by Microsoft.
(since Xamarin was bought by Microsoft, that's technically [but not culturally] Microsoft.)
You will usually get your C# stuff to compile on mono, but not the VB.NET stuff.
Mono misses some advanced features, like WSE/WCF and WebParts.
Many of the Mono implementations are incomplete (e.g. throw NotImplementedException in ECDSA encryption), buggy (e.g. ODBC/ADO.NET with Firebird), behave differently than on .NET (for example XML-serialization) or otherwise unstable (ASP.NET MVC) and unacceptably slow (Regex). On the upside, the Mono toolchain also works on ARM.

As far as .NET Core is concerned, when they say cross-platform, don't expect that cross-platform means that you could actually just apt-get install .NET Core on ARM-Linux, like you can with ElasticSearch. You'll have to compile the entire framework from source.
That is, if you have that space (e.g. on a Chromebook, which has a 16 to 32 GB total HD).
It also used to have issues of incompatibility with OpenSSL 1.1 and libcurl.
Those have been rectified in the latest version of .NET Core Version 2.2.
So much for cross-platform.

I found a statement on the official site that said, "Code written for it is also portable across application stacks, such as Mono".

As long as that code doesn't rely on WinAPI-calls, Windows-dll-pinvokes, COM-Components, a case-insensitive file system, the default-system-encoding (codepage) and doesn't have directory separator issues, that's correct. However, .NET Core code runs on .NET Core, and not on Mono. So mixing the two will be difficult. And since Mono is quite unstable and slow (for web applications), I wouldn't recommend it anyway. Try image-processing on .NET core, e.g. WebP or moving GIF or multipage-tiff or writing text on an image, you'll be nastily surprised.

Note:
As of .NET Core 2.0, there is System.Drawing.Common (NuGet), which contains most of the functionality of System.Drawing. It should be more or less feature-complete in .NET-Core 2.1. However, System.Drawing.Common uses GDI+, and therefore won't work on Azure (System.Drawing libraries are available in Azure Cloud Service [basically just a VM], but not in Azure Web App [basically shared hosting?])
So far, System.Drawing.Common works fine on Linux/Mac, but has issues on iOS/Android - if it works at all, there.
Prior to .NET Core 2.0, that is to say sometime mid-February 2017, you could use SkiaSharp for imaging (example) (you still can).
Post .net-core 2.0, you'll notice that SixLabors ImageSharp is the way to go, since System.Drawing is not necessarely secure, and has a lot of potential or real memory leaks, which is why you shouldn't use GDI in web-applications; Note that SkiaSharp is a lot faster than ImageSharp, because it uses native-libraries (which can also be a drawback). Also, note that while GDI+ works on Linux & Mac, that doesn't mean it works on iOS/Android.

Code not written for .NET (non-Core) is not portable to .NET Core.
Meaning, if you want a non-GPL C# library like PDFSharp to create PDF-documents (very commonplace), you're out of luck (at the moment) (not anymore). Never mind ReportViewer control, which uses Windows-pInvokes (to encrypt, create mcdf documents via COM, and to get font, character, kerning, font embedding information, measure strings and do line-breaking, and for actually drawing tiffs of acceptable quality), and doesn't even run on Mono on Linux
(I'm working on that).

Also, code written in .NET Core is not portable to Mono, because Mono lacks the .NET Core runtime libraries (so far).

My goal is to use C#, LINQ, EF7, visual studio to create a website that can be ran/hosted in linux.

EF in any version that I tried so far was so goddamn slow (even on such simple things like one table with one left-join), I wouldn't recommend it ever - not on Windows either.
I would particularly not recommend EF if you have a database with unique-constrains, or varbinary/filestream/hierarchyid columns. (Not for schema-update either.)
And also not in a situation where DB-performance is critical (say 10+ to 100+ concurrent users).
Also, running a website/web-application on Linux will sooner or later mean you'll have to debug it.
There is no debugging support for .NET Core on Linux. (Not anymore, but requires JetBrains Rider.)
MonoDevelop does not (yet) support debugging .NET Core projects.
If you have problems, you're on your own. You'll have to use extensive logging.
Be careful, be advised extensive logging will fill your disk in no time, particularly if your program enters an infinite loop or recursion.
This is especially dangerous if your web-app runs as root, because log-in requires logfile-space - if there's no free space left, you won't be able to login anymore.
(Normally, about 5% of diskspace is reserved for user root [aka administrator on Windows], so at least the administrator can still log in if the disk is almost full. But if your applications run as root, that restriction does not apply for their disk usage, and so their logfiles can use 100% of the remaining free space, so not even the administrator can log in any more.)
It's therefore better not to encrypt that disk, that is, if you value your data/system.

Someone told me that he wanted it to be "in Mono", but I don't know what that means.

It either means he doesn't want to use .NET Core, or he just wants to use C# on Linux/Mac. My guess is he just wants to use C# for a Web-App on Linux. .NET Core is the way to go for that, if you absolutely want to do it in C#. Don't go with "Mono proper"; on the surface, it would seem to work at first - but believe me you will regret it because Mono's ASP.NET MVC isn't stable when your server runs long-term (longer than 1 day) - you have now been warned. See also the "did not complete" references when measuring Mono performance on the techempower benchmarks.

fortunes

I know I want to use the .Net Core 1.0 framework with the technologies I listed above. He also said he wanted to use "fast cgi". I don't know what that means either.

It means he wants to use a high-performance full-featured WebServer like nginx (Engine-X), possibly Apache.
Then he can run mono/dotnetCore with virtual name based hosting (multiple domain names on the same IP) and/or load-balancing. He can also run other websites with other technologies, without requiring a different port-number on the web-server. It means your website runs on a fastcgi-server, and nginx forwards all web-requests for a certain domain via the fastcgi-protocol to that server. It also means your website runs in a fastcgi-pipeline, and you have to be careful what you do, e.g. you can't use HTTP 1.1 when transmitting files.
Otherwise, files will be garbled at the destination.
See also here and here.

To conclude:
.NET Core at present (2016-09-28) is not really portable, nor is is really cross-platform (in particular the debug-tools).
Nor is native-compilation easy, especially for ARM.
And to me, it also does not look like its development is "really finished", yet.
For example, System.Data.DataTable/DataAdaper.Update is missing... (not anymore with .NET Core 2.0)
Together with the System.Data.Common.IDB* interfaces. (not anymore with .NET Core 1.1)
if there ever was one class that is often used, DataTable/DataAdapter would be it...
Also, the Linux-installer (.deb) fails, at least on my machine, and I'm sure I'm not the only one that has that problem.
Debug, maybe with Visual Studio Code, if you can build it on ARM (I managed to do that - do NOT follow Scott Hanselman's blog-post if you do that - there's a howto in the wiki of VS-Code on github), because they don't offer the executable.
Yeoman also fails. (I guess it has something to do with the nodejs version you installed - VS Code requires one version, Yeoman another... but it should run on the same computer. pretty lame
Never mind that it should run on the node version shipped by default on the OS.
Never mind that there should be no dependency on NodeJS in the first place.
The kestell server is also work in progress.
And judging by my experience with the mono-project, I highly doubt they ever tested .NET Core on FastCGI, or that they have any idea what FastCGI-support means for their framework, let alone that they tested it to make sure "everything works". In fact, I just tried making a fastcgi-application with .NET Core and just realized there is no FastCGI library for .NET Core "RTM"...

So when you're going to run .NET Core "RTM" behind nginx, you can only do it by proxying requests to kestrell (that semi-finished nodeJS-derived web-server) - there's no fastcgi support at present in .NET Core "RTM", AFAIK. Since there is no .net core fastcgi library, and no samples, it's also highly unlikely that anybody did any testing on the framework to make sure fastcgi works as expected.

I also question the performance.
In the (preliminary) techempower-benchmark (round 13), aspnetcore-linux ranks on 25% relative to the best performance, while comparable frameworks like Go (golang) rank at 96.9% of peak performance (and that is when returning plaintext without file-system access only). .NET Core does a little better on JSON-serialization, but it does not look compelling either (go reaches 98.5% of peak, .NET core 65%). That said, it can't possibly be worse than "mono proper".

Also, since it's still relatively new, not all of the major libraries have been ported (yet), and I doubt that some of them will ever be ported.
Imaging support is also questionable at best.
For anything encryption, use BouncyCastle instead.

Can you help me make sense of all these terms and if my expectations are realistic?

I hope i helped you making more sense with all these terms.
As far as your expecations go:
Developing a Linux application without knowing anything about Linux is a really stupid idea in the first place, and it's also bound to fail in some horrible way one way or the other. That said, because Linux comes at no licensing costs, it's a good idea in principle, BUT ONLY IF YOU KNOW WHAT YOU DO.
Developing an application for a platform where you can't debug your application on is another really bad idea.
Developing for fastcgi without knowing what consequences there are is yet another really bad idea.

Doing all these things on a "experimental" platform without any knowledge of that platform's specifics and without debugging support is suicide, if your project is more than just a personal homepage. On the other hand, I guess doing it with your personal homepage for learning purposes would probably be a very good experience - then you get to know what the framework and what the non-framework problems are.
You can for example (programmatically) loop-mount a case-insensitive fat32, hfs or JFS for your application, to get around the case-sensitivity issues (loop-mount not recommended in production).

To summarize
At present (2016-09-28), I would stay away from .NET Core (for production usage). Maybe in one to two years, you can take another look, but probably not before.
If you have a new web-project that you develop, start it in .NET Core, not mono.

If you want a framework that works on Linux (x86/AMD64/ARMhf) and Windows and Mac, that has no dependencies, i.e. only static linking and no dependency on .NET, Java or Windows, use Golang instead. It's more mature, and its performance is proven (Baidu uses it with 1 million concurrent users), and golang has a significantly lower memory footprint. Also golang is in the repositories, the .deb installs without problems, the sourcecode compiles - without requiring changes - and golang (in the meantime) has debugging support with delve and JetBrains Gogland on Linux (and Windows and Mac). Golang's build process (and runtime) also doesn't depend on NodeJS, which is yet another plus.

As far as mono goes, stay away from it.
It is nothing short of amazing how far mono has come, but unfortunately that's no substitute for its performance/scalability and stability issues for production applications.
Also, mono-development is quite dead, they largely only develop the parts relevant to Android and iOS anymore, because that's where Xamarin makes their money.
Don't expect Web-Development to be a first-class Xamarin/mono citizen.
.NET Core might be worth it, if you start a new project, but for existing large web-forms projects, porting over is largely out of the question, the changes required are huge. If you have a MVC-project, the amount of changes might be manageable, if your original application design was sane, which is mostly not the case for most existing so-called "historically grown" applications.

December 2016 Update:
Native compilation has been removed from .NET Core preview, as it is not yet ready...

Seems like they have improved pretty heavily on the raw text-file benchmark, but on the other hand, it's gotten pretty buggy. Also, it further deteriorated in the JSON benchmarks. Curious also that entity framework shall be faster for updates than Dapper - although both at record slowness. This is very unlikely to be true. Looks like there still are more than just a few bugs to hunt.

Also, there seems to be relief coming on the Linux IDE front.
JetBrains released "Project Rider", an early access preview of a C#/.NET Core IDE for Linux (and Mac and Windows), that can handle Visual Studio Project files. Finally a C# IDE that is usable & that isn't slow as hell.

Conclusion: .NET Core still is pre-release quality software as we march into 2017. Port your libraries, but stay away from it for production usage, until framework quality stabilizes.
And keep an eye on Project Rider.

buggy .net core

2017 Update
Have migrated my (brother's) homepage to .NET Core for now.
So far, the runtime on Linux seems to be stable enough (at least for small projects) - it survived a load test with ease - mono never did.
Also, it looks like I mixed up .NET-Core-native and .NET-Core-self-contained-deployment. Self-contained deployment works, but it is a bit underdocumented, although it's super easy (the build/publish tools are a bit unstable, yet - if you encounter "Positive number required. - Build FAILED." - run the same command again, and it works).

You can run

dotnet restore -r win81-x64
dotnet build -r win81-x64
dotnet publish -f netcoreapp1.1 -c Release -r win81-x64

Note: As per .NET Core 3, you can publish everything minified as a single file:

dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true
dotnet publish -r linux-x64 -c Release /p:PublishSingleFile=true

However, unlike go, it's not a statically linked executable, but a self-extracting zip file, so when deploying, you might run into problems, especially if the temp directory is locked down by group policy, or some other issues. Works fine for a hello-world program, though. And if you don't minify, the executable size will clock in at something around 100 MB.

And you get a self-contained .exe-file (in the publish directory), which you can move to a Windows 8.1 machine without .NET framework installed and let it run. Nice. It's here that dotNET-Core just starts to get interesting. (mind the gaps, SkiaSharp doesn't work on Windows 8.1 / Windows Server 2012 R2, [yet] - the ecosystem has to catch up first - but interestingly, the Skia-dll-load-fail doesn't crash the entire server/application - so everything else works)

(Note: SkiaSharp on Windows 8.1 is missing the appropriate VC runtime files - msvcp140.dll and vcruntime140.dll. Copy them into the publish-directory, and Skia will work on Windows 8.1.)

August 2017 Update
.NET Core 2.0 released.
Be careful - comes with (huge breaking) changes in authentication...
On the upside, it brought the DataTable/DataAdaper/DataSet classes back, and many more.
Realized .NET Core is still missing support for Apache SparkSQL, because Mobius isn't yet ported. That's bad, because that means no SparkSQL support for my IoT Cassandra Cluster, so no joins...
Experimental ARM support (runtime only, not SDK - too bad for devwork on my Chromebook - looking forward to 2.1 or 3.0).
PdfSharp is now experimentally ported to .NET Core.
JetBrains Rider left EAP. You can now use it to develop & debug .NET Core on Linux - though so far only .NET Core 1.1 until the update for .NET Core 2.0 support goes live.

May 2018 Update
.NET Core 2.1 release imminent. Maybe this will fix NTLM-authentication on Linux (NTLM authentication doesn't work on Linux {and possibly Mac} in .NET-Core 2.0 with multiple authenticate headers, such as negotiate, commonly sent with ms-exchange, and they're apparently only fixing it in v2.1, no bugfix release for 2.0).
But I'm not installing preview releases on my machine. So waiting.
v2.1 is also said to greatly reduce compile times. That would be good.

Also, note that on Linux, .NET Core is 64-Bit only !
There is no, and there will be no, x86-32 version of .NET Core on Linux.
And the ARM port is ARM-32 only. No ARM-64, yet.
And on ARM, you (at present) only have the runtime, not the dotnet-SDK.

And one more thing:
Because .NET-Core uses OpenSSL 1.0, .NET Core on Linux doesn't run on Arch Linux, and by derivation not on Manjaro (the most popular Linux distro by far at this point in time), because Arch Linux uses OpenSSL 1.1. So if you're using Arch Linux, you're out of luck (with Gentoo, too).

Edit:

Latest version of .NET Core 2.2+ supports OpenSSL 1.1. So you can use it on Arch or (k)Ubuntu 19.04+. You might have to use the .NET-Core install script though, because there are no packages, yet.

On the upside, performance has definitely improved: fortunes

plaintext

.NET Core 3:
.NET-Core v 3.0 is said to bring WinForms and WPF to .NET-Core.
However, while WinForms and WPF will be .NET Core, WinForms and WPF in .NET-Core will run on Windows only, because WinForms/WPF will use the Windows-API.

Note:
.NET Core 3.0 is now out (RTM), and there is WinForms and WPF support, but only for C# (on Windows). There is no WinForms-Core-Designer. The designer will, eventually, come with a Visual Studio update, somewhen. WinForms support for VB.NET is not supported, but is planned for .NET 5.0 somewhen in 2020.

PS:

echo "DOTNET_CLI_TELEMETRY_OPTOUT=1" >> /etc/environment
export DOTNET_CLI_TELEMETRY_OPTOUT=1 

If you've used it on windows, you probably never saw this:

The .NET Core tools collect usage data in order to improve your experience.
The data is anonymous and does not include command-line arguments.
The data is collected by Microsoft and shared with the community.
You can opt out of telemetry by setting a DOTNET_CLI_TELEMETRY_OPTOUT environment variable to 1 using your favorite shell.
You can read more about .NET Core tools telemetry @ https://aka.ms/dotnet-cli-telemetry.

I thought I'd mention that I think monodevelop (aka Xamarin Studio, the Mono IDE, or Visual Studio Mac as it is now called on Mac) has evolved quite nicely, and is - in the meantime - largely usable.
However, JetBrains Rider (2018 EAP at this point in time) is definitely a lot nicer and more reliable (and the included decompiler is a life-safer), that is to say, if you develop .NET-Core on Linux or Mac. MonoDevelop does not support Debug-StepThrough on Linux in .NET Core, though, since MS does not license their debugging API dll (except for VisualStudio Mac ... ). However, you can use the Samsung debugger for .NET Core through the .NET Core debugger extension for Samsung Debugger for MonoDevelop

Disclaimer:
I don't use Mac, so I can't say if what I wrote here applies to FreeBSD-Unix based Mac as well. I am refering to the Linux (Debian/Ubuntu/Mint) version of JetBrains Rider, mono, MonoDevelop/VisualStudioMac/XamarinStudio and .NET-Core. Also, Apple is contemplating a move from Intel-processors to self-manufactured ARM(ARM-64?)-based processors, so much of what applies to Mac right now might not apply to Mac in the future (2020+).

Also, when I write "mono is quite unstable and slow", the unstable relates to WinFroms & WebForms applications, specifically executing web-applications via fastcgi or with XSP (on the 4.x version of mono), as well as XML-serialization-handling peculiarities, and the quite-slow relates to WinForms, and regular expressions in particular (ASP.NET-MVC uses regular expressions for routing as well).

When I write about my experience about mono 2.x, 3.x and 4.x, that also does not necessarely mean these issues haven't been resolved by now, or by the time you are reading this, nor that if they are fixed now, that there can't be a regression later that reintroduces any of these bugs/features. Nor does that mean that if you embed the mono-runtime, you'll get the same results as when you use the (dev) system's mono runtime. It also doesn't mean that embedding the mono-runtime (anywhere) is necessarely free.

All that doesn't necessarely mean mono is ill-suited for iOS or Android, or that it has the same issues there. I don't use mono on Android or IOS, so I'm in no positon to say anything about stability, usability, costs and performance on these platforms. Obviously, if you use .NET on Android, you have some other costs considerations to do as well, such as weighting xamarin-costs vs. costs and time for porting existing code to Java. One hears mono on Android and IOS shall be quite good. Take it with a grain of salt. For one, don't expect the default-system-encoding to be the same on android/ios vs. Windows, and don't expect the android filesystem to be case-insensitive, and don't expect any windows fonts to be present.

Certificate is trusted by PC but not by Android

could be that you're missing the certificate on your device.

try looking at this answer: How to install trusted CA certificate on Android device? to see how to install the CA on your own device.

What do I use on linux to make a python program executable

I do the following:

  1. put #! /usr/bin/env python3 at top of script
  2. chmod u+x file.py
  3. Change .py to .command in file name

This essentially turns the file into a bash executable. When you double-click it, it should run. This works in Unix-based systems.

How do I wait for a promise to finish before returning the variable of a function?

You're not actually using promises here. Parse lets you use callbacks or promises; your choice.

To use promises, do the following:

query.find().then(function() {
    console.log("success!");
}, function() {
    console.log("error");
});

Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then() call. So far this would be exactly the same as regular callbacks.

To actually make good use of promises is when you chain them, like this:

query.find().then(function() {
    console.log("success!");

    return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
    console.log("error");
}).then(function() {
    console.log("success on second callback!");
}, function() {
    console.log("error on second callback");
});

JSONException: Value of type java.lang.String cannot be converted to JSONObject

if value of the Key is coming as String and you want to convert it to JSONObject,

First take your key.value into a String variable like

 String data = yourResponse.yourKey;

then convert into JSONArray

JSONObject myObj=new JSONObject(data);

Contain form within a bootstrap popover?

I would put my form into the markup and not into some data tag. This is how it could work:

JS Code:

$('#popover').popover({ 
    html : true,
    title: function() {
      return $("#popover-head").html();
    },
    content: function() {
      return $("#popover-content").html();
    }
});

HTML Markup:

<a href="#" id="popover">the popover link</a>
<div id="popover-head" class="hide">
  some title
</div>
<div id="popover-content" class="hide">
  <!-- MyForm -->
</div>

Demo

Alternative Approaches:

X-Editable

You might want to take a look at X-Editable. A library that allows you to create editable elements on your page based on popovers.

X-Editable demo

Webcomponents

Mike Costello has released Bootstrap Web Components. This nifty library has a Popovers Component that lets you embed the form as markup:

<button id="popover-target" data-original-title="MyTitle" title="">Popover</button>

<bs-popover title="Popover with Title" for="popover-target">
  <!-- MyForm -->
</bs-popover>

Demo

List<String> to ArrayList<String> conversion issue

First of all, why is the map a HashMap<String, ArrayList<String>> and not a HashMap<String, List<String>>? Is there some reason why the value must be a specific implementation of interface List (ArrayList in this case)?

Arrays.asList does not return a java.util.ArrayList, so you can't assign the return value of Arrays.asList to a variable of type ArrayList.

Instead of:

allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));

Try this:

allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));

Calling a java method from c++ in Android

If it's an object method, you need to pass the object to CallObjectMethod:

jobject result = env->CallObjectMethod(obj, messageMe, jstr);

What you were doing was the equivalent of jstr.messageMe().

Since your is a void method, you should call:

env->CallVoidMethod(obj, messageMe, jstr);

If you want to return a result, you need to change your JNI signature (the ()V means a method of void return type) and also the return type in your Java code.

Apply style to cells of first row

This should do the work:

.category_table tr:first-child td {
    vertical-align: top;
}

HashMap - getting First Key value

Remember that the insertion order isn't respected in a map generally speaking. Try this :

    /**
     * Get the first element of a map. A map doesn't guarantee the insertion order
     * @param map
     * @param <E>
     * @param <K>
     * @return
     */
    public static <E,K> K getFirstKeyValue(Map<E,K> map){
        K value = null;
        if(map != null && map.size() > 0){
            Map.Entry<E,K> entry =  map.entrySet().iterator().next();
            if(entry != null)
                value = entry.getValue();
        }
        return  value;
    }

I use this only when I am sure that that map.size() == 1 .

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

How can building a heap be O(n) time complexity?

There are already some great answers but I would like to add a little visual explanation

enter image description here

Now, take a look at the image, there are
n/2^1 green nodes with height 0 (here 23/2 = 12)
n/2^2 red nodes with height 1 (here 23/4 = 6)
n/2^3 blue node with height 2 (here 23/8 = 3)
n/2^4 purple nodes with height 3 (here 23/16 = 2)
so there are n/2^(h+1) nodes for height h
To find the time complexity lets count the amount of work done or max no of iterations performed by each node
now it can be noticed that each node can perform(atmost) iterations == height of the node

Green  = n/2^1 * 0 (no iterations since no children)  
red    = n/2^2 * 1 (heapify will perform atmost one swap for each red node)  
blue   = n/2^3 * 2 (heapify will perform atmost two swaps for each blue node)  
purple = n/2^4 * 3 (heapify will perform atmost three swaps for each purple node)   

so for any nodes with height h maximum work done is n/2^(h+1) * h

Now total work done is

->(n/2^1 * 0) + (n/2^2 * 1)+ (n/2^3 * 2) + (n/2^4 * 3) +...+ (n/2^(h+1) * h)  
-> n * ( 0 + 1/4 + 2/8 + 3/16 +...+ h/2^(h+1) ) 

now for any value of h, the sequence

-> ( 0 + 1/4 + 2/8 + 3/16 +...+ h/2^(h+1) ) 

will never exceed 1
Thus the time complexity will never exceed O(n) for building heap

How do I move a file from one location to another in Java?

Java 6

public boolean moveFile(String sourcePath, String targetPath) {

    File fileToMove = new File(sourcePath);

    return fileToMove.renameTo(new File(targetPath));
}

Java 7 (Using NIO)

public boolean moveFile(String sourcePath, String targetPath) {

    boolean fileMoved = true;

    try {

        Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);

    } catch (Exception e) {

        fileMoved = false;
        e.printStackTrace();
    }

    return fileMoved;
}

Java Delegates?

I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.

How It Works

There is a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.

With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.

In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array does not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to its inner workings.

The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.

What follows is an example using a callback to process the files in a directory tree. This is an initial validation pass which just counts the files to process and ensure none exceed a predetermined maximum size. In this case we just create the callback inline with the API invocation. However, we reflect the target method out as a static value so that the reflection is not done every time.

static private final Method             COUNT =Callback.getMethod(Xxx.class,"callback_count",true,File.class,File.class);

...

IoUtil.processDirectory(root,new Callback(this,COUNT),selector);

...

private void callback_count(File dir, File fil) {
    if(fil!=null) {                                                                             // file is null for processing a directory
        fileTotal++;
        if(fil.length()>fileSizeLimit) {
            throw new Abort("Failed","File size exceeds maximum of "+TextUtil.formatNumber(fileSizeLimit)+" bytes: "+fil);
            }
        }
    progress("Counting",dir,fileTotal);
    }

IoUtil.processDirectory():

/**
 * Process a directory using callbacks.  To interrupt, the callback must throw an (unchecked) exception.
 * Subdirectories are processed only if the selector is null or selects the directories, and are done
 * after the files in any given directory.  When the callback is invoked for a directory, the file
 * argument is null;
 * <p>
 * The callback signature is:
 * <pre>    void callback(File dir, File ent);</pre>
 * <p>
 * @return          The number of files processed.
 */
static public int processDirectory(File dir, Callback cbk, FileSelector sel) {
    return _processDirectory(dir,new Callback.WithParms(cbk,2),sel);
    }

static private int _processDirectory(File dir, Callback.WithParms cbk, FileSelector sel) {
    int                                 cnt=0;

    if(!dir.isDirectory()) {
        if(sel==null || sel.accept(dir)) { cbk.invoke(dir.getParent(),dir); cnt++; }
        }
    else {
        cbk.invoke(dir,(Object[])null);

        File[] lst=(sel==null ? dir.listFiles() : dir.listFiles(sel));
        if(lst!=null) {
            for(int xa=0; xa<lst.length; xa++) {
                File ent=lst[xa];
                if(!ent.isDirectory()) {
                    cbk.invoke(dir,ent);
                    lst[xa]=null;
                    cnt++;
                    }
                }
            for(int xa=0; xa<lst.length; xa++) {
                File ent=lst[xa];
                if(ent!=null) { cnt+=_processDirectory(ent,cbk,sel); }
                }
            }
        }
    return cnt;
    }

This example illustrates the beauty of this approach - the application specific logic is abstracted into the callback, and the drudgery of recursively walking a directory tree is tucked nicely away in a completely reusable static utility method. And we don't have to repeatedly pay the price of defining and implementing an interface for every new use. Of course, the argument for an interface is that it is far more explicit about what to implement (it's enforced, not simply documented) - but in practice I have not found it to be a problem to get the callback definition right.

Defining and implementing an interface is not really so bad (unless you're distributing applets, as I am, where avoiding creating extra classes actually matters), but where this really shines is when you have multiple callbacks in a single class. Not only is being forced to push them each into a separate inner class added overhead in the deployed application, but it's downright tedious to program and all that boiler-plate code is really just "noise".

What are .iml files in Android Studio?

What are iml files in Android Studio project?

A Google search on iml file turns up:

IML is a module file created by IntelliJ IDEA, an IDE used to develop Java applications. It stores information about a development module, which may be a Java, Plugin, Android, or Maven component; saves the module paths, dependencies, and other settings.

(from this page)

why not to use gradle scripts to integrate with external modules that you add to your project.

You do "use gradle scripts to integrate with external modules", or your own modules.

However, Gradle is not IntelliJ IDEA's native project model — that is separate, held in .iml files and the metadata in .idea/ directories. In Android Studio, that stuff is largely generated out of the Gradle build scripts, which is why you are sometimes prompted to "sync project with Gradle files" when you change files like build.gradle. This is also why you don't bother putting .iml files or .idea/ in version control, as their contents will be regenerated.

If I have a team that work in different IDE's like Eclipse and AS how to make project IDE agnostic?

To a large extent, you can't.

You are welcome to have an Android project that uses the Eclipse-style directory structure (e.g., resources and manifest in the project root directory). You can teach Gradle, via build.gradle, how to find files in that structure. However, other metadata (compileSdkVersion, dependencies, etc.) will not be nearly as easily replicated.

Other alternatives include:

  • Move everybody over to another build system, like Maven, that is equally integrated (or not, depending upon your perspective) to both Eclipse and Android Studio

  • Hope that Andmore takes off soon, so that perhaps you can have an Eclipse IDE that can build Android projects from Gradle build scripts

  • Have everyone use one IDE

JQuery - how to select dropdown item based on value

$('#yourdropddownid').val('fg');

Optionally,

$('select>option:eq(3)').attr('selected', true);

where 3 is the index of the option you want.

Live Demo

How to view the committed files you have not pushed yet?

The previous answers are all good, but they all show origin/master. These days, following the best practices, I rarely work directly on a master branch, let alone from origin repo.

So if you are like me who work in a branch, here are tips:

  1. Say you are already on a branch. If not, git checkout that branch
  2. git log # to show a list of commit such as x08d46ffb1369e603c46ae96, You need only the latest commit which comes first.
  3. git show --name-only x08d46ffb1369e603c46ae96 # to show the files commited
  4. git show x08d46ffb1369e603c46ae96 # show the detail diff of each changed file

Or more simply, just use HEAD:

  1. git show --name-only HEAD # to show a list of files committed
  2. git show HEAD # to show the detail diff.

jQuery window scroll event does not fire up

Your CSS is actually setting the rest of the document to not show overflow therefore the document itself isn't scrolling. The easiest fix for this is bind the event to the thing that is scrolling, which in your case is div#page.

So its easy as changing:

$(document).scroll(function() {  // OR  $(window).scroll(function() {
    didScroll = true;
});

to

$('div#page').scroll(function() {
    didScroll = true;
});

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

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

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

Copy data from one existing row to another existing row in SQL?

This works well for coping entire records.

UPDATE your_table
SET new_field = sourse_field

Prevent linebreak after </div>

Try applying the clear:none css attribute to the label.

.label {
     clear:none;
}

WPF C# button style

To solve your question definitely need to use the Style and Template for the Button. But how exactly does he look like? Decisions may be several. For example, Button are two texts to better define the relevant TextBlocks? Can be directly in the template, but then use the buttons will be limited, because the template can be only one ContentPresenter. I decided to do things differently, to identify one ContentPresenter with an icon in the form of a Path, and the content is set using the buttons on the side.

The style:

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="#373737" />
    <Setter Property="Foreground" Value="White" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="SnapsToDevicePixels" Value="True" />

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border CornerRadius="4" Background="{TemplateBinding Background}">
                    <Grid>
                        <Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
                        <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />                                
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#E59400" />
                        <Setter Property="Foreground" Value="White" />
                        <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                    </Trigger>

                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="OrangeRed" />
                        <Setter Property="Foreground" Value="White" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Sample of using:

<Button Width="200" Height="50" VerticalAlignment="Top" Margin="0,20,0,0" />
    <Button.Content>
        <StackPanel>
            <TextBlock Text="Watch Now" FontSize="20" />
            <TextBlock Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
        </StackPanel>
    </Button.Content>
</Button>

Output

enter image description here

It is best to StackPanel determine the Resources and set the Button so:

<Window.Resources>
    <StackPanel x:Key="MyStackPanel">
        <TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
        <TextBlock Name="DurationValue" Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
    </StackPanel>
</Window.Resources>

<Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />

The question remains with setting the value for TextBlock Duration, because this value must be dynamic. I implemented it using attached DependencyProperty. Set it to the window, like that:

<Window Name="MyWindow" local:MyDependencyClass.CurrentDuration="Duration: 50m" ... />

Using in TextBlock:

<TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />

In fact, there is no difference for anyone to determine the attached DependencyProperty, because it is the predominant feature.

Example of set value:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
}

A complete listing of examples:

XAML

<Window x:Class="ButtonHelp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ButtonHelp"
    Name="MyWindow"
    Title="MainWindow" Height="350" Width="525"
    WindowStartupLocation="CenterScreen"
    local:MyDependencyClass.CurrentDuration="Duration: 50m">

<Window.Resources>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="#373737" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="FontSize" Value="15" />
        <Setter Property="FontFamily" Value="./#Segoe UI" />
        <Setter Property="SnapsToDevicePixels" Value="True" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border CornerRadius="4" Background="{TemplateBinding Background}">
                        <Grid>
                            <Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
                            <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />                                
                        </Grid>
                    </Border>

                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#E59400" />
                            <Setter Property="Foreground" Value="White" />
                            <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                        </Trigger>

                        <Trigger Property="IsPressed" Value="True">
                            <Setter Property="Background" Value="OrangeRed" />
                            <Setter Property="Foreground" Value="White" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <StackPanel x:Key="MyStackPanel">
        <TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
        <TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />
    </StackPanel>
</Window.Resources>

<Grid>        
    <Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />

    <Button Content="Set some duration" Style="{x:Null}" Width="140" Height="30" VerticalAlignment="Top" HorizontalAlignment="Left" Click="Button_Click" />
</Grid>

Code behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
    }
}

public class MyDependencyClass : DependencyObject
{
    public static readonly DependencyProperty CurrentDurationProperty;        

    public static void SetCurrentDuration(DependencyObject DepObject, string value)
    {
        DepObject.SetValue(CurrentDurationProperty, value);
    }

    public static string GetCurrentDuration(DependencyObject DepObject)
    {
        return (string)DepObject.GetValue(CurrentDurationProperty);
    }

    static MyDependencyClass()
    {
        PropertyMetadata MyPropertyMetadata = new PropertyMetadata("Duration: 0m");

        CurrentDurationProperty = DependencyProperty.RegisterAttached("CurrentDuration",
                                                            typeof(string),
                                                            typeof(MyDependencyClass),
                                                            MyPropertyMetadata);
    }
}

SQL SERVER: Get total days between two dates

PRINT DATEDIFF(DAY, '1/1/2011', '3/1/2011') will give you what you're after.

This gives the number of times the midnight boundary is crossed between the two dates. You may decide to need to add one to this if you're including both dates in the count - or subtract one if you don't want to include either date.

Determine if an element has a CSS class with jQuery

from the FAQ

elem = $("#elemid");
if (elem.is (".class")) {
   // whatever
}

or:

elem = $("#elemid");
if (elem.hasClass ("class")) {
   // whatever
}

.htaccess deny from all

This syntax has changed with the newer Apache HTTPd server, please see upgrade to apache 2.4 doc for full details.

2.2 configuration syntax was

Order deny,allow
Deny from all

2.4 configuration now is

Require all denied

Thus, this 2.2 syntax

order deny,allow
deny from all
allow from 127.0.0.1

Would ne now written

Require local

SQL Server Insert if not exists

If your clustered index consist from only those fields than the simple, fast and reliable option is to use IGNORE_DUP_KEY

If you create the Clustered index with IGNORE_DUP_KEY ON

Than you can just use:

INSERT INTO EmailsRecebidos (De, Assunto, Data) VALUES (@_DE, @_ASSUNTO, @_DATA)

This should be safe in all cases!

Kendo grid date column not formatting

This might be helpful:

columns.Bound(date=> date.START_DATE).Title("Start Date").Format("{0:MM dd, yyyy}");

What is the HTML5 equivalent to the align attribute in table cells?

Add this code into your StyleSheet:

margin-top:80px;

How can I remove the last character of a string in python?

For a path use os.path.abspath

import os    
print os.path.abspath(my_file_path)

Convert timestamp to readable date/time PHP

Try this one:

echo date('m/d/Y H:i:s', 1541843467);

Program to find largest and smallest among 5 numbers without using array

If you like to keep things simple, then here is my solution.

It works for any number of integers taken from standard input. It also works for negative integers. Enter end when you are done.

#include <iostream>

int main()
{
int max,min,input;
std::cout<<"Enter the number: ";
std::cin>>input;
min=max=input;

while(std::cin>>input){
    if(input>max) max=input;
    if(input<min) min=input;
    std::cout<<"Enter the number: ";
}
std::cout<<"\nMax: "<<max<<"\nMin: "<<min;
}

Excel: Use a cell value as a parameter for a SQL query

If you are using microsoft query, you can add "?" to your query...

select name from user where id= ?

that will popup a small window asking for the cell/data/etc when you go back to excel.

In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.

How to insert a text at the beginning of a file?

If the file is only one line, you can use:

sed 's/^/insert this /' oldfile > newfile

If it's more than one line. one of:

sed '1s/^/insert this /' oldfile > newfile
sed '1,1s/^/insert this /' oldfile > newfile

I've included the latter so that you know how to do ranges of lines. Both of these "replace" the start line marker on their affected lines with the text you want to insert. You can also (assuming your sed is modern enough) use:

sed -i 'whatever command you choose' filename

to do in-place editing.

Multi column forms with fieldsets

There are a couple of things that need to be adjusted in your layout:

  1. You are nesting col elements within form-group elements. This should be the other way around (the form-group should be within the col-sm-xx element).

  2. You should always use a row div for each new "row" in your design. In your case, you would need at least 5 rows (Username, Password and co, Title/First/Last name, email, Language). Otherwise, your problematic .col-sm-12 is still on the same row with the above 3 .col-sm-4 resulting in a total of columns greater than 12, and causing the overlap problem.

Here is a fixed demo.

And an excerpt of what the problematic section HTML should become:

<fieldset>
    <legend>Personal Information</legend>
    <div class='row'>
        <div class='col-sm-4'>    
            <div class='form-group'>
                <label for="user_title">Title</label>
                <input class="form-control" id="user_title" name="user[title]" size="30" type="text" />
            </div>
        </div>
        <div class='col-sm-4'>
            <div class='form-group'>
                <label for="user_firstname">First name</label>
                <input class="form-control" id="user_firstname" name="user[firstname]" required="true" size="30" type="text" />
            </div>
        </div>
        <div class='col-sm-4'>
            <div class='form-group'>
                <label for="user_lastname">Last name</label>
                <input class="form-control" id="user_lastname" name="user[lastname]" required="true" size="30" type="text" />
            </div>
        </div>
    </div>
    <div class='row'>
        <div class='col-sm-12'>
            <div class='form-group'>

                <label for="user_email">Email</label>
                <input class="form-control required email" id="user_email" name="user[email]" required="true" size="30" type="text" />
            </div>
        </div>
    </div>
</fieldset>

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

I see the accepted answer but you dont have to actually push the apk and then run the command on adb shell direct adb install with -t flag actually works

adb install -t "path to apk in ur computer"

attaching a screenshot for reference enter image description here

How to find the default JMX port number?

Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?

By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...

-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications

If you are running you should be able to access any of those system properties to see if they have been set:

if (System.getProperty("com.sun.management.jmxremote") == null) {
    System.out.println("JMX remote is disabled");
} else [
    String portString = System.getProperty("com.sun.management.jmxremote.port");
    if (portString != null) {
        System.out.println("JMX running on port "
            + Integer.parseInt(portString));
    }
}

Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts or if it is set to an incorrect interface address then you can override it with the following:

-Djava.rmi.server.hostname=<IP address>

As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port is actually the RMI port. This tells the client what port the JMX server is running on.

Python DNS module import error

ok to resolve this First install dns for python by cmd using pip install dnspython
(if you use conda first type activate and then you will go in base (in cmd) and then type above code) it will install it in anaconda site package ,copy the location of that site package folder from cmd, and open it . Now copy all dns folders and paste them in python site package folder. it will resolve it .

actually the thing is our code is not able to find the specified package in python\site package bcz it is in anaconda\site package. so you have to COPY IT (not cut).

Java Best Practices to Prevent Cross Site Scripting

Use both. In fact refer a guide like the OWASP XSS Prevention cheat sheet, on the possible cases for usage of output encoding and input validation.

Input validation helps when you cannot rely on output encoding in certain cases. For instance, you're better off validating inputs appearing in URLs rather than encoding the URLs themselves (Apache will not serve a URL that is url-encoded). Or for that matter, validate inputs that appear in JavaScript expressions.

Ultimately, a simple thumb rule will help - if you do not trust user input enough or if you suspect that certain sources can result in XSS attacks despite output encoding, validate it against a whitelist.

Do take a look at the OWASP ESAPI source code on how the output encoders and input validators are written in a security library.

Loop through a comma-separated shell variable

Here is an alternative tr based solution that doesn't use echo, expressed as a one-liner.

for v in $(tr ',' '\n' <<< "$var") ; do something_with "$v" ; done

It feels tidier without echo but that is just my personal preference.

How to show android checkbox at right side?

furthermore from Hazhir imput, for this issue is necessary inject that property in the checkbox xml configuration android:paddingLeft="0dp", this is for avoid the empty space at the checkbox left side.

Java Array Sort descending?

For discussions above, here is an easy example to sort the primitive arrays in descending order.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] nums = { 5, 4, 1, 2, 9, 7, 3, 8, 6, 0 };
        Arrays.sort(nums);

        // reverse the array, just like dumping the array!
        // swap(1st, 1st-last) <= 1st: 0, 1st-last: nums.length - 1
        // swap(2nd, 2nd-last) <= 2nd: i++,  2nd-last: j--
        // swap(3rd, 3rd-last) <= 3rd: i++,  3rd-last: j--
        //
        for (int i = 0, j = nums.length - 1, tmp; i < j; i++, j--) {
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }

        // dump the array (for Java 4/5/6/7/8/9)
        for (int i = 0; i < nums.length; i++) {
            System.out.println("nums[" + i + "] = " + nums[i]);
        }
    }
}

Output:

nums[0] = 9
nums[1] = 8
nums[2] = 7
nums[3] = 6
nums[4] = 5
nums[5] = 4
nums[6] = 3
nums[7] = 2
nums[8] = 1
nums[9] = 0

SQL Server find and replace specific word in all rows of specific column

You can also export the database and then use a program like notepad++ to replace words and then inmport aigain.

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

If your cer file has binary format you must convert it by

openssl x509 -inform DER -in YOUR_CERTIFICATE.cer -out YOUR_CERTIFICATE.crt

How to use andWhere and orWhere in Doctrine?

One thing missing here: if you have a varying number of elements that you want to put together to something like

WHERE [...] AND (field LIKE '%abc%' OR field LIKE '%def%')

and dont want to assemble a DQL-String yourself, you can use the orX mentioned above like this:

$patterns = ['abc', 'def'];
$orStatements = $qb->expr()->orX();
foreach ($patterns as $pattern) {
    $orStatements->add(
        $qb->expr()->like('field', $qb->expr()->literal('%' . $pattern . '%'))
    );
}
$qb->andWhere($orStatements);

Sound effects in JavaScript / HTML5

The selected answer will work in everything except IE. I wrote a tutorial on how to make it work cross browser = http://www.andy-howard.com/how-to-play-sounds-cross-browser-including-ie/index.html

Here is the function I wrote;

function playSomeSounds(soundPath)
 {

 var trident = !!navigator.userAgent.match(/Trident\/7.0/);
 var net = !!navigator.userAgent.match(/.NET4.0E/);
 var IE11 = trident && net
 var IEold = ( navigator.userAgent.match(/MSIE/i) ? true : false );
 if(IE11 || IEold){
 document.all.sound.src = soundPath;
 }
 else
 {
 var snd = new Audio(soundPath); // buffers automatically when created
 snd.play();
 }
 };

You also need to add the following tag to the html page:

<bgsound id="sound">

Finally you can call the function and simply pass through the path here:

playSomeSounds("sounds/welcome.wav");

How to prevent sticky hover effects for buttons on touch devices

What I did so far in my projects was was to revert the :hover changes on touch devices:

.myhoveredclass {
    background-color:green;
}
.myhoveredclass:hover {
    background-color:red;
}
@media screen and (-webkit-min-device-pixel-ratio:0) {
    .myhoveredclass:hover, .myhoveredclass:active, .myhoveredclass:focus {
        background-color:green;
    }
}

All class names and named colors just for demonstration purposes ;-)

How to get the first five character of a String

Use the PadRight function to prevent the string from being too short, grab what you need then trim the spaces from the end all in one statement.

strSomeString = strSomeString.PadRight(50).Substring(0,50).TrimEnd();

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

FAIL - Application at context path /Hello could not be started

check web.xml file maybe servletContextlistener not doing well . in my case i added servletContextlistener and let him an empty and gave me the same error, i tried to delete it from project files but it still in web.xml file .finally i delete it from the web.xml and save the file . run the project and it stated successfully

Permission denied (publickey) when SSH Access to Amazon EC2 instance

I forgot to add the username (ubuntu) when connecting my Ubuntu instance. So I tried this:

ssh -i /path/my-key-pair.pem my-ec2-instance.amazonaws.com

and the correct way was

ssh -i /path/my-key-pair.pem [email protected]

How to use executables from a package installed locally in node_modules?

update: If you're on the recent npm (version >5.2)

You can use:

npx <command>

npx looks for command in .bin directory of your node_modules

old answer:

For Windows

Store the following in a file called npm-exec.bat and add it to your %PATH%

@echo off
set cmd="npm bin"
FOR /F "tokens=*" %%i IN (' %cmd% ') DO SET modules=%%i
"%modules%"\%*

Usage

Then you can use it like npm-exec <command> <arg0> <arg1> ...

For example

To execute wdio installed in local node_modules directory, do:

npm-exec wdio wdio.conf.js

i.e. it will run .\node_modules\.bin\wdio wdio.conf.js

jQuery hasClass() - check for more than one class

Works for me:

 if ( $("element").hasClass( "class1") || $("element").hasClass("class2") ) {

 //do something here

 }

How to get the absolute path to the public_html folder?

Out of curiosity, why don't you just use the url for the said folder?

http://www.mysite.com/images

Assuming that the folder never changes location, that would be the easiest way to do it.

Math constant PI value in C

Just define:

#define M_PI acos(-1.0)

It should give you exact PI number that math functions are working with. So if they change PI value they are working with in tangent or cosine or sine, then your program should be always up-to-dated ;)

How can I use std::maps with user-defined types as key?

By default std::map (and std::set) use operator< to determine sorting. Therefore, you need to define operator< on your class.

Two objects are deemed equivalent if !(a < b) && !(b < a).

If, for some reason, you'd like to use a different comparator, the third template argument of the map can be changed, to std::greater, for example.

Can a normal Class implement multiple interfaces?

public class A implements C,D {...} valid

this is the way to implement multiple inheritence in java

text-align:center won't work with form <label> tag (?)

label is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center but since the label is only as wide as the text you don't notice.

The best thing to do is to apply a specific width to the label that is greater than the width of the content - this will give you the results you want.

Reading string by char till end of line C/C++

A text file does not have \0 at the end of lines. It has \n. \n is a character, not a string, so it must be enclosed in single quotes

if (c == '\n')

How to show SVG file on React Native?

import React from 'react'
import SvgUri from 'react-native-svg-uri';

export default function Splash() {
  return (
    <View style={styles.container}>
      {/* provided the svg file is stored locally */}
      <SvgUri
        width="400"
        height="200"
        source={require('./logo.svg')}
      />
      {/* if the svg is online */}
      <SvgUri
        width="200"
        height="200"
        source={{ uri: 'http://thenewcode.com/assets/images/thumbnails/homer-simpson.svg' }}
      />

      <Text style={styles.logoText}>
        Text
      </Text>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  logoText: {
    fontSize: 50
  }
});

javascript function wait until another function to finish

In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.

Here is an example I have just written to demonstrate how you could do it using deferreds/promises.

Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.

Hope this helps!

$(function(){
    function1().done(function(){
        // function1 is done, we can now call function2
        console.log('function1 is done!');

        function2().done(function(){
            //function2 is done
            console.log('function2 is done!');
        });
    });
});

function function1(){
    var dfrd1 = $.Deferred();
    var dfrd2= $.Deferred();

    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function1 is done!');
        dfrd1.resolve();
    }, 1000);

    setTimeout(function(){
        // doing more async stuff
        console.log('task 2 in function1 is done!');
        dfrd2.resolve();
    }, 750);

    return $.when(dfrd1, dfrd2).done(function(){
        console.log('both tasks in function1 are done');
        // Both asyncs tasks are done
    }).promise();
}

function function2(){
    var dfrd1 = $.Deferred();
    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function2 is done!');
        dfrd1.resolve();
    }, 2000);
    return dfrd1.promise();
}

How to initialize an array in one step using Ruby?

You can use an array literal:

array = [ '1', '2', '3' ]

You can also use a range:

array = ('1'..'3').to_a  # parentheses are required
# or
array = *('1'..'3')      # parentheses not required, but included for clarity

For arrays of whitespace-delimited strings, you can use Percent String syntax:

array = %w[ 1 2 3 ]

You can also pass a block to Array.new to determine what the value for each entry will be:

array = Array.new(3) { |i| (i+1).to_s }

Finally, although it doesn't produce the same array of three strings as the other answers above, note also that you can use enumerators in Ruby 1.8.7+ to create arrays; for example:

array = 1.step(17,3).to_a
#=> [1, 4, 7, 10, 13, 16]

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

Multiple contexts with the same path error running web service in Eclipse using Tomcat

  1. In your project's Properties, choose "Web Project Settings".
  2. Change "Context root".
  3. Clean your server
  4. now you can restart your server

HintPath vs ReferencePath in Visual Studio

Although this is an old document, but it helped me resolve the problem of 'HintPath' being ignored on another machine. It was because the referenced DLL needed to be in source control as well:

https://msdn.microsoft.com/en-us/library/ee817675.aspx#tdlg_ch4_includeoutersystemassemblieswithprojects

Excerpt:

To include and then reference an outer-system assembly
1. In Solution Explorer, right-click the project that needs to reference the assembly,,and then click Add Existing Item.
2. Browse to the assembly, and then click OK. The assembly is then copied into the project folder and automatically added to VSS (assuming the project is already under source control).
3. Use the Browse button in the Add Reference dialog box to set a file reference to assembly in the project folder.

Node.js: get path from the request

var http = require('http');
var url  = require('url');
var fs   = require('fs');

var neededstats = [];

http.createServer(function(req, res) {
    if (req.url == '/index.html' || req.url == '/') {
        fs.readFile('./index.html', function(err, data) {
            res.end(data);
        });
    } else {
        var p = __dirname + '/' + req.params.filepath;
        fs.stat(p, function(err, stats) {
            if (err) {
                throw err;
            }
            neededstats.push(stats.mtime);
            neededstats.push(stats.size);
            res.send(neededstats);
        });
    }
}).listen(8080, '0.0.0.0');
console.log('Server running.');

I have not tested your code but other things works

If you want to get the path info from request url

 var url_parts = url.parse(req.url);
 console.log(url_parts);
 console.log(url_parts.pathname);

1.If you are getting the URL parameters still not able to read the file just correct your file path in my example. If you place index.html in same directory as server code it would work...

2.if you have big folder structure that you want to host using node then I would advise you to use some framework like expressjs

If you want raw solution to file path

var http = require("http");
var url = require("url");

function start() {
function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}

http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}

exports.start = start;

source : http://www.nodebeginner.org/

How do you read from stdin?

Here's from Learning Python:

import sys
data = sys.stdin.readlines()
print "Counted", len(data), "lines."

On Unix, you could test it by doing something like:

% cat countlines.py | python countlines.py 
Counted 3 lines.

On Windows or DOS, you'd do:

C:\> type countlines.py | python countlines.py 
Counted 3 lines.

Is there a list of screen resolutions for all Android based phones and tablets?

hdpi 480x800 px Samsung S2

xhdpi 720x1280 px - Nexus 4 phone - 4.7,4.8 inches Samsung Galaxy S3 Motorola Moto G

xxhdpi 1080x1920 px - Nexus 5 phone - 4.95 inches Samsung Galaxy S4 Samsung Galaxy S5 Samsung Galaxy Note 3 - 5.7 inches LG G2 HTC One M8 HTC One M9 Sony Xperia Z1
Sony Xperia Z2 Sony Xperia Z3 Sony Xperia Z3+

xxxhdpi 1440x2560 px - Nexus 6 phablet - 6 inches Samsung S6 Samsung S6 Edge Samsung Galaxy Note 4 - 5.7 inches LG G3
LG G4

xxhdpi 1920×1200 px - Nexus 7 tablet - 7 inches Sony Z3 Tablet Compact LG G Pad 8.3 - 8.3 inches Sony Xperia Z2 Tablet - 10.1 inches

xxxhdpi 2560×1600 px - Nexus 10 tablet - 10.1 inches ~Google Nexus 9 Sony Xperia Z4 tablet Samsung Galaxy Note Pro 12.2 Samsung Galaxy Note 10.1 Samsung Galaxy Tab S 10.5 Dell Venue 8 7840

Difference between string and text in rails?

The accepted answer is awesome, it properly explains the difference between string vs text (mostly the limit size in the database, but there are a few other gotchas), but I wanted to point out a small issue that got me through it as that answer didn't completely do it for me.

The max size :limit => 1 to 4294967296 didn't work exactly as put, I needed to go -1 from that max size. I'm storing large JSON blobs and they might be crazy huge sometimes.

Here's my migration with the larger value in place with the value MySQL doesn't complain about.

Note the 5 at the end of the limit instead of 6

class ChangeUserSyncRecordDetailsToText < ActiveRecord::Migration[5.1]
  def up
    change_column :user_sync_records, :details, :text, :limit => 4294967295
  end

  def down
    change_column :user_sync_records, :details, :string, :limit => 1000
  end
end

Global Variable from a different file Python

Importing file2 in file1.py makes the global (i.e., module level) names bound in file2 available to following code in file1 -- the only such name is SomeClass. It does not do the reverse: names defined in file1 are not made available to code in file2 when file1 imports file2. This would be the case even if you imported the right way (import file2, as @nate correctly recommends) rather than in the horrible, horrible way you're doing it (if everybody under the Sun forgot the very existence of the construct from ... import *, life would be so much better for everybody).

Apparently you want to make global names defined in file1 available to code in file2 and vice versa. This is known as a "cyclical dependency" and is a terrible idea (in Python, or anywhere else for that matter).

So, rather than showing you the incredibly fragile, often unmaintainable hacks to achieve (some semblance of) a cyclical dependency in Python, I'd much rather discuss the many excellent way in which you can avoid such terrible structure.

For example, you could put global names that need to be available to both modules in a third module (e.g. file3.py, to continue your naming streak;-) and import that third module into each of the other two (import file3 in both file1 and file2, and then use file3.foo etc, that is, qualified names, for the purpose of accessing or setting those global names from either or both of the other modules, not barenames).

Of course, more and more specific help could be offered if you clarified (by editing your Q) exactly why you think you need a cyclical dependency (just one easy prediction: no matter what makes you think you need a cyclical dependency, you're wrong;-).

Combine or merge JSON on node.js without jQuery

There is an easy way of doing it in Node.js

var object1 = {name: "John"};
var object2 = {location: "San Jose"};

To combine/extend this we can use ... operator in ECMA6

_x000D_
_x000D_
var object1 = {name: "John"};_x000D_
var object2 = {location: "San Jose"};_x000D_
_x000D_
var result = {_x000D_
  ...object1,_x000D_
  ...object2_x000D_
}_x000D_
_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

MySQL my.ini location

In my case, the folder ProgramData was hidden by default on windows 7, so I was unable to find my.ini file.

After selecting show hidden files and folders option, I was able to find the my.ini file at the location: C:\ProgramData\MySQL\MySQL Server 5.6.

Display hidden files and folders on windows 7:

  1. Right-click the Windows Logo button and choose Open Windows Explorer.

  2. Click Organize and choose Folder and Search Options.

  3. Click the View tab, select Show hidden files and folders and then clear the checkbox for Hide protected system operating files.

  4. Click Yes on the warning and then click OK.

How can I get stock quotes using Google Finance API?

In order to find chart data using the financial data API of Google, one must simply go to Google as if looking for a search term, type finance into the search engine, and a link to Google finance will appear. Once at the Google finance search engine, type the ticker name into the financial data API engine and the result will be displayed. However, it should be noted that all Google finance charts are delayed by 15 minutes, and at most can be used for a better understanding of the ticker's past history, rather than current price.

A solution to the delayed chart information is to obtain a real-time financial data API. An example of one would be the barchartondemand interface that has real-time quote information, along with other detailed features that make it simpler to find the exact chart you're looking for. With fully customizable features, and specific programming tools for the precise trading information you need, barchartondemand's tools outdo Google finance by a wide margin.

How can I add comments in MySQL?

Several ways:

# Comment
-- Comment
/* Comment */

Remember to put the space after --.

See the documentation.

What is ".NET Core"?

The current documentation has a good explanation of what .NET Core is, areas to use and so on. The following characteristics best define .NET Core:

Flexible deployment: Can be included in your app or installed side-by-side user- or machine-wide.

Cross-platform: Runs on Windows, macOS and Linux; can be ported to other OSes. The supported operating systems (OSes), CPUs and application scenarios will grow over time, provided by Microsoft, other companies, and individuals.

Command-line tools: All product scenarios can be exercised at the command-line.

Compatible: .NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library.

Open source: The .NET Core platform is open source, using MIT and Apache 2 licenses. Documentation is licensed under CC-BY. .NET Core is a .NET Foundation project.

Supported by Microsoft: .NET Core is supported by Microsoft, per .NET Core Support

And here is what .NET Core includes:

A .NET runtime, which provides a type system, assembly loading, a garbage collector, native interoperability and other basic services.

A set of framework libraries, which provide primitive data types, application composition types and fundamental utilities.

A set of SDK tools and language compilers that enable the base developer experience, available in the .NET Core SDK.

The 'dotnet' application host, which is used to launch .NET Core applications. It selects the runtime and hosts the runtime, provides an assembly loading policy and launches the app. The same host is also used to launch SDK tools in much the same way.

Make a float only show two decimal places

You can also try using NSNumberFormatter:

NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = @"0.##";
NSString* s = [nf stringFromNumber: [NSNumber numberWithFloat: myFloat]];

You may need to also set the negative format, but I think it's smart enough to figure it out.

How do I get SUM function in MySQL to return '0' if no values are found?

Use COALESCE to avoid that outcome.

SELECT COALESCE(SUM(column),0)
FROM   table
WHERE  ...

To see it in action, please see this sql fiddle: http://www.sqlfiddle.com/#!2/d1542/3/0


More Information:

Given three tables (one with all numbers, one with all nulls, and one with a mixture):

SQL Fiddle

MySQL 5.5.32 Schema Setup:

CREATE TABLE foo
(
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  val   INT
);

INSERT INTO foo (val) VALUES
(null),(1),(null),(2),(null),(3),(null),(4),(null),(5),(null),(6),(null);

CREATE TABLE bar
(
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  val   INT
);

INSERT INTO bar (val) VALUES
(1),(2),(3),(4),(5),(6);

CREATE TABLE baz
(
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  val   INT
);

INSERT INTO baz (val) VALUES
(null),(null),(null),(null),(null),(null);

Query 1:

SELECT  'foo'                   as table_name,
        'mixed null/non-null'   as description,
        21                      as expected_sum,
        COALESCE(SUM(val), 0)   as actual_sum
FROM    foo
UNION ALL

SELECT  'bar'                   as table_name,
        'all non-null'          as description,
        21                      as expected_sum,
        COALESCE(SUM(val), 0)   as actual_sum
FROM    bar
UNION ALL

SELECT  'baz'                   as table_name,
        'all null'              as description,
        0                       as expected_sum,
        COALESCE(SUM(val), 0)   as actual_sum
FROM    baz

Results:

| TABLE_NAME |         DESCRIPTION | EXPECTED_SUM | ACTUAL_SUM |
|------------|---------------------|--------------|------------|
|        foo | mixed null/non-null |           21 |         21 |
|        bar |        all non-null |           21 |         21 |
|        baz |            all null |            0 |          0 |

How to get Git to clone into current directory

Do

git clone https://[email protected]/user/projectname.git .

Directory must be empty

Dynamic loading of images in WPF

Here is the extension method to load an image from URI:

public static BitmapImage GetBitmapImage(
    this Uri imageAbsolutePath,
    BitmapCacheOption bitmapCacheOption = BitmapCacheOption.Default)
{
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.CacheOption = bitmapCacheOption;
    image.UriSource = imageAbsolutePath;
    image.EndInit();

    return image;
}

Sample of use:

Uri _imageUri = new Uri(imageAbsolutePath);
ImageXamlElement.Source = _imageUri.GetBitmapImage(BitmapCacheOption.OnLoad);

Simple as that!

Getting Excel to refresh data on sheet from within VBA

This should do the trick...

'recalculate all open workbooks
Application.Calculate

'recalculate a specific worksheet
Worksheets(1).Calculate

' recalculate a specific range
Worksheets(1).Columns(1).Calculate

CSS container div not getting height

I ran into this same issue, and I have come up with four total viable solutions:

  1. Make the container display: flex; (this is my favorite solution)
  2. Add overflow: auto; or overflow: hidden; to the container
  3. Add the following CSS for the container:
.c:after {
    clear: both;
    content: "";
    display: block;
}
  1. Make the following the last item inside the container:
<div style="clear: both;"></div>

How do I accomplish an if/else in mustache.js?

This is something you solve in the "controller", which is the point of logicless templating.

// some function that retreived data through ajax
function( view ){

   if ( !view.avatar ) {
      // DEFAULTS can be a global settings object you define elsewhere
      // so that you don't have to maintain these values all over the place
      // in your code.
      view.avatar = DEFAULTS.AVATAR;
   }

   // do template stuff here

}

This is actually a LOT better then maintaining image url's or other media that might or might not change in your templates, but takes some getting used to. The point is to unlearn template tunnel vision, an avatar img url is bound to be used in other templates, are you going to maintain that url on X templates or a single DEFAULTS settings object? ;)

Another option is to do the following:

// augment view
view.hasAvatar = !!view.avatar;
view.noAvatar = !view.avatar;

And in the template:

{{#hasAvatar}}
    SHOW AVATAR
{{/hasAvatar}}
{{#noAvatar}}
    SHOW DEFAULT
{{/noAvatar}}

But that's going against the whole meaning of logicless templating. If that's what you want to do, you want logical templating and you should not use Mustache, though do give it yourself a fair chance of learning this concept ;)

Android ADB device offline, can't issue commands

I hit the same issue on a Nexus 7 running 4.2.2 OTA update. I'm almost certain I had an ADB connection over USB and Wi-Fi after the update until it just stopped working. To fix, I updated my SDK using:

android update sdk --no-ui

Now my development tools are:

  • SDK rev 16.0.2
  • SDK tools rev 21.1
  • SDK API 17, rev 2

Adding rows to dataset

DataSet myDataset = new DataSet();

DataTable customers = myDataset.Tables.Add("Customers");

customers.Columns.Add("Name");
customers.Columns.Add("Age");

customers.Rows.Add("Chris", "25");

//Get data
DataTable myCustomers = myDataset.Tables["Customers"];
DataRow currentRow = null;
for (int i = 0; i < myCustomers.Rows.Count; i++)
{
    currentRow = myCustomers.Rows[i];
    listBox1.Items.Add(string.Format("{0} is {1} YEARS OLD", currentRow["Name"], currentRow["Age"]));    
}

How to add an object to an ArrayList in Java

Try this one:

Data objt = new Data(name, address, contact);
Contacts.add(objt);

How to write a cursor inside a stored procedure in SQL Server 2008

Try the following snippet. You can call the the below stored procedure from your application, so that NoOfUses in the coupon table will be updated.

CREATE PROCEDURE [dbo].[sp_UpdateCouponCount]
AS

Declare     @couponCount int,
            @CouponName nvarchar(50),
            @couponIdFromQuery int


Declare curP cursor For

  select COUNT(*) as totalcount , Name as name,couponuse.couponid  as couponid from Coupon as coupon 
  join CouponUse as couponuse on coupon.id = couponuse.couponid
  where couponuse.id=@cuponId
  group by couponuse.couponid , coupon.Name

OPEN curP 
Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery

While @@Fetch_Status = 0 Begin

    print @couponCount
    print @CouponName

    update Coupon SET NoofUses=@couponCount
    where couponuse.id=@couponIdFromQuery


Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery

End -- End of Fetch

Close curP
Deallocate curP

Hope this helps!

Why doesn't Console.Writeline, Console.Write work in Visual Studio Express?

using System.Diagnostics;


Trace.WriteLine("This line will show on Output window"); 
Trace.Flush();

This works on Microsoft Team Explorer for Visual Studio 2013

Refer to microsoft.com

Check if a Bash array contains a value

If you want to do a quick and dirty test to see if it's worth iterating over the whole array to get a precise match, Bash can treat arrays like scalars. Test for a match in the scalar, if none then skipping the loop saves time. Obviously you can get false positives.

array=(word "two words" words)
if [[ ${array[@]} =~ words ]]
then
    echo "Checking"
    for element in "${array[@]}"
    do
        if [[ $element == "words" ]]
        then
            echo "Match"
        fi
    done
fi

This will output "Checking" and "Match". With array=(word "two words" something) it will only output "Checking". With array=(word "two widgets" something) there will be no output.

Rails migration for change column

I think this should work.

change_column :table_name, :column_name, :date

What is the difference between Nexus and Maven?

Whatever I understood from my learning and what I think it is is here. I am Quoting some part from a book i learnt this things. Nexus Repository Manager and Nexus Repository Manager OSS started as a repository manager supporting the Maven repository format. While it supports many other repository formats now, the Maven repository format is still the most common and well supported format for build and provisioning tools running on the JVM and beyond. This chapter shows example configurations for using the repository manager with Apache Maven and a number of other tools. The setups take advantage of merging many repositories and exposing them via a repository group. Setting this up is documented in the chapter in addition to the configuration used by specific tools.

Details

Angular: date filter adds timezone, how to output UTC?

The 'Z' is what adds the timezone info. As for output UTC, that seems to be the subject of some confusion -- people seem to gravitate toward moment.js.

Borrowing from this answer, you could do something like this without moment.js:

controller

var app1 = angular.module('app1',[]);

app1.controller('ctrl',['$scope',function($scope){

  var toUTCDate = function(date){
    var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
    return _utc;
  };

  var millisToUTCDate = function(millis){
    return toUTCDate(new Date(millis));
  };

    $scope.toUTCDate = toUTCDate;
    $scope.millisToUTCDate = millisToUTCDate;

  }]);

template

<html ng-app="app1">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="ctrl">
      <div>
      utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
      </div>
      <div>
      local {{1400167800 | date:'dd-M-yyyy H:mm'}}
      </div>
    </div>
  </body>

</html>

here's plunker to play with it

See also this and this.

Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.

Using Jquery AJAX function with datatype HTML

Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.

Ajax call:

$.ajax({
  type : 'POST',
  url : 'post.php',
  dataType : 'html',
  data: {
      email : $('#email').val()
  },
  success : function(data){
      $('#waiting').hide(500);
      $('#message').removeClass().addClass((data == '') ? 'error' : 'success')
     .html(data).show(500);
      if (data == '') {
          $('#message').html("Format your email correcly");
          $('#demoForm').show(500);
      }
  },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
      $('#waiting').hide(500);
      $('#message').removeClass().addClass('error')
      .text('There was an error.').show(500);
      $('#demoForm').show(500);
  }

});

post.php

<?php
sleep(1);

function processEmail($email) {
    if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
        // your logic here (ex: add into database)
        return true;
    }
    return false;
}

if (processEmail($_POST['email'])) {
    echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}

Jmeter - Run .jmx file through command line and get the summary report in a excel

JMeter can be launched in non-GUI mode as follows:

jmeter -n -t /path/to/your/test.jmx -l /path/to/results/file.jtl

You can set what would you like to see in result jtl file via playing with JMeter Properties.

See jmeter.properties file under /bin folder of your JMeter installation and look for those starting with

jmeter.save.saveservice.

Defaults are listed below:

#jmeter.save.saveservice.output_format=csv
#jmeter.save.saveservice.assertion_results_failure_message=false
#jmeter.save.saveservice.assertion_results=none
#jmeter.save.saveservice.data_type=true
#jmeter.save.saveservice.label=true
#jmeter.save.saveservice.response_code=true
#jmeter.save.saveservice.response_data=false
#jmeter.save.saveservice.response_data.on_error=false
#jmeter.save.saveservice.response_message=true
#jmeter.save.saveservice.successful=true
#jmeter.save.saveservice.thread_name=true
#jmeter.save.saveservice.time=true
#jmeter.save.saveservice.subresults=true
#jmeter.save.saveservice.assertions=true
#jmeter.save.saveservice.latency=true
#jmeter.save.saveservice.samplerData=false
#jmeter.save.saveservice.responseHeaders=false
#jmeter.save.saveservice.requestHeaders=false
#jmeter.save.saveservice.encoding=false
#jmeter.save.saveservice.bytes=true
#jmeter.save.saveservice.url=false
#jmeter.save.saveservice.filename=false
#jmeter.save.saveservice.hostname=false
#jmeter.save.saveservice.thread_counts=false
#jmeter.save.saveservice.sample_count=false
#jmeter.save.saveservice.idle_time=false
#jmeter.save.saveservice.timestamp_format=ms
#jmeter.save.saveservice.timestamp_format=yyyy/MM/dd HH:mm:ss.SSS
#jmeter.save.saveservice.default_delimiter=,
#jmeter.save.saveservice.default_delimiter=\t
#jmeter.save.saveservice.print_field_names=false
#jmeter.save.saveservice.xml_pi=<?xml-stylesheet type="text/xsl" href="../extras/jmeter-results-detail-report_21.xsl"?>
#jmeter.save.saveservice.base_prefix=~/
#jmeter.save.saveservice.autoflush=false

Uncomment the one you are interested in and set it's value to change the default. Another option is override property in user.properties file or provide it as a command-line argument using -J key as follows:

jmeter -Jjmeter.save.saveservice.print_field_names=true -n /path/to/your/test.jmx -l /path/to/results/file.jtl

See Apache JMeter Properties Customization Guide for more details on what can be done using JMeter Properties.

Checking oracle sid and database name

I presume SELECT user FROM dual; should give you the current user

and SELECT sys_context('userenv','instance_name') FROM dual; the name of the instance

I believe you can get SID as SELECT sys_context('USERENV', 'SID') FROM DUAL;

mkdir -p functionality in Python

import os
import tempfile

path = tempfile.mktemp(dir=path)
os.makedirs(path)
os.rmdir(path)

C# Set collection?

I know this is an old thread, but I was running into the same problem and found HashSet to be very unreliable because given the same seed, GetHashCode() returned different codes. So, I thought, why not just use a List and hide the add method like this

public class UniqueList<T> : List<T>
{
    public new void Add(T obj)
    {
        if(!Contains(obj))
        {
            base.Add(obj);
        }
    }
}

Because List uses the Equals method solely to determine equality, you can define the Equals method on your T type to make sure you get the desired results.

How to override toString() properly in Java?

If you're interested in Unit-Tests, then you can declare a public "ToStringTemplate", and then you can unit test your toString. Even if you don't unit-test it, I think its "cleaner" and uses String.format.

public class Kid {

    public static final String ToStringTemplate = "KidName='%1s', Height='%2s', GregCalendar='%3s'";

    private String kidName;
    private double height;
    private GregorianCalendar gregCalendar;

    public String getKidName() {
        return kidName;
    }

    public void setKidName(String kidName) {
        this.kidName = kidName;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public GregorianCalendar getGregCalendar() {
        return gregCalendar;
    }

    public void setGregCalendar(GregorianCalendar gregCalendar) {
        this.gregCalendar = gregCalendar;
    }

    public String toString() { 
        return String.format(ToStringTemplate, this.getKidName(), this.getHeight(), this.getGregCalendar());
    } 
}

Now you can unit test by create the Kid, setting the properties, and doing your own string.format on the ToStringTemplate and comparing.

making ToStringTemplate static-final means "ONE VERSION" of the truth, rather than having a "copy" of the template in the unit-test.

Merge PDF files with PHP

I created an abstraction layer over FPDI (might accommodate other engines). I published it as a Symfony2 bundle depending on a library, and as the library itself.

The bundle

The Library

usage:

public function handlePdfChanges(Document $document, array $formRawData)
{
    $oldPath = $document->getUploadRootDir($this->kernel) . $document->getOldPath();
    $newTmpPath = $document->getFile()->getRealPath();

    switch ($formRawData['insertOptions']['insertPosition']) {
        case PdfInsertType::POSITION_BEGINNING:
            // prepend 
            $newPdf = $this->pdfManager->insert($oldPath, $newTmpPath);
            break;
        case PdfInsertType::POSITION_END: 
            // Append
            $newPdf = $this->pdfManager->append($oldPath, $newTmpPath);
            break;
        case PdfInsertType::POSITION_PAGE: 
            // insert at page n: PdfA={p1; p2; p3}, PdfB={pA; pB; pC} 
            // insert(PdfA, PdfB, 2) will render {p1; pA; pB; pC; p2; p3} 
            $newPdf = $this->pdfManager->insert(
                    $oldPath, $newTmpPath, $formRawData['insertOptions']['pageNumber']
                );
            break;
        case PdfInsertType::POSITION_REPLACE: 
            // does nothing. overrides old file.
            return;
            break;
    }
    $pageCount = $newPdf->getPageCount();
    $newPdf->renderFile($mergedPdfPath = "$newTmpPath.merged");
    $document->setFile(new File($mergedPdfPath, true));
    return $pageCount;
}

How do I resolve a path relative to an ASP.NET MVC 4 application root?

To get the absolute path use this:

String path = HttpContext.Current.Server.MapPath("~/Data/data.html");

EDIT:

To get the Controller's Context remove .Current from the above line. By using HttpContext by itself it's easier to Test because it's based on the Controller's Context therefore more localized.

I realize now that I dislike how Server.MapPath works (internally eventually calls HostingEnvironment.MapPath) So I now recommend to always use HostingEnvironment.MapPath because its static and not dependent on the context unless of course you want that...

notifyDataSetChanged example

You can use the runOnUiThread() method as follows. If you're not using a ListActivity, just adapt the code to get a reference to your ArrayAdapter.

final ArrayAdapter adapter = ((ArrayAdapter)getListAdapter());
runOnUiThread(new Runnable() {
    public void run() {
        adapter.notifyDataSetChanged();
    }
});

How do I get a computer's name and IP address using VB.NET?

Thanks Shuwaiee

I made a slight change though as using it in a Private Sub already.

Dim GetIPAddress()

Dim strHostName As String

Dim strIPAddress As String

strHostName = System.Net.Dns.GetHostName()

strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString()

MessageBox.Show("Host Name: " & strHostName & vbCrLf & "IP Address: " & strIPAddress)

But also made a change to the way the details are displayed so that they can show on seperate lines using & vbCrLf &

MessageBox.Show("Host Name: " & strHostName & vbCrLf & "IP Address: " & strIPAddress)

Hope this helps someone.

Difference between declaring variables before or in loop?

As a general rule, I declare my variables in the inner-most possible scope. So, if you're not using intermediateResult outside of the loop, then I'd go with B.

How to convert View Model into JSON object in ASP.NET MVC?

<htmltag id=’elementId’ data-ZZZZ’=’@Html.Raw(Json.Encode(Model))’ />

Refer https://highspeedlowdrag.wordpress.com/2014/08/23/mvc-data-to-jquery-data/

I did below and it works like charm.

<input id="hdnElement" class="hdnElement" type="hidden" value='@Html.Raw(Json.Encode(Model))'>

How to import csv file in PHP?

PHP > 5.3 use fgetcsv() or str_getcsv(). Couldn't be simpler.

Twitter Bootstrap 3: How to center a block

You have to use style="width:value" with center block class

android: how to change layout on button click?

  Button btnDownload = (Button) findViewById(R.id.DownloadView);
  Button btnApp = (Button) findViewById(R.id.AppView);

  btnDownload.setOnClickListener(handler);
  btnApp.setOnClickListener(handler);

  View.OnClickListener handler = new View.OnClickListener(){

  public void onClick(View v) {

    if(v==btnDownload){ 
            // doStuff
            Intent intentMain = new Intent(CurrentActivity.this , 
                                           SecondActivity.class);
            CurrentActivity.this.startActivity(intentMain);
            Log.i("Content "," Main layout ");
    }

    if(v==btnApp){ 
            // doStuff
            Intent intentApp = new Intent(CurrentActivity.this, 
                                          ThirdActivity.class);

            CurrentActivity.this.startActivity(intentApp);

            Log.i("Content "," App layout ");

    }
   }
  };

Note : and then you should declare all your activities in the manifest .xml file like this :

<activity android:name=".SecondActivity" ></activity>
<activity android:name=".ThirdActivity" ></activity>

EDIT : update this part of Code :) :

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);// Add THIS LINE

    setContentView(R.layout.app);

    TextView tv = (TextView) this.findViewById(R.id.thetext);
    tv.setText("App View yo!?\n");
}

NB : check this (Broken link) Tutorial About How To Switch Between Activities.

getDate with Jquery Datepicker

I think you would want to add an 'onSelect' event handler to the initialization of your datepicker so your code gets triggered when the user selects a date. Try it out on jsFiddle

$(document).ready(function(){
    // Datepicker
    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        inline: true,
        minDate: new Date(2010, 1 - 1, 1),
        maxDate:new Date(2010, 12 - 1, 31),
        altField: '#datepicker_value',
        onSelect: function(){
            var day1 = $("#datepicker").datepicker('getDate').getDate();                 
            var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1;             
            var year1 = $("#datepicker").datepicker('getDate').getFullYear();
            var fullDate = year1 + "-" + month1 + "-" + day1;
            var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
            $('#page_output').html(str_output);
        }
    });
});