text:
Q: Retrieve the EMV Application File Locator without Get Processing Options I am writing code to extract as much data as possible from an EMV chip card.  I can select the application and I have code to send Get Processing Options, but that needs (in some cases) the PDOL to be evaluated and associated data supplied.
The data the PDOL asks for is based on a transaction though, and there will be no transaction in this sequence.  Once I have extracted the data then I'm done, so the only reason for GPO would be to get the Application File Locator (AFL).
I suspect the answer here is 'no', but is there any other way to get the AFL?  At the moment the only alternative is a brute-force series of Read Record calls with SFI from 1 to 10 and records from 1 to 31.  This is slow and, if I can get the AFL, unnecessary so I'm hoping for a more intelligent approach (but one that doesn't need GPO to be used).

A: As per EMV specifications PDOL if exists is returned in response to SELECT in A5 -  FCI Proprietary Template.
PDOL will provide the tag and length of data expected, but since you are not looking in a real transaction perspective, pack all tag data as zeros(make sure of the expected length) and send in GPO. It should return AFL which you could then use in READ RECORDS efficiently.

A: There is not a single way to retrieve AFL without issuing the GPO command.


text:
Q: Go function types that return structs being used with interfaces I have a struct in a package that has time consuming methods on it and is also time consuming to construct via it's factory function.  Therefore, in the package that depends on this other struct I would like to be able to test it using both a fake factory function and a fake struct once it has been created.  As the struct is constructed via a factory function I would like to fake the factory function and pass an alternative factory function into my struct during testing time.
An example of the expensive package would be:
package expensive

import "fmt"

type myStruct struct{}

func (m *myStruct) DoSomething() {
    fmt.Println("In Do something")
}

func (m *myStruct) DoSomethingElse() {
    fmt.Println("In do something else")
}

// CreateInstance is expensive to call
func CreateInstance() *myStruct {
    return &myStruct{}
}

My main package that uses this then looks like this:
package main

import "play/expensive"

func main() {
    thing := structToConstruct{expensive.CreateInstance}
    thing.performAction()
}

type myInterface interface {
    DoSomething()
}

type structToConstruct struct {
    factoryFunction func() myInterface
}

func (s *structToConstruct) performAction() {
    instance := s.factoryFunction()
    instance.DoSomething()
}

However, this code complains with the error:

.\main.go:6: cannot use expensive.CreateInstance (type func() *expensive.myStruct) as type func() myInterface in field value

However, *expensive.myStruct does implement the myInterface interface so I do not understand why Go is complaining about the type safety of this setup.
I've since realised after @jmaloney guideance that I could just wrapper my function like this in my main method:
    wrapper := func() myInterface {
        return expensive.CreateInstance()
    }
    thing := structToConstruct{wrapper}

and this then works but I still don't really understand why I can't use a struct that implements an interface when a function is expecting an instance of that interface to be returned especially when no type assertion/conversion is necessary on this fix as it is simply just calling the underlying factory function.
EDIT: I've since come across this proposal to add this to the language. The proposal was rejected:
https://github.com/golang/go/issues/12754

A: getInstance needs to return myInterface
package main

import "fmt"

func main() {
    var function func() myInterface

    function = getInstance

    newSomething := function()

    newSomething.doSomething()
}

type myInterface interface {
    doSomething()
}

type myStruct struct{}

func (m *myStruct) doSomething() {
    fmt.Println("doing something")
}

func getInstance() myInterface {
    return &myStruct{}
}

Playground example

However, *expensive.myStruct does implement the myInterface interface so I do not understand why Go is complaining about the type safety of this setup.

In that instance you were not dealing with Go's interfaces you were dealing with the type signature of your struct.
when you first declared your struct with factoryFunction func() *myFunction factoryFunction now always needs to match the declared signature.

A: See if this might help, have a function which returns an interface given the struct.
package main

import "fmt"

func main() {
    var instance myInterface

    // The return value of the getInstance function can be assigned to a variable
    // of type myInterface
    instance = getInstance()

    var function func(*myStruct) myInterface

    // But the function itself can't be assigned to a variable for a function
    // that returns a myInterface.  You get:
    // cannot use getInstance (type func() *myStruct) as type func() myInterface in assignment
    function = getMyInstance
    r := function(instance.(*myStruct))
    r.doSomething()
}

type myInterface interface {
    doSomething()
}

type myStruct struct{}

func (m *myStruct) doSomething() {
    fmt.Println("Done something")

}

func getInstance() *myStruct {
    return &myStruct{}
}

func getMyInstance(myInst *myStruct) myInterface {
    return myInst

}

Available at https://play.golang.org/p/h8iJ0i-Xym

redpajama_set_name: RedPajamaStackExchange


text:
Q: Upper Case all First Characters in a string Except certain words This convert the First Character of every word in a string to UpperCase
echo ucwords("hello world"); // Result : Hello World

How can I do the same except for certain words
example : new york branch 2 br property jbr
Should display : New York Branch 2 br Property jbr
// br and jbr are excluded from conversion but the br in the word branch is not affected by the exclusion

A: 1.You try doing it by first splitting the string by blank space like:
 $beforeb="new york branch 2 br property jbr"
 $afters=explode(" ",$beforeb);

2.Now using for each loop you can match every string and convert it into upper case if it doesnot with  words like br or jbr,and store it to an array ex,$array1[]
foreach($afters as $caseup){
$i=0;

 if($caseup=="br" || $caseup=="jbr"){   //selected words you dont want to make uppercase
   $array1[i]=$caseup;
 }
 else{
  $array1[i]=ucwords($caseup);
  }
  }

3.Then again convert the $array1[] into a string using implode() method


text:
Q: Android application stops after setText on TextView I have an android program which sends to another activity after clicking on a button. Mainly, I want to set the text from textview in the new windows so that it corresponds to the selected button. For example, if I click on button Writers, the next new activity should have a textview on which the word Writers appears. Everything works fine, except when I try to setText on the TextView icon for category. I also tried to call this change in the first activity, before launching the second one, it didn't work.
I also mention that if I comment the line with the setText, the program works just fine.
private String          category;
public final static String CATEGORY_MESSAGE = "e.c.project.CATEGORY";
public void onClick(View v) {
    switch(v.getId())
        {
            case R.id.actors:
                category = "actors";
                playTheGame(v);
            break;
            case R.id.cartoons:
                category = "cartoons";
                playTheGame(v);
        break;
            case R.id.singers:
                category = "singers";
                playTheGame(v);
            break;
            case R.id.writers:
                category = "writers";
                playTheGame(v);
            break;
        }
    }

    public void playTheGame( View view ){
        Intent intent = new Intent(this, PlayGame.class);
        String category = playGameButton.getText().toString();
        intent.putExtra(CATEGORY_MESSAGE, category);
//      TextView tv = (TextView) findViewById(R.id.categoryTV);
//      tv.setText(category);
        startActivity(intent);
    }

this is the OnCreate method from the second activity:
    private TextView            categoryTV;

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

    Intent intent = getIntent();
    String category = intent.getStringExtra(GameCategories.CATEGORY_MESSAGE);

    categoryTV = (TextView) findViewById(R.id.categoryTV);
    categoryTV.setText(category);

    setContentView(R.layout.activity_play_game);
    // Show the Up button in the action bar.
    setupActionBar();
}

A: You need to call setContentView(R.layout.activity_play_game); before categoryTV = (TextView) findViewById(R.id.categoryTV); Otherwise your TextView is null
   private TextView, categoryTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_play_game);  // make this call BEFORE initializing ANY views
       Intent intent = getIntent();
       String category = intent.getStringExtra(GameCategories.CATEGORY_MESSAGE);

       categoryTV = (TextView) findViewById(R.id.categoryTV);
       categoryTV.setText(category);

        // Show the Up button in the action bar.
         setupActionBar();
    }

Your Views exist in your Layout so if you try to access any of them before inflating your Layout, with setContentView() or an inflater, they will be null resulting in a NPE when you try to call a method on them such as setText()


text:
Q: Google API - Static Maps Frankly, I'm not sure what I'm doing wrong.  This is my code, but for some reason, the map is outputting a blank iFrame with a source URL that if I click will send me to the proper map, so the URL is being input correctly, but it's not actually being displayed on my website.
<?php $addressStr ="516 East Liberty Street, Ann Arbor, MI 48104"; ?>
<iframe width="206" height="175" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="<?php echo "http://maps.googleapis.com/maps/api/staticmap?center={$addressStr}&zoom=15&size=204x173&markers=color:orange|{$addressStr}&sensor=true&output=embed"; ?>"></iframe>

A: It's not an iframe. You need a standard <img> tag ?


text:
Q: Azure blockchain mining nodes not running I created a blockchain using azure's blockchain as a service.
I encountered the following problem :
In the admin site, I see that my mining node are not running :

And I can sent ether from an account to another for example.
However, I am sure that I started my VMs and it is confirmed when see my dashboard :

Can anyone help me with that ?

A: It seems that blockchain could not ssh to your VM. You need check your NSG and Azure Load Balancer Inbound NAR rules. Please the port is you needed.

You could use this template to deploy your blockchain service. Click Deploy to Azure. You could modify the value in Portal.

According to your scenario, you need modify 5 values.
"adminSitePort": 3000,
"sshNATFrontEndStartingPort": 3000,
"destinationPortRange": "3000",
"gethRPCPort": 8545,
"destinationPortRange": "8545",


text:
Q: Dependency Injection - When to use property injection I've a class which have a constructor like this:
    private string _someString;
    private ObjectA _objectA;
    private ObjectB _objectB;
    private Dictionary<Enum, long?> _dictionaryA;
    private Dictionary<Tuple<Enum,long?>, long?> _dictionaryB;

    public SomeDiClass(string someString)
    {
        _someString = someString;

        _objectA = new ObjectA();
        _objectB = new ObjectB();

        _dictionaryA = new Dictionary<Enum, long?>();
        _dictionaryB = new Dictionary<Tuple<Enum, long?>, long?>();
    }

