Programs & Examples On #Hoard

Hoard is a scalable memory allocator, which efficiently balance various orthogonal parameters, like Latency, scalability, false cache line sharing etc, which a memory allocator should take care of.

Grep characters before and after match?

You can use regexp grep for finding + second grep for highlight

echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}' | grep string

23_string_and

enter image description here

What is a Subclass

Think of a class as a description of the members of a set of things. All of the members of that set have common characteristics (methods and properties).

A subclass is a class that describes the members of a particular subset of the original set. They share many of characteristics of the main class, but may have properties or methods that are unique to members of the subclass.

You declare that one class is subclass of another via the "extends" keyword in Java.

public class B extends A
{
...
}

B is a subclass of A. Instances of class B will automatically exhibit many of the same properties as instances of class A.

This is the main concept of inheritance in Object-Oriented programming.

Using node.js as a simple web server

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    // change the to 'text/plain' to 'text/html' it will work as your index page
    res.end(index);
}).listen(9615);

I think you where searching for this. In your index.html, simply fill it with normal html code - whatever you want to render on it, like:

<html>
    <h1>Hello world</h1>
</html>

How to check if an app is installed from a web-page on an iPhone?

The date solution is much better than others, I had to increment the time on 50 like that this is a Tweeter example:

//on click or your event handler..
var twMessage = "Your Message to share";
var now = new Date().valueOf();
setTimeout(function () {
   if (new Date().valueOf() - now > 100) return;
   var twitterUrl = "https://twitter.com/share?text="+twMessage;
   window.open(twitterUrl, '_blank');
}, 50);
window.location = "twitter://post?message="+twMessage;

the only problem on Mobile IOS Safari is when you don't have the app installed on device, and so Safari show an alert that autodismiss when the new url is opened, anyway is a good solution for now!

Cast Int to enum in Java

I cache the values and create a simple static access method:

public static enum EnumAttributeType {
    ENUM_1,
    ENUM_2;
    private static EnumAttributeType[] values = null;
    public static EnumAttributeType fromInt(int i) {
        if(EnumAttributeType.values == null) {
            EnumAttributeType.values = EnumAttributeType.values();
        }
        return EnumAttributeType.values[i];
    }
}

Python unexpected EOF while parsing

I'm trying to answer in general, not related to this question, this error generally occurs when you break a syntax in half and forget the other half. Like in my case it was:

try :
 ....

since python was searching for a

except Exception as e:
 ....

but it encountered an EOF (End Of File), hence the error. See if you can find any incomplete syntax in your code.

Playing .mp3 and .wav in Java?

Use this library: import sun.audio.*;

public void Sound(String Path){
    try{
        InputStream in = new FileInputStream(new File(Path));
        AudioStream audios = new AudioStream(in);
        AudioPlayer.player.start(audios);
    }
    catch(Exception e){}
}

Why and when to use angular.copy? (Deep Copy)

Use angular.copy when assigning value of object or array to another variable and that object value should not be changed.

Without deep copy or using angular.copy, changing value of property or adding any new property update all object referencing that same object.

_x000D_
_x000D_
var app = angular.module('copyExample', []);_x000D_
app.controller('ExampleController', ['$scope',_x000D_
  function($scope) {_x000D_
    $scope.printToConsole = function() {_x000D_
      $scope.main = {_x000D_
        first: 'first',_x000D_
        second: 'second'_x000D_
      };_x000D_
_x000D_
      $scope.child = angular.copy($scope.main);_x000D_
      console.log('Main object :');_x000D_
      console.log($scope.main);_x000D_
      console.log('Child object with angular.copy :');_x000D_
      console.log($scope.child);_x000D_
_x000D_
      $scope.child.first = 'last';_x000D_
      console.log('New Child object :')_x000D_
      console.log($scope.child);_x000D_
      console.log('Main object after child change and using angular.copy :');_x000D_
      console.log($scope.main);_x000D_
      console.log('Assing main object without copy and updating child');_x000D_
_x000D_
      $scope.child = $scope.main;_x000D_
      $scope.child.first = 'last';_x000D_
      console.log('Main object after update:');_x000D_
      console.log($scope.main);_x000D_
      console.log('Child object after update:');_x000D_
      console.log($scope.child);_x000D_
    }_x000D_
  }_x000D_
]);_x000D_
_x000D_
// Basic object assigning example_x000D_
_x000D_
var main = {_x000D_
  first: 'first',_x000D_
  second: 'second'_x000D_
};_x000D_
var one = main; // same as main_x000D_
var two = main; // same as main_x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same_x000D_
_x000D_
two = {_x000D_
  three: 'three'_x000D_
}; // two changed but one and main remains same_x000D_
console.log('main :' + JSON.stringify(main)); // one and main are same_x000D_
console.log('one :' + JSON.stringify(one)); // one and main are same_x000D_
console.log('two :' + JSON.stringify(two)); // two is changed_x000D_
_x000D_
two = main; // same as main_x000D_
_x000D_
two.first = 'last'; // change value of object's property so changed value of all object property _x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same with new value_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same with new value_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same with new value
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="copyExample" ng-controller="ExampleController">_x000D_
  <button ng-click='printToConsole()'>Explain</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get index using LINQ?

An IEnumerable is not an ordered set.
Although most IEnumerables are ordered, some (such as Dictionary or HashSet) are not.

Therefore, LINQ does not have an IndexOf method.

However, you can write one yourself:

///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
    if (items == null) throw new ArgumentNullException("items");
    if (predicate == null) throw new ArgumentNullException("predicate");

    int retVal = 0;
    foreach (var item in items) {
        if (predicate(item)) return retVal;
        retVal++;
    }
    return -1;
}
///<summary>Finds the index of the first occurrence of an item in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="item">The item to find.</param>
///<returns>The index of the first matching item, or -1 if the item was not found.</returns>
public static int IndexOf<T>(this IEnumerable<T> items, T item) { return items.FindIndex(i => EqualityComparer<T>.Default.Equals(item, i)); }

How can I write maven build to add resources to classpath?

A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.

For instance, place your property file in a new folder src/main/config, and add the following to your pom:

 <build>
    <resources>
        <resource>
            <directory>src/main/config</directory>
        </resource>
    </resources>
 </build>

From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>my-config.properties</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>

so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).

How to use AND in IF Statement

Brief syntax lesson

Cells(Row, Column) identifies a cell. Row must be an integer between 1 and the maximum for version of Excel you are using. Column must be a identifier (for example: "A", "IV", "XFD") or a number (for example: 1, 256, 16384)

.Cells(Row, Column) identifies a cell within a sheet identified in a earlier With statement:

With ActiveSheet
  :
  .Cells(Row,Column)
  :
End With

If you omit the dot, Cells(Row,Column) is within the active worksheet. So wsh = ActiveWorkbook wsh.Range is not strictly necessary. However, I always use a With statement so I do not wonder which sheet I meant when I return to my code in six months time. So, I would write:

With ActiveSheet
  :
  .Range.  
  :
End With

Actually, I would not write the above unless I really did want the code to work on the active sheet. What if the user has the wrong sheet active when they started the macro. I would write:

With Sheets("xxxx")
  :
  .Range.  
  :
End With

because my code only works on sheet xxxx.

Cells(Row,Column) identifies a cell. Cells(Row,Column).xxxx identifies a property of the cell. Value is a property. Value is the default property so you can usually omit it and the compiler will know what you mean. But in certain situations the compiler can be confused so the advice to include the .Value is good.

Cells(Row,Column) like "*Miami*" will give True if the cell is "Miami", "South Miami", "Miami, North" or anything similar.

Cells(Row,Column).Value = "Miami" will give True if the cell is exactly equal to "Miami". "MIAMI" for example will give False. If you want to accept MIAMI, use the lower case function:

Lcase(Cells(Row,Column).Value) = "miami"  

My suggestions

Your sample code keeps changing as you try different suggestions which I find confusing. You were using Cells(Row,Column) <> "Miami" when I started typing this.

Use

If Cells(i, "A").Value like "*Miami*" And Cells(i, "D").Value like "*Florida*" Then
  Cells(i, "C").Value = "BA"

if you want to accept, for example, "South Miami" and "Miami, North".

Use

If Cells(i, "A").Value = "Miami" And Cells(i, "D").Value like "Florida" Then
  Cells(i, "C").Value = "BA"

if you want to accept, exactly, "Miami" and "Florida".

Use

If Lcase(Cells(i, "A").Value) = "miami" And _
   Lcase(Cells(i, "D").Value) = "florida" Then
  Cells(i, "C").Value = "BA"

if you don't care about case.

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

Call another rest api from my server in Spring-Boot

Instead of String you are trying to get custom POJO object details as output by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,

In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }
}

Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,

@Autowired
private RestTemplate restTemplate;

Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.

ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
    URL, 
    HttpMethod.GET, 
    null, 
    new ParameterizedTypeReference<List<POJO>>() {
    });
List<POJO> pojoObjList = responseEntity.getBody();

Happy Coding :)

How to randomly select rows in SQL?

There is a nice Microsoft SQL Server 2005 specific solution here. Deals with the problem where you are working with a large result set (not the question I know).

Selecting Rows Randomly from a Large Table http://msdn.microsoft.com/en-us/library/cc441928.aspx

Django - Static file not found

Another error can be not having your app listed in the INSTALLED_APPS listing like:

INSTALLED_APPS = [
    # ...
    'your_app',
]

Without having it in, you can face problems like not detecting your static files, basically all the files involving your app. Even though it can be correct as suggested in the correct answer by using:

STATICFILES_DIRS = (adding/path/of/your/app)

Can be one of the errors and should be reviewed if getting this error.

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

Replace the earlier function with the provided one. The simplest solution is:

def __unicode__(self):

    return unicode(self.nom_du_site)

Angular2, what is the correct way to disable an anchor element?

For [routerLink] you can use:

Adding this CSS should do what you want:

a.disabled {
   pointer-events: none;
   cursor: not-allowed; 
}

This should fix the issue mentioned by @MichelLiu in the comments:

<a href="#" [class.disabled]="isDisabled(link)"
    (keydown.enter)="!isDisabled(link)">{{ link.name }}</a>

Another approach

<a [routerLink]="['Other']" *ngIf="!isDisabled(link)">{{ link.name }}</a>
<a  *ngIf="isDisabled(link)">{{ link.name }}</a>  

Plunker example

How can I change the width and height of slides on Slick Carousel?

You could also use this:

$('.slider').slick({
   //other settings ................
   respondTo: 'slider', //makes the slider to change width depending on the container it is in
   adaptiveHeight: true //makes the height change depending on the height of the element inside
})

Maximum Length of Command Line String

From the Microsoft documentation: Command prompt (Cmd. exe) command-line string limitation

On computers running Microsoft Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters.

Adding options to select with javascript

None of the above solutions worked for me. Append method didn't give error when i tried but it didn't solve my problem. In the end i solved my problem with data property of select2. I used json and got the array and then give it in select2 element initialize. For more detail you can see my answer at below post.

https://stackoverflow.com/a/41297283/4928277

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

copy-item With Alternate Credentials

Since PowerShell doesn't support "-Credential" usage via many of the cmdlets (very annoying), and mapping a network drive via WMI proved to be very unreliable in PS, I found pre-caching the user credentials via a net use command to work quite well:

# cache credentials for our network path
net use \\server\C$ $password /USER:$username

Any operation that uses \\server\C$ in the path seems to work using the *-item cmdlets.

You can also delete the share when you're done:

net use \\server\C$ /delete

Struct inheritance in C++

Of course. In C++, structs and classes are nearly identical (things like defaulting to public instead of private are among the small differences).

Percentage Height HTML 5/CSS

bobince's answer will let you know in which cases "height: XX%;" will or won't work.

