Programs & Examples On #Getsystemmetrics

Java BigDecimal: Round to the nearest whole value

I don't think you can round it like that in a single command. Try

    ArrayList<BigDecimal> list = new ArrayList<BigDecimal>();
    list.add(new BigDecimal("100.12"));
    list.add(new BigDecimal("100.44"));
    list.add(new BigDecimal("100.50"));
    list.add(new BigDecimal("100.75"));

    for (BigDecimal bd : list){
        System.out.println(bd+" -> "+bd.setScale(0,RoundingMode.HALF_UP).setScale(2));
    }

Output:
100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.

How to get the nth element of a python list or a default if not available

(a[n:]+[default])[0]

This is probably better as a gets larger

(a[n:n+1]+[default])[0]

This works because if a[n:] is an empty list if n => len(a)

Here is an example of how this works with range(5)

>>> range(5)[3:4]
[3]
>>> range(5)[4:5]
[4]
>>> range(5)[5:6]
[]
>>> range(5)[6:7]
[]

And the full expression

>>> (range(5)[3:4]+[999])[0]
3
>>> (range(5)[4:5]+[999])[0]
4
>>> (range(5)[5:6]+[999])[0]
999
>>> (range(5)[6:7]+[999])[0]
999

A simple command line to download a remote maven2 artifact to the local repository?

Since version 2.1 of the Maven Dependency Plugin, there is a dependency:get goal for this purpose. To make sure you are using the right version of the plugin, you'll need to use the "fully qualified name":

mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \
    -DrepoUrl=http://download.java.net/maven/2/ \
    -Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT

How can I show current location on a Google Map on Android Marshmallow?

For using FusedLocationProviderClient with Google Play Services 11 and higher:

see here: How to get current Location in GoogleMap using FusedLocationProviderClient

For using (now deprecated) FusedLocationProviderApi:

If your project uses Google Play Services 10 or lower, using the FusedLocationProviderApi is the optimal choice.

The FusedLocationProviderApi offers less battery drain than the old open source LocationManager API. Also, if you're already using Google Play Services for Google Maps, there's no reason not to use it.

Here is a full Activity class that places a Marker at the current location, and also moves the camera to the current position.

It also checks for the Location permission at runtime for Android 6 and later (Marshmallow, Nougat, Oreo). In order to properly handle the Location permission runtime check that is necessary on Android M/Android 6 and later, you need to ensure that the user has granted your app the Location permission before calling mGoogleMap.setMyLocationEnabled(true) and also before requesting location updates.

public class MapLocationActivity extends AppCompatActivity
        implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;

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

        getSupportActionBar().setTitle("Map Location Activity");

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {}

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {}

    @Override
    public void onLocationChanged(Location location)
    {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

        //move map camera
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapLocationActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        tools:context=".MapLocationActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

Result:

Show permission explanation if needed using an AlertDialog (this happens if the user denies a permission request, or grants the permission and then later revokes it in the settings):

enter image description here

Prompt the user for Location permission by calling ActivityCompat.requestPermissions():

enter image description here

Move camera to current location and place Marker when the Location permission is granted:

enter image description here

How to remove the last character from a bash grep output

you can strip the beginnings and ends of a string by N characters using this bash construct, as someone said already

$ fred=abcdefg.rpm
$ echo ${fred:1:-4}
bcdefg

HOWEVER, this is not supported in older versions of bash.. as I discovered just now writing a script for a Red hat EL6 install process. This is the sole reason for posting here. A hacky way to achieve this is to use sed with extended regex like this:

$ fred=abcdefg.rpm
$ echo $fred | sed -re 's/^.(.*)....$/\1/g'
bcdefg

How to initialize a list of strings (List<string>) with many string values

This is how you would do it.

_x000D_
_x000D_
List <string> list1 = new List <string>();
_x000D_
_x000D_
_x000D_

Do Not Forget to add

_x000D_
_x000D_
using System.Collections.Generic;
_x000D_
_x000D_
_x000D_

Trigger change() event when setting <select>'s value with val() function

As jQuery won't trigger native change event but only triggers its own change event. If you bind event without jQuery and then use jQuery to trigger it the callbacks you bound won't run !

The solution is then like below (100% working) :

var sortBySelect = document.querySelector("select.your-class"); 
sortBySelect.value = "new value"; 
sortBySelect.dispatchEvent(new Event("change"));

Ineligible Devices section appeared in Xcode 6.x.x

After trying the 2 answers above (changing deployment target and restarting my iOS device), what finally fixed it for me was restarting my Mac.

Entity Framework Code First - two Foreign Keys from same table

InverseProperty in EF Core makes the solution easy and clean.

InverseProperty

So the desired solution would be:

public class Team
{
    [Key]
    public int TeamId { get; set;} 
    public string Name { get; set; }

    [InverseProperty(nameof(Match.HomeTeam))]
    public ICollection<Match> HomeMatches{ get; set; }

    [InverseProperty(nameof(Match.GuestTeam))]
    public ICollection<Match> AwayMatches{ get; set; }
}


public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey(nameof(HomeTeam)), Column(Order = 0)]
    public int HomeTeamId { get; set; }
    [ForeignKey(nameof(GuestTeam)), Column(Order = 1)]
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public Team HomeTeam { get; set; }
    public Team GuestTeam { get; set; }
}

Adding input elements dynamically to form

You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():

If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.

Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.

Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.

_x000D_
_x000D_
<html>
<head>
    <script type='text/javascript'>
        function addFields(){
            // Number of inputs to create
            var number = document.getElementById("member").value;
            // Container <div> where dynamic content will be placed
            var container = document.getElementById("container");
            // Clear previous contents of the container
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }
            for (i=0;i<number;i++){
                // Append a node with a random text
                container.appendChild(document.createTextNode("Member " + (i+1)));
                // Create an <input> element, set its type and name attributes
                var input = document.createElement("input");
                input.type = "text";
                input.name = "member" + i;
                container.appendChild(input);
                // Append a line break 
                container.appendChild(document.createElement("br"));
            }
        }
    </script>
</head>
<body>
    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    <div id="container"/>
</body>
</html>
_x000D_
_x000D_
_x000D_

See a working sample in this JSFiddle.

When saving, how can you check if a field has changed?

I use following mixin:

from django.forms.models import model_to_dict


class ModelDiffMixin(object):
    """
    A model mixin that tracks model fields' values and provide some useful api
    to know what fields have been changed.
    """

    def __init__(self, *args, **kwargs):
        super(ModelDiffMixin, self).__init__(*args, **kwargs)
        self.__initial = self._dict

    @property
    def diff(self):
        d1 = self.__initial
        d2 = self._dict
        diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
        return dict(diffs)

    @property
    def has_changed(self):
        return bool(self.diff)

    @property
    def changed_fields(self):
        return self.diff.keys()

    def get_field_diff(self, field_name):
        """
        Returns a diff for field if it's changed and None otherwise.
        """
        return self.diff.get(field_name, None)

    def save(self, *args, **kwargs):
        """
        Saves model and set initial state.
        """
        super(ModelDiffMixin, self).save(*args, **kwargs)
        self.__initial = self._dict

    @property
    def _dict(self):
        return model_to_dict(self, fields=[field.name for field in
                             self._meta.fields])

Usage:

>>> p = Place()
>>> p.has_changed
False
>>> p.changed_fields
[]
>>> p.rank = 42
>>> p.has_changed
True
>>> p.changed_fields
['rank']
>>> p.diff
{'rank': (0, 42)}
>>> p.categories = [1, 3, 5]
>>> p.diff
{'categories': (None, [1, 3, 5]), 'rank': (0, 42)}
>>> p.get_field_diff('categories')
(None, [1, 3, 5])
>>> p.get_field_diff('rank')
(0, 42)
>>>

Note

Please note that this solution works well in context of current request only. Thus it's suitable primarily for simple cases. In concurrent environment where multiple requests can manipulate the same model instance at the same time, you definitely need a different approach.

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

    String str1,str2;
    Scanner S=new Scanner(System.in);
    str1=S.nextLine();
    System.out.println(str1);
    str2=S.nextLine();
    str1=str1.concat(str2);
    System.out.println(str1.toLowerCase()); 

Stop fixed position at footer

$(window).scroll(() => {
    const footerToTop = $('.your-footer').position().top;
    const scrollTop = $(document).scrollTop() + $(window).height();
    const difference = scrollTop - footerToTop;
    const bottomValue = scrollTop > footerToTop ? difference : 0;
    $('.your-fixed-element').css('bottom', bottomValue);
});

Switching from zsh to bash on OSX, and back again?

I switch between zsh and bash somewhat frequently. For a while, I used to have to source my bash_profile every switch. Then I found out you can (typically) do

exec bash --login

or just

exec bash -l

Why use deflate instead of gzip for text files served by Apache?

Why use deflate instead of gzip for text files served by Apache?

The simple answer is don't.


RFC 2616 defines deflate as:

deflate The "zlib" format defined in RFC 1950 in combination with the "deflate" compression mechanism described in RFC 1951

The zlib format is defined in RFC 1950 as :

     0   1
     +---+---+
     |CMF|FLG|   (more-->)
     +---+---+

       0   1   2   3
     +---+---+---+---+
     |     DICTID    |   (more-->)
     +---+---+---+---+

     +=====================+---+---+---+---+
     |...compressed data...|    ADLER32    |
     +=====================+---+---+---+---+

So, a few headers and an ADLER32 checksum

RFC 2616 defines gzip as:

gzip An encoding format produced by the file compression program "gzip" (GNU zip) as described in RFC 1952 [25]. This format is a Lempel-Ziv coding (LZ77) with a 32 bit CRC.

RFC 1952 defines the compressed data as:

The format presently uses the DEFLATE method of compression but can be easily extended to use other compression methods.

CRC-32 is slower than ADLER32

Compared to a cyclic redundancy check of the same length, it trades reliability for speed (preferring the latter).

So ... we have 2 compression mechanisms that use the same algorithm for compression, but a different algorithm for headers and checksum.

Now, the underlying TCP packets are already pretty reliable, so the issue here is not Adler 32 vs CRC-32 that GZIP uses.


Turns out many browsers over the years implemented an incorrect deflate algorithm. Instead of expecting the zlib header in RFC 1950 they simply expected the compressed payload. Similarly various web servers made the same mistake.

So, over the years browsers started implementing a fuzzy logic deflate implementation, they try for zlib header and adler checksum, if that fails they try for payload.

The result of having complex logic like that is that it is often broken. Verve Studio have a user contributed test section that show how bad the situation is.

For example: deflate works in Safari 4.0 but is broken in Safari 5.1, it also always has issues on IE.


So, best thing to do is avoid deflate altogether, the minor speed boost (due to adler 32) is not worth the risk of broken payloads.

Defining a HTML template to append using JQuery

Old question, but since the question asks "using jQuery", I thought I'd provide an option that lets you do this without introducing any vendor dependency.

While there are a lot of templating engines out there, many of their features have fallen in to disfavour recently, with iteration (<% for), conditionals (<% if) and transforms (<%= myString | uppercase %>) seen as microlanguage at best, and anti-patterns at worst. Modern templating practices encourage simply mapping an object to its DOM (or other) representation, e.g. what we see with properties mapped to components in ReactJS (especially stateless components).

Templates Inside HTML

One property you can rely on for keeping the HTML for your template next to the rest of your HTML, is by using a non-executing <script> type, e.g. <script type="text/template">. For your case:

<script type="text/template" data-template="listitem">
    <a href="${url}" class="list-group-item">
        <table>
            <tr>
                <td><img src="${img}"></td>
                <td><p class="list-group-item-text">${title}</p></td>
            </tr>
        </table>
    </a>
</script>

On document load, read your template and tokenize it using a simple String#split

var itemTpl = $('script[data-template="listitem"]').text().split(/\$\{(.+?)\}/g);

Notice that with our token, you get it in the alternating [text, property, text, property] format. This lets us nicely map it using an Array#map, with a mapping function:

function render(props) {
  return function(tok, i) { return (i % 2) ? props[tok] : tok; };
}

Where props could look like { url: 'http://foo.com', img: '/images/bar.png', title: 'Lorem Ipsum' }.

Putting it all together assuming you've parsed and loaded your itemTpl as above, and you have an items array in-scope:

$('.search').keyup(function () {
  $('.list-items').append(items.map(function (item) {
    return itemTpl.map(render(item)).join('');
  }));
});

This approach is also only just barely jQuery - you should be able to take the same approach using vanilla javascript with document.querySelector and .innerHTML.

jsfiddle

Templates inside JS

A question to ask yourself is: do you really want/need to define templates as HTML files? You can always componentize + re-use a template the same way you'd re-use most things you want to repeat: with a function.

In es7-land, using destructuring, template strings, and arrow-functions, you can write downright pretty looking component functions that can be easily loaded using the $.fn.html method above.

const Item = ({ url, img, title }) => `
  <a href="${url}" class="list-group-item">
    <div class="image">
      <img src="${img}" />
    </div>
    <p class="list-group-item-text">${title}</p>
  </a>
`;

Then you could easily render it, even mapped from an array, like so:

$('.list-items').html([
  { url: '/foo', img: 'foo.png', title: 'Foo item' },
  { url: '/bar', img: 'bar.png', title: 'Bar item' },
].map(Item).join(''));

Oh and final note: don't forget to sanitize your properties passed to a template, if they're read from a DB, or someone could pass in HTML (and then run scripts, etc.) from your page.

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

You can get a non-js-based redirection from an ajax call by putting in one of those meta refresh tags. This here seems to be working: return Content("<meta http-equiv=\"refresh\" content=\"0;URL='" + @Url.Action("Index", "Home") + "'\" />");

Note: I discovered that meta refreshes are auto-disabled by Firefox, rendering this not very useful.

Most efficient way to check for DBNull and then assign to a variable?

I try to avoid this check as much as possible.

Obviously doesn't need to be done for columns that can't hold null.

If you're storing in a Nullable value type (int?, etc.), you can just convert using as int?.

If you don't need to differentiate between string.Empty and null, you can just call .ToString(), since DBNull will return string.Empty.

OrderBy descending in Lambda expression?

Try this:

List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(4);
list.Add(3);
list.Add(2);

foreach (var item in list.OrderByDescending(x => x))
{
    Console.WriteLine(item);                
}

How to get name of dataframe column in pyspark?

The only way is to go an underlying level to the JVM.