I want to get the dependency creation out of this constructor. In a first step I would move the ObjectA and B dependency to the constructors parameters to inject them via constructor injection. I would like to use a IoC container for this purpose, that's where I stuck at the moment. The question is what to to with someString and the dictionaries. I need to inject them to the class, because the content of the dictionaries will be an important part of unit tests.
Would it be a good idea to inject the string and the dictionaries via property injection (I don't need them in other classes), so I would end up with something like this?:
    private ObjectA _objectA;
    private ObjectB _objectB;

    public string SomeString { get; set; }
    public Dictionary<Enum, long?> DictionaryA { get; set; }
    public Dictionary<Tuple<Enum, long?>, long?> DictionaryB { get; set; }

    public SomeDiClass(ObjectA objectA, ObjectB objectB)
    {
        _objectA = objectA;
        _objectB = objectB;
    }

Is there a best practice to solve something like this?

A: You should use property injection (or setter injection) when object creation of your type is out of your control. Like aspx Page, HttpHandler, ApiController etc. For all others situations it is recommended to use constructor injection.
To resolve dependencies for aspx Page using StructureMap, i use the following approach.
First, I create a BasePage class and use StructureMap's BuildUp() method in the constructor to resolve dependencies of the derived pages. Code is given below:
public class BasePage : Page
{
    public BasePage()
    {
        // instruct StructureMap to resolve dependencies
        ObjectFactory.BuildUp(this);
    }
}

public class Default : BasePage
{
     public ICustomerService customerService { get; set; }

     protected void Page_Load(object sender, EventArgs e)
     {
         // can start using customerService
     }
}

public class Login : BasePage
{
     public IAuthenticationService authenticationService { get; set; }

     protected void Page_Load(object sender, EventArgs e)
     {
         // can start using authenticationService
     }
}

A: Dependency Injection is not an end goal, but a solution to a particular set of problems. For instance, Dependency Injection makes it easy to replace abstractions for unit testing and makes your application more flexible, since you can swap, decorate and intercept dependencies without having to change the consuming classes. A good introduction to Dependency Injection can be found in this freely available chapter 1 of the book Dependency Injection Principles, Practices, and Patterns (DIPP&P), which I coauthored.
That doesn't mean that you should inject every dependency a class has, since it must help you in making the class more testable and the system more maintainable. So you have to ask yourself whether it helps from a testing perspective to inject those dictionaries from the outside or if it helps to make your application more flexible. To get a good grasp on what to inject—and what not—you should learn about the concepts of Volatile and Stable Dependencies, which can be read in section 1.3 of chapter 1 of DIPP&P.
Whether it helps from a testing or maintainability perspective, is a question that is hard to answer, because your question doesn't have enough detail. But here are some pointers:
The only things you typically want to inject into a class are services and configuration values.

*

*A service is some contract/abstraction/interface that provides 'a service.' This typically means that the service will do something on your behalf, such as calculate prices, communicate to the database, cache values, return the system's time, or format your hard drive :)

*A configuration value is what it is; just a value. But you need to inject it—it can't be hard coded into the class, and you don't want the class to fetch the value itself from the ConfigurationManager, for instance, because that would create a hidden dependency (on the Configurationmanager) and this would make the class harder to test.
Other things, such as primitives, messages, DTOs, collection types and entities, and anything else that doesn't provide any service (business logic) and isn't in the way of unit testing, doesn't have to be abstracted and, therefore, doesn't have to be injected (and in fact shouldn't be injected through the constructor or property). In your case the dictionaries some part of the internal state of the SomeDiClass class, not a service your class depends on.
If, on the other hand, those dictionaries are reused by other services, those dictionaries will have to be injected. But you never want to inject such dictionary itself directly, since the dictionary itself is no service. Instead you need to create an abstraction around them; something that hides the details of that dictionary and provides the application with a service around it.


text:
Q: Getting Access Denied I am trying to open ie11 using selnium web driver and java.
My code looks like this
public static void main(String[] args) {
    System.setProperty("webdriver.ie.driver",
    "C:\\Users\\ankit.pande\\Downloads\\IEDriverServer_x64_3.14.0\\IEDriverServer.exe");
    InternetExplorerOptions options = new InternetExplorerOptions();
    options.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
    WebDriver webDriver = new InternetExplorerDriver(options);
    webDriver.manage().window().maximize();
    String url = "https://www.toolsqa.com/automation-practice-form/";
    webDriver.navigate().to(url);
    webDriver.close();
}

I have changed the registry settings and Enabled protected mode(for all options)..Still I am getting

Exception in thread "main"
  org.openqa.selenium.SessionNotCreatedException: Unexpected error
  launching Internet Explorer. IELaunchURL() returned HRESULT 80070005
  ('Access is denied.') for URL 'http://localhost:15641/'

error


text:
Q: I want to track my current location in an Android application Here I create one project that will track our current location.
But I have a problem coding it...  I don't know exactly how to use the OVERLAY class and when it is called.
I have posted my code.. Please help me
package com.techno.gps;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public class gps extends MapActivity{

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

     // Get a reference to the MapView
        MapView myMapView = (MapView)findViewById(R.id.mapView);
        // Get the Map View's controller
        mapController = myMapView.getController();
        // Configure the map display options
        myMapView.setSatellite(true);
        myMapView.setStreetView(true);
        myMapView.displayZoomControls(false);
        // Zoom in
        mapController.setZoom(17);
        //add postionoverlay
        positionOverlay = new MyPositionOverlay();
        List<Overlay> overlays = myMapView.getOverlays();
        overlays.add(positionOverlay);

        LocationManager locationManager;
        String context = Context.LOCATION_SERVICE;
        locationManager = (LocationManager)getSystemService(context);

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        String provider = locationManager.getBestProvider(criteria, true);
        location = locationManager.getLastKnownLocation(provider);
        updateWithNewLocation(location);
        locationManager.requestLocationUpdates(provider, 2000, 10,locationListener);

    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

    private void updateWithNewLocation(Location location)
    {
        String latLongString;
        TextView myLocationText;
        myLocationText = (TextView)findViewById(R.id.myLocationText);

        String addressString = "No address found";
        if (location != null) {
        // Update the map location.
        positionOverlay.setLocation(location);
        Double geoLat = location.getLatitude()*1E6;
        Double geoLng = location.getLongitude()*1E6;
        GeoPoint point = new GeoPoint(geoLat.intValue(),
        geoLng.intValue());
        mapController.animateTo(point);
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        latLongString = "Lat: "+ lat + " Long:" + lng;
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        Geocoder gc = new Geocoder(this, Locale.getDefault());
        try
        {
                List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
                StringBuilder sb = new StringBuilder();
                if (addresses.size() > 0)
                {
                    Address address = addresses.get(0);
                    for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                    {
                        sb.append(address.getAddressLine(i)).append("\n");
                    }
                    sb.append(address.getLocality()).append("\n");
                    sb.append(address.getPostalCode()).append("\n");
                    sb.append(address.getCountryName());
                }
                addressString = sb.toString();
                }
                catch (IOException e)
                {

                }

        }
            else
            {
                latLongString = "No location found";
            }
            myLocationText.setText("Your Current Position is:\n" +latLongString + "\n" + addressString);

        }

        private final LocationListener locationListener = new LocationListener()
        {
                public void onLocationChanged(Location location) {
                updateWithNewLocation(location);
        }
        public void onProviderDisabled(String provider)
        {
            updateWithNewLocation(null);
        }
        public void onProviderEnabled(String provider)
        {

        }
        public void onStatusChanged(String provider, int status,Bundle extras)
        {

        }
    };

    public class MyPositionOverlay extends Overlay
    {
        Location location;
        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow)
        {
            Projection projection = mapView.getProjection();
            if (shadow == false) {
            // Get the current location
            Double latitude = location.getLatitude()*1E6;
            Double longitude = location.getLongitude()*1E6;
            GeoPoint geoPoint;
            geoPoint = new GeoPoint(latitude.intValue(),longitude.intValue());
            // Convert the location to screen pixels
            int mRadius=5;
            Point point = new Point();
            projection.toPixels(geoPoint, point);
            RectF oval = new RectF(point.x - mRadius, point.y - mRadius,
            point.x + mRadius, point.y + mRadius);
            // Setup the paint
            Paint paint = new Paint();
            paint.setARGB(250, 255, 0, 0);
            paint.setAntiAlias(true);
            paint.setFakeBoldText(true);
            Paint backPaint = new Paint();
            backPaint.setARGB(175, 50, 50, 50);
            backPaint.setAntiAlias(true);
            RectF backRect = new RectF(point.x + 2 + mRadius,
            point.y - 3*mRadius,
            point.x + 65, point.y + mRadius);
            // Draw the marker
            canvas.drawOval(oval, paint);
            canvas.drawRoundRect(backRect, 5, 5, backPaint);
            canvas.drawText("Here I Am", point.x + 2*mRadius, point.y, paint);
            }
            super.draw(canvas, mapView, shadow);
        }
        @Override
        public boolean onTap(GeoPoint point, MapView mapView)
        {
            // Return true if screen tap is handled by this overlay
            return false;
        }

        public Location getLocation() {
        return location;
        }
        public void setLocation(Location location) {
        this.location = location;
        }

   }

}

thanks...

A: Strange that you don't know your own code. You should try writing it by yourself. Copy-pasting does not work always.
To answer your question. An Overlay is drawable object that can be shown on top of the map on a different layer above the MapView.
This is the part of the code where you add that drawing to the MapView.
    positionOverlay = new MyPositionOverlay();
    List<Overlay> overlays = myMapView.getOverlays();
    overlays.add(positionOverlay);

You are doing this in OnCreate(). Which does not makes sense, because you have no position fix yet.

*

*Add the overlay when you get a pos-fix in updateWithNewLocation()

*To call draw forcefully use MapView.invalidate()

A: i have the same example code, with 2.2 android, works, but don't drow the overlay, with my position, otherwise, with debuggin you can see code working properltly. Really strange.
I think code is correct, because, in onCreate, code is initializated, then in updateWithNewLocation, the overlay is updated with positionOverlay.setLocation(location);


text:
Q: android onClick event not firing I really need a help on this point because its the only thing not working in my app.
I have a listview managed by an adapter that is extending BaseAdapter.
In the getview function im using the convertView to set up a OnClickListener.
This OnClickListener work well when I am touching the screen but if I use the trackball of the HTC Desire, I see the row flashing on the screen, but the OnClickListener is not called...
I've read the android dev guide : http://developer.android.com/guide/topics/ui/ui-events.html
and its say that I should receive a onClick event from the trackball...
Im putting here my getview code in case someone see anything strange. If you have any idea on what I can do, please let me know.
public View getView(int position, View convertView, ViewGroup parent) {
        //ici on va utiliser un mécanisme de cache avec le Tag Holder
        MyTag holder;
        if (convertView == null){
            //On se branche sur le bon layout
            // convertView = inflater.inflate(android.R.layout.simple_list_item_2, null)
             convertView = inflater.inflate(R.layout.twolines, null);
            holder          = new MyTag();
            //on récupère les éléments du layout dans le holder
            holder.txtData  = (TextView)convertView.findViewById(R.id.productTitle);
            holder.txtExtra = (TextView)convertView.findViewById(android.R.id.text2);
            holder.imgScreenshot = (ImageView)convertView.findViewById(R.id.Screenshot);
            holder.imgFlag = (ImageView)convertView.findViewById(R.id.Flag);

            //holder.mLoginButton = (LoginButton) convertView.findViewById(R.id.login);
            holder.mPostButton = (ImageView) convertView.findViewById(R.id.postButton);

            //sauvegarde du holder
            convertView.setTag(holder);
        } else {
            holder = (MyTag)convertView.getTag();
        }

        //Facebook post button management
        holder.mPostButton.setOnClickListener((OnClickListener) new OnPostClickListener(convertView.getContext(),mFacebook, Long.toString(data[position].videoId), data[position].title, data[position].publisher, data[position].imageUrl));

        holder.mPostButton.setImageResource(com.cedemo.scan.utils.getPostButtonResId());

        //data update
        if(data[position].title != null)
            holder.txtData.setText(data[position].title);
        if(data[position].publisher != null)
            holder.txtExtra.setText(data[position].publisher);

        //get and set the language flag
        if(data[position].language != null)
            holder.imgFlag.setImageResource(com.cedemo.scan.utils.getFlag(data[position].language));

        //set the screenshot
        if(data[position].myVideoScreenshotBm != null)
            holder.imgScreenshot.setImageBitmap(data[position].myVideoScreenshotBm);

                    /* =================================================================

                       THIS FUNCTION IS NOT CALLED WHEN I CLICK ON THE TRACKBALL
                       BUT IS CALLED WHEN I TOUCH THE SCREEN.
                       WHEN I USE THE TRACKBALL THE SELECTED ROW IS FLASHING ONCE.

                       ================================================================= */
        //set the click mechanic if there is a valid video url
        if(data[position].url != null) {
            convertView.setOnClickListener((OnClickListener) new OnProductClickListener(position));

        }

        return convertView;
    }

A: Maybe you want to use the recommended method setOnItemClickListener() on the ListView instead - I guess it is a bad style to set the listeners directly within the adapter.


text:
Q: Transferring an iMovie project with AirDrop gives "Insufficient Space" repeatedly I've come across this problem a few times now.

*

*I initiate a transfer of an iMovie project from my iPhone to my son's iPad (both with current software as of August 2016: iOS 9 and iMovie 2).

*The transfer appears to complete, but then we see Insufficient Space. There's not enough disk space to copy this project. About X MB more space is needed on my son's iPad.

*We free up some space on my son's iPad (more than X MB) and repeat the transfer.

*Sadly, we see the same error message.  The free space we created in the previous step has disappeared.

*We free up some more space and repeat this process, my hair gradually turning white.

Where is the free space going, and how can we successfully transfer the project?

A: I think the following is what actually happens when using AirDrop to transfer an iMovie project from one iOS device to another:

*

*The project is transferred from the sending device into an "iTunes" holding area on the receiving device.  (I'm putting "iTunes" in quotes here, because iTunes the desktop app isn't actually involved in this AirDrop process).

*The receiving device then copies the project from there into the main iMovie area.

The issue described in the question occurs when there is enough space to complete step (1), but not step (2).
The "iTunes" holding area can be managed, once you understand this and know what to look for.
On the main iMovie screen (which allows selection between Video / Projects / Theatre), there is an arrow-into-box icon.  This is at top left (iPad) or bottom left (iPhone):

Press the arrow-into-box icon and then select the iTunes tab.  This lists the items available in the "iTunes" holding area I described above.

Projects that failed to complete an AirDrop transfer due to a failure at step 2 are listed here.  This is the cause of the repeated lack of space.
Tapping on an item imports it into iMovie (as in step 2 above), if there is enough space.
Tapping the bin icon allows items to be deleted.  Deleting unwanted items should help to free up enough space to resolve the issue.


text:
Q: Is there a way to use css pseudo classes as mixins with lesscss compilers? I was trying to use a class with psuedo class in the less css mixin
a:link{
    color:#138CB4;
    text-decoration:none;
}
a:visited{
    a:link;
    color:#84B6CD;
}

But out put I got is this, which an invalid css
a:link{
    color: #138CB4;
    text-decoration: none;
}
a:visited{
    a: link;
    color: #84B6CD;
}

Am I missing something here or mixins don't support pseudo classes yet.

A: I don't believe that is how you use mixin's in Less.
You have defined the link pseudo class and then nested it under the visited pseudo class.  This doesn't actually mean anything and is why your are getting that output.
If I think what you are aiming for is to re-use your link styles across :visited and :link, you actually will want this:
.link {
  color: #138CB4;
  text-decoration: none;
}

a:link {
  .link;
}

a:visited{
  .link;
  color: #84B6CD;
}

A: I was a little confused by this at first, too, and found myself jumping through hoops to get it to work.  Although your post is old enough that it might pre-date this functionality for all I know.
Anyway, if you're just trying to add additional styles to an existing style via pseudo-selectors, you can use the '&' operator.  It works kind of like a 'this' keyword, and turns nesting into a simple combination.  So you should be able to do:
a {
  color: #138CB4;
  text-decoration: none;

  &:visited {
    color: #84B6CD;
  }
}

This should compile out to something like:
a {
  color: #138CB4;
  text-decoration: none;
}

a:visited {
    color: #84B6CD;
}

Note that you can also use the & to combine 'sub-selectors':
.outer {
  color: blue;

  .error {
    //this will select elements that are .error inside-of/descending-from .outer
  }

  &.error {
    //This will select elements that are .outer AND .error
    color: red;
  }
}

The official definition is unfortunately hiding in plain sight in the Nesting Rules part of the documentation.

A: Not fully sure, what you want to achieve. But if you got tired of :link,:visted,:active (aka normal link) vs. :focus, :hover (hover styles), this works:
.anchor( @- ) {
    a, a:link, a:visited, a:active {
        @-();
    }
}
.anchorH( @- ) {
    a:focus, a:hover {
        @-();
    }
}

for example:
.anchor({
    background: #fff;
});

.anchorH({
    background: #ddd; /* darken on hover or focus */
});


text:
Q: Trigger custom events in Google Analytics, using script containing gtag Im trying to create a script that sends custom events to GA, whenever visitors click on certain links - in this case all 'tel:' links.
But no events are getting fired in my script atm - and I'm getting a "keep alive" error.
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=-UA-1234567-89"></script>
<script type="text/javascript">
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-1234567-89');

jQuery("a[href^='tel']").on('click', function (){
    gtag('event', 'klik', {
      'event_category': 'mobil_opkald',
    });
});
</script>

Any help is greatly appreciated!


text:
Q: Get Schema Registry URL from Connect properties How to get the schema registry url from the connect properties with in a connector ?
I like to access this schema url with in my connector to get schema based on an ID.
Yes , i can explicitly pass schema.url as a property in my connector. But is there other way to get it automatically in the connector from connect proeprties ?
Thank You,


text:
Q: How to safely experiment with scripts that fork themselves I was experimenting with a bash script that would recursively fork and call itself. The terminating condition was subtle and I got it a wrong a few times, the result being a script that called itself ad infinitum. What's a safe way to sandbox a script like this while debugging it so that every time there's a mistake, I don't have to deal with stopping the infinite tower that fills up the process table?

A: You could use ulimit
ulimit -u 20

Will limit the maximum number of processes runned by your user

A: You could simply count the numbers of processes with your script name and terminate if the number gets too high.
This blog post introduces a function to achieve this:
count_process(){
  return $(ps -ef | grep -v grep | grep -c $1)
}

Explanation (taken from blog post):

*

*ps -ef will return a list of all running processes (in detail),

*and the process list will then be filtered first to exclude any instances of grep

*and second to count the processes specified with $1
For re-usability the author provides the function as little script:
#!/bin/sh
#
#   /usr/bin/processCount
#   Source: http://samcaldwell.net/index.php/technical-articles/3-how-to-articles/68-how-do-i-count-the-number-of-linux-instances-of-a-given-process-using-a-bash-script
#
[ -z $1 ] && {
  echo " "
  echo "Missing expected input."
  echo " "
  echo "USAGE:"
  echo " "
  echo " $0 <executable file>"
  echo " "
  echo " NOTE: When executing this script use the path and filename of the"
  echo " program. Using only the process name can potentially return inaccurate"
  echo " results."
  echo " "
  exit 1
}

echo $(ps -ef | grep -v grep | grep -v $0 | grep -c $1)

#script ends here.


text:
Q: finding the area between two curves using two parts I think I have this correct, but would like to check my concepts are sound because this needed two integrations.

So, it looks to me like this would best be done by a dy problem, divided into two parts as follows: {in this question I will finally figure out how to write integrals with bounds in Mathjax}
$A=\int_0^1 y^\frac14 dy + \int_1^e (1-ln y) dy$
The other issue with this answer, although intuitively correct, is that we have not yet learned integration by parts.  So, integrating $ln y$ was on my own from the internet.
Is the integral for the area set up correctly?


text:
Q: DLL out int not accepted I have built a DLL in C#.
In the following function the IDE tells my that the function _api.Version has some invalid arguments. But I don't think that this is true.
    public int getVersion(out int uMaj, out int uMin, out int uBuild, out int uDev)
    {
        ApiError error;
        error = _api.Version(uMaj, uMin, uBuild, uDev); //IDE does not like this
        int iRet = (int)error;
        return iRet;
    }

The "Version" function is defined as follows:
    public ApiError Version(out int major, out int minor, out int build, out int device);

Does anybody see my error?
Thank you for the help!
The entire code of my DLL is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using B.Api;

namespace ABWrapperNET
{

    public class clsWrapper
    {
        someApi _api = new someApi();

        public int getVersion(out int uMaj, out int uMin, out int uBuild, out int uDev)
        {
            ApiError error;
            error = _api.Version(uMaj, uMin, uBuild, uDev);
            int iRet = (int)error;
            return iRet;
        }
    }
}

A: In C#, you need to specify out and ref modifiers at the call site as well as in the member declaration. That means that anyone reading the code is aware of what is going on. (This is a big boost to readability, in my view.)
So you want:
public int GetVersion(out int uMaj, out int uMin, out int uBuild, out int uDev)
{
    ApiError error = _api.Version(out uMaj, out uMin, out uBuild, out uDev);
    return (int)error;
}

Note:

*

*I've fixed the method name to follow .NET naming conventions

*I've removed the pointless declaration/assignment split for error

*I've removed the temporary variable for the cast to int; you could reintroduce this for debugging purposes if you want

*I would personally get rid of the u prefix on each method parameter, having something like:
public int GetVersion(out int major, out int minor, out int build, out int foo)

... replacing foo with whatever the abbreviation "dev" is meant to represent.
You should also consider just returning a Version object, and use exceptions for errors:
public Version GetVersion()
{
    int major, minor, build, foo;
    ApiError error = _api.Version(out major, out minor, out build, out foo);
    if (error != ApiError.Success) // Or whatever it uses
    {
        // You'd probably need to create this class yourself
        throw new ApiException(error);
    }
}

A: In your call to the function, you need to prefix the variable names with out.
I would guess this requirement is for readability purposes. Normally a programmer would not expect an integer being passed to a function to be modified, so if out or ref weren't there, the variable being modified would be a huge surprise.


text:
Q: ELKI: How to create Database from several files in java I try to get data from several csv files. I use ConcatenateFilesDatabaseConnection for db
Database getDbFromFiles(List<File> files) {
    ListParameterization params = new ListParameterization();
    params.addParameter(ConcatenateFilesDatabaseConnection.Parameterizer.PARSER_ID, files);
    Database db = ClassGenericsUtil.parameterizeOrAbort(StaticArrayDatabase.class, params);
return db;
    }

like for FileBasedDatabaseConnection
ListParameterization params = new ListParameterization();
params.addParameter(FileBasedDatabaseConnection.Parameterizer.INPUT_ID, filename);
Database db = ClassGenericsUtil.parameterizeOrAbort(StaticArrayDatabase.class, params);

but when i run i get error

de.lmu.ifi.dbs.elki.utilities.optionhandling.UnspecifiedParameterException:
  No value given for parameter "dbc.in": Expected: The name of the input
  file to be parsed.
  de.lmu.ifi.dbs.elki.utilities.optionhandling.WrongParameterValueException:
  Wrong value of parameter dbc.parser. Read:
  [src\main\resources\data1.csv, src\main\resources\data2.csv,
  src\main\resources\data3.csv]. Expected: Parser to provide the
  database. Implementing de.lmu.ifi.dbs.elki.datasource.parser.Parser

Maybe someone worked with several files on ELKI and knew how
to do it right. I did not find the code to handle multiple files in ELKI

A: You set the parser to a List<File>. That cannot work.
A parser is a program routine that interprets the input of some (text) data stream.
You need to set the right parameter (the input file name, not the parser).
https://github.com/elki-project/elki/blob/709dbfa01b40ad023885b0745bad2f26184a4ac7/elki-input/src/main/java/de/lmu/ifi/dbs/elki/datasource/ConcatenateFilesDatabaseConnection.java#L164


text:
Q: In bash, why does the "local" keyword pass function arguments? In bash, it seems you can use the "local" keyword to refer to input arguments to a function. Is this documented behaviour? If so, where can I read about it?
$ f() { local g; for g; do echo $g; done; }
$ f foo bar
foo
bar

According to https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html

local [option] name[=value] …
  For each argument, a local variable named name is created, and assigned value.

But I see nothing about assigning the function's $1, $2 etc to the variable if no other value is provided.
I am more familiar with doing it this way:
for g in "$@"

Is either way better? More cross-compatible?
My bash on macOs 10.14:

GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)
  Copyright (C) 2007 Free Software Foundation, Inc.