If you want to create an element with a set ratio (height: % of it's own width), the best way to do that is by effectively setting the height using padding-bottom. Example for square:

<div class="square-container">
  <div class="square-content">
    <!-- put your content in here -->
  </div>
</div>

.square-container {  /* any display: block; element */
  position: relative;
  height: 0;
  padding-bottom: 100%; /* of parent width */
}
.square-content {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
}

The square container will just be made of padding, and the content will expand to fill the container. Long article from 2009 on this subject: http://alistapart.com/article/creating-intrinsic-ratios-for-video

What is the best method of handling currency/money?

Simple code for Ruby & Rails

<%= number_to_currency(1234567890.50) %>

OUT PUT => $1,234,567,890.50

How to edit data in result grid in SQL Server Management Studio

The way you can do this is by:

  • turning your select query into a view
  • right click on the view and choose Edit All Rows (you will get a grid of values you can edit - even if the values are from different tables).

You can also add Insert/Update triggers to your view that will allow you to grab the values from your view fields and then use T-SQL to manage updates to multiple tables.

git add remote branch

If the remote branch already exists then you can (probably) get away with..

git checkout branch_name

and git will automatically set up to track the remote branch with the same name on origin.

How to get a complete list of ticker symbols from Yahoo Finance?

i had a similar problem. yahoo doesn't offer it, but you can get one by looking through the document.write statements on nyse.com's list and finding the .js file where they just happen to store the list of companies starting with the given letter as a js array literal. you can also get nice tidy csv files from nasdaq.com here: http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download (replace exchange=nasdaq with exchange=nyse for nyse symbols).

Check if argparse optional argument is set or not

I think using the option default=argparse.SUPPRESS makes most sense. Then, instead of checking if the argument is not None, one checks if the argument is in the resulting namespace.

Example:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--foo", default=argparse.SUPPRESS)
ns = parser.parse_args()

print("Parsed arguments: {}".format(ns))
print("foo in namespace?: {}".format("foo" in ns))

Usage:

$ python argparse_test.py --foo 1
Parsed arguments: Namespace(foo='1')
foo in namespace?: True
Argument is not supplied:
$ python argparse_test.py
Parsed arguments: Namespace()
foo in namespace?: False

How to get Latitude and Longitude of the mobile device in android?

Update 2020: Using Kotlin Coroutine to get Lat, lang & Address of the Device

This is an old question and most answers are outdated. This is how I do it my apps now:

This class help to track the device location and return list of Address of device using Geocoding. Put it in some util class

import android.Manifest
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.*
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.core.app.ActivityCompat
import com.bmw.weatherapp.R
import kotlinx.coroutines.*
import java.io.IOException
import java.lang.ref.WeakReference
import java.util.*
import kotlin.coroutines.CoroutineContext

/**
 * Use GPS or Network Provider to get Device Location
 */
class DeviceLocationTracker(context: Context, deviceLocationListener: DeviceLocationListener) : LocationListener, CoroutineScope {
    private var deviceLocation: Location? = null
    private val context: WeakReference<Context>
    private var locationManager: LocationManager? = null
    private var deviceLocationListener: DeviceLocationListener
    private val job = Job()
    override val coroutineContext: CoroutineContext
        get() = job + Dispatchers.Main

    init {
        this.context = WeakReference(context)
        this.deviceLocationListener = deviceLocationListener
        initializeLocationProviders()
    }

    private fun initializeLocationProviders() {
        //Init Location Manger if not already initialized
        if (null == locationManager) {
            locationManager = context.get()
                    ?.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        }
        locationManager?.apply {
            // flag for GPS status
            val isGPSEnabled = isProviderEnabled(LocationManager.GPS_PROVIDER)

            // flag for network status
            val isNetworkEnabled = isProviderEnabled(LocationManager.PASSIVE_PROVIDER)

            //If we have permission
            if (ActivityCompat.checkSelfPermission(context.get()!!, Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(context.get()!!, Manifest.permission.ACCESS_COARSE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {

                //First Try GPS
                if (isGPSEnabled) {
                    requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            UPDATE_FREQUENCY_TIME,
                            UPDATE_FREQUENCY_DISTANCE.toFloat(), this@DeviceLocationTracker)
                    deviceLocation = locationManager!!.getLastKnownLocation(LocationManager.GPS_PROVIDER)
                } else {
                    // Show alert to open GPS
                    context.get()?.apply {
                        AlertDialog.Builder(this)
                                .setTitle(getString(R.string.title_enable_gps))
                                .setMessage(getString(R.string.desc_enable_gps))
                                .setPositiveButton(getString(R.string.btn_settings)
                                ) { dialog, which ->
                                    val intent = Intent(
                                            Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                                    startActivity(intent)
                                }.setNegativeButton(getString(R.string.btn_cancel))
                                { dialog, which -> dialog.cancel() }.show()
                    }
                }

                //If failed try using NetworkManger
                if(null==deviceLocation && isNetworkEnabled) {
                    requestLocationUpdates(
                            LocationManager.PASSIVE_PROVIDER,
                            0, 0f,
                            this@DeviceLocationTracker)
                    deviceLocation = locationManager!!.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
                }
            }
        }
    }

    /**
     * Stop using GPS listener
     * Must call this function to stop using GPS
     */
    fun stopUpdate() {
        if (locationManager != null) {
            locationManager!!.removeUpdates(this@DeviceLocationTracker)
        }
    }

    override fun onLocationChanged(newDeviceLocation: Location) {
        deviceLocation = newDeviceLocation
        launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                var addressList: List<Address?>? = null
                try {
                    addressList = Geocoder(context.get(),
                            Locale.ENGLISH).getFromLocation(
                            newDeviceLocation.latitude,
                            newDeviceLocation.longitude,
                            1)
                    deviceLocationListener.onDeviceLocationChanged(addressList)
                    Log.i(TAG, "Fetch address list"+addressList)

                } catch (e: IOException) {
                    Log.e(TAG, "Failed Fetched Address List")
                }
            }
        }
    }

    override fun onProviderDisabled(provider: String) {}
    override fun onProviderEnabled(provider: String) {}
    override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
    interface DeviceLocationListener {
        fun onDeviceLocationChanged(results: List<Address>?)
    }

    companion object {
        // The minimum distance to change Updates in meters
        private const val UPDATE_FREQUENCY_DISTANCE: Long = 1 // 10 meters

        // The minimum time between updates in milliseconds
        private const val UPDATE_FREQUENCY_TIME: Long = 1 // 1 minute
        private val TAG = DeviceLocationTracker::class.java.simpleName
    }
}

Add Strings for alert dialog in case GPS is disabled

   <string name="title_enable_gps">Enable GPS</string>
   <string name="desc_enable_gps">GPS is not enabled. Do you want to go to settings menu?</string>
    <string name="btn_settings">Open Settings</string>
    <string name="btn_cancel">Cancel</string>

Add these permission in your Android manifest and request them in app start

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Usage

Implement DeviceLocationListener in your Activity/Fragment class

  class MainActivity : AppCompatActivity, DeviceLocationTracker.DeviceLocationListener {
    

Override onDeviceLocationChanged callback. You will get current location in onDeviceLocationChanged

  override fun onDeviceLocationChanged(results: List<Address>?) {
        val currntLocation = results?.get(0);
        currntLocation?.apply {
             currentlLat = latitude
             currentLng = longitude
             Country = countryCode
             cityName = getAddressLine(0)
          
        }

    }

To start tracking create a DeviceLocationTracker object in onCreate method of your. Pass the Activity as Context & this as DeviceLocationListener.

private lateinit var deviceLocationTracker: DeviceLocationTracker

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ...
        deviceLocationTracker= DeviceLocationTracker(this, this)

That is it, now you will start to get location update in onDeviceLocationChanged.

Bootstrap 3 Gutter Size

Bootstrap 3 introduced row-no-gutters in v3.4.0

https://getbootstrap.com/docs/3.4/css/#grid-remove-gutters

You could make a row without gutters, and have a row with gutters inside it for the parts you do want to have a gutter.

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

The URI depends on the version of JSTL you are using. For Version 1.0 use:

http://java.sun.com/jstl/core

and for 1.1 (and later), you need to use:

http://java.sun.com/jsp/jstl/core

How to dynamically allocate memory space for a string and get that string from user?

First, define a new function to read the input (according to the structure of your input) and store the string, which means the memory in stack used. Set the length of string to be enough for your input.

Second, use strlen to measure the exact used length of string stored before, and malloc to allocate memory in heap, whose length is defined by strlen. The code is shown below.

int strLength = strlen(strInStack);
if (strLength == 0) {
    printf("\"strInStack\" is empty.\n");
}
else {
    char *strInHeap = (char *)malloc((strLength+1) * sizeof(char));
    strcpy(strInHeap, strInStack);
}
return strInHeap;

Finally, copy the value of strInStack to strInHeap using strcpy, and return the pointer to strInHeap. The strInStack will be freed automatically because it only exits in this sub-function.

How to check whether a string is a valid HTTP URL?

bool passed = Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps)

Static image src in Vue.js template

If you want to bind a string to the src attribute, you should wrap it on single quotes:

<img v-bind:src="'/static/img/clear.gif'">
<!-- or shorthand -->
<img :src="'/static/img/clear.gif'">

IMO you do not need to bind a string, you could use the simple way:

<img src="/static/img/clear.gif">

Check an example about the image preload here: http://codepen.io/pespantelis/pen/RWVZxL

*ngIf and *ngFor on same element causing error

I didn't want to wrap my *ngFor into another div with *ngIf or use [ngClass], so I created a pipe named show:

show.pipe.ts

export class ShowPipe implements PipeTransform {    
  transform(values: any[], show: boolean): any[] {
    if (!show) {
      return[];
    }
    return values;
  }
}

any.page.html

<table>
  <tr *ngFor="let arr of anyArray | show : ngIfCondition">
    <td>{{arr.label}}</td>
  </tr>
</table>

Calculating days between two dates with Java

We can make use of LocalDate and ChronoUnit java library, Below code is working fine. Date should be in format yyyy-MM-dd.

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
class Solution {
    public int daysBetweenDates(String date1, String date2) {
        LocalDate dt1 = LocalDate.parse(date1);
        LocalDate dt2= LocalDate.parse(date2);

        long diffDays = ChronoUnit.DAYS.between(dt1, dt2);

        return Math.abs((int)diffDays);
    }
}

How to install latest version of Node using Brew

You can use nodebrew. It can switch node versions too.

PHP CSV string to array

Handy oneliner:

$csv = array_map('str_getcsv', file('data.csv'));

Which equals operator (== vs ===) should be used in JavaScript comparisons?

The dilemma of "Should I use == or === in JavaScript comparison" is equal or analogous to a question of: "Should I use a 'spoon' or a 'fork' for eating.

The only reasonable answer to this question is that

  1. You should use Dynamic Type comparison e.g.:== for loose Type comparisons.
  2. You should use Static Type comparison e.g.:=== for strong Type comparisons.

That's because they are not the same. They don't have the same purpose and are not meant to be used for the same purpose.

Of course both 'forks' and 'spoons' are meant for 'eating', but you will chose to use them accordingly to what you've been served to eat.

Meaning: you'll resolve to using a 'spoon' i.e.: == for having a 'soup', and / or the 'fork' i.e.: === for picking.

Asking if it is better to use a "fork" or a "spoon" for "eating" - is equall to asking if it is better to use a static [===] versus dynamic [==] eq., op. in JS. Both questions are equally wrong and reflect a very narrow or shallow understanding of the subject in question.

Open Jquery modal dialog on click event

If you want to put some page in the dialog then you can use these

function Popup()
{
 $("#pop").load('login.html').dialog({
 height: 625,
 width: 600,
 modal:true,
 close: function(event,ui){
     $("pop").dialog('destroy');

        }
 }); 

}

HTML:

<Div id="pop"  style="display:none;">

</Div>

How can I convert a VBScript to an executable (EXE) file?

You can try VbsEdit. Get the latest version from Adersoft's VbsEdit http://www.vbsedit.com its a small download but it is a powerful tool to create and edit vbs files and convert them into executables without unpacking to temporary folder. (unless you get an old version like version 4.x.x.x) I've been using this program since 2008, and it's free to evaluate forever but comes with a reminder to activate and each time you Start your script from the vbsedit window you will have to wait a few seconds, Or you could purchase it for $60 to remove those minor annoyances.
Unlike ScriptCryptor, the converted exe won't have any limitations if you are still evaluating, it will run without any unwanted additional windows.

Find the max of 3 numbers in Java with different data types

Without using third party libraries, calling the same method more than once or creating an array, you can find the maximum of an arbitrary number of doubles like so

public static double max(double... n) {
    int i = 0;
    double max = n[i];

    while (++i < n.length)
        if (n[i] > max)
            max = n[i];

    return max;
}

In your example, max could be used like this

final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;

public static void main(String[] args) {
    double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}

jQueryUI modal dialog does not show close button (x)

Using the principle of the idea user2620505 got result with implementation of addClass:

...
open: function(){
    $('.ui-dialog-titlebar-close').addClass('ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only');
    $('.ui-dialog-titlebar-close').append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
}, 
...

If English is bad forgive me, I am using Google Translate.

What is SaaS, PaaS and IaaS? With examples

Here is another take with AWS Example of each service:

IaaS (Infrastructure as a Service): You get the whole infrastructure with hardware. You chose the type of OS that needs to be installed. You will have to install the necessary software.

AWS Example: EC2 which has only the hardware and you select the base OS to be installed. If you want to install Hadoop on that you have to do it yourself, it's just the base infrastructure AWS has provided.

PaaS (Platform as a Service): Provides you the infrastructure with OS and necessary base software. You will have to run your scripts to get the desired output.

AWS Example: EMR Which has the hardware (EC2) + Base OS + Hadoop software already installed. You will have to run hive/spark scripts to query tables and get results. You will need to invoke the instance and wait for 10 min for the setup to be ready. You have to take care of how many clusters you need based on the jobs you are running, but not worry about the cluster configuration.

SaaS (Software as a Service): You don't have to worry about Hardware or even Software. Everything will be installed and available for you to use instantly.

AWS Example: Athena, which is just a UI for you to query tables in S3 (with metadata stored in Glu). Just open the browser login to AWS and start running your queries, no worry about RAM/Storage/CPU/number of clusters, everything the cloud takes care of.

Convert Char to String in C

This is an old question, but I'd say none of the answers really fits the OP's question. All he wanted/needed to do is this:

char c = std::fgetc(fp);
std::strcpy(buffer, &c);

The relevant aspect here is the fact, that the second argument of strcpy() doesn't need to be a char array / c-string. In fact, none of the arguments is a char or char array at all. They are both char pointers:

strcpy(char* dest, const char* src);

dest : A non-const char pointer
Its value has to be the memory address of an element of a writable char array (with at least one more element after that).
src : A const char pointer
Its value can be the address of a single char, or of an element in a char array. That array must contain the special character \0 within its remaining elements (starting with src), to mark the end of the c-string that should be copied.

How do I use checkboxes in an IF-THEN statement in Excel VBA 2010?

It seems that in VBA macro code for an ActiveX checkbox control you use

If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)

and for a Form checkbox control you use

If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)