df.col._jc.toString().encode('utf8')

This is also how it is converted to a str in the pyspark code itself.

From pyspark/sql/column.py:

def __repr__(self):
    return 'Column<%s>' % self._jc.toString().encode('utf8')

Understanding the map function

Python3 - map(func, iterable)

One thing that wasn't mentioned completely (although @BlooB kinda mentioned it) is that map returns a map object NOT a list. This is a big difference when it comes to time performance on initialization and iteration. Consider these two tests.

import time
def test1(iterable):
    a = time.clock()
    map(str, iterable)
    a = time.clock() - a

    b = time.clock()
    [ str(x) for x in iterable ]
    b = time.clock() - b

    print(a,b)


def test2(iterable):
    a = time.clock()
    [ x for x in map(str, iterable)]
    a = time.clock() - a

    b = time.clock()
    [ str(x) for x in iterable ]
    b = time.clock() - b

    print(a,b)


test1(range(2000000))  # Prints ~1.7e-5s   ~8s
test2(range(2000000))  # Prints ~9s        ~8s

As you can see initializing the map function takes almost no time at all. However iterating through the map object takes longer than simply iterating through the iterable. This means that the function passed to map() is not applied to each element until the element is reached in the iteration. If you want a list use list comprehension. If you plan to iterate through in a for loop and will break at some point, then use map.

Solving Quadratic Equation

# syntaxis:2.7
# solution for quadratic equation
# a*x**2 + b*x + c = 0

d = b**2-4*a*c # discriminant

if d < 0:
    print 'No solutions'
elif d == 0:
    x1 = -b / (2*a)
    print 'The sole solution is',x1
else: # if d > 0
    x1 = (-b + math.sqrt(d)) / (2*a)
    x2 = (-b - math.sqrt(d)) / (2*a)
    print 'Solutions are',x1,'and',x2

Java - How to create a custom dialog box?

i created a custom dialog API. check it out here https://github.com/MarkMyWord03/CustomDialog. It supports message and confirmation box. input and option dialog just like in joptionpane will be implemented soon.

Sample Error Dialog from CUstomDialog API: CustomDialog Error Message

Removing NA observations with dplyr::filter()

For example:

you can use:

df %>% filter(!is.na(a))

to remove the NA in column a.

Call multiple functions onClick ReactJS

this onclick={()=>{ f1(); f2() }} helped me a lot if i want two different functions at the same time. But now i want to create an audiorecorder with only one button. So if i click first i want to run the StartFunction f1() and if i click again then i want to run StopFunction f2().

How do you guys realize this?

Detect when an HTML5 video finishes

JQUERY

$("#video1").bind("ended", function() {
   //TO DO: Your code goes here...
});

HTML

<video id="video1" width="420">
  <source src="path/filename.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

Event types HTML Audio and Video DOM Reference

Example on ToggleButton

Move this

 btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
     editString = ed.getText().toString();

inside onClick

Also you change the state of the toogle button whether its 0 or 1

http://developer.android.com/guide/topics/ui/controls/togglebutton.html

Example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="20dp"
        android:text="Button" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="26dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="51dp"
        android:text="Switch" />

    <ToggleButton
        android:id="@+id/togglebutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/switch1"
        android:layout_marginTop="58dp"
        android:onClick="onToggleClicked"
        android:textOff="Vibrate off"
        android:textOn="Vibrate on" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity implements OnClickListener {

    EditText ed;
    Switch sb;
    ToggleButton tb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ed = (EditText) findViewById(R.id.editText1);
        Button b = (Button) findViewById(R.id.button1);
        sb = (Switch)findViewById(R.id.switch1);
        tb = (ToggleButton)findViewById(R.id.togglebutton);
        b.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        String s = ed.getText().toString();
         if(s.equals("1")){

             tb.setText("TOGGLE ON");
             tb.setActivated(true);
             sb.setChecked(true);

         }
         else if(s.equals("0")){

             tb.setText("TOGGLE OFF");
             tb.setActivated(false);
             sb.setChecked(false);

    }

    }
     }

Snaps

enter image description here

enter image description here

Java ArrayList replace at specific index

Check out the set(int index, E element) method in the List interface

No plot window in matplotlib

Modern IPython uses the "--matplotlib" argument with an optional backend parameter. It defaults to "auto", which is usually good enough on Mac and Windows. I haven't tested it on Ubuntu or any other Linux distribution, but I would expect it to work.

ipython --matplotlib

Global Events in Angular

This is my version:

export interface IEventListenr extends OnDestroy{
    ngOnDestroy(): void
}

@Injectable()
export class EventManagerService {


    private listeners = {};
    private subject = new EventEmitter();
    private eventObserver = this.subject.asObservable();


    constructor() {

        this.eventObserver.subscribe(({name,args})=>{



             if(this.listeners[name])
             {
                 for(let listener of this.listeners[name])
                 {
                     listener.callback(args);
                 }
             }
        })

    }

    public registerEvent(eventName:string,eventListener:IEventListenr,callback:any)
    {

        if(!this.listeners[eventName])
             this.listeners[eventName] = [];

         let eventExist = false;
         for(let listener of this.listeners[eventName])
         {

             if(listener.eventListener.constructor.name==eventListener.constructor.name)
             {
                 eventExist = true;
                 break;
             }
         }

        if(!eventExist)
        {
             this.listeners[eventName].push({eventListener,callback});
        }
    }

    public unregisterEvent(eventName:string,eventListener:IEventListenr)
    {

        if(this.listeners[eventName])
        {
            for(let i = 0; i<this.listeners[eventName].length;i++)
            {

                if(this.listeners[eventName][i].eventListener.constructor.name==eventListener.constructor.name)
                {
                    this.listeners[eventName].splice(i, 1);
                    break;
                }
            }
        }


    }


    emit(name:string,...args:any[])
    {
        this.subject.next({name,args});
    }
}

use:

export class <YOURCOMPONENT> implements IEventListener{

  constructor(private eventManager: EventManagerService) {


    this.eventManager.registerEvent('EVENT_NAME',this,(args:any)=>{
       ....
    })


  }

  ngOnDestroy(): void {
    this.eventManager.unregisterEvent('closeModal',this)
  }

}

emit:

 this.eventManager.emit("EVENT_NAME");

Most useful NLog configurations

Log to Twitter

Based on this post about a log4net Twitter Appender, I thought I would try my hand at writing a NLog Twitter Target (using NLog 1.0 refresh, not 2.0). Alas, so far I have not been able to get a Tweet to actually post successfully. I don't know if it is something wrong in my code, Twitter, our company's internet connection/firewall, or what. I am posting the code here in case someone is interested in trying it out. Note that there are three different "Post" methods. The first one that I tried is PostMessageToTwitter. PostMessageToTwitter is essentially the same as PostLoggingEvent in the orignal post. If I use that I get a 401 exception. PostMessageBasic gets the same exception. PostMessage runs with no errors, but the message still does not make it up to Twitter. PostMessage and PostMessageBasic are based on examples that I found here on SO.

FYI - I just now found a comment by @Jason Diller to an answer in this post that says that twitter is going to turn off basic authentication "next month". This was back in May 2010 and it is now December 2010, so I guess that could be why this is not working.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.IO;

using NLog;
using NLog.Targets;
using NLog.Config;

namespace NLogExtensions
{
  [Target("TwitterTarget")]
  public class TwitterTarget : TargetWithLayout
  {
    private const string REQUEST_CONTENT_TYPE = "application/x-www-form-urlencoded";  

    private const string REQUEST_METHOD = "POST";  

    // The source attribute has been removed from the Twitter API,  
    // unless you're using OAuth.  
    // Even if you are using OAuth, there's still an approval process.  
    // Not worth it; "API" will work for now!  
    // private const string TWITTER_SOURCE_NAME = "Log4Net";  
    private const string TWITTER_UPDATE_URL_FORMAT = "http://twitter.com/statuses/update.xml?status={0}";  

    [RequiredParameter]
    public string TwitterUserName { get; set; }

    [RequiredParameter]
    public string TwitterPassword { get; set; }

    protected override void Write(LogEventInfo logEvent)
    {
      if (string.IsNullOrWhiteSpace(TwitterUserName) || string.IsNullOrWhiteSpace(TwitterPassword)) return;

      string msg = this.CompiledLayout.GetFormattedMessage(logEvent);

      if (string.IsNullOrWhiteSpace(msg)) return;

      try
      {
        //PostMessageToTwitter(msg);
        PostMessageBasic(msg);
      }
      catch (Exception ex)
      {
        //Should probably do something here ...
      }
    }

    private void PostMessageBasic(string msg)
    {
      // Create a webclient with the twitter account credentials, which will be used to set the HTTP header for basic authentication 
      WebClient client = new WebClient { Credentials = new NetworkCredential { UserName = TwitterUserName, Password = TwitterPassword } };

      // Don't wait to receive a 100 Continue HTTP response from the server before sending out the message body 
      ServicePointManager.Expect100Continue = false;

      // Construct the message body 
      byte[] messageBody = Encoding.ASCII.GetBytes("status=" + msg);

      // Send the HTTP headers and message body (a.k.a. Post the data) 
      client.UploadData(@"http://twitter.com/statuses/update.xml", messageBody);
    }

    private void PostMessage(string msg)
    {
      string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(TwitterUserName + ":" + TwitterPassword));
      byte [] bytes = System.Text.Encoding.UTF8.GetBytes("status=" + msg.ToTweet());
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
      request.Method = "POST";
      request.ServicePoint.Expect100Continue = false;
      request.Headers.Add("Authorization", "Basic " + user);
      request.ContentType = "application/x-www-form-urlencoded";
      request.ContentLength = bytes.Length;
      Stream reqStream = request.GetRequestStream();
      reqStream.Write(bytes, 0, bytes.Length);
      reqStream.Close();
    }

    private void PostMessageToTwitter(string msg)
    {
      var updateRequest = HttpWebRequest.Create(string.Format(TWITTER_UPDATE_URL_FORMAT,
                                                HttpUtility.UrlEncode(msg.ToTweet()))) as HttpWebRequest;
      updateRequest.ContentLength = 0;
      updateRequest.ContentType = REQUEST_CONTENT_TYPE;
      updateRequest.Credentials = new NetworkCredential(TwitterUserName, TwitterPassword);
      updateRequest.Method = REQUEST_METHOD;

      updateRequest.ServicePoint.Expect100Continue = false;

      var updateResponse = updateRequest.GetResponse() as HttpWebResponse;

      if (updateResponse.StatusCode != HttpStatusCode.OK && updateResponse.StatusCode != HttpStatusCode.Continue)
      {
        throw new Exception(string.Format("An error occurred while invoking the Twitter REST API [Response Code: {0}]", updateResponse.StatusCode));
      }
    }
  }

  public static class Extensions
  {
    public static string ToTweet(this string s)
    {
      if (string.IsNullOrEmpty(s) || s.Length < 140)
      {
        return s;
      }

      return s.Substring(0, 137) + "...";
    }
  }
}

Configure it like this:

Tell NLog the assembly containing the target:

<extensions>
  <add assembly="NLogExtensions"/>
</extensions>

Configure the target:

<targets>
    <target name="twitter" type="TwitterTarget" TwitterUserName="yourtwittername" TwitterPassword="yourtwitterpassword" layout="${longdate} ${logger} ${level} ${message}" />
</targets>

If someone tries this out and has success, post back with your findings.

Launch an app from within another (iPhone)

In Swift 4.1 and Xcode 9.4.1

I have two apps 1)PageViewControllerExample and 2)DelegateExample. Now i want to open DelegateExample app with PageViewControllerExample app. When i click open button in PageViewControllerExample, DelegateExample app will be opened.

For this we need to make some changes in .plist files for both the apps.

Step 1

In DelegateExample app open .plist file and add URL Types and URL Schemes. Here we need to add our required name like "myapp".

enter image description here

Step 2

In PageViewControllerExample app open .plist file and add this code

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>myapp</string>
</array>

Now we can open DelegateExample app when we click button in PageViewControllerExample.

//In PageViewControllerExample create IBAction
@IBAction func openapp(_ sender: UIButton) {

    let customURL = URL(string: "myapp://")
    if UIApplication.shared.canOpenURL(customURL!) {

        //let systemVersion = UIDevice.current.systemVersion//Get OS version
        //if Double(systemVersion)! >= 10.0 {//10 or above versions
            //print(systemVersion)
            //UIApplication.shared.open(customURL!, options: [:], completionHandler: nil)
        //} else {
            //UIApplication.shared.openURL(customURL!)
        //}

        //OR

        if #available(iOS 10.0, *) {
            UIApplication.shared.open(customURL!, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(customURL!)
        }
    } else {
         //Print alert here
    }
}

How to give color to each class in scatter plot in R?

One way is to use the lattice package and xyplot():

R> DF <- data.frame(x=1:10, y=rnorm(10)+5, 
+>                  z=sample(letters[1:3], 10, replace=TRUE))
R> DF
    x       y z
1   1 3.91191 c
2   2 4.57506 a
3   3 3.16771 b
4   4 5.37539 c
5   5 4.99113 c
6   6 5.41421 a
7   7 6.68071 b
8   8 5.58991 c
9   9 5.03851 a
10 10 4.59293 b
R> with(DF, xyplot(y ~ x, group=z))

By giving explicit grouping information via variable z, you obtain different colors. You can specify colors etc, see the lattice documentation.

Because z here is a factor variable for which we obtain the levels (== numeric indices), you can also do

R> with(DF, plot(x, y, col=z))

but that is less transparent (to me, at least :) then xyplot() et al.

How to call a parent class function from derived class function?

Given a parent class named Parent and a child class named Child, you can do something like this:

class Parent {
public:
    virtual void print(int x);
};

class Child : public Parent {
    void print(int x) override;
};

void Parent::print(int x) {
    // some default behavior
}

void Child::print(int x) {
    // use Parent's print method; implicitly passes 'this' to Parent::print
    Parent::print(x);
}

Note that Parent is the class's actual name and not a keyword.

Best Way to View Generated Source of Webpage?

I know this is an old post, but I just found this piece of gold. This is old (2006), but still works with IE9. I personnally added a bookmark with this.

Just copy paste this in your browser's address bar:

javascript:void(window.open("javascript:document.open(\"text/plain\");document.write(opener.document.body.parentNode.outerHTML)"))