A: This has nothing to do with the local command. When you use the for command without the in clause, it defaults to looping over the positional arguments.
for g

is equivalent to
for g in "$@"

This is in the Bash Manual

If 'in words' is not present, the for command executes the commands once for each positional parameter that is set, as if in "$@" had been specified (see Special Parameters).


text:
Q: Initializing a class with designated initializer - confusion I am reading a book which teaches that we should implement a designated initializer of class, and then let other initializers call this one (which I agree with).
Now, I am in a section in this book, which says: "The designated initializer of UITableViewController is initWithStyle:". And then goes in the implementation like this:
// inside ItemsViewController.m, subclass of UITableViewController

-(id) init{
    // Call the superclass's designated initializer
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {

    }
    return self;
}

- (id)initWithStyle:(UITableViewStyle)style
{
    return [self init];
}

After this code, the book also says: "This will ensure that all instances of ItemsViewController use the UITableViewStyleGrouped style, no matter what initialization message is sent to it."
To stick to the principle I described in the beginning of the post, I might had implemented this class like this:
// inside ItemsViewController.m, subclass of UITableViewController

// Implement the designated initializer first
-(id) initWithStyle:(UITableViewStyle)style
    // Call the superclass's designated initializer
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {

    }
    return self;
}

// Call designated initializer
- (id)init
{
    return [self initWithStyle: nil];
}