Use 'class' or 'typename' for template parameters?

Stan Lippman talked about this here. I thought it was interesting.

Summary: Stroustrup originally used class to specify types in templates to avoid introducing a new keyword. Some in the committee worried that this overloading of the keyword led to confusion. Later, the committee introduced a new keyword typename to resolve syntactic ambiguity, and decided to let it also be used to specify template types to reduce confusion, but for backward compatibility, class kept its overloaded meaning.

Do checkbox inputs only post data if they're checked?

I have a page (form) that dynamically generates checkbox so these answers have been a great help. My solution is very similar to many here but I can't help thinking it is easier to implement.

First I put a hidden input box in line with my checkbox , i.e.

 <td><input class = "chkhide" type="hidden" name="delete_milestone[]" value="off"/><input type="checkbox" name="delete_milestone[]"   class="chk_milestone" ></td>

Now if all the checkboxes are un-selected then values returned by the hidden field will all be off.

For example, here with five dynamically inserted checkboxes, the form POSTS the following values:

  'delete_milestone' => 
array (size=7)
  0 => string 'off' (length=3)
  1 => string 'off' (length=3)
  2 => string 'off' (length=3)
  3 => string 'on' (length=2)
  4 => string 'off' (length=3)
  5 => string 'on' (length=2)
  6 => string 'off' (length=3)

This shows that only the 3rd and 4th checkboxes are on or checked.

In essence the dummy or hidden input field just indicates that everything is off unless there is an "on" below the off index, which then gives you the index you need without a single line of client side code.

.

Save and retrieve image (binary) from SQL Server using Entity Framework 6

Convert the image to a byte[] and store that in the database.


Add this column to your model:

public byte[] Content { get; set; }

Then convert your image to a byte array and store that like you would any other data:

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using(var ms = new MemoryStream())
    {
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

        return ms.ToArray();
    }
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     using(var ms = new MemoryStream(byteArrayIn))
     {
         var returnImage = Image.FromStream(ms);

         return returnImage;
     }
}

Source: Fastest way to convert Image to Byte array

var image = new ImageEntity()
{
   Content = ImageToByteArray(image)
};

_context.Images.Add(image);
_context.SaveChanges();

When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

This stops working when the byte[] gets to big. It will work for files under 100Mb

sql: check if entry in table A exists in table B

The classical answer that works in almost every environment is

SELECT ID, Name, blah, blah
FROM TableB TB
LEFT JOIN TableA TA
ON TB.ID=TA.ID
WHERE TA.ID IS NULL

sometimes NOT EXISTS may be not implemented (not working).

How to wait for 2 seconds?

The documentation for WAITFOR() doesn't explicitly lay out the required string format.

This will wait for 2 seconds:

WAITFOR DELAY '00:00:02';

The format is hh:mi:ss.mmm.

Center a popup window on screen?

I had an issue with centering a popup window in the external monitor and window.screenX and window.screenY were negative values (-1920, -1200) respectively. I have tried all the above of the suggested solutions and they worked well in primary monitors. I wanted to leave

  • 200 px margin for left and right
  • 150 px margin for top and bottom

Here is what worked for me:

 function createPopupWindow(url) {
    var height = screen.height;
    var width = screen.width;
    var left, top, win;

    if (width > 1050) {
        width = width - 200;
    } else {
        width = 850;
    }

    if (height > 850) {
        height = height - 150;
    } else {
        height = 700;
    }

    if (window.screenX < 0) {
        left = (window.screenX - width) / 2;
    } else {
        left = (screen.width - width) / 2;
    }

    if (window.screenY < 0) {
        top = (window.screenY + height) / 4;
    } else {
        top = (screen.height - height) / 4;
    }

    win=window.open( url,"myTarget", "width="+width+", height="+height+",left="+left+",top="+top+"menubar=no, status=no, location=no, resizable=yes, scrollbars=yes");
    if (win.focus) {
        win.focus();
    }
}

How to stop process from .BAT file?

taskkill /F /IM notepad.exe this is the best way to kill the task from task manager.

Convert comma separated string to array in PL/SQL

A quick search on my BBDD took me to a function called split:

create or replace function split
( 
p_list varchar2, 
p_del varchar2 := ','
) 
return split_tbl pipelined
is 
l_idx pls_integer; 
l_list varchar2(32767) := p_list;AA 
l_value varchar2(32767);
begin 
loop 
l_idx := instr(l_list,p_del); 
if l_idx > 0 then 
pipe row(substr(l_list,1,l_idx-1)); 
l_list := substr(l_list,l_idx+length(p_del));
else 
pipe row(l_list); 
exit; 
end if; 
end loop; 
return;
end split;

I don't know if it'll be of use, but we found it here...

call javascript function on hyperlink click

Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.

Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:

[c# example only probably not the way you're writing out your js]
Response.Write("<a href=\"/link/for/javascriptDisabled/Browsers.aspx\" id=\"uxAncMyLink\">My Link</a>");

[Javascript]  
document.getElementById('uxAncMyLink').onclick = function(e){

// do some stuff here

    return false;
    }

That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.

Hope that is of use.

How to set the text/value/content of an `Entry` widget using a button in tkinter

Your problem is that when you do this:

a = Button(win, text="plant", command=setText("plant"))

it tries to evaluate what to set for the command. So when instantiating the Button object, it actually calls setText("plant"). This is wrong, because you don't want to call the setText method yet. Then it takes the return value of this call (which is None), and sets that to the command of the button. That's why clicking the button does nothing, because there is no command set for it.

If you do as Milan Skála suggested and use a lambda expression instead, then your code will work (assuming you fix the indentation and the parentheses).

Instead of command=setText("plant"), which actually calls the function, you can set command=lambda:setText("plant") which specifies something which will call the function later, when you want to call it.

If you don't like lambdas, another (slightly more cumbersome) way would be to define a pair of functions to do what you want:

def set_to_plant():
    set_text("plant")
def set_to_animal():
    set_text("animal")

and then you can use command=set_to_plant and command=set_to_animal - these will evaluate to the corresponding functions, but are definitely not the same as command=set_to_plant() which would of course evaluate to None again.

Node.js console.log() not logging anything

In a node.js server console.log outputs to the terminal window, not to the browser's console window.

How are you running your server? You should see the output directly after you start it.

How to correctly close a feature branch in Mercurial?

One way is to just leave merged feature branches open (and inactive):

$ hg up default
$ hg merge feature-x
$ hg ci -m merge

$ hg heads
    (1 head)

$ hg branches
default    43:...
feature-x  41:...
    (2 branches)

$ hg branches -a
default    43:...
    (1 branch)

Another way is to close a feature branch before merging using an extra commit:

$ hg up feature-x
$ hg ci -m 'Closed branch feature-x' --close-branch
$ hg up default
$ hg merge feature-x
$ hg ci -m merge

$ hg heads
    (1 head)

$ hg branches
default    43:...
    (1 branch)

The first one is simpler, but it leaves an open branch. The second one leaves no open heads/branches, but it requires one more auxiliary commit. One may combine the last actual commit to the feature branch with this extra commit using --close-branch, but one should know in advance which commit will be the last one.

Update: Since Mercurial 1.5 you can close the branch at any time so it will not appear in both hg branches and hg heads anymore. The only thing that could possibly annoy you is that technically the revision graph will still have one more revision without childen.

Update 2: Since Mercurial 1.8 bookmarks have become a core feature of Mercurial. Bookmarks are more convenient for branching than named branches. See also this question:

How do I best silence a warning about unused variables?

Use compiler's flag, e.g. flag for GCC: -Wno-unused-variable

How do I convert NSMutableArray to NSArray?

If you're constructing an array via mutability and then want to return an immutable version, you can simply return the mutable array as an "NSArray" via inheritance.

- (NSArray *)arrayOfStrings {
    NSMutableArray *mutableArray = [NSMutableArray array];
    mutableArray[0] = @"foo";
    mutableArray[1] = @"bar";

    return mutableArray;
}

If you "trust" the caller to treat the (technically still mutable) return object as an immutable NSArray, this is a cheaper option than [mutableArray copy].

Apple concurs:

To determine whether it can change a received object, the receiver of a message must rely on the formal type of the return value. If it receives, for example, an array object typed as immutable, it should not attempt to mutate it. It is not an acceptable programming practice to determine if an object is mutable based on its class membership.

The above practice is discussed in more detail here:

Best Practice: Return mutableArray.copy or mutableArray if return type is NSArray

Change the project theme in Android Studio?

In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click on android:theme = "@style/AppTheme" in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

At parent= in styles.xml you can browse all available styles by using auto-complete inside the "". E.g. try parent="Theme." with your cursor right after the . and then pressing Ctrl + Space.

You can also preview themes in the preview window in Android Studio.

enter image description here

Stop and Start a service via batch or cmd file?

or you can start remote service with this cmd : sc \\<computer> start <service>

How do I subscribe to all topics of a MQTT broker

You can use mosquitto_sub (which is part of the mosquitto-clients package) and subscribe to the wildcard topic #:

mosquitto_sub -v -h broker_ip -p 1883 -t '#'

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

you could try

$('*').not('#div').bind('touchmove', false);

add this if necessary

$('#div').bind('touchmove');

note that everything is fixed except #div

How to list all AWS S3 objects in a bucket using Java

It might be a workaround but this solved my problem:

ObjectListing listing = s3.listObjects( bucketName, prefix );
List<S3ObjectSummary> summaries = listing.getObjectSummaries();

while (listing.isTruncated()) {
   listing = s3.listNextBatchOfObjects (listing);
   summaries.addAll (listing.getObjectSummaries());
}

Create zip file and ignore directory structure

Retain the parent directory so unzip doesn't spew files everywhere

When zipping directories, keeping the parent directory in the archive will help to avoid littering your current directory when you later unzip the archive file

So to avoid retaining all paths, and since you can't use -j and -r together ( you'll get an error ), you can do this instead:

cd path/to/parent/dir/;
zip -r ../my.zip ../$(basename $PWD)
cd -;

The ../$(basename $PWD) is the magic that retains the parent directory.

So now unzip my.zip will give a folder containing all your files:

parent-directory
+-- file1
+-- file2
+-- dir1
¦   +-- file3
¦   +-- file4

Instead of littering the current directory with the unzipped files:

file1
file2
dir1
+-- file3
+-- file4

How to set custom location for local installation of npm package?

If you want this in config, you can set npm config like so:

npm config set prefix "$(pwd)/vendor/node_modules"

or

npm config set prefix "$HOME/vendor/node_modules"

Check your config with

npm config ls -l

Or as @pje says and use the --prefix flag

android: how to align image in the horizontal center of an imageview?

Give width of image as match_parent and height as required, say 300 dp.

<ImageView
    android:id = "@+id/imgXYZ"
    android:layout_width = "match_parent"
    android:layout_height = "300dp"
    android:src="@drawable/imageXYZ"
    />

How to POST URL in data of a curl request

Perhaps you don't have to include the single quotes:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"

Update: Reading curl's manual, you could actually separate both fields with two --data:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"

You could also try --data-binary:

curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"

And --data-urlencode:

curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"