As for firefox, web developper tool bar does the job. I usually use this, but sometimes, some dirty 3rd party asp.net controls generates differents markups based on the user agent...

EDIT

As Bryan pointed in the comment, some browser remove the javascript: part when copy/pasting in url bar. I just tested and that's the case with IE10.

Sql Query to list all views in an SQL Server 2005 database

Run this adding DatabaseName in where condition.

  SELECT TABLE_NAME, ROW_NUMBER() OVER(ORDER BY TABLE_NAME) AS 'RowNumber' 
  FROM INFORMATION_SCHEMA.VIEWS 
  WHERE TABLE_CATALOG = 'DatabaseName'

or remove where condition adding use.

  use DataBaseName

  SELECT TABLE_NAME, ROW_NUMBER() OVER(ORDER BY TABLE_NAME) AS 'RowNumber' 
  FROM INFORMATION_SCHEMA.VIEWS 

How to get the contents of a webpage in a shell variable?

There is the wget command or the curl.

You can now use the file you downloaded with wget. Or you can handle a stream with curl.


Resources :

How to exclude 0 from MIN formula Excel

By far the most efficient method is to use the SMALL and COUNTIF formula as shown below;

SMALL Returns the k-th smallest value in a data set.

=SMALL(A1:A100,COUNTIF($A$1:$A$100,0)+1)

Where the countif is counting the zeros in the range (+1) and is used to tell SMALL to return the k-th smallest value.

Credit: link

Merge PDF files with PHP

Both the accepted answer and even the FDPI homepage seem to give botched or incomplete examples. Here's mine which works and is easy to implement. As expected it requires fpdf and fpdi libraries:

require('fpdf.php');
require('fpdi.php');

$files = ['doc1.pdf', 'doc2.pdf', 'doc3.pdf'];

$pdf = new FPDI();

// iterate over array of files and merge
foreach ($files as $file) {
    $pageCount = $pdf->setSourceFile($file);
    for ($i = 0; $i < $pageCount; $i++) {
        $tpl = $pdf->importPage($i + 1, '/MediaBox');
        $pdf->addPage();
        $pdf->useTemplate($tpl);
    }
}

// output the pdf as a file (http://www.fpdf.org/en/doc/output.htm)
$pdf->Output('F','merged.pdf');

Can't update data-attribute value

Use that instead, if you wish to change the attribute data-num of node element, not of data object:

DEMO

$('#changeData').click(function (e) { 
    e.preventDefault();
    var num = +$('#foo').attr("data-num");
    console.log(num);
    num = num + 1;
    console.log(num);
    $('#foo').attr('data-num', num);
});

PS: but you should use the data() object in virtually all cases, but not all...

Issue with background color in JavaFX 8

Try this one in your css document,

-fx-background-color : #ffaadd;

or

-fx-base : #ffaadd; 

Also, you can set background color on your object with this code directly.

yourPane.setBackground(new Background(new BackgroundFill(Color.DARKGREEN, CornerRadii.EMPTY, Insets.EMPTY)));

Volley - POST/GET parameters

This helper class manages parameters for GET and POST requests:

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;    

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject> {
    private int mMethod;
    private String mUrl;
    private Map<String, String> mParams;
    private Listener<JSONObject> mListener;

    public CustomRequest(int method, String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.mMethod = method;
        this.mUrl = url;
        this.mParams = params;
        this.mListener = reponseListener;
    }

@Override
public String getUrl() {
    if(mMethod == Request.Method.GET) {
        if(mParams != null) {
            StringBuilder stringBuilder = new StringBuilder(mUrl);
            Iterator<Map.Entry<String, String>> iterator = mParams.entrySet().iterator();
            int i = 1;
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                if (i == 1) {
                    stringBuilder.append("?" + entry.getKey() + "=" + entry.getValue());
                } else {
                    stringBuilder.append("&" + entry.getKey() + "=" + entry.getValue());
                }
                iterator.remove(); // avoids a ConcurrentModificationException
                i++;
            }
            mUrl = stringBuilder.toString();
        }
    }
    return mUrl;
}

    @Override
    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return mParams;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        mListener.onResponse(response);
    }
}

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

you have to use echo before base_url() function. otherwise it woudn't print the base url.

Using media breakpoints in Bootstrap 4-alpha

Bootstrap has a way of using media queries to define the different task for different sites. It uses four breakpoints.

we have extra small screen sizes which are less than 576 pixels that small in which I mean it's size from 576 to 768 pixels.

medium screen sizes take up screen size from 768 pixels up to 992 pixels large screen size from 992 pixels up to 1200 pixels.

E.g Small Text

This means that at the small screen between 576px and 768px, center the text For medium screen, change "sm" to "md" and same goes to large "lg"

Pandas every nth row

There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__.

df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

For example, to get every 2 rows, you can do

df[::2]

   a  b  c
0  x  x  x
2  x  x  x
4  x  x  x

There's also GroupBy.first/GroupBy.head, you group on the index:

df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')

df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do

# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

How to fix the height of a <div> element?

You can also use min-height and max-height. It was very useful for me

How can I write to the console in PHP?

I might be late for a party, but I was looking for an implementation of logging function which:

  • takes a variable number of comma separated arguments, just like javascript console.log(),
  • gives a formatted output (not just a serialized string),
  • is distinguishable from a common javascript console.log().

So the output looks like that:

enter image description here

(The snippet below is tested on php 7.2.11. I'm not sure about its php backward compatibility. It can be an issue for javascript as well (in a term of old browsers), because it creates a trailing comma after console.log() arguments – which is not legal until ES 2017.)

<?php

function console_log(...$args)
{
    $args_as_json = array_map(function ($item) {
        return json_encode($item);
    }, $args);

    $js_code = "<script>console.log('%c  log from PHP: ','background: #474A8A; color: #B0B3D6; line-height: 2',";
    foreach ($args_as_json as $arg) {
        $js_code .= "{$arg},";
    }
    $js_code .= ")</script>";

    echo $js_code;
}

$list = ['foo', 'bar'];
$obj = new stdClass();
$obj->first_name = 'John';
$obj->last_name = 'Johnson';

echo console_log($list, 'Hello World', 123, $obj);

?>

Convert a Python list with strings all to lowercase or uppercase

Solution:

>>> s = []
>>> p = ['This', 'That', 'There', 'is', 'apple']
>>> [s.append(i.lower()) if not i.islower() else s.append(i) for i in p]
>>> s
>>> ['this', 'that', 'there', 'is','apple']

This solution will create a separate list containing the lowercase items, regardless of their original case. If the original case is upper then the list s will contain lowercase of the respective item in list p. If the original case of the list item is already lowercase in list p then the list s will retain the item's case and keep it in lowercase. Now you can use list s instead of list p.

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

"Change to if (typeof $next == 'object' && $next.length) $next[0].offsetWidth" -did not help. if you convert Bootstrap 3 to php(for WordPress theme), when adding WP_Query ($loop = new WP_Query( $args );) insert $count = 0;. And and at the end before endwhile; add $count++;.

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

First I copied cv2.pyd from /opencv/build/python/2.7/x86 to C:/Python27/Lib/site-packeges. The error was

"RuntimeError: module compiled against API version 9 but this version of numpy is 7"

Then I installed numpy-1.8.0-win32-superpack-python2.7.exe and opencv works fine.

>>> import cv2
>>> print cv2.__version__
2.4.13

GitHub relative link in Markdown file

Just wanted to add this because none of the above solutions worked if target link is directory with spaces in it's name. If target link is a directory and it has space then even escaping space with \ doesn't render the link on Github. Only solution worked for me is using %20 for each space.

e.g.: if directory structure is this

Top_dir
|-----README.md
|-----Cur_dir1
      |----Dir A
           |----README.md
      |----Dir B
           |----README.md

To make link to Dir A in README.md present in Top_dir you can do this:

[Dir 1](Cur_dir1/Dir%20A)

X11/Xlib.h not found in Ubuntu

A quick search using...

apt search Xlib.h

Turns up the package libx11-dev but you shouldn't need this for pure OpenGL programming. What tutorial are you using?

You can add Xlib.h to your system by running the following...

sudo apt install libx11-dev

Does Python have an ordered set?

If you're using the ordered set to maintain a sorted order, consider using a sorted set implementation from PyPI. The sortedcontainers module provides a SortedSet for just this purpose. Some benefits: pure-Python, fast-as-C implementations, 100% unit test coverage, hours of stress testing.

Installing from PyPI is easy with pip:

pip install sortedcontainers

Note that if you can't pip install, simply pull down the sortedlist.py and sortedset.py files from the open-source repository.

Once installed you can simply:

from sortedcontainers import SortedSet
help(SortedSet)

The sortedcontainers module also maintains a performance comparison with several alternative implementations.

For the comment that asked about Python's bag data type, there's alternatively a SortedList data type which can be used to efficiently implement a bag.

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

Lots of answers so far, which are all excellent pointers to API's and tutorials. One thing I'd like to add is that I work out how far the markers are from my location using something like:

float distance = (float) loc.distanceTo(loc2);

Hope this helps refine the detail for your problem. It returns a rough estimate of distance (in m) between points, and is useful for getting rid of POI that might be too far away - good to declutter your map?

Compare two folders which has many files inside contents

I used

diff -rqyl folder1 folder2 --exclude=node_modules

in my nodejs apps.

App.Config Transformation for projects which are not Web Projects in Visual Studio?

Another solution I've found is NOT to use the transformations but just have a separate config file, e.g. app.Release.config. Then add this line to your csproj file.

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <AppConfig>App.Release.config</AppConfig>
  </PropertyGroup>

This will not only generate the right myprogram.exe.config file but if you're using Setup and Deployment Project in Visual Studio to generate MSI, it'll force the deployment project to use the correct config file when packaging.

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

Another thing is - if your keys are very complicated sometimes you need to replace the places of the fields and it helps :

if this dosent work:

foreign key (ISBN, Title) references BookTitle (ISBN, Title)

Then this might work (not for this specific example but in general) :

foreign key (Title,ISBN) references BookTitle (Title,ISBN)

File inside jar is not visible for spring

I had similar problem when using Tomcat6.x and none of the advices I found was helping. At the end I deleted work folder (of Tomcat) and the problem gone.

I know it is illogical but for documentation purpose...

How to Select Top 100 rows in Oracle?

Assuming that create_time contains the time the order was created, and you want the 100 clients with the latest orders, you can:

  • add the create_time in your innermost query
  • order the results of your outer query by the create_time desc
  • add an outermost query that filters the first 100 rows using ROWNUM

Query:

  SELECT * FROM (
     SELECT * FROM (
        SELECT 
          id, 
          client_id, 
          create_time,
          ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn 
        FROM order
      ) 
      WHERE rn=1
      ORDER BY create_time desc
  ) WHERE rownum <= 100

UPDATE for Oracle 12c

With release 12.1, Oracle introduced "real" Top-N queries. Using the new FETCH FIRST... syntax, you can also use:

  SELECT * FROM (
    SELECT 
      id, 
      client_id, 
      create_time,
      ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn 
    FROM order
  ) 
  WHERE rn = 1
  ORDER BY create_time desc
  FETCH FIRST 100 ROWS ONLY)

Compile/run assembler in Linux?

My suggestion would be to get the book Programming From Ground Up:

http://nongnu.askapache.com/pgubook/ProgrammingGroundUp-1-0-booksize.pdf

That is a very good starting point for getting into assembler programming under linux and it explains a lot of the basics you need to understand to get started.

Fake "click" to activate an onclick method

For IE there is fireEvent() method. Don't know if that works for other browsers.

Visual Studio Code pylint: Unable to import 'protorpc'

I was still getting these errors even after confirming that the correct python and pylint were being used from my virtual env.

Eventually I figured out that in Visual Studio Code I was A) opening my project directory, which is B) where my Python virtual environment was, but I was C) running my main Python program from two levels deeper. Those three things need to be in sync for everything to work.

Here's what I would recommend:

  1. In Visual Studio Code, open the directory containing your main Python program. (This may or may not be the top level of the project directory.)

  2. Select Terminal menu > New Terminal, and create an virtual environment directly inside the same directory.

    python3 -m venv env
    
  3. Install pylint in the virtual environment. If you select any Python file in the sidebar, Visual Studio Code will offer to do this for you. Alternatively, source env/bin/activate then pip install pylint.

  4. In the blue bottom bar of the editor window, choose the Python interpreter env/bin/python. Alternatively, go to Settings and set "Python: Python Path." This sets python.pythonPath in Settings.json.

How to create a GUID/UUID in Python

If you're using Python 2.5 or later, the uuid module is already included with the Python standard distribution.

Ex:

>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')

Oracle - How to create a materialized view with FAST REFRESH and JOINS

Have you tried it without the ANSI join ?

CREATE MATERIALIZED VIEW MV_Test
  NOLOGGING
  CACHE
  BUILD IMMEDIATE 
  REFRESH FAST ON COMMIT 
  AS
SELECT V.*, P.* FROM TPM_PROJECTVERSION V,TPM_PROJECT P 
WHERE  P.PROJECTID = V.PROJECTID

cvc-elt.1: Cannot find the declaration of element 'MyElement'

I got this same error working in Eclipse with Maven with the additional information

schema_reference.4: Failed to read schema document 'https://maven.apache.org/xsd/maven-4.0.0.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

This was after copying in a new controller and it's interface from a Thymeleaf example. Honestly, no matter how careful I am I still am at a loss to understand how one is expected to figure this out. On a (lucky) guess I right clicked the project, clicked Maven and Update Project which cleared up the issue.

Can't import Numpy in Python

I was trying to import numpy in python 3.2.1 on windows 7.

Followed suggestions in above answer for numpy-1.6.1.zip as below after unzipping it

cd numpy-1.6
python setup.py install

but got an error with a statement as below

unable to find vcvarsall.bat

For this error I found a related question here which suggested installing mingW. MingW was taking some time to install.

In the meanwhile tried to install numpy 1.6 again using the direct windows installer available at this link the file name is "numpy-1.6.1-win32-superpack-python3.2.exe"

Installation went smoothly and now I am able to import numpy without using mingW.

Long story short try using windows installer for numpy, if one is available.

Get second child using jQuery

Try this:

$("td:eq(1)", $(t))

or

$("td", $(t)).eq(1)

How to view the roles and permissions granted to any database user in Azure SQL server instance?