But I think I am missing something? I think the book uses init as designated initializer in their case?

A: If you have custom tableviewcell class then you dont need to implement initwithstyle initializer and also that initialilzer will not be called for primitive and class member objects.you will have to suffer.so follow the standard initialiser.

A: Construction
// Implement the designated initializer first
-(id) initWithStyle:(UITableViewStyle)style
    // Call the superclass's designated initializer
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {

    }
    return self; }

is confusing for user of class, because he will think that you provided initWithStyle constructor to allow him setting controllers' style. You should use your first init method.

A: Basically your code and the code in the book do the same thing. there are different types of initializers for classes, you use the one you need. What the example in the book wants to show you is how to overwrite them if you need some custom initializers later on. Sow it's understandable that it doesn't really make sense from a real live application point of view but from a learning overwriting initializers and customization i think it's ok.


text:
Q: Error in remote mySQL access I am trying to remotely access mySQL server. This is the code used by me.
 Connection conn = null;
    try
    {
       String url = "jdbc:mysql://172.18.227.237:3306/struts2";
       Class.forName ("com.mysql.jdbc.Driver");
       conn = DriverManager.getConnection (url,"root","admin");
       System.out.println ("Database connection established");
    }

But I get the following error:
 com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Access denied for user 'root'@'172.20.169.174' to database 'struts2'
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1026)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:910)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3923)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1273)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2031)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:298)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.Connect.main(Connect.java:17)

I have been granted access permission to my IP, But yet I get error.

A: Have you flushed the privileges after granting access to root at that IP?  Privileges won't work until they have been loaded by the MySQL engine, so you have to issue a 'FLUSH PRIVILEGES' command.


text:
Q: Python: "for" loops creates empty from previous result on appending Here is general goal: i need a list of all doubles combination.
Here is what happened: next append to Output variable cleaning previous result.
Main code:
mainArray = ["Value1", "Value2", "Value3", "Value4", "Value5", "Value6"]

result = []

def combine():
    for x in mainArray:
        for i in mainArray:
            temp = []
            temp.append(x)
            temp.append(i)
            if temp[0] != temp[1]:
                result.append(temp)
                print(result)
            temp.clear()

combine()
print("Output Result: ", result)

Console output:
$py comp.py
True
[['Value1', 'Value2']]
[[], ['Value1', 'Value3']]
[[], [], ['Value1', 'Value4']]
[[], [], [], ['Value1', 'Value5']]
[[], [], [], [], ['Value1', 'Value6']]
[[], [], [], [], [], ['Value2', 'Value1']]
[[], [], [], [], [], [], ['Value2', 'Value3']]
[[], [], [], [], [], [], [], ['Value2', 'Value4']]
[[], [], [], [], [], [], [], [], ['Value2', 'Value5']]
//etc
Output Result:  [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]

A: You should rather use standard library itertools.combinations for this.
import itertools

mainArray = ["Value1", "Value2", "Value3", "Value4", "Value5", "Value6"]
print(list(itertools.combinations(mainArray, 2)))
# [('Value1', 'Value2'), ('Value1', 'Value3'), ('Value1', 'Value4'), ('Value1', 'Value5'), ('Value1', 'Value6'), ('Value2', 'Value3'), ('Value2', 'Value4'), ('Value2', 'Value5'), ('Value2', 'Value6'), ('Value3', 'Value4'), ('Value3', 'Value5'), ('Value3', 'Value6'), ('Value4', 'Value5'), ('Value4', 'Value6'), ('Value5', 'Value6')]