Using git commit -a with vim

To exit hitting :q will let you quit.

If you want to quit without saving you can hit :q!

A google search on "vim cheatsheet" can provide you with a reference you should print out with a collection of quick shortcuts.

http://www.fprintf.net/vimCheatSheet.html

why are there two different kinds of for loops in java?

There is an excellent summary of this feature in the article The For-Each Loop. It shows by example how using the for-each style can produce clearer code that is easier to read and write.

What is http multipart request?

A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

I came to this page purely to find out the better method to use in terms of performance - i.e. which is faster:

querySelector / querySelectorAll or getElementsByClassName

and I found this: https://jsperf.com/getelementsbyclassname-vs-queryselectorall/18

It runs a test on the 2 x examples above, plus it chucks in a test for jQuery's equivalent selector as well. my test results were as follows:

getElementsByClassName = 1,138,018 operations / sec - <<< clear winner
querySelectorAll = 39,033 operations / sec
jquery select = 381,648 operations / sec

How to update and delete a cookie?

http://www.quirksmode.org/js/cookies.html

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

How to create a backup of a single table in a postgres database?

you can use this command

pg_dump --table=yourTable --data-only --column-inserts yourDataBase > file.sql

you should change yourTable, yourDataBase to your case

How do I insert values into a Map<K, V>?

Try this code

HashMap<String, String> map = new HashMap<String, String>();
map.put("EmpID", EmpID);
map.put("UnChecked", "1");

Importing CommonCrypto in a Swift framework

I found a GitHub project that successfully uses CommonCrypto in a Swift framework: SHA256-Swift. Also, this article about the same problem with sqlite3 was useful.

Based on the above, the steps are:

1) Create a CommonCrypto directory inside the project directory. Within, create a module.map file. The module map will allow us to use the CommonCrypto library as a module within Swift. Its contents are:

module CommonCrypto [system] {
    header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    link "CommonCrypto"
    export *
}

2) In Build Settings, within Swift Compiler - Search Paths, add the CommonCrypto directory to Import Paths (SWIFT_INCLUDE_PATHS).

Build Settings

3) Finally, import CommonCrypto inside your Swift files as any other modules. For example:

import CommonCrypto

extension String {

    func hnk_MD5String() -> String {
        if let data = self.dataUsingEncoding(NSUTF8StringEncoding)
        {
            let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))
            let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes)
            CC_MD5(data.bytes, CC_LONG(data.length), resultBytes)
            let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, length: result.length)
            let MD5 = NSMutableString()
            for c in resultEnumerator {
                MD5.appendFormat("%02x", c)
            }
            return MD5
        }
        return ""
    }
}

Limitations

Using the custom framework in another project fails at compile time with the error missing required module 'CommonCrypto'. This is because the CommonCrypto module does not appear to be included with the custom framework. A workaround is to repeat step 2 (setting Import Paths) in the project that uses the framework.

The module map is not platform independent (it currently points to a specific platform, the iOS 8 Simulator). I don't know how to make the header path relative to the current platform.

Updates for iOS 8 <= We should remove the line link "CommonCrypto", to get the successful compilation.

UPDATE / EDIT

I kept getting the following build error:

ld: library not found for -lCommonCrypto for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Unless I removed the line link "CommonCrypto" from the module.map file I created. Once I removed this line it built ok.

How to return a resolved promise from an AngularJS Service using $q?

Return your promise , return deferred.promise.
It is the promise API that has the 'then' method.

https://docs.angularjs.org/api/ng/service/$q

Calling resolve does not return a promise it only signals the promise that the promise is resolved so it can execute the 'then' logic.

Basic pattern as follows, rinse and repeat
http://plnkr.co/edit/fJmmEP5xOrEMfLvLWy1h?p=preview

<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.0-beta.5" 
        src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>

<div ng-controller="test">
  <button ng-click="test()">test</button>
</div>
<script>
  var app = angular.module("app",[]);

  app.controller("test",function($scope,$q){

    $scope.$test = function(){
      var deferred = $q.defer();
      deferred.resolve("Hi");
      return deferred.promise;
    };

    $scope.test=function(){
      $scope.$test()
      .then(function(data){
        console.log(data);
      });
    }      
  });

  angular.bootstrap(document,["app"]);

</script>

nodejs vs node on ubuntu 12.04

You need to manually create a symlink /usr/bin/node. Shortcut for bash compatible shells:

sudo ln -s `which nodejs` /usr/bin/node

Or if you use non-standard shells, just hardcode the path you find with which nodejs:

sudo ln -s /usr/bin/nodejs /usr/bin/node

Later edit

I found this explanation in the link you posted

There is a naming conflict with the node package (Amateur Packet Radio Node Program), and the nodejs binary has been renamed from node to nodejs. You'll need to symlink /usr/bin/node to /usr/bin/nodejs or you could uninstall the Amateur Packet Radio Node Program to avoid that conflict.

Later later edit

It's been a while since I answered this. Although the solution I posted up here worked for me several times, users have reported a few more solutions within the comments:

From @user229115

sudo update-alternatives --install /usr/bin/node node /usr/bin/nodejs 10

From AskUbuntu (user leftium)

sudo apt-get --purge remove node
sudo apt-get --purge remove nodejs
sudo apt-get install nodejs

How do I create a constant in Python?

A better approach to creating constants in Python is to take inspiration from the excellent attrs library, which helps Python programmers create classes without boilerplate. The short-con package does the same for constants by providing a convenience wrapper around attr.make_class. [Disclaimer: I am the author of short-con.]

Values can be declared explicitly via either a dict or kwargs: These examples do the same thing. The constants() function supports all features of the library, and cons() is a helper for simple kwarg-based usage.

from short_con import constants, cons

Pieces = constants('Pieces', dict(king = 0, queen = 9, rook = 5, bishop = 3, knight = 3, pawn = 1))
Pieces = cons('Pieces', king = 0, queen = 9, rook = 5, bishop = 3, knight = 3, pawn = 1)

For situations when the values are the same as (or can be derived from) the attribute names, usage is even more compact. Just supply names as a space-delimited string, list, or tuple.

NAMES = 'KING QUEEN ROOK BISHOP KNIGHT PAWN'
xs = NAMES.split()

Pieces = constants('Pieces', NAMES)      # All of these do the same thing.
Pieces = constants('Pieces', xs)
Pieces = constants('Pieces', tuple(xs))

The name-based usages support a few stylistic conventions: uppercase or lowercase attribute names, along with enum-style values.

The underlying values are directly accessible, unlike constants created by the built-in enum library:

Pieces.QUEEN        # short-con usage
Pieces.QUEEN.value  # enum library usage

And the object is directly iterable and convertible to other collections:

for name, value in Pieces:
    print(name, value)

d = dict(Pieces)
tups = list(Pieces)

Remove HTML tags from a String

It sounds like you want to go from HTML to plain text.
If that is the case look at www.htmlparser.org. Here is an example that strips all the tags out from the html file found at a URL.
It makes use of org.htmlparser.beans.StringBean.

static public String getUrlContentsAsText(String url) {
    String content = "";
    StringBean stringBean = new StringBean();
    stringBean.setURL(url);
    content = stringBean.getStrings();
    return content;
}

HTML iframe - disable scroll

Just add an iframe styled like either option below. I hope this solves the problem.

1st option:

<iframe src="https://www.skyhub.ca/featured-listing" style="position: absolute; visibility: hidden;" onload="this.style.position='static'; this.style.visibility='visible';" scrolling="no" frameborder="0" marginheight="0px" marginwidth="0px" height="400px" width="1200px" allowfullscreen></iframe>

2nd option:

<iframe src="https://www.skyhub.ca/featured-listing" style="display: none;" onload="this.style.display='block';" scrolling="no" frameborder="0" marginheight="0px" marginwidth="0px" height="400px" width="1200px" allowfullscreen></iframe>

LEFT OUTER JOIN in LINQ

I would like to add that if you get the MoreLinq extension there is now support for both homogenous and heterogeneous left joins now

http://morelinq.github.io/2.8/ref/api/html/Overload_MoreLinq_MoreEnumerable_LeftJoin.htm

example:

//Pretend a ClientCompany object and an Employee object both have a ClientCompanyID key on them

return DataContext.ClientCompany
    .LeftJoin(DataContext.Employees,                         //Table being joined
        company => company.ClientCompanyID,                  //First key
        employee => employee.ClientCompanyID,                //Second Key
        company => new {company, employee = (Employee)null}, //Result selector when there isn't a match
        (company, employee) => new { company, employee });   //Result selector when there is a match

EDIT:

In retrospect this may work, but it converts the IQueryable to an IEnumerable as morelinq does not convert the query to SQL.

You can instead use a GroupJoin as described here: https://stackoverflow.com/a/24273804/4251433

This will ensure that it stays as an IQueryable in case you need to do further logical operations on it later.

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.

For that need to add the 2021 partition into that table

ALTER TABLE TABLE_NAME ADD PARTITION PARTITION_NAME VALUES LESS THAN (TO_DATE('2021-12-31 24:59:59', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) NOCOMPRESS

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

I do some quick tests and have the following findings:

1) if using SynchronousQueue:

After the threads reach the maximum size, any new work will be rejected with the exception like below.

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@3fee733d rejected from java.util.concurrent.ThreadPoolExecutor@5acf9800[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]

at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)

2) if using LinkedBlockingQueue:

The threads never increase from minimum size to maximum size, meaning the thread pool is fixed size as the minimum size.

How to force a SQL Server 2008 database to go Offline

Go offline

USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO

Go online

USE master
GO
ALTER DATABASE YourDatabaseName
SET ONLINE
GO

Node.js: for each … in not working

Unfortunately node does not support for each ... in, even though it is specified in JavaScript 1.6. Chrome uses the same JavaScript engine and is reported as having a similar shortcoming.

You'll have to settle for array.forEach(function(item) { /* etc etc */ }).

EDIT: From Google's official V8 website:

V8 implements ECMAScript as specified in ECMA-262.

On the same MDN website where it says that for each ...in is in JavaScript 1.6, it says that it is not in any ECMA version - hence, presumably, its absence from Node.

error C2039: 'string' : is not a member of 'std', header file problem

You need to have

#include <string>

in the header file too.The forward declaration on it's own doesn't do enough.

Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:

#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H

/* header goes in here */

#endif

This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

Formatting html email for Outlook

I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.

https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable

How to calculate the width of a text string of a specific font and font-size?

Update Sept 2019

This answer is a much cleaner way to do it using new syntax.

Original Answer

Based on Glenn Howes' excellent answer, I created an extension to calculate the width of a string. If you're doing something like setting the width of a UISegmentedControl, this can set the width based on the segment's title string.

extension String {

    func widthOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttributes)
        return size.width
    }

    func heightOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttributes)
        return size.height
    }

    func sizeOfString(usingFont font: UIFont) -> CGSize {
        let fontAttributes = [NSAttributedString.Key.font: font]
        return self.size(withAttributes: fontAttributes)
    }
}

usage:

    // Set width of segmentedControl
    let starString = "??"
    let starWidth = starString.widthOfString(usingFont: UIFont.systemFont(ofSize: 14)) + 16
    segmentedController.setWidth(starWidth, forSegmentAt: 3)

identifier "string" undefined?

You want to do #include <string> instead of string.h and then the type string lives in the std namespace, so you will need to use std::string to refer to it.

Calculating Distance between two Latitude and Longitude GeoCoordinates

Here is the JavaScript version guys and gals

function distanceTo(lat1, lon1, lat2, lon2, unit) {
      var rlat1 = Math.PI * lat1/180
      var rlat2 = Math.PI * lat2/180
      var rlon1 = Math.PI * lon1/180
      var rlon2 = Math.PI * lon2/180
      var theta = lon1-lon2
      var rtheta = Math.PI * theta/180
      var dist = Math.sin(rlat1) * Math.sin(rlat2) + Math.cos(rlat1) * Math.cos(rlat2) * Math.cos(rtheta);
      dist = Math.acos(dist)
      dist = dist * 180/Math.PI
      dist = dist * 60 * 1.1515
      if (unit=="K") { dist = dist * 1.609344 }
      if (unit=="N") { dist = dist * 0.8684 }
      return dist
}

How do you sign a Certificate Signing Request with your Certification Authority?

In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,

default_days     = 1000         # How long to certify for

defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:

openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.

Conditional formatting, entire row based

=$G1="X"

would be the correct (and easiest) method. Just select the entire sheet first, as conditional formatting only works on selected cells. I just tried it and it works perfectly. You must start at G1 rather than G2 otherwise it will offset the conditional formatting by a row.

Post order traversal of binary tree without recursion