To view database roles assigned to users, you can use sys.database_role_members

The following query returns the members of the database roles.

SELECT DP1.name AS DatabaseRoleName,   
    isnull (DP2.name, 'No members') AS DatabaseUserName   
FROM sys.database_role_members AS DRM  
RIGHT OUTER JOIN sys.database_principals AS DP1  
    ON DRM.role_principal_id = DP1.principal_id  
LEFT OUTER JOIN sys.database_principals AS DP2  
    ON DRM.member_principal_id = DP2.principal_id  
WHERE DP1.type = 'R'
ORDER BY DP1.name;  

How can I style an Android Switch?

It's an awesome detailed reply by Janusz. But just for the sake of people who are coming to this page for answers, the easier way is at http://android-holo-colors.com/ (dead link) linked from Android Asset Studio

A good description of all the tools are at AndroidOnRocks.com (site offline now)

However, I highly recommend everybody to read the reply from Janusz as it will make understanding clearer. Use the tool to do stuffs real quick

Getting a union of two arrays in JavaScript

_x000D_
_x000D_
function unique(arrayName)_x000D_
{_x000D_
  var newArray=new Array();_x000D_
  label: for(var i=0; i<arrayName.length;i++ )_x000D_
  {  _x000D_
    for(var j=0; j<newArray.length;j++ )_x000D_
    {_x000D_
      if(newArray[j]==arrayName[i]) _x000D_
        continue label;_x000D_
    }_x000D_
    newArray[newArray.length] = arrayName[i];_x000D_
  }_x000D_
  return newArray;_x000D_
}_x000D_
_x000D_
var arr1 = new Array(0,2,4,4,4,4,4,5,5,6,6,6,7,7,8,9,5,1,2,3,0);_x000D_
var arr2= new Array(3,5,8,1,2,32,1,2,1,2,4,7,8,9,1,2,1,2,3,4,5);_x000D_
var union = unique(arr1.concat(arr2));_x000D_
console.log(union);
_x000D_
_x000D_
_x000D_

What does %w(array) mean?

Instead of %w() we should use %w[]

According to Ruby style guide:

Prefer %w to the literal array syntax when you need an array of words (non-empty strings without spaces and special characters in them). Apply this rule only to arrays with two or more elements.

# bad
STATES = ['draft', 'open', 'closed']

# good
STATES = %w[draft open closed]

Use the braces that are the most appropriate for the various kinds of percent literals.

[] for array literals(%w, %i, %W, %I) as it is aligned with the standard array literals.

# bad
%w(one two three)
%i(one two three)

# good
%w[one two three]
%i[one two three]

For more read here.

How to get current user in asp.net core

Have another way of getting current user in Asp.NET Core - and I think I saw it somewhere here, on SO ^^

// Stores UserManager
private readonly UserManager<ApplicationUser> _manager; 

// Inject UserManager using dependency injection.
// Works only if you choose "Individual user accounts" during project creation.
public DemoController(UserManager<ApplicationUser> manager)  
{  
    _manager = manager;  
}

// You can also just take part after return and use it in async methods.
private async Task<ApplicationUser> GetCurrentUser()  
{  
    return await _manager.GetUserAsync(HttpContext.User);  
}  

// Generic demo method.
public async Task DemoMethod()  
{  
    var user = await GetCurrentUser(); 
    string userEmail = user.Email; // Here you gets user email 
    string userId = user.Id;
}  

That code goes to controller named DemoController. Won't work without both await (won't compile) ;)

What is the $? (dollar question mark) variable in shell scripting?

Minimal POSIX C exit status example

To understand $?, you must first understand the concept of process exit status which is defined by POSIX. In Linux:

  • when a process calls the exit system call, the kernel stores the value passed to the system call (an int) even after the process dies.

    The exit system call is called by the exit() ANSI C function, and indirectly when you do return from main.

  • the process that called the exiting child process (Bash), often with fork + exec, can retrieve the exit status of the child with the wait system call

Consider the Bash code:

$ false
$ echo $?
1

The C "equivalent" is:

false.c

#include <stdlib.h> /* exit */

int main(void) {
    exit(1);
}

bash.c

#include <unistd.h> /* execl */
#include <stdlib.h> /* fork */
#include <sys/wait.h> /* wait, WEXITSTATUS */
#include <stdio.h> /* printf */

int main(void) {
    if (fork() == 0) {
        /* Call false. */
        execl("./false", "./false", (char *)NULL);
    }
    int status;
    /* Wait for a child to finish. */
    wait(&status);
    /* Status encodes multiple fields,
     * we need WEXITSTATUS to get the exit status:
     * http://stackoverflow.com/questions/3659616/returning-exit-code-from-child
     **/
    printf("$? = %d\n", WEXITSTATUS(status));
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o bash bash.c
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o false false.c
./bash

Output:

$? = 1

In Bash, when you hit enter, a fork + exec + wait happens like above, and bash then sets $? to the exit status of the forked process.

Note: for built-in commands like echo, a process need not be spawned, and Bash just sets $? to 0 to simulate an external process.

Standards and documentation

POSIX 7 2.5.2 "Special Parameters" http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02 :

? Expands to the decimal exit status of the most recent pipeline (see Pipelines).

man bash "Special Parameters":

The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. [...]

? Expands to the exit status of the most recently executed foreground pipeline.

ANSI C and POSIX then recommend that:

  • 0 means the program was successful

  • other values: the program failed somehow.

    The exact value could indicate the type of failure.

    ANSI C does not define the meaning of any vaues, and POSIX specifies values larger than 125: What is the meaning of "POSIX"?

Bash uses exit status for if

In Bash, we often use the exit status $? implicitly to control if statements as in:

if true; then
  :
fi

where true is a program that just returns 0.

The above is equivalent to:

true
result=$?
if [ $result = 0 ]; then
  :
fi

And in:

if [ 1 = 1 ]; then
  :
fi

[ is just an program with a weird name (and Bash built-in that behaves like it), and 1 = 1 ] its arguments, see also: Difference between single and double square brackets in Bash

'uint32_t' identifier not found error

Boost.Config offers these typedefs for toolsets that do not provide them natively. The documentation for this specific functionality is here: Standard Integer Types

show/hide a div on hover and hover out

I found using css opacity is better for a simple show/hide hover, and you can add css3 transitions to make a nice finished hover effect. The transitions will just be dropped by older IE browsers, so it degrades gracefully to.

JS fiddle Demo

CSS

#stuff {
    opacity: 0.0;
    -webkit-transition: all 500ms ease-in-out;
    -moz-transition: all 500ms ease-in-out;
    -ms-transition: all 500ms ease-in-out;
    -o-transition: all 500ms ease-in-out;
    transition: all 500ms ease-in-out;
}
#hover {
    width:80px;
    height:20px;
    background-color:green;
    margin-bottom:15px;
}
#hover:hover + #stuff {
    opacity: 1.0;
}

HTML

<div id="hover">Hover</div>
<div id="stuff">stuff</div>

What are the differences between a clustered and a non-clustered index?

Clustered Index

  • Only one per table
  • Faster to read than non clustered as data is physically stored in index order

Non Clustered Index

  • Can be used many times per table
  • Quicker for insert and update operations than a clustered index

Both types of index will improve performance when select data with fields that use the index but will slow down update and insert operations.

Because of the slower insert and update clustered indexes should be set on a field that is normally incremental ie Id or Timestamp.

SQL Server will normally only use an index if its selectivity is above 95%.

How do I run a spring boot executable jar in a Production environment?

This is a simple, you can use spring boot maven plugin to finish your code deploy.

the plugin config like:

<plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <jvmArguments>-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=${debug.port}
                    </jvmArguments>
                    <profiles>
                        <profile>test</profile>
                    </profiles>
                    <executable>true</executable>
                </configuration>
            </plugin>

And, the jvmArtuments is add for you jvm. profiles will choose a profile to start your app. executable can make your app driectly run.

and if you add mvnw to your project, or you have a maven enveriment. You can just call./mvnw spring-boot:run for mvnw or mvn spring-boot:run for maven.

How to select where ID in Array Rails ActiveRecord without exception

Update: This answer is more relevant for Rails 4.x

Do this:

current_user.comments.where(:id=>[123,"456","Michael Jackson"])

The stronger side of this approach is that it returns a Relation object, to which you can join more .where clauses, .limit clauses, etc., which is very helpful. It also allows non-existent IDs without throwing exceptions.

The newer Ruby syntax would be:

current_user.comments.where(id: [123, "456", "Michael Jackson"])

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

Reading Space separated input in python

For Python3:

a, b = list(map(str, input().split()))
v = int(b)

Show Youtube video source into HTML5 video tag?

how about doing it the way hooktube does it? they don't actually use the video URL for the html5 element, but the google video redirector url that calls upon that video. check out here's how they present some despacito random video...

<video id="player-obj" controls="" src="https://redirector.googlevideo.com/videoplayback?ratebypass=yes&amp;mt=1510077993----SKIPPED----amp;utmg=ytap1,,hd720"><source>Your browser does not support HTML5 video.</video>

the code is for the following video page https://hooktube.com/watch?v=72UO0v5ESUo

youtube to mp3 on the other hand has turned into extremely monetized monster that returns now download.html on half of video download requests... annoying...

the 2 links in this answer are to my personal experiences with both resources. how hooktube is nice and fresh and actually helps avoid censorship and geo restrictions.. check it out, it's pretty cool. and youtubeinmp4 is a popup monster now known as ConvertInMp4...

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

How do I get cURL to not show the progress bar?

curl -s http://google.com > temp.html

works for curl version 7.19.5 on Ubuntu 9.10 (no progress bar). But if for some reason that does not work on your platform, you could always redirect stderr to /dev/null:

curl  http://google.com 2>/dev/null > temp.html

How to read Excel cell having Date with Apache POI?

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;


Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
if(cell.getCellTypeEnum() == CellType.NUMERIC||cell.getCellTypeEnum() == CellType.FORMULA)
   {
    

 String cellValue=String.valueOf(cell.getNumericCellValue());
     if(HSSFDateUtil.isCellDateFormatted(cell))
      {
          DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
          Date date = cell.getDateCellValue();
          cellValue = df.format(date);
       }
          System.out.println(cellValue);
    }

Which rows are returned when using LIMIT with OFFSET in MySQL?

It will return 18 results starting on record #9 and finishing on record #26.

Start by reading the query from offset. First you offset by 8, which means you skip the first 8 results of the query. Then you limit by 18. Which means you consider records 9, 10, 11, 12, 13, 14, 15, 16....24, 25, 26 which are a total of 18 records.

Check this out.

And also the official documentation.

What's the difference between "git reset" and "git checkout"?

In their simplest form, reset resets the index without touching the working tree, while checkout changes the working tree without touching the index.

Resets the index to match HEAD, working tree left alone:

git reset

Conceptually, this checks out the index into the working tree. To get it to actually do anything you would have to use -f to force it to overwrite any local changes. This is a safety feature to make sure that the "no argument" form isn't destructive:

git checkout

Once you start adding parameters it is true that there is some overlap.

checkout is usually used with a branch, tag or commit. In this case it will reset HEAD and the index to the given commit as well as performing the checkout of the index into the working tree.

Also, if you supply --hard to reset you can ask reset to overwrite the working tree as well as resetting the index.

If you current have a branch checked out out there is a crucial different between reset and checkout when you supply an alternative branch or commit. reset will change the current branch to point at the selected commit whereas checkout will leave the current branch alone but will checkout the supplied branch or commit instead.

Other forms of reset and commit involve supplying paths.