A: Remove temp.clear() from your code.
mainArray = ["Value1", "Value2", "Value3", "Value4", "Value5", "Value6"]

result = []

def combine():
    for x in mainArray:
        for i in mainArray:
            temp = []
            temp.append(x)
            temp.append(i)
            if temp[0] != temp[1]:
                result.append(temp)

combine()
print("Output Result: ", result)

When you append an object to a list, the list doesn't get a separate copy of that item. So if you clear the object after adding to a list, it will get cleared in the contents of the list as well.

A: The result.append(temp) line doesn't make a copy of the temp, it just appends a reference, one you are clearing a few lines below. You can do result.append(temp[:]) to create a copy, but Dušan Maďar is right, don't do it yourself, you have a ready to use library to do this.
Edit: posted at the same time the previous reply has been posted, yep, removing temp.clear() is enough, temp = [] creates a new list every time, you pass it into append, and that should work just fine.

A: arrays are mutable data type so when you modify an array which contains another array, it will affect the value
eg
array= [1,2,3]
result= []
result.append(array)
print(result)
#[[1,2,3]]
array.append(4)
print(result)
#[[1,2,3,4]]

to solve your problem you can append a copy of the array instead using array.copy()
mainArray = ["Value1", "Value2", "Value3", "Value4", "Value5", "Value6"]

result = []

def combine():
    for x in mainArray:
        for i in mainArray:
            temp = []
            temp.append(x)
            temp.append(i)
            if temp[0] != temp[1]:
                result.append(temp.copy())
                print(result)
            temp.clear()

combine()
print("Output Result: ", result)


text:
Q: (v) is actually (*&v) since when? Could C++ standards gurus please enlighten me:
Since which C++ standard version has this statement failed because (v) seems to be equivalent to (*&v)?
I.e. for example the code:
 #define DEC(V) ( ((V)>0)? ((V)-=1) : 0 )
 ...{...
        register int v=1;
        int r = DEC(v) ;
 ...}...

This now produces warnings under -std=c++17 like:

cannot take address of register variable
left hand side of operand must be lvalue

Many C macros enclose ALL macro parameters in parentheses, of which the above is meant only to be a representative example.
The actual macros that produce warnings are for instance
the RTA_* macros in /usr/include/linux/rtnetlink.h.
Short of not using/redefining these macros in C++, is there any workaround?

A: Your worry is unwarranted since the file in question does not actually contain the register keyword:
grep "register" /usr/include/linux/rtnetlink.h

outputs nothing. Either way, you shouldn't be receiving the warning since:

*

*System headers don't emit warnings by default, at least in GCC

*It isn't wise to try to compile a file that belongs to a systems project like the linux kernel in C++ mode, as there may be subtle and nasty breaking changes
Just include the file normally or link the C code to your C++ binary. Report a bug if you really are getting a warning that should normally be suppressed to your compiler vendor.

A: If you look at the revision summary of the latest C++1z draft, you'd see this in [diff.cpp14.dcl.dcl]

[dcl.stc]
Change: Removal of register storage-class-specifier.
Rationale: Enable repurposing of deprecated keyword in future
  revisions of this International Standard.
Effect on original feature: A valid C++ 2014 declaration utilizing the register
  storage-class-specifier is ill-formed in this International Standard.
  The specifier can simply be removed to retain the original meaning.

The warning may be due to that.

A: register is no longer a storage class specifier, you should remove it.  Compilers may not be issuing the right error or warnings but your code should not have register to begin with
The following is a quote from the standard informing people about what they should do with regards to register in their code (relevant part emphasized), you probably have an old version of that file
C.1.6 Clause 10: declarations [diff.dcl]

Change: In C++, register is not a storage class specifier.
Rationale: The storage class specifier had no effect in C++.
Effect on original feature: Deletion of semantically well-defined feature.
Difficulty of converting: Syntactic transformation.
How widely used: Common.


text:
Q: How to parse a string value using FParsec How do I parse a simple string out of another string.
In the FParsec Tutorial there is the following code given:
let str s = pstring s
let floatBetweenBrackets = str "[" >>. pfloat .>> str "]"

I don't want to parse a float between backets but more a string within an expression.
Sth. Like:
Location := LocationKeyWord path EOL
Given a helper function
let test p s =
    match run p s with
    | Success(result,_,_)  -> printfn "%A" result
    | Failure(message,_,_) -> eprintfn "%A" message

And a parser-function: let pLocation = ...
When I call test pLocation "Location /root/somepath"
It should print "/root/somepath"
My first attempt was to modify the tutorial code as the following:
let pLocation = str "Location " >>. str

But this gives me an error:
Error 244   Typeerror. Expected:
    Parser<'a,'b>
Given:
    string -> Parser<string,'c>
The type CharStream<'a> doesn't match with the Type string

A: str doesn't work for your path because it is designed to match/parse a constant string. str works well for the constant "Location " but you need to provide a parser for the path part too. You don't specify what that might be so here is an example that just parses any characters.
let path = manyChars anyChar
let pLocation = str "Location " >>. path
test pLocation "Location /root/somepath"

You might want to a different parser for the path, for example this parses any characters until a newline or end of file so that you could parse many lines.
let path = many1CharsTill anyChar (skipNewline <|> eof)

You could make other parsers that don't accept spaces or handle quoted paths, etc.


text:
Q: Why actual type is Double? fromNotes :: [(Char, Int)] -> [Double]
fromNotes = map freq
  where
    freq (x,y) =  440 * 2**((midi x y - midi 'A' 4)/12)
    midi c o = o * 12 + getIndex c s 0 + 12
    s = "CcDdEFfGgAaB"
    getIndex c (x:xs) i
            | c == x    = i
            | otherwise = getIndex c xs (i+1)