void display_without_recursion(struct btree **b) 
{
    deque< struct btree* > dtree;
        if(*b)
    dtree.push_back(*b);
        while(!dtree.empty() )
    {
        struct btree* t = dtree.front();
        cout << t->nodedata << " " ;
        dtree.pop_front();
        if(t->right)
        dtree.push_front(t->right);
        if(t->left)
        dtree.push_front(t->left);
    }
    cout << endl;
}

How to do a batch insert in MySQL

mysql allows you to insert multiple rows at once INSERT manual

font-family is inherit. How to find out the font-family in chrome developer pane?

Developer Tools > Elements > Computed > Rendered Fonts

The picture you attached to your question shows the Style tab. If you change to the next tab, Computed, you can check the Rendered Fonts, that shows the actual font-family rendered.

Developer Tools > Elements > Computed > Rendered Fonts

Open the terminal in visual studio?

Microsoft just included an integrated Windows Terminal in Visual Studio version 16.3 Preview 3. Go to Tools > Options > Preview Features, enable the Experimental VS Terminal option and restart Visual Studio.

https://devblogs.microsoft.com/visualstudio/say-hello-to-the-new-visual-studio-terminal/

How to put two divs side by side

Have a look at CSS and HTML in depth you will figure this out. It just floating the boxes left and right and those boxes need to be inside a same div. http://www.w3schools.com/html/html_layout.asp might be a good resource.

how can I enable PHP Extension intl?

For instalation of magento on local host you need to uncomment the extension=php_intl.dll in php.ini and copy all icudt57.dll,icuin57.dll,icuio57.dll,icule57.dll,iculx57.dll,icuuc57.dll files from php folder to XAMPP\apache\bin folder.

Then Restart the xamp server

Correct way to find max in an Array in Swift

var numbers = [1, 2, 7, 5];    
var val = sort(numbers){$0 > $1}[0];

How to find out the username and password for mysql database

If you forget your password for SQL plus 10g then follow the steps :

  1. START
  2. Type RUN in the search box
  3. Type 'cnc' in the box captioned as OPEN and a black box will appear 4.There will be some text already in the box. (C:\Users\admin>) Just beside that start typing 'sqlplus/nolog' press ENTER key
  4. On the next line type 'conn sys/change_on_install as sysdba' (press ENTER) 6.(in the next line after sql-> type) 'alter user scott account unlock' .
  5. Now open your slpplus and type user name as 'scott' and password as 'tiger'.

If it asks your old password then type the one you have given while installing.

Pass row number as variable in excel sheet

Assuming your row number is in B1, you can use INDIRECT:

=INDIRECT("A" & B1)

This takes a cell reference as a string (in this case, the concatenation of A and the value of B1 - 5), and returns the value at that cell.

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Force page scroll position to top at page refresh in HTML

You can also try

$(document).ready(function(){
    $(window).scrollTop(0);
});

If you want to scroll at x position than you can change the value of 0 to x.

How to start up spring-boot application via command line?

One of the ways that you can run your spring-boot application from command line is as follows :

1) First go to your project directory in command line [where is your project located ?]

2) Then in the next step you have to create jar file for that, this can be done as

mvnw package [for WINDOWS OS ] or ./mvnw package [for MAC OS] , this will create jar file for our application.

3) jar file is created in the target sub-directory

4)Now go to target sub directory as jar was created inside of it , i.e cd target

5) Now run the jar file in there. Use command java -jar name.jar [ name is the name of your created jar file.]

and there you go , you are done . Now you can run project in browser,

 http://localhost:port_number

Why is there no ForEach extension method on IEnumerable?

I've always wondered that myself, that is why that I always carry this with me:

public static void ForEach<T>(this IEnumerable<T> col, Action<T> action)
{
    if (action == null)
    {
        throw new ArgumentNullException("action");
    }
    foreach (var item in col)
    {
        action(item);
    }
}

Nice little extension method.

C# DLL config file

It is not trivial to create a .NET configuration file for a .DLL, and for good reason. The .NET configuration mechanism has a lot of features built into it to facilitate easy upgrading/updating of the app, and to protect installed apps from trampling each others configuration files.

There is a big difference between how a DLL is used and how an application is used. You are unlikely to have multiple copies of an application installed on the same machine for the same user. But you may very well have 100 different apps or libraries all making use of some .NET DLL.

Whereas there is rarely a need to track settings separately for different copies of an app within one user profile, it's very unlikely that you would want all of the different usages of a DLL to share configuration with each other. For this reason, when you retrieve a Configuration object using the "normal" method, the object you get back is tied to the configuration of the App Domain you are executing in, rather than the particular assembly.

The App Domain is bound to the root assembly which loaded the assembly which your code is actually in. In most cases this will be the assembly of your main .EXE, which is what loaded up the .DLL. It is possible to spin up other app domains within an application, but you must explicitly provide information on what the root assembly of that app domain is.

Because of all this, the procedure for creating a library-specific config file is not so convenient. It is the same process you would use for creating an arbitrary portable config file not tied to any particular assembly, but for which you want to make use of .NET's XML schema, config section and config element mechanisms, etc. This entails creating an ExeConfigurationFileMap object, loading in the data to identify where the config file will be stored, and then calling ConfigurationManager.OpenMappedExeConfiguration to open it up into a new Configuration instance. This will cut you off from the version protection offered by the automatic path generation mechanism.

Statistically speaking, you're probably using this library in an in-house setting, and it's unlikely you'll have multiple apps making use of it within any one machine/user. But if not, there is something you should keep in mind. If you use a single global config file for your DLL, regardless of the app that is referencing it, you need to worry about access conflicts. If two apps referencing your library happen to be running at the same time, each with their own Configuration object open, then when one saves changes, it will cause an exception next time you try to retrieve or save data in the other app.

The safest and simplest way of getting around this is to require that the assembly which is loading your DLL also provide some information about itself, or to detect it by examining the App Domain of the referencing assembly. Use this to create some sort of folder structure for keeping separate user config files for each app referencing your DLL.

If you are certain you want to have global settings for your DLL no matter where it is referenced, you'll need to determine your location for it rather than .NET figuring out an appropriate one automatically. You'll also need to be aggressive about managing access to the file. You'll need to cache as much as possible, keeping the Configuration instance around ONLY as long as it takes to load or to save, opening immediately before and disposing immediately after. And finally, you'll need a lock mechanism to protect the file while it's being edited by one of the apps that use the library.

How to check for an undefined or null variable in JavaScript?

Firstly you have to be very clear about what you test. JavaScript has all sorts of implicit conversions to trip you up, and two different types of equality comparator: == and ===.

A function, test(val) that tests for null or undefined should have the following characteristics:

 test(null)         => true
 test(undefined)    => true
 test(0)            => false
 test(1)            => false
 test(true)         => false
 test(false)        => false
 test('s')          => false
 test([])           => false

Let's see which of the ideas here actually pass our test.

These work:

val == null
val === null || val === undefined
typeof(val) == 'undefined' || val == null
typeof(val) === 'undefined' || val === null

These do not work:

typeof(val) === 'undefined'
!!val

I created a jsperf entry to compare the correctness and performance of these approaches. Results are inconclusive for the time being as there haven't been enough runs across different browsers/platforms. Please take a minute to run the test on your computer!

At present, it seems that the simple val == null test gives the best performance. It's also pretty much the shortest. The test may be negated to val != null if you want the complement.

Calculating text width