If you supply paths to reset you cannot supply --hard and reset will only change the index version of the supplied paths to the version in the supplied commit (or HEAD if you don't specify a commit).

If you supply paths to checkout, like reset it will update the index version of the supplied paths to match the supplied commit (or HEAD) but it will always checkout the index version of the supplied paths into the working tree.

JSLint says "missing radix parameter"

It always a good practice to pass radix with parseInt -

parseInt(string, radix)

For decimal -

parseInt(id.substring(id.length - 1), 10)

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with "0x", the radix is 16 (hexadecimal)
  • If the string begins with "0", the radix is 8 (octal). This feature is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

(Reference)

How do you create a read-only user in PostgreSQL?

Here is the best way I've found to add read-only users (using PostgreSQL 9.0 or newer):

$ sudo -upostgres psql postgres
postgres=# CREATE ROLE readonly WITH LOGIN ENCRYPTED PASSWORD '<USE_A_NICE_STRONG_PASSWORD_PLEASE';
postgres=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;

Then log in to all related machines (master + read-slave(s)/hot-standby(s), etc..) and run:

$ echo "hostssl <PUT_DBNAME_HERE> <PUT_READONLY_USERNAME_HERE> 0.0.0.0/0 md5" | sudo tee -a /etc/postgresql/9.2/main/pg_hba.conf
$ sudo service postgresql reload

What is the difference between AF_INET and PF_INET in socket programming?

Checking the header file solve's the problem. One can check for there system compiler.

For my system , AF_INET == PF_INET

AF == Address Family And PF == Protocol Family

Protocol families, same as address families.

enter image description here

Click outside menu to close in jquery

even i came across the same situation and one of my mentor put this idea across to myself.

step:1 when clicked on the button on which we should show the drop down menu. then add the below class name "more_wrap_background" to the current active page like shown below

$('.ui-page-active').append("<div class='more_wrap_background' id='more-wrap-bg'> </div>");

step-2 then add a clicks for the div tag like

$(document).on('click', '#more-wrap-bg', hideDropDown);

where hideDropDown is the function to be called to hide drop down menu

Step-3 and important step while hiding the drop down menu is that remove that class you that added earlier like

$('#more-wrap-bg').remove();

I am removing by using its id in the above code

.more_wrap_background {
  top: 0;
  padding: 0;
  margin: 0;
  background: rgba(0, 0, 0, 0.1);
  position: fixed;
  display: block;
  width: 100% !important;
  z-index: 999;//should be one less than the drop down menu's z-index
  height: 100% !important;
}

How do I find the current machine's full hostname in C (hostname and domain information)?

The easy way, try uname()

If that does not work, use gethostname() then gethostbyname() and finally gethostbyaddr()

The h_name of hostent{} should be your FQDN

Check if a string contains a substring in SQL Server 2005, using a stored procedure

CHARINDEX() searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found

if CHARINDEX('ME',@mainString) > 0
begin
    --do something
end

Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX call would look like:

CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')

(Add more recursive REPLACE() calls for any other punctuation that may occur)

What is the equivalent of "none" in django templates?

Look at the yesno helper

Eg:

{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}

Sorting JSON by values

Here's a multiple-level sort method. I'm including a snippet from an Angular JS module, but you can accomplish the same thing by scoping the sort keys objects such that your sort function has access to them. You can see the full module at Plunker.

$scope.sortMyData = function (a, b)
{
  var retVal = 0, key;
  for (var i = 0; i < $scope.sortKeys.length; i++)
  {
    if (retVal !== 0)
    {
      break;
    }
    else
    {
      key = $scope.sortKeys[i];
      if ('asc' === key.direction)
      {
        retVal = (a[key.field] < b[key.field]) ? -1 : (a[key.field] > b[key.field]) ? 1 : 0;
      }
      else
      {
        retVal = (a[key.field] < b[key.field]) ? 1 : (a[key.field] > b[key.field]) ? -1 : 0;
      }
    }
  }
  return retVal;
};

How to write and read a file with a HashMap?

since HashMap implements Serializable interface, you can simply use ObjectOutputStream class to write whole Map to file, and read it again using ObjectInputStream class

below simple code that explain usage of ObjectOutStream and ObjectInputStream

import java.util.*;
import java.io.*;
public class A{

    HashMap<String,String> hm;
    public A() {
        hm=new HashMap<String,String>();

        hm.put("1","A");
        hm.put("2","B");
        hm.put("3","C");

        method1(hm);

    }

public void method1(HashMap<String,String> map) {
    //write to file : "fileone"
    try {
        File fileOne=new File("fileone");
        FileOutputStream fos=new FileOutputStream(fileOne);
        ObjectOutputStream oos=new ObjectOutputStream(fos);

        oos.writeObject(map);
        oos.flush();
        oos.close();
        fos.close();
    } catch(Exception e) {}

    //read from file 
    try {
        File toRead=new File("fileone");
        FileInputStream fis=new FileInputStream(toRead);
        ObjectInputStream ois=new ObjectInputStream(fis);

        HashMap<String,String> mapInFile=(HashMap<String,String>)ois.readObject();

        ois.close();
        fis.close();
        //print All data in MAP
        for(Map.Entry<String,String> m :mapInFile.entrySet()){
            System.out.println(m.getKey()+" : "+m.getValue());
        }
    } catch(Exception e) {}
  }

public static void main(String args[]) {
        new A();
}

}

or if you want to write data as text to file you can simply iterate through Map and write key and value line by line, and read it again line by line and add to HashMap

import java.util.*;
import java.io.*;
public class A{

    HashMap<String,String> hm;
    public A(){
        hm=new HashMap<String,String>();

        hm.put("1","A");
        hm.put("2","B");
        hm.put("3","C");

        method2(hm);

    }

public void method2(HashMap<String,String> map) {
    //write to file : "fileone"
    try {
        File fileTwo=new File("filetwo.txt");
        FileOutputStream fos=new FileOutputStream(fileTwo);
        PrintWriter pw=new PrintWriter(fos);

        for(Map.Entry<String,String> m :map.entrySet()){
            pw.println(m.getKey()+"="+m.getValue());
        }

        pw.flush();
        pw.close();
        fos.close();
    } catch(Exception e) {}

    //read from file 
    try {
        File toRead=new File("filetwo.txt");
        FileInputStream fis=new FileInputStream(toRead);

        Scanner sc=new Scanner(fis);

        HashMap<String,String> mapInFile=new HashMap<String,String>();

        //read data from file line by line:
        String currentLine;
        while(sc.hasNextLine()) {
            currentLine=sc.nextLine();
            //now tokenize the currentLine:
            StringTokenizer st=new StringTokenizer(currentLine,"=",false);
            //put tokens ot currentLine in map
            mapInFile.put(st.nextToken(),st.nextToken());
        }
        fis.close();

        //print All data in MAP
        for(Map.Entry<String,String> m :mapInFile.entrySet()) {
            System.out.println(m.getKey()+" : "+m.getValue());
        }
    }catch(Exception e) {}
  }

public static void main(String args[]) {
        new A();
}

}

NOTE: above code may not be the fastest way to doing this task, but i want to show some application of classes

See ObjectOutputStream , ObjectInputStream, HashMap, Serializable, StringTokenizer

How to set some xlim and ylim in Seaborn lmplot facetgrid

The lmplot function returns a FacetGrid instance. This object has a method called set, to which you can pass key=value pairs and they will be set on each Axes object in the grid.

Secondly, you can set only one side of an Axes limit in matplotlib by passing None for the value you want to remain as the default.

Putting these together, we have:

g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))

enter image description here

How can I create a two dimensional array in JavaScript?

Creates n dimensional matrix array for Java Script, filling with initial default of value 0.

function arr (arg, def = 0){
      if (arg.length > 2){
        return Array(arg[0]).fill().map(()=>arr(arg.slice(1)));
      } else {
        return Array(arg[0]).fill().map(()=>Array(arg[1]).fill(def));
      }
    }

// Simple Usage of 4 dimensions
var s = arr([3,8,4,6])

// Use null default value with 2 dimensions
var k = arr([5,6] , null)

jQuery Datepicker localization

If you want to include some options besides regional localization, you have to use $.extend, like this:

$(function() {
   $('#Date').datepicker($.extend({
      showMonthAfterYear: false,
      dateFormat:'d MM, y'
    },
    $.datepicker.regional['fr']
  ));
});

How to send email via Django?

You need to use smtp as backend in settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

If you use backend as console, you will receive output in console

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

And also below settings in addition

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'password'

If you are using gmail for this, setup 2-step verification and Application specific password and copy and paste that password in above EMAIL_HOST_PASSWORD value.

how to download file using AngularJS and calling MVC API?

string trackPathTemp = track.trackPath;

            //The File Path
            var videoFilePath = HttpContext.Current.Server.MapPath("~/" + trackPathTemp);

            var stream = new FileStream(videoFilePath, FileMode.Open, FileAccess.Read);
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream)
            };
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("video/mp4");
            result.Content.Headers.ContentRange = new ContentRangeHeaderValue(0, stream.Length);
            // result.Content.Headers.Add("filename", "Video.mp4");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "Video.mp4"
            };
            return result;

jQuery add image inside of div tag

my 2 cents:

$('#theDiv').prepend($('<img>',{id:'theImg',src:'theImg.png'}))

datetime to string with series in python pandas

There is no str accessor for datetimes and you can't do dates.astype(str) either, you can call apply and use datetime.strftime:

In [73]:

dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0    2001-01-01
1    2001-03-31
dtype: object

You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.

Update

As of version 0.17.0 you can do this using dt.strftime

dates.dt.strftime('%Y-%m-%d')

will now work

How to create an alert message in jsp page after submit process is complete

So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.

In test.jsp

Create a javascript

<script type="text/javascript">
function alertName(){
alert("Form has been submitted");
} 
</script> 

and than at the bottom

<script type="text/javascript"> window.onload = alertName; </script>

Note:im not sure how to type the code in stackoverflow!. Edit: I just learned how to

Edit 2: TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.

To do that i would highly recommendation to use session!

So what you want to do is in your servlet:

session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);

than in the test.jsp

<%
session.setMaxInactiveInterval(2);
%>

 <script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
    if (Msg != "null") {
 function alertName(){
 alert("Form has been submitted");
 } 
 }
 </script> 

and than at the bottom

<script type="text/javascript"> window.onload = alertName; </script>

So everytime you submit that form a session will be pass on! If session is not null the function will run!

Set default syntax to different filetype in Sublime Text 2

Go to a Packages/User, create (or edit) a .sublime-settings file named after the Syntax where you want to add the extensions, Ini.sublime-settings in your case, then write there something like this:

{
    "extensions":["cfg"]
}

And then restart Sublime Text

What is a Question Mark "?" and Colon ":" Operator Used for?

a=1;
b=2;

x=3;
y=4;

answer = a > b ? x : y;

answer=4 since the condition is false it takes y value.

A question mark (?)
. The value to use if the condition is true

A colon (:)
. The value to use if the condition is false

No space left on device

Such difference between the output of du -sh and df -h may happen if some large file has been deleted, but is still opened by some process. Check with the command lsof | grep deleted to see which processes have opened descriptors to deleted files. You can restart the process and the space will be freed.

Why is setTimeout(fn, 0) sometimes useful?

The other thing this does is push the function invocation to the bottom of the stack, preventing a stack overflow if you are recursively calling a function. This has the effect of a while loop but lets the JavaScript engine fire other asynchronous timers.

Get java.nio.file.Path object from java.io.File

From the documentation:

Paths associated with the default provider are generally interoperable with the java.io.File class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented by java.io.File. The toPath method may be used to obtain a Path from the abstract path name represented by a java.io.File object. The resulting Path can be used to operate on the same file as the java.io.File object. In addition, the toFile method is useful to construct a File from the String representation of a Path.

(emphasis mine)

So, for toFile:

Returns a File object representing this path.

And toPath:

Returns a java.nio.file.Path object constructed from the this abstract path.

How to return part of string before a certain character?

In General a function to return string after substring is

_x000D_
_x000D_
function getStringAfterSubstring(parentString, substring) {_x000D_
    return parentString.substring(parentString.indexOf(substring) + substring.length)_x000D_
}_x000D_
_x000D_
function getStringBeforeSubstring(parentString, substring) {_x000D_
    return parentString.substring(0, parentString.indexOf(substring))_x000D_
}_x000D_
console.log(getStringAfterSubstring('abcxyz123uvw', '123'))_x000D_
console.log(getStringBeforeSubstring('abcxyz123uvw', '123'))
_x000D_
_x000D_
_x000D_

Convert a row of a data frame to vector

I recommend unlist, which keeps the names.

unlist(df[1,])
  a   b   c 
1.0 2.0 2.6 

is.vector(unlist(df[1,]))
[1] TRUE

If you don't want a named vector:

unname(unlist(df[1,]))
[1] 1.0 2.0 2.6

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

I've been quite happy with Swing for the desktop applications I've been involved in. However, I do share your view on Swing not offering advanced components. What I've done in these cases is to go for JIDE. It's not free, but not that pricey either and it gives you a whole lot more tools under your belt. Specifically, they do offer a filterable TreeTable.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

I found the solution to my problem. It was indeed because my MySQL server was not running.

It was caused by MySQL not being correctly set up on my machine, thus not being able to run.

To remedy this, I used a script which installs MySQL on Mac OSX Mountain Lion, which must have installed missing files.

Here is the link: http://code.macminivault.com/

Important Note: This script sets the root password as a randomly generated string, which it saves on the Desktop, so take care not to delete this file and to note the password. It also installs MySQL manager in your system preferences. I'm also not sure if removes any existing databases, so be careful about that.

How might I force a floating DIV to match the height of another floating DIV?

I can't understand why this issue gets pounded into the ground when in 30 seconds you can code a two-column table and solve the problem.

This div column height problem comes up all over a typical layout. Why resort to scripting when a plain old basic HTML tag will do it? Unless there are huge and numerous tables on a layout, I don't buy the argument that tables are significantly slower.

compression and decompression of string data in java

You can't convert binary data to String. As a solution you can encode binary data and then convert to String. For example, look at this How do you convert binary data to Strings and back in Java?

Can JavaScript connect with MySQL?

I think you would need to add something like PHP into the equation. PHP to interact with the database and then you could make AJAX calls with Javascript.

Reset C int array to zero : the fastest way?

This question, although rather old, needs some benchmarks, as it asks for not the most idiomatic way, or the way that can be written in the fewest number of lines, but the fastest way. And it is silly to answer that question without some actual testing. So I compared four solutions, memset vs. std::fill vs. ZERO of AnT's answer vs a solution I made using AVX intrinsics.

Note that this solution is not generic, it only works on data of 32 or 64 bits. Please comment if this code is doing something incorrect.

#include<immintrin.h>
#define intrin_ZERO(a,n){\
size_t x = 0;\
const size_t inc = 32 / sizeof(*(a));/*size of 256 bit register over size of variable*/\
for (;x < n-inc;x+=inc)\
    _mm256_storeu_ps((float *)((a)+x),_mm256_setzero_ps());\
if(4 == sizeof(*(a))){\
    switch(n-x){\
    case 3:\
        (a)[x] = 0;x++;\
    case 2:\
        _mm_storeu_ps((float *)((a)+x),_mm_setzero_ps());break;\
    case 1:\
        (a)[x] = 0;\
        break;\
    case 0:\
        break;\
    };\
}\
else if(8 == sizeof(*(a))){\
switch(n-x){\
    case 7:\
        (a)[x] = 0;x++;\
    case 6:\
        (a)[x] = 0;x++;\
    case 5:\
        (a)[x] = 0;x++;\
    case 4:\
        _mm_storeu_ps((float *)((a)+x),_mm_setzero_ps());break;\
    case 3:\
        (a)[x] = 0;x++;\
    case 2:\
        ((long long *)(a))[x] = 0;break;\
    case 1:\
        (a)[x] = 0;\
        break;\
    case 0:\
        break;\
};\
}\
}

I will not claim that this is the fastest method, since I am not a low level optimization expert. Rather it is an example of a correct architecture dependent implementation that is faster than memset.

Now, onto the results. I calculated performance for size 100 int and long long arrays, both statically and dynamically allocated, but with the exception of msvc, which did a dead code elimination on static arrays, the results were extremely comparable, so I will show only dynamic array performance. Time markings are ms for 1 million iterations, using time.h's low precision clock function.

clang 3.8 (Using the clang-cl frontend, optimization flags= /OX /arch:AVX /Oi /Ot)

int:
memset:      99
fill:        97
ZERO:        98
intrin_ZERO: 90

long long:
memset:      285
fill:        286
ZERO:        285
intrin_ZERO: 188

gcc 5.1.0 (optimization flags: -O3 -march=native -mtune=native -mavx):

int:
memset:      268
fill:        268
ZERO:        268
intrin_ZERO: 91
long long:
memset:      402
fill:        399
ZERO:        400
intrin_ZERO: 185

msvc 2015 (optimization flags: /OX /arch:AVX /Oi /Ot):

int
memset:      196
fill:        613
ZERO:        221
intrin_ZERO: 95
long long:
memset:      273
fill:        559
ZERO:        376
intrin_ZERO: 188