The code gives the error:
* Couldn't match type `Int' with `Double'
Expected type: [(Char, Int)] -> [Double]
Actual type: [(Char, Double)] -> [Double]

From what i can tell the problem is in midi x y - midi 'A' 4.
But why is Haskell saying the actual type is a Double?

A: *

*fromNotes returns a [Double], so

*freq must return a Double, so

*2**((midi 'A' 4 - midi x y)/12) must be a Double, so

*midi must return a Double, so

*o * 12 must be a Double, so

*the second argument to midi must be a Double, so

*the y in midi x y must be a Double, so

*freq must take a Double as the second part of its tuple.

You can use fromIntegral :: Int -> Double at almost any step in that chain to fix things up. It's probably simplest to do it right away, as in
freq (x, y) = ... midi x (fromIntegral y) ...


text:
Q: Windows-7 Acer Aspire 5738 laptop simply turns off My laptop simply switches off on its own...and I mean switch off without warning or anything...as if someone cut the power supply so the computer did not show any warning etc.
And this happens only when the laptop is on Battery. It never happens when it's on AC power.
And it's not a phenomenon which happens each time the laptop is on battery..it's only once a day or like that.
What's amazing is that there are no event logs of the time when it switches off. The only helpful event logged is "Even ID 6008: The previous system shutdown at 10:20:53 AM on 5/3/2016 was unexpected."
The computer runs all day long (almost 14 hours at a stretch) with light usage (Chrome browser and office applications). No game etc is installed.
And I can also confirm that the battery was sufficiently charged (76%) the last time this happened. When the laptop switches off, I can turn the computer back ON without connecting it to AC power and continue to use it on battery.
Any ideas in troubleshooting this?
EDIT: Umm...guys...this is misery...the laptop switched off even on AC power this time...now a solution is needed ASAP...please..!!

A: Since it only happens when running on the battery and you get absolutely no warning, the most likely explanation is that your battery does not charge well.  That causes it to appear fully charge even if it's not, so the system can not predict properly when it will run out of charge.
This is probably a problem with the battery itself that is due to be replaced, but could in rarer cases be due to a bad charger.
The only way to be 100% sure is to replace one or the other.  Since it's most likely a battery problem, trying a new battery would be a good idea.

A: Check the power options in control panel to see how long your computer stay on while on battery (and your not working on the computer) before you check the battery, if it Turns off while your using it maybe the cause is different.


text:
Q: SIGEXIT in solaris I had a program issue which have the following pstack output.
 6600:   ora_d006_LOOKUP
 ffffffff7addbbd0 __systemcall6 (3, ffffffff7d300440, 0, ffffffff7adc1268, d, fff7) + 24
 ffffffff7adcba74 pthread_sigmask (2000, 0, 0, 0, ffffffff7d300200, d) + 1c4
 00000001068ff3bc sslssalck (ffffffff7fffb138, 2, ffffffff7fffb070, 0, 3e8, 10c24d7e0) + 7c
 00000001069358e8 sltmarm (a00029810, 29810, 10c3f3ab0, 3f9, a00000000, 29810) + 88
 00000001069aa734 ltmdvp (8006689e, 3f9, 0, 10c55ba38, 10c3f8160, 10c3f34d0) + 154
 00000001068ff2a4 sslsstehdlr (e, 0, ffffffff7fffb570, 7fffff84, 10c3ed0d8, 10c24d7e0) + 224
 ffffffff7add7498 __sighndlr (e, 0, ffffffff7fffb570, 1068fcba0, 0, d) + c
 ffffffff7adcb02c call_user_handler (ffffffff7d300200, ffffffff7d300200, ffffffff7fffb570, c, 0, 0) + 3e0
 ffffffff7adcb238 sigacthandler (0, 0, ffffffff7fffb570, ffffffff7d300200, 0, ffffffff7af3e000) + 68
 --- called from signal handler with signal 0 (SIGEXIT) ---
 ffffffff7addad48 ioctl (10c3f80c0, bb8, 400, 10c426810, 10c6aae90, 2001420c) + c
 0000000109e47668 nteveque (10c40c940, bb8, ffffffff7fffca98, 1afbfb85a4, 1c, 98) + 28
 0000000109e3f0c0 ntevque (7, bb8, 10c2cbfd0, 10c40c940, ffffffff7fffca98, 10c2cbfd0) + 80
 0000000109d8e738 nsevwait (0, 0, 10c25cc00, 0, 10c25cc04, 10c3f7a60) + 1b8
 000000010092e7b4 ksnwait (10c25cc00, 6, 10c403fb0, 10c25c000, 10c25c, 10c000) + 54
 000000010072060c ksliwat (0, ffffffff7fffd8e8, 1770, 10c25b, 10c000, 0) + 140c
 0000000100704b28 kslwait (1770, ffffffff7fffd8e8, ffffffff7fffd8e8, ffffffff7fffd8e8, 0, 0) + e8
 00000001065707a0 kmdmai (1b1bfffe00, 10c2628e8, 1b02faf258, 10c26c190, 10c25b, 38000d000) + e40
 00000001063b0400 opirip (10a726000, 0, 380002, 380000, 38002a000, 38002a) + a80
 00000001035c59cc opidrv (32, 4, ffffffff7ffff590, 1ebb90, ffffffff7af45050, ffffffff7ffff9a0) + 30c
 000000010474117c sou2o (ffffffff7ffff568, 32, 4, ffffffff7ffff590, 10c000, 10b800) + 5c
 0000000100604f64 opimai_real (3, ffffffff7ffff838, ffffffff7ffffb60, ffffffff7ffffbb5, 0, 0) + 204
 0000000104757380 ssthrdmain (10c000, 3, 44dc00, 100604d60, 10c27c000, 10c27c) + 140
 0000000100604c74 main (3, ffffffff7ffff948, 0, ffffffff7ffff840, ffffffff7ffff950, ffffffff7d300200) + 134
 0000000100604b1c _start (0, 0, 0, 0, 0, 0) + 17c

this process is used to dispatch request from client. During the issue, no more request can be sent in and this process consumed many SYS cpu.
I guess the issue started with "signal handler with signal 0 (SIGEXIT)"
 After some google,  I found SIGEXIT is not a common SIGNAL. many people said it is a pseudo signal.
How do I trap EXIT in a solaris 11 shell script?
But how can I set up a signal handle for this "pseudo" signal with c/c++ on solaris?
 how can I make the program have the following output?
  ...  my_handle_signal ....
  --- called from signal handler with signal 0 (SIGEXIT) ---
  ... xxxx


text:
Q: Routing /api endpoints to EC2 instance I am currently routing www.example.com to my CloudFront distribution to server the frontend.
How can I point the /api endpoint to the load balancer? I tried created a new hosted zone in the for example.com/api but my /api endpoints seem to still be hitting CloudFront.

A: Route53 is a DNS service. DNS only handles translating hostnames to IP addresses. DNS does not handle the path portion of a URL in any way. The /api part of the URL is never even sent to Route53.
It's entirely unclear what you mean when you say you created a new hosted zone for the /api path.
The solution to your problem is to configure your load balancer as a second origin in your CloudFront distribution, and configure CloudFront to route /api requests to that origin.


text:
Q: strange ' showing in formula bar but not in cell After doing a TransferSpreadsheet command to export data from Access to Excel, the data shows a strange ' in front of all the data. But this character only shows in the formula bar, it is not visible in the cells.
If I edit the cell and try to remove the ', it just comes back.
I've only left a few cells visible for confidentiality of my client.
Just wondering what is going on here...


text:
Q: x64 CVTSD2SI instruction and REX.W Here is the instruction:
F2 REX.W 0F 2D /r CVTSD2SI r64, xmm/m64

Convert one double-precision floating-point
value from xmm/m64 to one signed quadword
integer sign-extended into r64.

How do I encode this?  The REX.W is what I'm having trouble with.  Do I just encode the opcode with a 0x48 or a 0x08?  So the opcode would look like this: F2, 48, 0F, 2D?

A:
So the opcode would look like this: F2, 48, 0F, 2D?

Exactly. Just stick the arguments after it and it's good to go. For example:
cvtsd2si rax, xmm0  ; F2 48 0F 2D C0  (vex: C4 E1 FB 2D C0)
cvtsd2si r8, xmm0   ; F2 4C 0F 2D C0  (vex: C4 61 FB 2D C0)


text:
Q: ssh and home directory permissions sshd will refuse to accept public key authentication if the user's home directory is group-accessible, even if ~/.ssh is set to 700? If the permissions on ~/.ssh are acceptable, why do the permissions on ~ matter?

A: Okay to fix this you could either go the insecure route and set StrictModes no in your /etc/ssh/sshd_config as was already mentioned or you could go the complicated way and store the ssh-keys for all users in a directory accessible to root only. Here a the steps for the latter:

*

*Create a directory to hold the new keys. Here we'll use /usr/share/sshkeys, wich might not be the best place but the best I can think of out of my head.
sudo mkdir /usr/share/sshkeys

*Edit /etc/ssh/sshd_config to include the line
AuthorizedKeysFile /usr/share/sshkeys/%u

*Copy the old authorized key file from your user (here called "exampleuser") to the new directory
mv /home/exampleuser/.ssh/authorized_keys /usr/share/sshkeys/exampleuser

*(Optional but recommended since exampleuser will expect to be able to add keys the usual way) Link the new keyfile to the location of the old and give the user access to the new key file
sudo chown exampleuser /usr/share/sshkeys/exampleuser
sudo chmod 600 /usr/share/sshkeys/exampleuser
ln -s /usr/share/sshkeys/exampleuser /home/exampleuser/.ssh/authorized_keys

*Restart the ssh daemon
sudo service sshd restart

A: I guess the reason is that if your home directory is writable by someone else, then a malicious user can create ~/.ssh, add desired keys and then change permissions on it to 700.
Even if you already have a ~/.ssh, it can simply be renamed to something else and a new one created.
However, on modern systems such trick is usually not possible due to chown working only for super-user, this has not always been the case:

In earlier versions of UNIX, all users could run the chown command to
  change the ownership of a file that they owned to that of any other
  user on the system.
  (http://www.diablotin.com/librairie/networking/puis/ch05_07.htm)

Whether chmod behaves one way or another depends on libc compilation options, and for the sake of security OpenSSH server is slightly paranoid.


text:
Q: AutoCompleteTextView set OnClickListener on Keyboard-SearchButton how can I set an OnClickListener on the keyboard search button?
I added to my ACTV the imeOptions attribute. So i have a searchbutton instead of a enter button.
android:imeOptions="actionSearch"

I already have a solution, but this only works with an editText.
actv.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch();
                return true;
            }
            return false;
        }
    });

How can I make this work on an AutoCompleteTextView or is there any code which works better? if i use this code, eclipse says that the listener isn't available for the actv.
Thanks


text:
Q: Render ManytoManyfield in django templates without duplicating the content of the parent Model I have great difficulty on this one.
I am trying to render my template like this following:
Company name A:
-> postalcode 1
-> postalcode 2
and I am have this result for now:
Company name A:
-> postalcode 1
Company name A:
-> postalcode 2
I know it is from the for loop that I have over cp but I don't how to access to the M2M field to show it like I would like.
(and I have an additional m2m field so it would be another for loop)
Here is my code:
models.py
class Company(models.Model):
    utilisateur = models.ForeignKey(User)
    nom_cpny = models.CharField(max_length=200)
    code_postal_cpny = models.ManyToManyField('Place', blank=True)
    gestion_cpny = models.ManyToManyField('Companytype', blank=True)

    def __unicode__(self):
            return self.nom_cpny

class Place(models.Model):
    postalcode = models.CharField(max_length=200)
    ville = models.CharField(max_length=200)
    region = models.CharField(max_length=200)
    departement = models.CharField(max_length=200)
    longitude = models.DecimalField(max_digits=9, decimal_places=6)
    latitude = models.DecimalField(max_digits=9, decimal_places=6)
    pays = models.CharField(max_length=100)

    def __unicode__(self):
        return unicode(self.postalcode)

class Companytype(models.Model):

    cpny_type = models.CharField(max_length=100, blank=False)
    employee_base = models.IntegerField(blank=False)

    def __unicode__(self):
        return self.cpny_type

views.py
@login_required
def listing_cpny(request):

    cpny_in = Company.objects.all().filter(utilisateur=request.user)
    utilisateur = request.user

    args = {}
    args.update(csrf(request))

    args['cpny_in'] = cpny_in
    args['utilisateur'] = utilisateur

    return render_to_response('b_dashboard_annonces.html', args) views.py

b_dashboard_annonces.html
{% for annonce in cpny_in %}
    {% for cp in annonce.code_postal_cpny.all %}
    {% if annonce.utilisateur.id == utilisateur.id %}

    {{annonce.nom_cpny}}
    {{cp }}

    {% endif %}
    {% endfor %}
{% endfor %}

Many thanks for your help!

A: This should work for you
{% for annonce in cpny_in %}

        {{annonce.nom_cpny}}

        {% for cp in annonce.code_postal_cpny.all %}
            {% if annonce.utilisateur.id == utilisateur.id %}
                {{cp }}
            {% endif %}
        {% endfor %}

{% endfor %}


text:
Q: enable resizing the icon when clicking the maximaize or minimaize button in the browser I have written this code to resize the icon on resizing the browser. The code does not work when clicking the maximaize button or the minimaize button.
How can I enable invoking my displayWindowSize function when clicking the maximaize and minimaize button in the browser to resize the switch_ico icon?

A: The resize events do definitely trigger in chrome/firefox.
A resize, maximize, unmaximize event will trigger the resize event.
A minimize (the one which hide the browser completely) will trigger a visibility change event.
Are you sure the problem isn't caused by something else?
the code below will increase a counter each them a resize/visibility change is triggered.
note that since the snippet is run in an iframe, you'll have to expand the snippet to full-page in order to see the events

//window.onresize = displayWindowSize;
//window.onload = displayWindowSize;

$(window).resize(function() {
  setTimeout(function() {
    displayWindowSize();
  }, 100);
});

var resizeCount=0;
function displayWindowSize(){
  $('.resize-count').text("resizes:" + ++resizeCount);

};

document.addEventListener("visibilitychange", function() {
  displayMinimize()
}, false);
var minimizeCount=0;
function displayMinimize(){
  $('.visibility-count').text("visibility:" + ++minimizeCount);
};

resizes: none

visibility: none


text:
Q: Prove that any finite dimensional complex vector space has a conjugate linear operator This is an exercise in my linear algebra textbook. I considered the isomorphism $v\rightarrow\bar{v}$ but it might not be a linear operator since it maps $V$ to $\bar{V}$.
A map $L$ is conjugate linear if $L(u+v) = L(u)+L(v)$ and $L(av) = \bar{a}L(v)$.

A: What do you mean by $\overline{V}$ and by $\overline{v}$ ?
Let $\{v_1,...,v_n\}$ be a basis of $V$. If $v \in V$ then there are (uniquely determined)  $c_1,...,c_n \in \mathbb C$ such that
$v=c_1v_1+...+c_nv_n$.
Now define
$L(v):=\overline{c_1}v_1+...+\overline{c_n}v_n$.


text:
Q: Java JScrollBar Design I want customize the JScrollBar Design. I use Mac to develop the app with eclipse. I already tried to scrollPane.getVerticalScrollBar().setBackground(Color.BLACK); but nothing happen.
My code:
scrollPane = new JScrollPane(scriptView);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
scrollPane.getVerticalScrollBar().setUnitIncrement(6);
window.getContentPane().add(scrollPane);

The Object scriptView is from the class JEditorPane.
How it should look:

Thanks for every help.

A: I guess you are looking for a transparent scrollbar.

This is just presented as an idea(NOT tested code):
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.basic.*;

public class TranslucentScrollBarTest {
  public JComponent makeUI() {
    JTextArea cmp = new JTextArea();
    String str = "1234567890abcdefghijklmnopqrstuvwxyz";
    for(int i=0; i<20; i++) {
      cmp.append(str+str+"\n");
    }
    cmp.setForeground(Color.WHITE);
    cmp.setBackground(Color.BLACK);
    cmp.setOpaque(true);

    JScrollPane scrollPane = new JScrollPane(
      cmp, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
      ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setComponentZOrder(scrollPane.getVerticalScrollBar(), 0);
    scrollPane.setComponentZOrder(scrollPane.getViewport(), 1);
    scrollPane.getVerticalScrollBar().setOpaque(false);

    scrollPane.setLayout(new ScrollPaneLayout() {
      @Override
      public void layoutContainer(Container parent) {
        JScrollPane scrollPane = (JScrollPane)parent;

        Rectangle availR = scrollPane.getBounds();
        availR.x = availR.y = 0;

        Insets insets = parent.getInsets();
        availR.x = insets.left;
        availR.y = insets.top;
        availR.width  -= insets.left + insets.right;
        availR.height -= insets.top  + insets.bottom;

        Rectangle vsbR = new Rectangle();
        vsbR.width  = 12;
        vsbR.height = availR.height;
        vsbR.x = availR.x + availR.width - vsbR.width;
        vsbR.y = availR.y;

        if(viewport != null) {
          viewport.setBounds(availR);
        }
        if(vsb != null) {
          vsb.setVisible(true);
          vsb.setBounds(vsbR);
        }
      }
    });
    scrollPane.getVerticalScrollBar().setUI(new BasicScrollBarUI() {
      private final Dimension d = new Dimension();
      @Override protected JButton createDecreaseButton(int orientation) {
        return new JButton() {
          @Override public Dimension getPreferredSize() {
            return d;
          }
        };
      }
      @Override protected JButton createIncreaseButton(int orientation) {
        return new JButton() {
          @Override public Dimension getPreferredSize() {
            return d;
          }
        };
      }
      @Override
      protected void paintTrack(Graphics g, JComponent c, Rectangle r) {}
      @Override
      protected void paintThumb(Graphics g, JComponent c, Rectangle r) {
        Graphics2D g2 = (Graphics2D)g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        Color color = null;
        JScrollBar sb = (JScrollBar)c;
        if(!sb.isEnabled() || r.width>r.height) {
          return;
        }else if(isDragging) {
          color = new Color(200,200,100,200);
        }else if(isThumbRollover()) {
          color = new Color(255,255,100,200);
        }else {
          color = new Color(220,220,200,200);
        }
        g2.setPaint(color);
        g2.fillRoundRect(r.x,r.y,r.width,r.height,10,10);
        g2.setPaint(Color.WHITE);
        g2.drawRoundRect(r.x,r.y,r.width,r.height,10,10);
        g2.dispose();
      }
      @Override
      protected void setThumbBounds(int x, int y, int width, int height) {
        super.setThumbBounds(x, y, width, height);
        scrollbar.repaint();
      }
    });
    return scrollPane;
  }
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        createAndShowGUI();
      }
    });
  }
  public static void createAndShowGUI() {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new TranslucentScrollBarTest().makeUI());
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}

A: Here is an improved version I did for a private project. It also supports horizontal scrollbar.
Code:
import javax.swing.*;
import javax.swing.plaf.basic.BasicScrollBarUI;

import java.awt.*;

/**
* This is an implementation of a JScrollPane with a modern UI
*
* @author Philipp Danner
*
*/
public class ModernScrollPane extends JScrollPane {

    private static final long serialVersionUID = 8607734981506765935L;

    private static final int SCROLL_BAR_ALPHA_ROLLOVER = 100;
    private static final int SCROLL_BAR_ALPHA = 50;
    private static final int THUMB_SIZE = 8;
    private static final int SB_SIZE = 10;
    private static final Color THUMB_COLOR = Color.Black;

    public ModernScrollPane(Component view) {
        this(view, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED);
    }

    public ModernScrollPane(int vsbPolicy, int hsbPolicy) {
        this(null, vsbPolicy, hsbPolicy);
    }

    public ModernScrollPane(Component view, int vsbPolicy, int hsbPolicy) {

        setBorder(null);

        // Set ScrollBar UI
        JScrollBar verticalScrollBar = getVerticalScrollBar();
        verticalScrollBar.setOpaque(false);
        verticalScrollBar.setUI(new ModernScrollBarUI(this));

        JScrollBar horizontalScrollBar = getHorizontalScrollBar();
        horizontalScrollBar.setOpaque(false);
        horizontalScrollBar.setUI(new ModernScrollBarUI(this));

        setLayout(new ScrollPaneLayout() {
            private static final long serialVersionUID = 5740408979909014146L;

            @Override
            public void layoutContainer(Container parent) {
                Rectangle availR = ((JScrollPane) parent).getBounds();
                availR.x = availR.y = 0;

                // viewport
                Insets insets = parent.getInsets();
                availR.x = insets.left;
                availR.y = insets.top;
                availR.width -= insets.left + insets.right;
                availR.height -= insets.top + insets.bottom;
                if (viewport != null) {
                    viewport.setBounds(availR);
                }

                boolean vsbNeeded = isVerticalScrollBarfNecessary();
                boolean hsbNeeded = isHorizontalScrollBarNecessary();

                // vertical scroll bar
                Rectangle vsbR = new Rectangle();
                vsbR.width = SB_SIZE;
                vsbR.height = availR.height - (hsbNeeded ? vsbR.width : 0);
                vsbR.x = availR.x + availR.width - vsbR.width;
                vsbR.y = availR.y;
                if (vsb != null) {
                    vsb.setBounds(vsbR);
                }

                // horizontal scroll bar
                Rectangle hsbR = new Rectangle();
                hsbR.height = SB_SIZE;
                hsbR.width = availR.width - (vsbNeeded ? hsbR.height : 0);
                hsbR.x = availR.x;
                hsbR.y = availR.y + availR.height - hsbR.height;
                if (hsb != null) {
                    hsb.setBounds(hsbR);
                }
            }
        });

        // Layering
        setComponentZOrder(getVerticalScrollBar(), 0);
        setComponentZOrder(getHorizontalScrollBar(), 1);
        setComponentZOrder(getViewport(), 2);

        viewport.setView(view);
    }
    private boolean isVerticalScrollBarfNecessary() {
        Rectangle viewRect = viewport.getViewRect();
        Dimension viewSize = viewport.getViewSize();
        return viewSize.getHeight() > viewRect.getHeight();
    }

    private boolean isHorizontalScrollBarNecessary() {
        Rectangle viewRect = viewport.getViewRect();
        Dimension viewSize = viewport.getViewSize();
        return viewSize.getWidth() > viewRect.getWidth();
    }

    /**
     * Class extending the BasicScrollBarUI and overrides all necessary methods
     */
    private static class ModernScrollBarUI extends BasicScrollBarUI {

        private JScrollPane sp;

        public ModernScrollBarUI(ModernScrollPane sp) {
            this.sp = sp;
        }

        @Override
        protected JButton createDecreaseButton(int orientation) {
            return new InvisibleScrollBarButton();
        }

        @Override
        protected JButton createIncreaseButton(int orientation) {
            return new InvisibleScrollBarButton();
        }

        @Override
        protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
        }

        @Override
        protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
            int alpha = isThumbRollover() ? SCROLL_BAR_ALPHA_ROLLOVER : SCROLL_BAR_ALPHA;
            int orientation = scrollbar.getOrientation();
            int x = thumbBounds.x;
            int y = thumbBounds.y;

            int width = orientation == JScrollBar.VERTICAL ? THUMB_SIZE : thumbBounds.width;
            width = Math.max(width, THUMB_SIZE);

            int height = orientation == JScrollBar.VERTICAL ? thumbBounds.height : THUMB_SIZE;
            height = Math.max(height, THUMB_SIZE);

            Graphics2D graphics2D = (Graphics2D) g.create();
            graphics2D.setColor(new Color(THUMB_COLOR.getRed(), THUMB_COLOR.getGreen(), THUMB_COLOR.getBlue(), alpha));
            graphics2D.fillRect(x, y, width, height);
            graphics2D.dispose();
        }

        @Override
        protected void setThumbBounds(int x, int y, int width, int height) {
            super.setThumbBounds(x, y, width, height);
            sp.repaint();
        }

        /**
         * Invisible Buttons, to hide scroll bar buttons
         */
        private static class InvisibleScrollBarButton extends JButton {

            private static final long serialVersionUID = 1552427919226628689L;

            private InvisibleScrollBarButton() {
                setOpaque(false);
                setFocusable(false);
                setFocusPainted(false);
                setBorderPainted(false);
                setBorder(BorderFactory.createEmptyBorder());
            }
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(400, 400));

        JPanel content = new JPanel();
        content.setBackground(Color.WHITE);
        content.setPreferredSize(new Dimension(500, 500));
        content.add(new JLabel("test"));
        frame.add(new ModernScrollPane(content));

        frame.pack();
        frame.setVisible(true);
    }
}

A: Custom scrollbar preview :

Custom scrollbar code :
public class CustomScrollBarUI extends BasicScrollBarUI {

      private final Dimension d = new Dimension();

      @Override
      protected JButton createDecreaseButton(int orientation) {
        return new JButton() {

            private static final long serialVersionUID = -3592643796245558676L;

            @Override
              public Dimension getPreferredSize() {
                return d;
              }
            };
      }

      @Override
      protected JButton createIncreaseButton(int orientation) {
        return new JButton() {

            private static final long serialVersionUID = 1L;

        @Override
          public Dimension getPreferredSize() {
            return d;
          }
        };
      }

      @Override
      protected void paintTrack(Graphics g, JComponent c, Rectangle r) {
      }

      @Override
      protected void paintThumb(Graphics g, JComponent c, Rectangle r) {
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Color color = null;
        JScrollBar sb = (JScrollBar) c;
        if (!sb.isEnabled() || r.width > r.height) {
          return;
        } else if (isDragging) {
          color = Color.DARK_GRAY; // change color
        } else if (isThumbRollover()) {
          color = Color.LIGHT_GRAY; // change color
        } else {
          color = Color.GRAY; // change color
        }
        g2.setPaint(color);
        g2.fillRoundRect(r.x, r.y, r.width, r.height, 10, 10);
        g2.setPaint(Color.WHITE);
        g2.drawRoundRect(r.x, r.y, r.width, r.height, 10, 10);
        g2.dispose();
      }

      @Override
      protected void setThumbBounds(int x, int y, int width, int height) {
        super.setThumbBounds(x, y, width, height);
        scrollbar.repaint();
      }
    }

Then use it like this:
YOUR_COMPONENT.getVerticalScrollBar().setUI(new CustomScrollBarUI());

A: Sadly the proposed solutions will break JTable and won't display the table header, but I found this solution that seems to work.


text:
Q: Connecting Springboot application to Azure databricks I'm trying to connect SpringBoot Application to Azure Databricks.
Below is something I have tried....
application.properties
spring.datasource.url = jdbc:spark://adb-**********.*.azuredatabricks.net:**/default;transportMode=http;ssl=1;httpPath=sql/protocolv1/o/******/******-*****-abcd341
spring.datasource.username = username
spring.datasource.password = Generated Token

pom.xml
Below are some dependencies I'm using...
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.10</artifactId>
    <version>1.5.2</version>
</dependency>

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.10</artifactId>
    <version>1.5.2</version>
</dependency>

<dependency>
    <groupId>com.databricks</groupId>
    <artifactId>spark-avro_2.10</artifactId>
    <version>2.0.1</version>
</dependency>

I'm getting below error..
***************************
APPLICATION FAILED TO START
***************************

Description:

Cannot determine embedded database driver class for database type NONE

Action:

If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

Suggest me if I'm missing any maven dependency.
Thanks in Advance..

A: To connect from the Spring Boot you need to use JDBC driver, not Spark jars (remove them - you don't need them).  You can get JDBC driver as described in documentation, or very recently - directly via Maven using following coordinates:
    <dependency>
      <groupId>com.databricks</groupId>
      <artifactId>databricks-jdbc</artifactId>
      <version>2.6.25-1</version>
    </dependency>

and then use standard JDBC APIs exposed by Spring.  I have a simple example that uses JdbcTemplate to access data in Databricks - you just need to construct JDBC URL correctly:
String host = "";
String httpPath = "";
String token = "";

String jdbcUrl = "jdbc:databricks://" + host +
       ":443/default;transportMode=http;ssl=1;httpPath=" +
       httpPath + ";AuthMech=3;UID=token;PWD=" + token;

and then just access data:
// define data source
SimpleDriverDataSource ds = new SimpleDriverDataSource();
ds.setDriver(new Driver());
ds.setUrl(jdbcUrl);
JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

// query data
List<Map<String, Object>> data = jdbcTemplate.queryForList(query);
for (Map<String, Object> row: data) {
....
}

P.S. You may omit username or at least set it to the token value...

A: Try adding the "spring.datasource.driverClassName" , and let me know if that helps you to proceed


text:
Q: Xamarin orientation info.plist I am having a problem in ISO setting the device orientation. For iPhone I would like to lock it to only Portrait mode but for iPad I would like the user to be able to use Portrait, Landscape left and right. The setting will not save for each device.

Do I need to do this a different way?

A: Open up your info.plist with a text editor. There should be two orientation sections where you can define orientations per idiom as follows
<key>UISupportedInterfaceOrientations</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array>

If this isn't working properly, you can also address this in code. In AppDelegate.cs try overriding GetSupportedInterfaceOrientations.
public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations
(
  UIApplication application,
  [Transient] UIWindow forWindow
)
{
  // You will need to figure out how to determine what kind of device you're on. I suggest Xamarin.Essentials, they probably have a service for that.
  if (iPhone)
  {
    return UIInterfaceOrientationMask.Portrait;
  }

  if (iPad)
  {
    return UIInterfaceOrientationMask.AllButUpsideDown;
  }

  return UIInterfaceOrientationMask.All;
}


text:
Q: Failure to generate user instance of SQL Server error, when setup application is run on another computer I am unable to run my c# application on a different computer other than my own computer. I have an attached mdf database file in my project. I have 'SQL SERVER 2008' as pre-requisite in the setup project. The application is installing & running fine on my machine, but when i install and run it on another machine, it shows the following error:
Description:
Stopped working

Problem signature:
Problem Event Name: CLR20r3
Problem Signature 01:   esbi.exe
Problem Signature 02:   1.0.0.0
Problem Signature 03:   4dd8feca
Problem Signature 04:   System.Data
Problem Signature 05:   2.0.0.0
Problem Signature 06:   4a274a01
Problem Signature 07:   2744
Problem Signature 08:   11
Problem Signature 09:   System.Data.SqlClient.Sql
OS Version: 6.1.7600.2.0.0.256.1
Locale ID:  1033

So, I planted a try-catch block on the first opening of connection to the database & caught the following error:

System.Data.SqlClient.SqlException: Failed to generate a user interface of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.

The connection string i am using to connect to the database is
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\esbi.mdf;Integrated Security=True;User Instance=True

what am i doing wrong?? Is it something with the connection string??
any suggestions?

A: It could be the ".\SQLEXPRESS" in the connection string.  When I deploy to my server that runs the full version of SQL I have to change that to "(local)".

A: I had a wpf app that ran on my development machine but gave the System.Data.SqlClient.Sql error when deployed to a server. In my project I changed the "Target profile:" on the "Application" tab from
".NET Framework 4 Client_profile" to
".NET Framework 4" and then closed, opened and relinked it.
The app then ran without the error as the server had a matching .NET framework


text:
Q: Will a satellite orbiting the moon have a tidal locked orbit? Suppose an artificial satellite is launched to orbit the moon. Ignore 3-body problem issues, just assume it follows a roughly titled elliptical orbit relative to the plane cutting through earth's equator.
The moon is tidally locked to the earth--that is, the moon's surface itself rotates with the same period the moon rotates around the earth.
My question is will this apply to the artificial satellite orbiting the moon? That is, will the orientation of the satellite's orbiting plane remain fixed or will it also rotate in the moon's 28 day cycle?

A: If we ignore other bodies, the orbital plane will remain fixed. It will not turn along with the Moon as the Moon orbits. That would require a force acting on the satellite which is not in the orbital plane.
Orbits do precess in real-world examples, but that is under the influence of other bodies (or of uneven features of the body orbited), and it is usually on a much slower timescale than what we're talking about here.

A: No, because orbital speed is just dependent on the orbital altitude. Which means that you can find the orbital altitude that corresponds to the same effect as the spin-orbit lock of the earth-moon system, but at an arbitrary altitude that would not be the case.


text:
Q: Is it possible that $\mathcal{X} = \mathcal{Y}$, yet $\mathcal{X} \in \mathcal{Y}$? Is it possible for a set to equal another set, yet the former set be an element in the latter set?  I.e.:
$\mathcal{X} = \mathcal{Y}$, yet $\mathcal{X} \in \mathcal{Y}$


text:
Q: How to compare user input in unix So I'm writing a simple script and I cant seem to get it to work.
It throws a error at the if statement.
#!/bin/bash
echo "Whats your name ?"
read NAME

if [$NAME == "SSJ" ]
then
  echo "Welcome back SSJ"
fi

A: Do it like this:
#!/bin/bash
echo "Whats your name ?"
read name

if [ "$name" = "SSJ" ]
then
  echo "Welcome back SSJ"
fi

A: Try this :
#!/bin/bash
echo "Whats your name ?"
read NAME

if [ "$NAME" == "SSJ" ]; then
  echo "Welcome back SSJ"
fi