The textWidth functions provided in the answers and that accept a string as an argument will not account for leading and trailing white spaces (those are not rendered in the dummy container). Also, they will not work if the text contains any html markup (a sub-string <br> won't produce any output and &nbsp; will return the length of one space).

This is only a problem for the textWidth functions which accept a string, because if a DOM element is given, and .html() is called upon the element, then there is probably no need to fix this for such use case.

But if, for example, you are calculating the width of the text to dynamically modify the width of an text input element as the user types (my current use case), you'll probably want to replace leading and trailing spaces with &nbsp; and encode the string to html.

I used philfreo's solution so here is a version of it that fixes this (with comments on additions):

$.fn.textWidth = function(text, font) {
    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').appendTo(document.body);
    var htmlText = text || this.val() || this.text();
    htmlText = $.fn.textWidth.fakeEl.text(htmlText).html(); //encode to Html
    htmlText = htmlText.replace(/\s/g, "&nbsp;"); //replace trailing and leading spaces
    $.fn.textWidth.fakeEl.html(htmlText).css('font', font || this.css('font'));
    return $.fn.textWidth.fakeEl.width();
};

MySQL Cannot drop index needed in a foreign key constraint

Step 1

List foreign key ( NOTE that its different from index name )

SHOW CREATE TABLE  <Table Name>

The result will show you the foreign key name.

Format:

CONSTRAINT `FOREIGN_KEY_NAME` FOREIGN KEY (`FOREIGN_KEY_COLUMN`) REFERENCES `FOREIGN_KEY_TABLE` (`id`),

Step 2

Drop (Foreign/primary/key) Key

ALTER TABLE <Table Name> DROP FOREIGN KEY <Foreign key name>

Step 3

Drop the index.

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?

When I had this problem, I had included the mail-api.jar in my maven pom file. That's the API specification only. The fix is to replace this:

<!-- DO NOT USE - it's just the API, not an implementation -->
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>

with the reference implementation of that api:

<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>

I know it has sun in the package name, but that's the latest version. I learned this from https://stackoverflow.com/a/28935760/1128668

How to Use slideDown (or show) function on a table row?

I'd like to add a comment to #Vinny's post but dont have the rep so have to post an answer...

Found a bug with your plugin - when you just pass an object in with arguments they get overwritten if no other arguments are passed in. Easily resolved by changing the order the arguments are processed, code below. I've also added an option for destroying the row after closing (only as I had a need for it!): $('#row_id').slideRow('up', true); // destroys the row

(function ($) {
    var sR = {
        defaults: {
            slideSpeed: 400,
            easing: false,
            callback: false
        },
        thisCallArgs: {
            slideSpeed: 400,
            easing: false,
            callback: false,
            destroyAfterUp: false
        },
        methods: {
            up: function (arg1, arg2, arg3) {
                if (typeof arg2 == 'string') {
                    sR.thisCallArgs.easing = arg2;
                } else if (typeof arg2 == 'function') {
                    sR.thisCallArgs.callback = arg2;
                } else if (typeof arg2 == 'undefined') {
                    sR.thisCallArgs.easing = sR.defaults.easing;
                }
                if (typeof arg3 == 'function') {
                    sR.thisCallArgs.callback = arg3;
                } else if (typeof arg3 == 'undefined' && typeof arg2 != 'function') {
                    sR.thisCallArgs.callback = sR.defaults.callback;
                }
                if (typeof arg1 == 'object') {
                    for (p in arg1) {
                        sR.thisCallArgs[p] = arg1[p];
                    }
                } else if (typeof arg1 != 'undefined' && (typeof arg1 == 'number' || arg1 == 'slow' || arg1 == 'fast')) {
                    sR.thisCallArgs.slideSpeed = arg1;
                } else if (typeof arg1 != 'undefined' && (typeof arg1 == 'boolean')) {
                    sR.thisCallArgs.destroyAfterUp = arg1;
                } else {
                    sR.thisCallArgs.slideSpeed = sR.defaults.slideSpeed;
                }

                var $row = $(this);
                var $cells = $row.children('th, td');
                $cells.wrapInner('<div class="slideRowUp" />');
                var currentPadding = $cells.css('padding');
                $cellContentWrappers = $(this).find('.slideRowUp');
                $cellContentWrappers.slideUp(sR.thisCallArgs.slideSpeed, sR.thisCallArgs.easing).parent().animate({
                    paddingTop: '0px',
                    paddingBottom: '0px'
                }, {
                    complete: function () {
                        $(this).children('.slideRowUp').replaceWith($(this).children('.slideRowUp').contents());
                        $(this).parent().css({ 'display': 'none' });
                        $(this).css({ 'padding': currentPadding });
                    }
                });
                var wait = setInterval(function () {
                    if ($cellContentWrappers.is(':animated') === false) {
                        clearInterval(wait);
                        if (sR.thisCallArgs.destroyAfterUp)
                        {
                            $row.replaceWith('');
                        }
                        if (typeof sR.thisCallArgs.callback == 'function') {
                            sR.thisCallArgs.callback.call(this);
                        }
                    }
                }, 100);
                return $(this);
            },
            down: function (arg1, arg2, arg3) {

                if (typeof arg2 == 'string') {
                    sR.thisCallArgs.easing = arg2;
                } else if (typeof arg2 == 'function') {
                    sR.thisCallArgs.callback = arg2;
                } else if (typeof arg2 == 'undefined') {
                    sR.thisCallArgs.easing = sR.defaults.easing;
                }
                if (typeof arg3 == 'function') {
                    sR.thisCallArgs.callback = arg3;
                } else if (typeof arg3 == 'undefined' && typeof arg2 != 'function') {
                    sR.thisCallArgs.callback = sR.defaults.callback;
                }
                if (typeof arg1 == 'object') {
                    for (p in arg1) {
                        sR.thisCallArgs.eval(p) = arg1[p];
                    }
                } else if (typeof arg1 != 'undefined' && (typeof arg1 == 'number' || arg1 == 'slow' || arg1 == 'fast')) {
                    sR.thisCallArgs.slideSpeed = arg1;
                } else {
                    sR.thisCallArgs.slideSpeed = sR.defaults.slideSpeed;
                }

                var $cells = $(this).children('th, td');
                $cells.wrapInner('<div class="slideRowDown" style="display:none;" />');
                $cellContentWrappers = $cells.find('.slideRowDown');
                $(this).show();
                $cellContentWrappers.slideDown(sR.thisCallArgs.slideSpeed, sR.thisCallArgs.easing, function () { $(this).replaceWith($(this).contents()); });

                var wait = setInterval(function () {
                    if ($cellContentWrappers.is(':animated') === false) {
                        clearInterval(wait);
                        if (typeof sR.thisCallArgs.callback == 'function') {
                            sR.thisCallArgs.callback.call(this);
                        }
                    }
                }, 100);
                return $(this);
            }
        }
    };

    $.fn.slideRow = function (method, arg1, arg2, arg3) {
        if (typeof method != 'undefined') {
            if (sR.methods[method]) {
                return sR.methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
            }
        }
    };
})(jQuery);

What is Node.js?

Node.js is an open source command line tool built for the server side JavaScript code. You can download a tarball, compile and install the source. It lets you run JavaScript programs.

The JavaScript is executed by the V8, a JavaScript engine developed by Google which is used in Chrome browser. It uses a JavaScript API to access the network and file system.

It is popular for its performance and the ability to perform parallel operations.

Understanding node.js is the best explanation of node.js I have found so far.

Following are some good articles on the topic.

Forbidden: You don't have permission to access / on this server, WAMP Error

1.

first of all Port 80(or what ever you are using) and 443 must be allow for both TCP and UDP packets. To do this, create 2 inbound rules for TPC and UDP on Windows Firewall for port 80 and 443. (or you can disable your whole firewall for testing but permanent solution if allow inbound rule)

2.

If you are using WAMPServer 3 See bottom of answer

For WAMPServer versions <= 2.5

You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf file.

Change this section from :

#   onlineoffline tag - don't remove
     Order Deny,Allow
     Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

To :

#   onlineoffline tag - don't remove
    Order Allow,Deny
      Allow from all

if "Allow from all" line not work for your then use "Require all granted" then it will work for you.

WAMPServer 3 has a different method

In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost so dont amend the httpd.conf file at all, leave it as you found it.

Using the menus, edit the httpd-vhosts.conf file.

enter image description here

It should look like this :

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

Amend it to

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Note:if you are running wamp for other than port 80 then VirtualHost will be like VirtualHost *:86.(86 or port whatever you are using) instead of VirtualHost *:80

3. Dont forget to restart All Services of Wamp or Apache after making this change

How do I put a variable inside a string?

If you would want to put multiple values into the string you could make use of format

nums = [1,2,3]
plot.savefig('hanning{0}{1}{2}.pdf'.format(*nums))

Would result in the string hanning123.pdf. This can be done with any array.

How can I display the users profile pic using the facebook graph api?

to get different sizes, you can use the type parameter:

You can specify the picture size you want with the type argument, which should be one of square (50x50), small (50 pixels wide, variable height), and large (about 200 pixels wide, variable height): http://graph.facebook.com/squall3d/picture?type=large.

Class Diagrams in VS 2017

You need to install “Visual Studio extension development” workload and “Class Designer” optional component from the Visual Studio 2017 Installer to get the feature.

See: Visual Studio Community 2017 component directory

But this kind of item is not available on all project types. Just try for yourself:

  • In a Console App (.NET Framework) is available;

  • In a Console App (.NET Core) is not available.

I couldn't find more info on future availability also for .NET Core projects.

Python: No acceptable C compiler found in $PATH when installing python

On Arch Linux run the following:

sudo pacman -S base-devel

TypeScript: casting HTMLElement

Just to clarify, this is correct.

Cannot convert 'NodeList' to 'HTMLScriptElement[]'

as a NodeList is not an actual array (e.g. it doesn't contain .forEach, .slice, .push, etc...).

Thus if it did convert to HTMLScriptElement[] in the type system, you'd get no type errors if you tried to call Array.prototype members on it at compile time, but it would fail at run time.

Email and phone Number Validation in android

public boolean checkForEmail() {
        Context c;
        EditText mEtEmail=(EditText)findViewById(R.id.etEmail);
        String mStrEmail = mEtEmail.getText().toString();
        if (android.util.Patterns.EMAIL_ADDRESS.matcher(mStrEmail).matches()) {
            return true;
        }
        Toast.makeText(this,"Email is not valid", Toast.LENGTH_LONG).show();
        return false;
    }


    public boolean checkForMobile() {
        Context c;
        EditText mEtMobile=(EditText)findViewById(R.id.etMobile);
        String mStrMobile = mEtMobile.getText().toString();
        if (android.util.Patterns.PHONE.matcher(mStrMobile).matches()) {
            return true;
        }
        Toast.makeText(this,"Phone No is not valid", Toast.LENGTH_LONG).show();
        return false;
    }

jQuery: Count number of list elements?

I think this should do it:

var ct = $('#mylist').children().size(); 

How to verify if nginx is running or not?

The modern (systemctl) way of doing it:

systemctl is-active nginx

You can use the exit value in your shell scripts as follows:

systemctl -q is-active nginx && echo "It is active, do something"

How can I check if a jQuery plugin is loaded?

If we're talking about a proper jQuery plugin (one that extends the fn namespace), then the proper way to detect the plugin would be:

if(typeof $.fn.pluginname !== 'undefined') { ... }

Or because every plugin is pretty much guaranteed to have some value that equates to true, you can use the shorter

if ($.fn.pluginname) { ... }

BTW, the $ and jQuery are interchangable, as the odd-looking wrapper around a plugin demonstrates:

(function($) {
    //
})(jQuery))

the closure

(function($) {
    //
})

is followed immediately by a call to that closure 'passing' jQuery as the parameter

(jQuery)

the $ in the closure is set equal to jQuery

How to tell if a connection is dead in python

If I'm not mistaken this is usually handled via a timeout.

How to unlock android phone through ADB

I would like to share my way, first of all i had Huawei ascend p7 and my touch screen stopped handling touch, so none of the above solutions helped me to be unlock the phone, i have found a better clever way to do it since i can see the screen on thus i thought that my display is 1080 x 1920 px thus i had to simulate a drawing on my photoshop with keypad with (x,y) so i can try instead with input mouse tap command.

screenshot of simulation

Since i have pin lock as you can see in the picture, i have got all the (x,y) for all the numbers on the screen to simulate touch and unlock my screen and have to backup my data, thus if my password is 123 i did all the following commands

adb shell input mouse tap 100 1150
adb shell input mouse tap 500 1150
adb shell input mouse tap 900 1150

And then my phone just got unlocked, i hope it was helpful.

How to force JS to do math instead of putting two strings together

You can add + behind the variable and it will force it to be an integer

var dots = 5
    function increase(){
        dots = +dots + 5;
    }

How to tell Maven to disregard SSL errors (and trusting all certs)?

You can disable SSL certificate checking by adding one or more of these command line parameters:

  • -Dmaven.wagon.http.ssl.insecure=true - enable use of relaxed SSL check for user generated certificates.
  • -Dmaven.wagon.http.ssl.allowall=true - enable match of the server's X.509 certificate with hostname. If disabled, a browser like check will be used.
  • -Dmaven.wagon.http.ssl.ignore.validity.dates=true - ignore issues with certificate dates.

Official documentation: http://maven.apache.org/wagon/wagon-providers/wagon-http/

Here's the oneliner for an easy copy-and-paste:

-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true

Ajay Gautam suggested that you could also add the above to the ~/.mavenrc file as not to have to specify it every time at command line:

$ cat ~/.mavenrc 
MAVEN_OPTS="-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true"

Can I store images in MySQL

You can store images in MySQL as blobs. However, this is problematic for a couple of reasons:

  • The images can be harder to manipulate: you must first retrieve them from the database before bulk operations can be performed.
  • Except in very rare cases where the entire database is stored in RAM, MySQL databases are ultimately stored on disk. This means that your DB images are converted to blobs, inserted into a database, and then stored on disk; you can save a lot of overhead by simply storing them on disk.

Instead, consider updating your table to add an image_path field. For example:

ALTER TABLE `your_table`
ADD COLUMN `image_path` varchar(1024)

Then store your images on disk, and update the table with the image path. When you need to use the images, retrieve them from disk using the path specified.

An advantageous side-effect of this approach is that the images do not necessarily be stored on disk; you could just as easily store a URL instead of an image path, and retrieve images from any internet-connected location.

Super-simple example of C# observer/observable with delegates

The observer pattern is usually implemented with events.

Here's an example:

using System;

class Observable
{
    public event EventHandler SomethingHappened;

    public void DoSomething() =>
        SomethingHappened?.Invoke(this, EventArgs.Empty);
}

class Observer
{
    public void HandleEvent(object sender, EventArgs args)
    {
        Console.WriteLine("Something happened to " + sender);
    }
}

class Test
{
    static void Main()
    {
        Observable observable = new Observable();
        Observer observer = new Observer();
        observable.SomethingHappened += observer.HandleEvent;

        observable.DoSomething();
    }
}

See the linked article for a lot more detail.

Note that the above example uses C# 6 null-conditional operator to implement DoSomething safely to handle cases where SomethingHappened has not been subscribed to, and is therefore null. If you're using an older version of C#, you'd need code like this:

public void DoSomething()
{
    var handler = SomethingHappened;
    if (handler != null)
    {
        handler(this, EventArgs.Empty);
    }
}

jQuery: How to detect window width on the fly?

I dont know if this useful for you when you resize your page:

$(window).resize(function() {
       if(screen.width == window.innerWidth){
           alert("you are on normal page with 100% zoom");
       } else if(screen.width > window.innerWidth){
           alert("you have zoomed in the page i.e more than 100%");
       } else {
           alert("you have zoomed out i.e less than 100%");
       }
    });

Windows could not start the Apache2 on Local Computer - problem

Remove apache from Control Panel and delete the apache folder from Program Files and restart the machine, then install apache again. This will solve the problem; if not do the following: Install IIS if not installed, then start IIS and stop it ... Using services start apache service... enjoy apache.

Java, how to compare Strings with String Arrays

If I understand your question correctly, it appears you want to know the following:

How do I check if my String array contains usercode, the String that was just inputted?

See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.

Abstract class in Java

A class that is declared using the abstract keyword is known as abstract class. Abstraction is a process of hiding the data implementation details, and showing only functionality to the user. Abstraction lets you focus on what the object does instead of how it does it.

Main things of abstract class

  • An abstract class may or may not contain abstract methods.There can be non abstract methods.

    An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

    ex : abstract void moveTo(double deltaX, double deltaY);

  • If a class has at least one abstract method then that class must be abstract

  • Abstract classes may not be instantiated (You are not allowed to create object of Abstract class)

  • To use an abstract class, you have to inherit it from another class. Provide implementations to all the abstract methods in it.

  • If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

Declare abstract class Specifying abstract keyword before the class during declaration makes it abstract. Have a look at the code below:

abstract class AbstractDemo{ }

Declare abstract method Specifying abstract keyword before the method during declaration makes it abstract. Have a look at the code below,

abstract void moveTo();//no body

Why we need to abstract classes

In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and many other graphic objects. These objects all have certain states (for ex -: position, orientation, line color, fill color) and behaviors (for ex -: moveTo, rotate, resize, draw) in common. Some of these states and behaviors are the same for all graphic objects (for ex : fill color, position, and moveTo). Others require different implementation(for ex: resize or draw). All graphic objects must be able to draw or resize themselves, they just differ in how they do it.

This is a perfect situation for an abstract superclass. You can take advantage of the similarities, and declare all the graphic objects to inherit from the same abstract parent object (for ex : GraphicObject) as shown in the following figure. enter image description here

First, you declare an abstract class, GraphicObject, to provide member variables and methods that are wholly shared by all subclasses, such as the current position and the moveTo method. GraphicObject also declared abstract methods, such as draw or resize, that need to be a implemented by all subclasses but must be implemented in different ways. The GraphicObject class can look something like this:

abstract class GraphicObject {

  void moveTo(int x, int y) {
    // Inside this method we have to change the position of the graphic 
    // object according to x,y     
    // This is the same in every GraphicObject. Then we can implement here. 
  }

  abstract void draw(); // But every GraphicObject drawing case is 
                        // unique, not common. Then we have to create that 
                        // case inside each class. Then create these    
                        // methods as abstract 
  abstract void resize();
}

Usage of abstract method in sub classes Each non abstract subclasses of GraphicObject, such as Circle and Rectangle, must provide implementations for the draw and resize methods.

class Circle extends GraphicObject {
  void draw() {
    //Add to some implementation here
  }
  void resize() {
    //Add to some implementation here   
  }
}
class Rectangle extends GraphicObject {
  void draw() {
    //Add to some implementation here
  }
  void resize() {
    //Add to some implementation here
  }
}

Inside the main method you can call all methods like this:

public static void main(String args[]){
   GraphicObject c = new Circle();
   c.draw();
   c.resize();
   c.moveTo(4,5);   
}

Ways to achieve abstraction in Java

There are two ways to achieve abstraction in java

  • Abstract class (0 to 100%)
  • Interface (100%)

Abstract class with constructors, data members, methods, etc

abstract class GraphicObject {

  GraphicObject (){
    System.out.println("GraphicObject  is created");
  }
  void moveTo(int y, int x) {
       System.out.println("Change position according to "+ x+ " and " + y);
  }
  abstract void draw();
}

class Circle extends GraphicObject {
  void draw() {
    System.out.println("Draw the Circle");
  }
}

class TestAbstract {  
 public static void main(String args[]){

   GraphicObject  grObj = new Circle ();
   grObj.draw();
   grObj.moveTo(4,6);
 }
}

Output:

GraphicObject  is created
Draw the Circle
Change position according to 6 and 4

Remember two rules:

  • If the class has few abstract methods and few concrete methods, declare it as an abstract class.

  • If the class has only abstract methods, declare it as an interface.

References:

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

How to set MimeBodyPart ContentType to "text/html"?

I have used below code in my SpringBoot application.

MimeMessage message = sender.createMimeMessage();
message.setContent(message, "text/html");
MimeMessageHelper helper = new MimeMessageHelper(message);

helper.setFrom(fromAddress);
helper.setTo(toAddress);
helper.setSubject(mailSubject);
helper.setText(mailText, true);

sender.send(message);

LaTeX Optional Arguments

All you need is the following:

\makeatletter
\def\sec#1{\def\tempa{#1}\futurelet\next\sec@i}% Save first argument
\def\sec@i{\ifx\next\bgroup\expandafter\sec@ii\else\expandafter\sec@end\fi}%Check brace
\def\sec@ii#1{\section*{\tempa\ and #1}}%Two args
\def\sec@end{\section*{\tempa}}%Single args
\makeatother

\sec{Hello}
%Output: Hello
\sec{Hello}{Hi}
%Output: Hello and Hi

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

Differences between "java -cp" and "java -jar"?

java -cp CLASSPATH is necesssary if you wish to specify all code in the classpath. This is useful for debugging code.

The jarred executable format: java -jar JarFile can be used if you wish to start the app with a single short command. You can specify additional dependent jar files in your MANIFEST using space separated jars in a Class-Path entry, e.g.:

Class-Path: mysql.jar infobus.jar acme/beans.jar

Both are comparable in terms of performance.

Using jQuery To Get Size of Viewport

Please note that CSS3 viewport units (vh,vw) wouldn't play well on iOS When you scroll the page, viewport size is somehow recalculated and your size of element which uses viewport units also increases. So, actually some javascript is required.

Remove grid, background color, and top and right borders from ggplot2

The above options do not work for maps created with sf and geom_sf(). Hence, I want to add the relevant ndiscr parameter here. This will create a nice clean map showing only the features.

library(sf)
library(ggplot2)

ggplot() + 
  geom_sf(data = some_shp) + 
  theme_minimal() +                     # white background
  theme(axis.text = element_blank(),    # remove geographic coordinates
        axis.ticks = element_blank()) + # remove ticks
  coord_sf(ndiscr = 0)                  # remove grid in the background

Check if date is a valid one

Was able to find the solution. Since the date I am getting is in ISO format, only providing date to moment will validate it, no need to pass the dateFormat.

var date = moment("2016-10-19");

And then date.isValid() gives desired result.

How to edit my Excel dropdown list?

The answers above will work for changing the values.

If you want to change the number of cells in your list (e.g. I have a list called 'revisions' which has 4 items, I now need 7 items) you will find that you can't simply select your list and amend it on the sheet, So:

go to your 'Formulas' tab

choose "Name Manager"

a pop up box will show what is available for editing. Your list should be in it. Select your list and edit the range.

socket.error:[errno 99] cannot assign requested address and namespace in python

when you bind localhost or 127.0.0.1, it means you can only connect to your service from local.

you cannot bind 10.0.0.1 because it not belong to you, you can only bind ip owned by your computer

you can bind 0.0.0.0 because it means all ip on your computer, so any ip can connect to your service if they can connect to any of your ip

How to use passive FTP mode in Windows command prompt?

According to this Egnyte article, Passive FTP is supported from Windows 8.1 onwards.

The Registry key:

"HKEY_CURRENT_USER\Software\Microsoft\FTP\Use PASV"

should be set with the value: yes

If you don't like poking around in the Registry, do the following:

  1. Press WinKey+R to open the Run dialog.
  2. Type inetcpl.cpl and press Enter. The Internet Options dialog will open.
  3. Click on the Advanced tab.
  4. Make your way down to the Browsing secction of the tree view, and ensure the Use Passive FTP item is set to on.
  5. Click on the OK button.

Every time you use ftp.exe, remember to pass the

quote pasv

command immediately after logging in to a remote host.

PS: Grant ftp.exe access to private networks if your Firewall complains.

How can I escape latex code received through user input?

If you want to convert an existing string to raw string, then we can reassign that like below

s1 = "welcome\tto\tPython"
raw_s1 = "%r"%s1
print(raw_s1)

Will print

welcome\tto\tPython

How can I easily convert DataReader to List<T>?

I have written the following method using this case.

First, add the namespace: System.Reflection

For Example: T is return type(ClassName) and dr is parameter to mapping DataReader

C#, Call mapping method like the following:

List<Person> personList = new List<Person>();
personList = DataReaderMapToList<Person>(dataReaderForPerson);

This is the mapping method:

public static List<T> DataReaderMapToList<T>(IDataReader dr)
{
    List<T> list = new List<T>();
    T obj = default(T);
    while (dr.Read()) {
        obj = Activator.CreateInstance<T>();
        foreach (PropertyInfo prop in obj.GetType().GetProperties()) {
            if (!object.Equals(dr[prop.Name], DBNull.Value)) {
                prop.SetValue(obj, dr[prop.Name], null);
            }
        }
        list.Add(obj);
    }
    return list;
}

VB.NET, Call mapping method like the following:

Dim personList As New List(Of Person)
personList = DataReaderMapToList(Of Person)(dataReaderForPerson)

This is the mapping method:

Public Shared Function DataReaderMapToList(Of T)(ByVal dr As IDataReader) As List(Of T)
        Dim list As New List(Of T)
        Dim obj As T
        While dr.Read()
            obj = Activator.CreateInstance(Of T)()
            For Each prop As PropertyInfo In obj.GetType().GetProperties()
                If Not Object.Equals(dr(prop.Name), DBNull.Value) Then
                    prop.SetValue(obj, dr(prop.Name), Nothing)
                End If
            Next
            list.Add(obj)
        End While
        Return list
    End Function

how to compare the Java Byte[] array?

Cause they're not equal, ie: they're different arrays with equal elements inside.

Try using Arrays.equals() or Arrays.deepEquals().

Download data url file

This can be solved 100% entirely with HTML alone. Just set the href attribute to "data:(mimetypeheader),(url)". For instance...

<a
    href="data:video/mp4,http://www.example.com/video.mp4"
    target="_blank"
    download="video.mp4"
>Download Video</a>

Working example: JSFiddle Demo.

Because we use a Data URL, we are allowed to set the mimetype which indicates the type of data to download. Documentation:

Data URLs are composed of four parts: a prefix (data:), a MIME type indicating the type of data, an optional base64 token if non-textual, and the data itself. (Source: MDN Web Docs: Data URLs.)

Components:

  • <a ...> : The link tag.
  • href="data:video/mp4,http://www.example.com/video.mp4" : Here we are setting the link to the a data: with a header preconfigured to video/mp4. This is followed by the header mimetype. I.E., for a .txt file, it would would be text/plain. And then a comma separates it from the link we want to download.
  • target="_blank" : This indicates a new tab should be opened, it's not essential, but it helps guide the browser to the desired behavior.
  • download: This is the name of the file you're downloading.

Setting Column width in Apache POI

With Scala there is a nice Wrapper spoiwo

You can do it like this:

Workbook(mySheet.withColumns(
      Column(autoSized = true),
      Column(width = new Width(100, WidthUnit.Character)),
      Column(width = new Width(100, WidthUnit.Character)))
    )

C# - Multiple generic types in one list

Following leppie's answer, why not make MetaData an interface:

public interface IMetaData { }

public class Metadata<DataType> : IMetaData where DataType : struct
{
    private DataType mDataType;
}

Execution failed for task ':app:compileDebugAidl': aidl is missing

To build your application without aidl is missing error with compileSdkVersion 23 and buildToolsVersion "23.0.1" you should specify latest versions for Android Gradle plugin (and Google Play Services Gradle plugin if you are using it) in main build.gradle file:

buildscript {
    repositories {
        ...
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1'
        classpath 'com.google.gms:google-services:1.3.1'
    }
}

Value Change Listener to JTextField

Add a listener to the underlying Document, which is automatically created for you.

// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
  public void changedUpdate(DocumentEvent e) {
    warn();
  }
  public void removeUpdate(DocumentEvent e) {
    warn();
  }
  public void insertUpdate(DocumentEvent e) {
    warn();
  }

  public void warn() {
     if (Integer.parseInt(textField.getText())<=0){
       JOptionPane.showMessageDialog(null,
          "Error: Please enter number bigger than 0", "Error Message",
          JOptionPane.ERROR_MESSAGE);
     }
  }
});