There is a lot interesting going on here: llvm killing gcc, MSVC's typical spotty optimizations (it does an impressive dead code elimination on static arrays and then has awful performance for fill). Although my implementation is significantly faster, this may only be because it recognizes that bit clearing has much less overhead than any other setting operation.

Clang's implementation merits more looking at, as it is significantly faster. Some additional testing shows that its memset is in fact specialized for zero--non zero memsets for 400 byte array are much slower (~220ms) and are comparable to gcc's. However, the nonzero memsetting with an 800 byte array makes no speed difference, which is probably why in that case, their memset has worse performance than my implementation--the specialization is only for small arrays, and the cuttoff is right around 800 bytes. Also note that gcc 'fill' and 'ZERO' are not optimizing to memset (looking at generated code), gcc is simply generating code with identical performance characteristics.

Conclusion: memset is not really optimized for this task as well as people would pretend it is (otherwise gcc and msvc and llvm's memset would have the same performance). If performance matters then memset should not be a final solution, especially for these awkward medium sized arrays, because it is not specialized for bit clearing, and it is not hand optimized any better than the compiler can do on its own.

Understanding __get__ and __set__ and Python descriptors

The descriptor is how Python's property type is implemented. A descriptor simply implements __get__, __set__, etc. and is then added to another class in its definition (as you did above with the Temperature class). For example:

temp=Temperature()
temp.celsius #calls celsius.__get__

Accessing the property you assigned the descriptor to (celsius in the above example) calls the appropriate descriptor method.

instance in __get__ is the instance of the class (so above, __get__ would receive temp, while owner is the class with the descriptor (so it would be Temperature).

You need to use a descriptor class to encapsulate the logic that powers it. That way, if the descriptor is used to cache some expensive operation (for example), it could store the value on itself and not its class.

An article about descriptors can be found here.

EDIT: As jchl pointed out in the comments, if you simply try Temperature.celsius, instance will be None.

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

Internet Explorer 10 does not attempt to read conditional comments anymore. This means it will treat conditional comments just like any other browser would: as regular HTML comments, meant to be ignored entirely. Looking at the markup given in the question as an example, all browsers including IE10 will ignore the comment portions, highlighted gray, entirely. The HTML5 standard makes no mention of conditional comment syntax, and this is exactly why they have chosen to stop supporting it in IE10.

Note, however, that conditional compilation in JScript is still supported, as shown in the comments as well as the more recent answers. It's not going away in the final release either, unlike jQuery.browser. And of course, it goes without saying that user-agent sniffing remains as fragile as ever and should never be used under any circumstances.

If you really must target IE10, either use conditional compilation which may still see support in the near future, or — if you can help it — use a feature detection library such as Modernizr instead of (or in conjunction with) browser detection. Unless your use case requires noscript or accommodating IE10 on the server side, user-agent sniffing is going to be more of a headache than a viable option.

Sounds pretty cumbersome, but remember that as a modern browser that's highly conformant to today's Web standards1, assuming you've written interoperable code that is highly standards-compliant, you shouldn't have to set aside special code for IE10 unless absolutely necessary, i.e. it's supposed to resemble other browsers in terms of behavior and rendering.2 And it sounds far-fetched, given IE's history, but how many times have you expected Firefox or Chrome to behave the same way only to be met with dismay?

If you do have a legitimate reason to be targeting certain browsers, by all means sniff them out with the other tools given to you. I'm just saying that you're going to be much more hard-pressed to find such a reason today than what it used to be, and it's really just not something you can rely on.


1 Not only IE10, but IE9, and even IE8 which handles most of the mature CSS2.1 standard far better than Chrome, simply because IE8 was so focused on standards compliance (at which time CSS2.1 was already pretty stable with only minor differences from today's recommendation) while Chrome seems to be little more than a half-polished tech demo of cutting-edge pseudo-standards.

2 And I may be biased when I say this, but it sure as hell does. If your code works in other browsers but not IE, the odds that it's an issue with your own code rather than IE10 are far better compared to, say, 3 years ago, with previous versions of IE. Again, I may be biased, but let's be honest: aren't you too? Just look at your comments.

How to get DATE from DATETIME Column in SQL?

Try this:

SELECT SUM(transaction_amount) FROM TransactionMaster WHERE Card_No ='123' AND CONVERT(VARCHAR(10),GETDATE(),111)

The GETDATE() function returns the current date and time from the SQL Server.

How to detect scroll position of page using jQuery

Now that works for me...

$(document).ready(function(){

    $(window).resize(function(e){
        console.log(e);                   
    });

    $(window).scroll(function (event) {
        var sc = $(window).scrollTop();
        console.log(sc);
    });

})

it works well... and then you can use JQuery/TweenMax to track elements and control them.

Switch/toggle div (jQuery)

I think you want this:

$('#recover-password').show();

or

$('#recover-password').toggle();

This is made possible by jQuery.

How to combine two vectors into a data frame

This should do the trick, to produce the data frame you asked for, using only base R:

df <- data.frame(cond=c(rep("x", times=length(x)), 
                        rep("y", times=length(y))), 
                 rating=c(x, y))

df
  cond rating
1    x      1
2    x      2
3    x      3
4    y    100
5    y    200
6    y    300

However, from your initial description, I'd say that this is perhaps a more likely usecase:

df2 <- data.frame(x, y)
colnames(df2) <- c(x_name, y_name)

df2
  cond rating
1    1    100
2    2    200
3    3    300

[edit: moved parentheses in example 1]

laravel throwing MethodNotAllowedHttpException

That is because you are posting data through a get method.

Instead of

Route::get('/validate', 'MemberController@validateCredentials');

Try this

Route::post('/validate', 'MemberController@validateCredentials');

Calling remove in foreach loop in Java

It's better to use an Iterator when you want to remove element from a list

because the source code of remove is

if (numMoved > 0)
    System.arraycopy(elementData, index+1, elementData, index,
             numMoved);
elementData[--size] = null;

so ,if you remove an element from the list, the list will be restructure ,the other element's index will be changed, this can result something that you want to happened.

How do I post button value to PHP?

Give them all a name that is the same

For example

<input type="button" value="a" name="btn" onclick="a" />
<input type="button" value="b" name="btn" onclick="b" />

Then in your php use:

$val = $_POST['btn']

Edit, as BalusC said; If you're not going to use onclick for doing any javascript (for example, sending the form) then get rid of it and use type="submit"

ImportError: No module named 'MySQL'

I found that @gdxn96 solution worked for me, but with 1 change.

sudo wget http://cdn.mysql.com//Downloads/Connector-Python/mysql-connector-python-2.1.3.tar.gz
tar -zxvf mysql-connector-python-2.1.3.tar
cd mysql-connector-python-2.1.3
sudo python3 setup.py install

How do I print out the value of this boolean? (Java)

First of all, your variable "isLeapYear" is the same name as the method. That's just bad practice.

Second, you're not declaring "isLeapYear" as a variable. Java is strongly typed so you need a boolean isLeapYear; in the beginning of your method.

This call: System.out.println(boolean isLeapYear); is just wrong. There are no declarations in method calls.

Once you have declared isLeapYear to be a boolean variable, you can call System.out.println(isLeapYear);

UPDATE: I just saw it's declared as a field. So just remove the line System.out.println(boolean isLeapYear); You should understand that you can't call isLeapYear from the main() method. You cannot call a non static method from a static method with an instance. If you want to call it, you need to add

booleanfun myBoolFun = new booleanfun();
System.out.println(myBoolFun.isLeapYear);

I really suggest you use Eclipse, it will let you know of such compilation errors on the fly and its much easier to learn that way.

Evenly distributing n points on a sphere

edit: This does not answer the question the OP meant to ask, leaving it here in case people find it useful somehow.

We use the multiplication rule of probability, combined with infinitessimals. This results in 2 lines of code to achieve your desired result:

longitude: f = uniform([0,2pi))
azimuth:   ? = -arcsin(1 - 2*uniform([0,1]))

(defined in the following coordinate system:)

enter image description here

Your language typically has a uniform random number primitive. For example in python you can use random.random() to return a number in the range [0,1). You can multiply this number by k to get a random number in the range [0,k). Thus in python, uniform([0,2pi)) would mean random.random()*2*math.pi.


Proof

Now we can't assign ? uniformly, otherwise we'd get clumping at the poles. We wish to assign probabilities proportional to the surface area of the spherical wedge (the ? in this diagram is actually f):

enter image description here

An angular displacement df at the equator will result in a displacement of df*r. What will that displacement be at an arbitrary azimuth ?? Well, the radius from the z-axis is r*sin(?), so the arclength of that "latitude" intersecting the wedge is df * r*sin(?). Thus we calculate the cumulative distribution of the area to sample from it, by integrating the area of the slice from the south pole to the north pole.

enter image description here (where stuff=df*r)

We will now attempt to get the inverse of the CDF to sample from it: http://en.wikipedia.org/wiki/Inverse_transform_sampling

First we normalize by dividing our almost-CDF by its maximum value. This has the side-effect of cancelling out the df and r.

azimuthalCDF: cumProb = (sin(?)+1)/2 from -pi/2 to pi/2

inverseCDF: ? = -sin^(-1)(1 - 2*cumProb)

Thus:

let x by a random float in range [0,1]
? = -arcsin(1-2*x)

How to load specific image from assets with Swift

Since swift 3.0 there is more convenient way: #imageLiterals here is text example. And below animated example from here:

enter image description here

Add and Remove Views in Android Dynamically?

//MainActivity :





 package com.edittext.demo;
    import android.app.Activity;
    import android.os.Bundle;
    import android.text.TextUtils;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.Toast;

    public class MainActivity extends Activity {

        private EditText edtText;
        private LinearLayout LinearMain;
        private Button btnAdd, btnClear;
        private int no;

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

            edtText = (EditText)findViewById(R.id.edtMain);
            btnAdd = (Button)findViewById(R.id.btnAdd);
            btnClear = (Button)findViewById(R.id.btnClear);
            LinearMain = (LinearLayout)findViewById(R.id.LinearMain);

            btnAdd.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(edtText.getText().toString().trim())) {
                        no = Integer.parseInt(edtText.getText().toString());
                        CreateEdittext();
                    }else {
                        Toast.makeText(MainActivity.this, "Please entere value", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            btnClear.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    LinearMain.removeAllViews();
                    edtText.setText("");
                }
            });

            /*edtText.addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,int after) {
                }
                @Override
                public void afterTextChanged(Editable s) {
                }
            });*/

        }

        protected void CreateEdittext() {
            final EditText[] text = new EditText[no];
            final Button[] add = new Button[no];
            final LinearLayout[] LinearChild = new LinearLayout[no];
            LinearMain.removeAllViews();

            for (int i = 0; i < no; i++){

                View view = getLayoutInflater().inflate(R.layout.edit_text, LinearMain,false);
                text[i] = (EditText)view.findViewById(R.id.edtText);
                text[i].setId(i);
                text[i].setTag(""+i);

                add[i] = (Button)view.findViewById(R.id.btnAdd);
                add[i].setId(i);
                add[i].setTag(""+i);

                LinearChild[i] = (LinearLayout)view.findViewById(R.id.child_linear);
                LinearChild[i].setId(i);
                LinearChild[i].setTag(""+i);

                LinearMain.addView(view);

                add[i].setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        //Toast.makeText(MainActivity.this, "add text "+v.getTag(), Toast.LENGTH_SHORT).show();
                        int a = Integer.parseInt(text[v.getId()].getText().toString());
                        LinearChild[v.getId()].removeAllViews();
                        for (int k = 0; k < a; k++){

                            EditText text = (EditText) new EditText(MainActivity.this);
                            text.setId(k);
                            text.setTag(""+k);

                            LinearChild[v.getId()].addView(text);
                        }
                    }
                });
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

    }

// Now add xml main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:orientation="horizontal" >

    <EditText
        android:id="@+id/edtMain"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_weight="1"
        android:ems="10"
        android:hint="Enter value" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="Add" />

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:text="Clear" />
</LinearLayout>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp" >

    <LinearLayout
        android:id="@+id/LinearMain"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    </LinearLayout>
</ScrollView>

// now add view xml file..

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:orientation="horizontal" >

    <EditText
        android:id="@+id/edtText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:ems="10" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="Add" />
</LinearLayout>

<LinearLayout
    android:id="@+id/child_linear"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="5dp"
    android:orientation="vertical" >
</LinearLayout>

Why is my method undefined for the type object?

Change your main to:

public static void main(String[] args) {
    EchoServer echoServer = new EchoServer();
    echoServer.listen();
}

When you declare Object EchoServer0; you have a few mistakes.

  1. EchoServer0 is of type Object, therefore it doesn't have the method listen().
  2. You will also need to create an instance of it with new.
  3. Another problem, this is only regarding naming conventions, you should call your variables starting by lower case letters, echoServer0 instead of EchoServer0. Uppercase names are usually for class names.
  4. You should not create a variable with the same name as its class. It is confusing.

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

A check of ibliblio and java.net repositories reveal that jmx related jar is not present in either. I think you should manually download jms and install them locally as discussed here.

MongoDB relationships: embed or reference?

MongoDB gives freedom to be schema-less and this feature can result in pain in the long term if not thought or planned well,

There are 2 options either Embed or Reference. I will not go through definitions as the above answers have well defined them.

When embedding you should answer one question is your embedded document going to grow, if yes then how much (remember there is a limit of 16 MB per document) So if you have something like a comment on a post, what is the limit of comment count, if that post goes viral and people start adding comments. In such cases, reference could be a better option (but even reference can grow and reach 16 MB limit).

So how to balance it, the answer is a combination of different patterns, check these links, and create your own mix and match based on your use case.

https://www.mongodb.com/blog/post/building-with-patterns-a-summary

https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1

Replace non ASCII character from string

FailedDev's answer is good, but can be improved. If you want to preserve the ascii equivalents, you need to normalize first:

String subjectString = "öäü";
subjectString = Normalizer.normalize(subjectString, Normalizer.Form.NFD);
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");

=> will produce "oau"

That way, characters like "öäü" will be mapped to "oau", which at least preserves some information. Without normalization, the resulting String will be blank.

How to put img inline with text

This should display the image inline:

.content-dir-item img.mail {
    display: inline-block;
    *display: inline; /* for older IE */
    *zoom: 1; /* for older IE */
}

How to build & install GLFW 3 and use it in a Linux project