Credit card expiration dates - Inclusive or exclusive?

If you are writing a site which takes credit card numbers for payment:

  1. You should probably be as permissive as possible, so that if it does expire, you allow the credit card company to catch it. So, allow it until the last second of the last day of the month.
  2. Don't write your own credit card processing code. If^H^HWhen you write a bug, someone will lose real money. We all make mistakes, just don't make decisions that turn your mistakes into catastrophes.

IF - ELSE IF - ELSE Structure in Excel

=IF(CR<=10, "RED", if(CR<50, "YELLOW", if(CR<101, "GREEN")))

CR = ColRow (Cell) This is an example. In this example when value in Cell is less then or equal to 10 then RED word will appear on that cell. In the same manner other if conditions are true if first if is false.

How to include duplicate keys in HashMap?

hashMaps can't have duplicate keys. That said, you can create a map with list values:

Map<Integer, List<String>>

However, using this approach will have performance implications.

Convert PEM traditional private key to PKCS8 private key

Try using following command. I haven't tried it but I think it should work.

openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt

css absolute position won't work with margin-left:auto margin-right: auto

When you are defining styles for division which is positioned absolutely, they specifying margins are useless. Because they are no longer inside the regular DOM tree.

You can use float to do the trick.

.divtagABS {
    float: left;
    margin-left: auto;  
    margin-right:auto;
 }

Make button width fit to the text

If you are developing to a modern browser. https://caniuse.com/#search=fit%20content

You can use:

width: fit-content;

How to inject JPA EntityManager using spring

Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

How can I perform static code analysis in PHP?

I have tried using php -l and a couple of other tools.

However, the best one in my experience (your mileage may vary, of course) is scheck of pfff toolset. I heard about pfff on Quora (Is there a good PHP lint / static analysis tool?).

You can compile and install it. There are no nice packages (on my Linux Mint Debian system, I had to install the libpcre3-dev, ocaml, libcairo-dev, libgtk-3-dev and libgimp2.0-dev dependencies first) but it should be worth an install.

The results are reported like

$ ~/sw/pfff/scheck ~/code/github/sc/
login-now.php:7:4: CHECK: Unused Local variable $title
go-automatic.php:14:77: CHECK: Use of undeclared variable $goUrl.

How to access global js variable in AngularJS directive

Copy the global variable to a variable in the scope in your controller.

function MyCtrl($scope) {
   $scope.variable1 = variable1;
}

Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).

But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.

Android Studio rendering problems

All you had to do is go to styles.xml file and replace your parent theme from

 Theme.AppCompat.Light.DarkActionBar 
to 
 Base.Theme.AppCompat.Light.DarkActionBar

Creating a new database and new connection in Oracle SQL Developer

Open Oracle SQLDeveloper

Right click on connection tab and select new connection

Enter HR_ORCL in connection name and HR for the username and password.

Specify localhost for your Hostname and enter ORCL for the SID.

Click Test.

The status of the connection Test Successfully.

The connection was not saved however click on Save button to save the connection. And then click on Connect button to connect your database.

The connection is saved and you see the connection list.

Run as java application option disabled in eclipse

Run As > Java Application wont show up if the class that you want to run does not contain the main method. Make sure that the class you trying to run has main defined in it.

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Select Help->About

for 64 bit.. it would say version as 64 bit Edition.

I see this in IE 9.. may be true with lesser versions too..

How to quickly clear a JavaScript Object?

Something new to think about looking forward to Object.observe in ES7 and with data-binding in general. Consider:

var foo={
   name: "hello"
};

Object.observe(foo, function(){alert('modified');}); // bind to foo

foo={}; // You are no longer bound to foo but to an orphaned version of it
foo.name="there"; // This change will be missed by Object.observe()

So under that circumstance #2 can be the best choice.

How to get a file or blob from an object URL?

Using fetch for example like below:

 fetch(<"yoururl">, {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + <your access token if need>
    },
       })
.then((response) => response.blob())
.then((blob) => {
// 2. Create blob link to download
 const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `sample.xlsx`);
 // 3. Append to html page
 document.body.appendChild(link);
 // 4. Force download
 link.click();
 // 5. Clean up and remove the link
 link.parentNode.removeChild(link);
})

You can paste in on Chrome console to test. the file with download with 'sample.xlsx' Hope it can help!

Python, add items from txt file into a list

Names = []
for line in open('names.txt','r').readlines():
    Names.append(line.strip())

strip() cut spaces in before and after string...

Java IOException "Too many open files"

For UNIX:

As Stephen C has suggested, changing the maximum file descriptor value to a higher value avoids this problem.

Try looking at your present file descriptor capacity:

   $ ulimit -n

Then change the limit according to your requirements.

   $ ulimit -n <value>

Note that this just changes the limits in the current shell and any child / descendant process. To make the change "stick" you need to put it into the relevant shell script or initialization file.

What is exactly the base pointer and stack pointer? To what do they point?

First of all, the stack pointer points to the bottom of the stack since x86 stacks build from high address values to lower address values. The stack pointer is the point where the next call to push (or call) will place the next value. It's operation is equivalent to the C/C++ statement:

 // push eax
 --*esp = eax
 // pop eax
 eax = *esp++;

 // a function call, in this case, the caller must clean up the function parameters
 move eax,some value
 push eax
 call some address  // this pushes the next value of the instruction pointer onto the
                    // stack and changes the instruction pointer to "some address"
 add esp,4 // remove eax from the stack

 // a function
 push ebp // save the old stack frame
 move ebp, esp
 ... // do stuff
 pop ebp  // restore the old stack frame
 ret

The base pointer is top of the current frame. ebp generally points to your return address. ebp+4 points to the first parameter of your function (or the this value of a class method). ebp-4 points to the first local variable of your function, usually the old value of ebp so you can restore the prior frame pointer.

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

Vue.js data-bind style backgroundImage not working

<div :style="{ backgroundImage: `url(${post.image})` }">

there are multiple ways but i found template string easy and simple

How to export a table dataframe in PySpark to csv?

How about this (in you don't want an one liner) ?

for row in df.collect():
    d = row.asDict()
    s = "%d\t%s\t%s\n" % (d["int_column"], d["string_column"], d["string_column"])
    f.write(s)

f is a opened file descriptor. Also the separator is a TAB char, but it's easy to change to whatever you want.

Free space in a CMD shell

I make a variation to generate this out from script:

volume C: - 49 GB total space / 29512314880 byte(s) free

I use diskpart to get this information.

@echo off
setlocal enableextensions enabledelayedexpansion
set chkfile=drivechk.tmp
if "%1" == "" goto :usage
set drive=%1
set drive=%drive:\=%
set drive=%drive::=%
dir %drive%:>nul 2>%chkfile%
for %%? in (%chkfile%) do (
  set chksize=%%~z?
)
if %chksize% neq 0 (
  more %chkfile%
  del %chkfile%
  goto :eof
)
del %chkfile%
echo list volume | diskpart | find /I " %drive% " >%chkfile%
for /f "tokens=6" %%a in ('type %chkfile%' ) do (
    set dsksz=%%a
)
for /f "tokens=7" %%a in ('type %chkfile%' ) do (
    set dskunit=%%a
)
del %chkfile%
for /f "tokens=3" %%a in ('dir %drive%:\') do (
  set bytesfree=%%a
)
set bytesfree=%bytesfree:,=%
echo volume %drive%: - %dsksz% %dskunit% total space / %bytesfree% byte(s) free
endlocal

goto :eof
:usage
  echo.
  echo   usage: freedisk ^<driveletter^> (eg.: freedisk c)

load jquery after the page is fully loaded

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

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

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

What's the algorithm to calculate aspect ratio?

Here is a version of James Farey's best rational approximation algorithm with adjustable level of fuzziness ported to javascript from the aspect ratio calculation code originally written in python.

The method takes a float (width/height) and an upper limit for the fraction numerator/denominator.

In the example below I am setting an upper limit of 50 because I need 1035x582 (1.77835051546) to be treated as 16:9 (1.77777777778) rather than 345:194 which you get with the plain gcd algorithm listed in other answers.

<html>
<body>
<script type="text/javascript">
function aspect_ratio(val, lim) {

    var lower = [0, 1];
    var upper = [1, 0];

    while (true) {
        var mediant = [lower[0] + upper[0], lower[1] + upper[1]];

        if (val * mediant[1] > mediant[0]) {
            if (lim < mediant[1]) {
                return upper;
            }
            lower = mediant;
        } else if (val * mediant[1] == mediant[0]) {
            if (lim >= mediant[1]) {
                return mediant;
            }
            if (lower[1] < upper[1]) {
                return lower;
            }
            return upper;
        } else {
            if (lim < mediant[1]) {
                return lower;
            }
            upper = mediant;
        }
    }
}

document.write (aspect_ratio(800 / 600, 50) +"<br/>");
document.write (aspect_ratio(1035 / 582, 50) + "<br/>");
document.write (aspect_ratio(2560 / 1440, 50) + "<br/>");

    </script>
</body></html>

The result:

 4,3  // (1.33333333333) (800 x 600)
 16,9 // (1.77777777778) (2560.0 x 1440)
 16,9 // (1.77835051546) (1035.0 x 582)

How do I vertically align text in a paragraph?

You can use line-height for that. Just set it up to the exact height of your p tag.

p.event_desc {
  line-height:35px;
}

Initializing a two dimensional std::vector

vector<vector<int>> board;
for(int i=0;i<m;i++) {
    board.push_back({});
    for(int j=0;j<n;j++) {
        board[i].push_back(0);
    }
}

This code snippet first inserts an empty vector at each turn, in the other nested loop it pushes the elements inside the vector created by the outer loop. Hope this solves the problem.

How do I build an import library (.lib) AND a DLL in Visual C++?

you also should specify def name in the project settings here:

Configuration > Properties/Input/Advanced/Module > Definition File

Two Decimal places using c#

Your question is asking to display two decimal places. Using the following String.format will help:

String.Format("{0:.##}", Debitvalue)

this will display then number with up to two decimal places(e.g. 2.10 would be shown as 2.1 ).

Use "{0:.00}", if you want always show two decimal places(e.g. 2.10 would be shown as 2.10 )

Or if you want the currency symbol displayed use the following:

String.Format("{0:C}", Debitvalue)

What is the difference between Select and Project Operations

The difference come in relational algebra where project affects columns and select affect rows. However in query syntax, select is the word. There is no such query as project. Assuming there is a table named users with hundreds of thousands of records (rows) and the table has 6 fields (userID, Fname,Lname,age,pword,salary). Lets say we want to restrict access to sensitive data (userID,pword and salary) and also restrict amount of data to be accessed. In mysql maria DB we create a view as follows ( Create view user1 as select Fname,Lname, age from users limit 100;) from our view we issue (select Fname from users1;) . This query is both a select and a project

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

As Filburt says; but also note that it's usually better to write

test="not(Count = 'N/A')"

If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.

6 YEARS LATER

Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.

The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.

In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA") returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA" returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA") is the appropriate formulation.

How do I set the path to a DLL file in Visual Studio?

The search path that the loader uses when you call LoadLibrary() can be altered by using the SetDllDirectory() function. So you could just call this and add the path to your dependency before you load it.

See also DLL Search Order.

PHP cURL not working - WAMP on Windows 7 64 bit

Well, just uninstall WAMP 64-bit and go with the 32-bit version. It worked in my case.

subtract two times in python

You have two datetime.time objects so for that you just create two timedelta using datetime.timedetla and then substract as you do right now using "-" operand. Following is the example way to substract two times without using datetime.

enter = datetime.time(hour=1)  # Example enter time
exit = datetime.time(hour=2)  # Example start time
enter_delta = datetime.timedelta(hours=enter.hour, minutes=enter.minute, seconds=enter.second)
exit_delta = datetime.timedelta(hours=exit.hour, minutes=exit.minute, seconds=exit.second)
difference_delta = exit_delta - enter_delta

difference_delta is your difference which you can use for your reasons.

ASP.NET MVC - passing parameters to the controller

To rephrase Jarret Meyer's answer, you need to change the parameter name to 'id' or add a route like this:

routes.MapRoute(
        "ViewStockNext", // Route name
        "Inventory/ViewStockNext/{firstItem}",  // URL with parameters
        new { controller = "Inventory", action = "ViewStockNext" }  // Parameter defaults
    );

The reason is the default route only looks for actions with no parameter or a parameter called 'id'.

Edit: Heh, nevermind Jarret added a route example after posting.

right align an image using CSS HTML

There are a few different ways to do this but following is a quick sample of one way.

<img src="yourimage.jpg" style="float:right" /><div style="clear:both">Your text here.</div>

I used inline styles for this sample but you can easily place these in a stylesheet and reference the class or id.

Calling a Function defined inside another function in Javascript

Again, not a direct answer to the question, but was led here by a web search. Ended up exposing the inner function without using return, etc. by simply assigning it to a global variable.

var fname;

function outer() {
    function inner() {
        console.log("hi");
    }
    fname = inner;
}

Now just

fname();

Adjusting the Xcode iPhone simulator scale and size

You can set any scale you wish. It`s became actual after 6+ simulator been presented

To obtain it follow next easy steps:

  1. quit simulator if open
  2. open terminal (from spotlight for example)
  3. paste next text to terminal and press enter

defaults write ~/Library/Preferences/com.apple.iphonesimulator SimulatorWindowLastScale "0.4"

You can try any scales changing 0.4 to desired value.

To reset this custom scale, just apply any standard scale from simulator menu in way described above.

Getting the difference between two repositories

See http://git.or.cz/gitwiki/GitTips, section "How to compare two local repositories" in "General".

In short you are using GIT_ALTERNATE_OBJECT_DIRECTORIES environment variable to have access to object database of the other repository, and using git rev-parse with --git-dir / GIT_DIR to convert symbolic name in other repository to SHA-1 identifier.

Modern version would look something like this (assuming that you are in 'repo_a'):

GIT_ALTERNATE_OBJECT_DIRECTORIES=../repo_b/.git/objects \
   git diff $(git --git-dir=../repo_b/.git rev-parse --verify HEAD) HEAD

where ../repo_b/.git is path to object database in repo_b (it would be repo_b.git if it were bare repository). Of course you can compare arbitrary versions, not only HEADs.


Note that if repo_a and repo_b are the same repository, it might make more sense to put both of them in the same repository, either using "git remote add -f ..." to create nickname(s) for repository for repeated updates, or obe off "git fetch ..."; as described in other responses.

Removing Duplicate Values from ArrayList

public static List<String> removeDuplicateElements(List<String> array){
    List<String> temp = new ArrayList<String>();
    List<Integer> count = new ArrayList<Integer>();
    for (int i=0; i<array.size()-2; i++){
        for (int j=i+1;j<array.size()-1;j++)
            {
                if (array.get(i).compareTo(array.get(j))==0) {
                    count.add(i);
                    int kk = i;
                }
            }
        }
        for (int i = count.size()+1;i>0;i--) {
            array.remove(i);
        }
        return array;
    }
}