2020 Updated Answer

It is 2020 (7 years later) and I have learned more about Linux during this time. Specifically that it might not be a good idea to run sudo make install when installing libraries, as these may interfere with the package management system. (In this case apt as I am using Debian 10.)

If this is not correct, please correct me in the comments.

Alternative proposed solution

This information is taken from the GLFW docs, however I have expanded/streamlined the information which is relevant to Linux users.

  • Go to home directory and clone glfw repository from github
cd ~
git clone https://github.com/glfw/glfw.git
cd glfw
  • You can at this point create a build directory and follow the instructions here (glfw build instructions), however I chose not to do that. The following command still seems to work in 2020 however it is not explicitly stated by the glfw online instructions.
cmake -G "Unix Makefiles"
  • You may need to run sudo apt-get build-dep glfw3 before (?). I ran both this command and sudo apt install xorg-dev as per the instructions.

  • Finally run make

  • Now in your project directory, do the following. (Go to your project which uses the glfw libs)

  • Create a CMakeLists.txt, mine looks like this

CMAKE_MINIMUM_REQUIRED(VERSION 3.7)
PROJECT(project)

SET(CMAKE_CXX_STANDARD 14)
SET(CMAKE_BUILD_TYPE DEBUG)

set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)

add_subdirectory(/home/<user>/glfw /home/<user>/glfw/src)


FIND_PACKAGE(OpenGL REQUIRED)

SET(SOURCE_FILES main.cpp)

ADD_EXECUTABLE(project ${SOURCE_FILES})
TARGET_LINK_LIBRARIES(project glfw)
TARGET_LINK_LIBRARIES(project OpenGL::GL)
  • If you don't like CMake then I appologize but in my opinion it is the easiest way to get your project working quickly. I would recommend learning to use it, at least to a basic level. Regretably I do not know of any good CMake tutorial

  • Then do cmake . and make, your project should be built and linked against glfw3 shared lib

  • There is some way of creating a dynamic linked lib. I believe I have used the static method here. Please comment / add a section in this answer below if you know more than I do

  • This should work on other systems, if not let me know and I will help if I am able to

The maximum recursion 100 has been exhausted before statement completion

it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);

DECLARE @STARTDATE datetime; 
DECLARE @EntDt datetime; 
set @STARTDATE = '01/01/2009';  
set @EntDt = '12/31/2009'; 
declare @dcnt int; 
;with DateList as   
 (   
    select @STARTDATE DateValue   
    union all   
    select DateValue + 1 from    DateList      
    where   DateValue + 1 < convert(VARCHAR(15),@EntDt,101)   
 )   
  select count(*) as DayCnt from (   
  select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
  where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )     
  )a
option (maxrecursion 365);

How do I select a random value from an enumeration?

Call Enum.GetValues; this returns an array that represents all possible values for your enum. Pick a random item from this array. Cast that item back to the original enum type.

Detecting IE11 using CSS Capability/Feature Detection

Use the following properties:

  • !!window.MSInputMethodContext
  • !!document.msFullscreenEnabled

Autoreload of modules in IPython

REVISED - please see Andrew_1510's answer below, as IPython has been updated.

...

It was a bit hard figure out how to get there from a dusty bug report, but:

It ships with IPython now!

import ipy_autoreload
%autoreload 2
%aimport your_mod

# %autoreload? for help

... then every time you call your_mod.dwim(), it'll pick up the latest version.

XML Error: Extra content at the end of the document

You need a root node

<?xml version="1.0" encoding="ISO-8859-1"?>    
<documents>
    <document>
        <name>Sample Document</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;wordcount3=0</url>
    </document>

    <document>
        <name>Sample</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;</url>
    </document>
</documents>

Replace a value in a data frame based on a conditional (`if`) statement

another useful way to replace values

library(plyr)
junk$nm <- revalue(junk$nm, c("B"="b"))

How to draw a circle with text in the middle?

If your content is going to wrap and be of unknown height, this is your best bet:

http://cssdeck.com/labs/aplvrmue

.badge {
  height: 100px;
  width: 100px;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  border-radius: 50%; /* may require vendor prefixes */
  background: yellow;
}

_x000D_
_x000D_
.badge {_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
  display: table-cell;_x000D_
  text-align: center;_x000D_
  vertical-align: middle;_x000D_
  border-radius: 50%;_x000D_
  background: yellow;_x000D_
}
_x000D_
<div class="badge">1</div>
_x000D_
_x000D_
_x000D_

Read MS Exchange email in C#

If your Exchange server is configured to support POP or IMAP, that's an easy way out.

Another option is WebDAV access. there is a library available for that. This might be your best option.

I think there are options using COM objects to access Exchange, but I'm not sure how easy it is.

It all depends on what exactly your administrator is willing to give you access to I guess.

How do I clear all options in a dropdown box?

You can use the following to clear all the elements.

var select = document.getElementById("DropList");
var length = select.options.length;
for (i = length-1; i >= 0; i--) {
  select.options[i] = null;
}

How to mark-up phone numbers?

The tel: scheme was used in the late 1990s and documented in early 2000 with RFC 2806 (which was obsoleted by the more-thorough RFC 3966 in 2004) and continues to be improved. Supporting tel: on the iPhone was not an arbitrary decision.

callto:, while supported by Skype, is not a standard and should be avoided unless specifically targeting Skype users.

Me? I'd just start including properly-formed tel: URIs on your pages (without sniffing the user agent) and wait for the rest of the world's phones to catch up :) .

Example:

_x000D_
_x000D_
<a href="tel:+18475555555">1-847-555-5555</a>
_x000D_
_x000D_
_x000D_

How to submit an HTML form without redirection

Okay, I'm not going to tell you a magical way of doing it because there isn't. If you have an action attribute set for a form element, it will redirect.

If you don't want it to redirect simply don't set any action and set onsubmit="someFunction();"

In your someFunction() you do whatever you want, (with AJAX or not) and in the ending, you add return false; to tell the browser not to submit the form...

Display TIFF image in all web browser

I found this resource that details the various methods: How to embed TIFF files in HTML documents

As mentioned, it will very much depend on browser support for the format. Viewing that page in Chrome on Windows didn't display any of the images.

It would also be helpful if you posted the code you've tried already.

Node.js Error: Cannot find module express

1.first check if express is install at correct location. 2. npm install express (run this command). 3. express will save under your "node_modules" folder

Increment value in mysql update query

Why don't you let PHP do the job?

"UPDATE member_profile SET points= ' ". ($points+1) ." '  WHERE user_id = '".$userid."'"

How to display div after click the button in Javascript?

<div  style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" onclick="document.getElementsByClassName('answer_list')[0].style.display = 'auto';">

REST, HTTP DELETE and parameters

In addition to Alex's answer:

Note that http://server/resource/id?force_delete=true identifies a different resource than http://server/resource/id. For example, it is a huge difference whether you delete /customers/?status=old or /customers/.

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

You do not need any client side code if doing this is ASP.NET. The example below is a boostrap input box with a search button with an fontawesome icon.

You will see that in place of using a regular < div > tag with a class of "input-group" I have used a asp:Panel. The DefaultButton property set to the id of my button, does the trick.

In example below, after typing something in the input textbox, you just hit enter and that will result in a submit.

<asp:Panel DefaultButton="btnblogsearch" runat="server" CssClass="input-group blogsearch">
<asp:TextBox ID="txtSearchWords" CssClass="form-control" runat="server" Width="100%" Placeholder="Search for..."></asp:TextBox>
<span class="input-group-btn">
    <asp:LinkButton ID="btnblogsearch" runat="server" CssClass="btn btn-default"><i class="fa fa-search"></i></asp:LinkButton>
</span></asp:Panel>

How do I profile memory usage in Python?

A simple example to calculate the memory usage of a block of codes / function using memory_profile, while returning result of the function:

import memory_profiler as mp

def fun(n):
    tmp = []
    for i in range(n):
        tmp.extend(list(range(i*i)))
    return "XXXXX"

calculate memory usage before running the code then calculate max usage during the code:

start_mem = mp.memory_usage(max_usage=True)
res = mp.memory_usage(proc=(fun, [100]), max_usage=True, retval=True) 
print('start mem', start_mem)
print('max mem', res[0][0])
print('used mem', res[0][0]-start_mem)
print('fun output', res[1])

calculate usage in sampling points while running function:

res = mp.memory_usage((fun, [100]), interval=.001, retval=True)
print('min mem', min(res[0]))
print('max mem', max(res[0]))
print('used mem', max(res[0])-min(res[0]))
print('fun output', res[1])

Credits: @skeept

How to use aria-expanded="true" to change a css property

Why javascript when you can use just css?

_x000D_
_x000D_
a[aria-expanded="true"]{_x000D_
  background-color: #42DCA3;_x000D_
}
_x000D_
<li class="active">_x000D_
   <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> _x000D_
       <span class="network-name">Google+</span>_x000D_
   </a>_x000D_
</li>_x000D_
<li class="active">_x000D_
   <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> _x000D_
       <span class="network-name">Google+</span>_x000D_
   </a>_x000D_
</li>
_x000D_
_x000D_
_x000D_

Is there a replacement for unistd.h for Windows (Visual C)?

I would recommend using mingw/msys as a development environment. Especially if you are porting simple console programs. Msys implements a Unix-like shell on Windows, and mingw is a port of the GNU compiler collection (GCC) and other GNU build tools to the Windows platform. It is an open-source project, and well-suited to the task. I currently use it to build utility programs and console applications for Windows XP, and it most certainly has that unistd.h header you are looking for.

The install procedure can be a little bit tricky, but I found that the best place to start is in MSYS.

SQL grouping by all the columns

nope. are you trying to do some aggregation? if so, you could do something like this to get what you need

;with a as
(
     select sum(IntField) as Total
     from Table
     group by CharField
)
select *, a.Total
from Table t
inner join a
on t.Field=a.Field

How to get file name when user select a file via <input type="file" />?

I'll answer this question via Simple Javascript that is supported in all browsers that I have tested so far (IE8 to IE11, Chrome, FF etc).

Here is the code.

_x000D_
_x000D_
function GetFileSizeNameAndType()_x000D_
        {_x000D_
        var fi = document.getElementById('file'); // GET THE FILE INPUT AS VARIABLE._x000D_
_x000D_
        var totalFileSize = 0;_x000D_
_x000D_
        // VALIDATE OR CHECK IF ANY FILE IS SELECTED._x000D_
        if (fi.files.length > 0)_x000D_
        {_x000D_
            // RUN A LOOP TO CHECK EACH SELECTED FILE._x000D_
            for (var i = 0; i <= fi.files.length - 1; i++)_x000D_
            {_x000D_
                //ACCESS THE SIZE PROPERTY OF THE ITEM OBJECT IN FILES COLLECTION. IN THIS WAY ALSO GET OTHER PROPERTIES LIKE FILENAME AND FILETYPE_x000D_
                var fsize = fi.files.item(i).size;_x000D_
                totalFileSize = totalFileSize + fsize;_x000D_
                document.getElementById('fp').innerHTML =_x000D_
                document.getElementById('fp').innerHTML_x000D_
                +_x000D_
                '<br /> ' + 'File Name is <b>' + fi.files.item(i).name_x000D_
                +_x000D_
                '</b> and Size is <b>' + Math.round((fsize / 1024)) //DEFAULT SIZE IS IN BYTES SO WE DIVIDING BY 1024 TO CONVERT IT IN KB_x000D_
                +_x000D_
                '</b> KB and File Type is <b>' + fi.files.item(i).type + "</b>.";_x000D_
            }_x000D_
        }_x000D_
        document.getElementById('divTotalSize').innerHTML = "Total File(s) Size is <b>" + Math.round(totalFileSize / 1024) + "</b> KB";_x000D_
    }
_x000D_
    <p>_x000D_
        <input type="file" id="file" multiple onchange="GetFileSizeNameAndType()" />_x000D_
    </p>_x000D_
_x000D_
    <div id="fp"></div>_x000D_
    <p>_x000D_
        <div id="divTotalSize"></div>_x000D_
    </p>
_x000D_
_x000D_
_x000D_

*Please note that we are displaying filesize in KB (Kilobytes). To get in MB divide it by 1024 * 1024 and so on*.

It'll perform file outputs like these on selecting Snapshot of a sample output of this code

Unresolved external symbol on static class members

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

Droppping schema and recreating it with utf8mb4 character set solved my issue.

Double precision floating values in Python?

For some applications you can use Fraction instead of floating-point numbers.

>>> from fractions import Fraction
>>> Fraction(1, 3**54)
Fraction(1, 58149737003040059690390169)

(For other applications, there's decimal, as suggested out by the other responses.)

Adding extra zeros in front of a number using jQuery?

var str = "43215"; 
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
                                str = "0" + str;

                        }
console.log("After : \n string :"+str+"\n Length :"+str.length);

It worked for me ! To increase the zeroes, update the 'max' variable

Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:

How to highlight a selected row in ngRepeat?

You probably want to have LI rather than the UL have the background-color:

.selected li {
  background-color: red;
}

Then you want to have a dynamic class for the UL:

<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">

Now you need to update the $scope.selected when clicking the row:

$scope.setSelected = function() {
   console.log("show", arguments, this);
   this.selected = 'selected';
}

and then un-select the previously highlighted row:

$scope.setSelected = function() {
   // console.log("show", arguments, this);
   if ($scope.lastSelected) {
     $scope.lastSelected.selected = '';
   }
   this.selected = 'selected';
   $scope.lastSelected = this;
}

Working solution:

http://plnkr.co/edit/wq6nxc?p=preview

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

Are you using the HTML5 required attribute?

That will cause Chrome 10 to display a balloon prompting the user to fill out the field.

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

Generating Unique Random Numbers in Java

This is the most simple method to generate unique random values in a range or from an array.

In this example, I will be using a predefined array but you can adapt this method to generate random numbers as well. First, we will create a sample array to retrieve our data from.

  1. Generate a random number and add it to the new array.
  2. Generate another random number and check if it is already stored in the new array.
  3. If not then add it and continue
  4. else reiterate the step.
ArrayList<Integer> sampleList = new ArrayList<>();
sampleList.add(1);
sampleList.add(2);
sampleList.add(3);
sampleList.add(4);
sampleList.add(5);
sampleList.add(6);
sampleList.add(7);
sampleList.add(8);

Now from the sampleList we will produce five random numbers that are unique.

int n;
randomList = new ArrayList<>();
for(int  i=0;i<5;i++){
    Random random = new Random();
    n=random.nextInt(8);     //Generate a random index between 0-7

    if(!randomList.contains(sampleList.get(n)))
    randomList.add(sampleList.get(n));
    else
        i--;    //reiterating the step
}
        

This is conceptually very simple. If the random value generated already exists then we will reiterate the step. This will continue until all the values generated are unique.

If you found this answer useful then you can vote it up as it is much simple in concept as compared to the other answers.

tmux set -g mouse-mode on doesn't work

So this option has been renamed in version 2.1 (18 October 2015)

From the changelog:

 Mouse-mode has been rewritten.  There's now no longer options for:
    - mouse-resize-pane
    - mouse-select-pane
    - mouse-select-window
    - mode-mouse

  Instead there is just one option:  'mouse' which turns on mouse support

So this is what I'm using now in my .tmux.conf file

set -g mouse on

How do I make a matrix from a list of vectors in R?

One option is to use do.call():

 > do.call(rbind, a)
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

Textarea onchange detection

I know this isn't exactly your question but I thought this might be useful. For certain applications it is nice to have the change function fire not every single time a key is pressed. This can be achieved with something like this:

var text = document.createElement('textarea');
text.rows = 10;
text.cols = 40;
document.body.appendChild(text);

text.onkeyup = function(){
var callcount = 0;
    var action = function(){
        alert('changed');
    }
    var delayAction = function(action, time){
        var expectcallcount = callcount;
        var delay = function(){
            if(callcount == expectcallcount){
                action();
            }
        }
        setTimeout(delay, time);
    }
    return function(eventtrigger){
        ++callcount;
        delayAction(action, 1200);
    }
}();

This works by testing if a more recent event has fired within a certain delay period. Good luck!

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

I think the textbox you are trying to access is not yet loaded onto the page at the time your javascript is being executed.

ie., For the Javascript to be able to read the textbox from the DOM of the page, the textbox must be available as an element. If the javascript is getting called before the textbox is written onto the page, the textbox will not be visible and so NULL is returned.

List Directories and get the name of the Directory

This will print all the subdirectories of the current directory:

print [name for name in os.listdir(".") if os.path.isdir(name)]

I'm not sure what you're doing with split("-"), but perhaps this code will help you find a solution?

If you want the full pathnames of the directories, use abspath:

print [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]

Note that these pieces of code will only get the immediate subdirectories. If you want sub-sub-directories and so on, you should use walk as others have suggested.

Rendering HTML in a WebView with custom CSS

Is it possible to have all the content rendered in-page, in a given div? You could then reset the css based on the id, and work on from there.

Say you give your div id="ocon"

In your css, have a definition like:

#ocon *{background:none;padding:0;etc,etc,}

and you can set values to clear all css from applying to the content. After that, you can just use

#ocon ul{}

or whatever, further down the stylesheet, to apply new styles to the content.

jdk7 32 bit windows version to download

Go to the download page and download the Windows x86 version with filename jdk-7-windows-i586.exe.

How to extract text from the PDF document?

Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)

Code:

include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf'); 
$a->decodePDF();
echo $a->output(); 

  • class.pdf2text.php Project Home

  • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser


__init__ and arguments in Python

The current object is explicitly passed to the method as the first parameter. self is the conventional name. You can call it anything you want but it is strongly advised that you stick with this convention to avoid confusion.

Rotate axis text in python matplotlib

Easy way

As described here, there is an existing method in the matplotlib.pyplot figure class that automatically rotates dates appropriately for you figure.

You can call it after you plot your data (i.e.ax.plot(dates,ydata) :

fig.autofmt_xdate()

If you need to format the labels further, checkout the above link.

Non-datetime objects

As per languitar's comment, the method I suggested for non-datetime xticks would not update correctly when zooming, etc. If it's not a datetime object used as your x-axis data, you should follow Tommy's answer:

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

How ViewBag in ASP.NET MVC works

ViewBag is of type dynamic but, is internally an System.Dynamic.ExpandoObject()

It is declared like this:

dynamic ViewBag = new System.Dynamic.ExpandoObject();

which is why you can do :

ViewBag.Foo = "Bar";

A Sample Expander Object Code:

public class ExpanderObject : DynamicObject, IDynamicMetaObjectProvider
{
    public Dictionary<string, object> objectDictionary;

    public ExpanderObject()
    {
        objectDictionary = new Dictionary<string, object>();
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        object val;
        if (objectDictionary.TryGetValue(binder.Name, out val))
        {
            result = val;
            return true;
        }
        result = null;
        return false;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        try
        {
            objectDictionary[binder.Name] = value;
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

jQuery changing style of HTML element

I think you can use this code also: and you can manage your class css better

<style>
   .navigationClass{
        display: inline-block;
        padding: 0px 0px 0px 6px;
        background-color: whitesmoke;
        border-radius: 2px;
    }
</style>
<div id="header" class="row">
    <div id="logo" class="col_12">And the winner is<span>n't...</span></div> 
    <div id="navigation" class="row"> 
        <ul id="pirra">
            <li><a href="#">Why?</a></li>
            <li><a href="#">Synopsis</a></li>
            <li><a href="#">Stills/Photos</a></li>
            <li><a href="#">Videos/clips</a></li>
            <li><a href="#">Quotes</a></li>
            <li><a href="#">Quiz</a></li>
        </ul>
    </div>
 <script>
    $(document).ready(function() {
$('#navigation ul li').addClass('navigationClass'); //add class navigationClass to the #navigation .

});
 </script>

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

I know this is an older question, but for reference, a really simple way for formatting dates without any data annotations or any other settings is as follows:

@Html.TextBoxFor(m => m.StartDate, new { @Value = Model.StartDate.ToString("dd-MMM-yyyy") })

The above format can of course be changed to whatever.

jQuery - hashchange event

There is a hashchange plug-in which wraps up the functionality and cross browser issues available here.

"No Content-Security-Policy meta tag found." error in my phonegap application

For me it was enough to reinstall whitelist plugin:

cordova plugin remove cordova-plugin-whitelist

and then

cordova plugin add cordova-plugin-whitelist

It looks like updating from previous versions of Cordova was not succesful.

Make column fixed position in bootstrap

With bootstrap 4 just use col-auto

<div class="container-fluid">
    <div class="row">
        <div class="col-sm-auto">
            Fixed content
        </div>
        <div class="col-sm">
            Normal scrollable content
        </div>
    </div>
</div>

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

The raw_json_encode() function above did not solve me the problem (for some reason, the callback function raised an error on my PHP 5.2.5 server).

But this other solution did actually work.

https://www.experts-exchange.com/questions/28628085/json-encode-fails-with-special-characters.html

Credits should go to Marco Gasi. I just call his function instead of calling json_encode():

function jsonRemoveUnicodeSequences( $json_struct )
{ 
    return preg_replace( "/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode( $json_struct ) );
}

How to add an element to the beginning of an OrderedDict?

EDIT (2019-02-03) Note that the following answer only works on older versions of Python. More recently, OrderedDict has been rewritten in C. In addition this does touch double-underscore attributes which is frowned upon.

I just wrote a subclass of OrderedDict in a project of mine for a similar purpose. Here's the gist.

Insertion operations are also constant time O(1) (they don't require you to rebuild the data structure), unlike most of these solutions.

>>> d1 = ListDict([('a', '1'), ('b', '2')])
>>> d1.insert_before('a', ('c', 3))
>>> d1
ListDict([('c', 3), ('a', '1'), ('b', '2')])

Which data structures and algorithms book should I buy?

If you want the algorithms to be implemented specifically in Java then there is Mitchell Waite's Series book "Data Structures & Algorithms in Java". It starts from basic data structures like linked lists, stacks and queues, and the basic algorithms for sorting and searching. Working your way through it you will eventually get to Tree data structures, Red-Black trees, 2-3 trees and Graphs.

All-in-all its not an extremely theoretical book, but if you just want an introduction in a language you are familiar with then its a good book. At the end of the day, if you want a deeper understanding of algorithms you're going to have to learn some of the more theoretical concepts, and read one of the classics, like Cormen/Leiserson/Rivest/Stein's Introduction to Algorithms.

What is the difference between URL parameters and query strings?

Parameters are key-value pairs that can appear inside URL path, and start with a semicolon character (;).

Query string appears after the path (if any) and starts with a question mark character (?).

Both parameters and query string contain key-value pairs.

In a GET request, parameters appear in the URL itself:

<scheme>://<username>:<password>@<host>:<port>/<path>;<parameters>?<query>#<fragment>

In a POST request, parameters can appear in the URL itself, but also in the datastream (as known as content).

Query string is always a part of the URL.

Parameters can be buried in form-data datastream when using POST method so they may not appear in the URL. Yes a POST request can define parameters as form data and in the URL, and this is not inconsistent because parameters can have several values.

I've found no explaination for this behavior so far. I guess it might be useful sometimes to "unhide" parameters from a POST request, or even let the code handling a GET request share some parts with the code handling a POST. Of course this can work only with server code supporting parameters in a URL.

Until you get better insights, I suggest you to use parameters only in form-data datastream of POST requests.

Sources:

What Every Developer Should Know About URLs

RFC 3986

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

You can take a look at source-code-wordle.de, I have analyzed there the most frequently used suffixes of class names of the .NET framework and some other libraries.

The top 20 are:

  • attribute
  • type
  • helper
  • collection
  • converter
  • handler
  • info
  • provider
  • exception
  • service
  • element
  • manager
  • node
  • option
  • factory
  • context
  • item
  • designer
  • base
  • editor

GitLab git user password

if you are sure that you have uploaded the content of key.pub into GitLab, then: 1- Open Git Bash "Not CMD" 2- Browse to Solution Folder "CD Path" 3- Type Git Init 4- Type Git Add . 4- Type Git Commit 6- Type Git Push

and it will work.. another hint: make sure the path of the file where you copied the key is correct and equivalent to the same path it showed on CMD when creating the keys

How can I mock an ES6 module import using Jest?

The question is already answered, but you can resolve it like this:

File dependency.js

const doSomething = (x) => x
export default doSomething;

File myModule.js

import doSomething from "./dependency";

export default (x) => doSomething(x * 2);

File myModule.spec.js

jest.mock('../dependency');
import doSomething from "../dependency";
import myModule from "../myModule";

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    doSomething.mockImplementation((x) => x * 10)

    myModule(2);

    expect(doSomething).toHaveBeenCalledWith(4);
    console.log(myModule(2)) // 40
  });
});

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

Simply check how many CPUs you are allocating. With one CPU you do not need to play with your bios.

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

In prototypeJS, we have method isJSON. You can try that. Even json might help.

"something".isJSON();
// -> false
"\"something\"".isJSON();
// -> true
"{ foo: 42 }".isJSON();
// -> false
"{ \"foo\": 42 }".isJSON();

Can I use a min-height for table, tr or td?

In CSS 2.1, the effect of 'min-height' and 'max-height' on tables, inline tables, table cells, table rows, and row groups is undefined.

So try wrapping the content in a div, and give the div a min-height jsFiddle here

<table cellspacing="0" cellpadding="0" border="0" style="width:300px">
    <tbody>
        <tr>
            <td>
                <div style="min-height: 100px; background-color: #ccc">
                    Hello World !
                </div>
            </td>
            <td>
                <div style="min-height: 100px; background-color: #f00">
                    Good Morning !
                </div>
            </td>
        </tr>
    </tbody>
</table>

Losing Session State

I was having a situation in ASP.NET 4.0 where my session would be reset on every page request (and my SESSION_START code would run on each page request). This didn't happen to every user for every session, but it usually happened, and when it did, it would happen on each page request.

My web.config sessionState tag had the same setting as the one mentioned above.

cookieless="false"

When I changed it to the following...

cookieless="UseCookies"

... the problem seemed to go away. Apparently true|false were old choices from ASP.NET 1. Starting in ASP.Net 2.0, the enumerated choices started being available. I guess these options were deprecated. The "false" value has never presented a problem in the past - I've only noticed in on ASP.NET 4.0. I don't know if something has changed in 4.0 that no longer supports it correctly.

Also, I just found this out not long ago. Since the problem was intermittent before, I suppose I could still encounter it, but so far it's working with this new setting.

Bootstrap 3 - 100% height of custom div inside column

My solution was to make all the parents 100% and set a specific percentage for each row:

html, body,div[class^="container"] ,.column {
    height: 100%;
}

.row0 {height: 10%;}
.row1 {height: 40%;}
.row2 {height: 50%;}

How to master AngularJS?

The video AngularJS Fundamentals In 60-ish Minutes provides a very good introduction and overview.

I would also highly recomend the AngularJS book from O'Reilly, mentioned by @Atropo.

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

function do_ajax(elem, mydata, filename)
{
    $.ajax({
        url: filename,
        context: elem,
        data: mydata,
        **contentType: false,
        processData: false**
        datatype: "html",
        success: function (data, textStatus, xhr) {
            elem.innerHTML = data;
        }
    });
}

How to update (append to) an href in jquery?

Here is what i tried to do to add parameter in the url which contain the specific character in the url.

jQuery('a[href*="google.com"]').attr('href', function(i,href) {
        //jquery date addition
        var requiredDate = new Date();
        var numberOfDaysToAdd = 60;
        requiredDate.setDate(requiredDate.getDate() + numberOfDaysToAdd); 
        //var convertedDate  = requiredDate.format('d-M-Y');
        //var newDate = datepicker.formatDate('yy/mm/dd', requiredDate );
        //console.log(requiredDate);

        var month   = requiredDate.getMonth()+1;
        var day     = requiredDate.getDate();

        var output = requiredDate.getFullYear() + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + ((''+day).length<2 ? '0' : '') + day;
        //

Working Example Click

Convert a string representation of a hex dump to a byte array using Java?

I know this is a very old thread, but still like to add my penny worth.

If I really need to code up a simple hex string to binary converter, I'd like to do it as follows.

public static byte[] hexToBinary(String s){

  /*
   * skipped any input validation code
   */

  byte[] data = new byte[s.length()/2];

  for( int i=0, j=0; 
       i<s.length() && j<data.length; 
       i+=2, j++)
  {
     data[j] = (byte)Integer.parseInt(s.substring(i, i+2), 16);
  }

  return data;
}