text:
Q: android.view.WindowLeaked - AlerDialog Builder I have an activity, in which the user is sent to device settings if the GPS is off to turn it on, and when the user is back from settings, then the device is asking for location permission.
So the first GPS dialog is done via AlertDialog builder, here is my full code:
      public class Okoli extends AppCompatActivity implements LocationListener {

    private final static int ALL_PERMISSIONS_RESULT = 101;
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;
    private static final long MIN_TIME_BW_UPDATES = 90000; //1.5 mins

    LocationManager locationManager;
    Location loc;
    ArrayList<String> permissions = new ArrayList<>();
    ArrayList<String> permissionsToRequest= new ArrayList<>();
    ArrayList<String> permissionsRejected = new ArrayList<>();
    boolean isGPS = false;
    boolean isNetwork = false;
    boolean canGetLocation = true;

    ArrayList<Actors> actorsList;
    ActorAdapterDist adapter;

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

        if(getSupportActionBar() != null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setTitle((Html.fromHtml("V okolí (vzdušná čiara)")));
            getSupportActionBar().setHomeAsUpIndicator(R.drawable.back);
        }

        setContentView(R.layout.okoli_fragment);

        actorsList = new ArrayList<>();
        adapter = new ActorAdapterDist(this, R.layout.okoli_item, actorsList);
        TextView listTitle = findViewById(R.id.booklist_title1);
        listTitle.setText("Čakám na signál GPS");

        getIntent().setAction("created");
        String MY_PREFS_NAME = "resumecheck";
        SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
        editor.putInt("idName", 2);
        editor.apply();

        ListView lv = findViewById(R.id.listViewx);   lv.setAdapter(adapter);

        locationManager = (LocationManager) this.getSystemService(Service.LOCATION_SERVICE);
        assert locationManager != null;
        isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        permissionsToRequest = findUnAskedPermissions(permissions);

        if (!isGPS && !isNetwork) {

            showSettingsAlert(getString(R.string.askgps),  new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    if (dialog != null) {
                        dialog.dismiss();  dialog = null;
                    }
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                }
            });
            getLastLocation();
        } else {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (permissionsToRequest.size() > 0) {
                    requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]),
                            ALL_PERMISSIONS_RESULT);
                    canGetLocation = false;
                }
            }

            getLocation();
        }

    }

    @Override
    public void onLocationChanged(Location location) {updateUI(location);}

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {}

    @Override
    public void onProviderEnabled(String s) {
        getLocation();
    }

    @Override
    public void onProviderDisabled(String s) {
        if (locationManager != null) {
            locationManager.removeUpdates(this);
        }
    }

    private void getLocation() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

        try {
            if (canGetLocation) {

                if (isGPS) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    if (locationManager != null) {
                        loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (loc != null) {updateUI(loc);}
                    }

                } else if (isNetwork) {
                    // from Network Provider
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    if (locationManager != null) {
                        loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (loc != null) {updateUI(loc);}
                    }

                } else {
                    loc.setLatitude(0);
                    loc.setLongitude(0);
                    updateUI(loc);
                }

            } else {
                Toast.makeText(this, R.string.nolocation,
                        Toast.LENGTH_LONG).show();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    private void getLastLocation() {
        try {
            Criteria criteria = new Criteria();
            String provider = locationManager.getBestProvider(criteria, false);

            if(provider==null) {    showSettingsAlert(getString(R.string.askgps),  new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                }
            });}

            else {

                Location location = locationManager.getLastKnownLocation(provider);
                if (location != null) {updateUI(location);}

            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    private ArrayList findUnAskedPermissions(ArrayList<String> wanted) {
        ArrayList<String> result = new ArrayList<>();

        for (String perm : wanted) {
            if (!hasPermission(perm)) {
                result.add(perm);
            }
        }

        return result;
    }

    private boolean hasPermission(String permission) {
        if (canAskPermission()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return (this.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
            }
        }
        return true;
    }

    private boolean canAskPermission() {
        return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode) {
            case ALL_PERMISSIONS_RESULT:

                for (String perms : permissionsToRequest) {
                    if (!hasPermission(perms)) {
                        permissionsRejected.add(perms);
                    }
                }

                if (permissionsRejected.size() > 0) {//Log.e("rejected", "onRequestPermissionsResult");

                 String MY_PREFS_NAME = "resumecheck";
                    SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
                    editor.putInt("idName", 2);
                    editor.apply();

                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {

                            editor.putInt("idName", 1);
                            editor.apply();

                            showMessageOKCancel(getString(R.string.denied),
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                requestPermissions(permissionsRejected.toArray(
                                                        new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);
                                            }
                                        }
                                    });
                            return;
                        }
                    }
                } else {
                    // Log.e("ON", "No rejected permissions.");
                    String MY_PREFS_NAME = "resumecheck";
                    SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
                    editor.putInt("idName", 2);
                    editor.apply();

                    canGetLocation = true;
                    getLocation();
                }
                break;
        }
    }

    public void showSettingsAlert(String message, DialogInterface.OnClickListener okListener) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Theme_AppCompat_Dialog_Alert);
        builder.setTitle(R.string.nogps);
        builder.setMessage(message);
        builder.setPositiveButton(R.string.ano, okListener);
        builder.setNegativeButton(R.string.nie, null);
        builder.create();
        builder.show();

    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {

        new AlertDialog.Builder(this, R.style.Theme_AppCompat_Dialog_Alert)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton(R.string.cancel, null)
                .create()
                .show();
    }

    public void updateUI(Location loc) {
        double Act1=loc.getLatitude();
        double Act2=loc.getLongitude();
        adapter.clear();adapter.notifyDataSetChanged();

        TextView listTitle = findViewById(R.id.booklist_title1);
        ListView lv = findViewById(R.id.listViewx);

        if (Act1 > 0.0) { listTitle.setVisibility(View.GONE);lv.setVisibility(View.VISIBLE);GetContacts task = new GetContacts (Act1, Act2);
            task.execute();
            //  new GetContacts().execute(Act1,Act2);
        } else {
            listTitle.setVisibility(View.VISIBLE);listTitle.setText("Čakám na signál GPS");lv.setVisibility(View.GONE);
        }
    }

    ProgressDialog dialog;

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

        if (locationManager != null) {
            locationManager.removeUpdates(this);
        }
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    class GetContacts extends AsyncTask<Double, Void, Boolean> {

        private Double act1;
        private Double act2;

        GetContacts(double act1, double act2) {
            this.act1 = act1;
            this.act2 = act2;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(Okoli.this);
            dialog.setMessage("Načítavam");
            dialog.setTitle("Pripájam sa k serveru");
            dialog.show();
            dialog.setCancelable(false);
dialog.dismiss();
            dialog=null;
        }

        @Override
        protected Boolean doInBackground(Double... args) {
            HttpHandler sh = new HttpHandler();
            String url = "https://www.myweb.sk";
            String jsonStr = sh.makeServiceCall(url);

            int pocet =0;

            if (jsonStr != null) {
                try {JSONObject jsonObj = new JSONObject(jsonStr);
                    JSONArray actors = jsonObj.getJSONArray("result");

                    double myDistx;
                    //Log.e("pocet",String.format("value = %d", actors.length()));

                    for (int i = 0; i < actors.length(); i++) {
                        JSONObject c = actors.getJSONObject(i);

                        Actors actor = new Actors();
                        double g1 = Double.parseDouble(c.getString("gps1"));
                        double g2 = Double.parseDouble(c.getString("gps2"));

                        myDistx = calculateDistance(act1, act2, g1, g2);

                        if (myDistx <= 50) {
                            actor.setLetter("x");
                            actor.setNazov(c.getString("nazov"));
                            actor.setThumb(c.getString("thumb"));
                            actor.setPerex(c.getString("perex"));
                            actor.setTyp(c.getString("typ"));
                            actor.setPlace(c.getString("place"));
                            actor.setGps1(c.getString("gps1"));
                            actor.setGps2(c.getString("gps2"));
                            actor.setExterier(c.getString("adresar"));

                            actor.setDist(myDistx);

                            actorsList.add(actor);
                            pocet++;
                        }
                    }

                    if (pocet == 0) {
                        runOnUiThread(new Runnable() {
                            public void run() {

                                Toast.makeText(Okoli.this.getApplicationContext(), R.string.nothing_around, Toast.LENGTH_LONG).show();
                            }
                        });

                    }

                    Collections.sort(actorsList, new Comparator<Actors>() {
                        @Override
                        public int compare(Actors lhs, Actors rhs) {
                            return lhs.getDist().compareTo(rhs.getDist());
                        }
                    });

                }  catch (final JSONException e) {
                    Okoli.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(Okoli.this.getApplicationContext(),
                                    "Chyba dát: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    }); }

                return true;

            } else {
                Okoli.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(Okoli.this.getApplicationContext(),
                                "Chyba internetového pripojenia.",
                                Toast.LENGTH_LONG).show();
                    }
                });
                return false;
            }
        }

        final static double AVERAGE_RADIUS_OF_EARTH = 6371;
        double calculateDistance(double userLat, double userLng, double venueLat, double venueLng) {

            double latDistance = Math.toRadians(userLat - venueLat);
            double lngDistance = Math.toRadians(userLng - venueLng);

            double a = (Math.sin(latDistance / 2) * Math.sin(latDistance / 2)) +
                    (Math.cos(Math.toRadians(userLat))) *
                            (Math.cos(Math.toRadians(venueLat))) *
                            (Math.sin(lngDistance / 2)) *
                            (Math.sin(lngDistance / 2));

            double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

            return (AVERAGE_RADIUS_OF_EARTH * c);
        }

        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();  dialog = null;
            }
            //dialog.dismiss();
            adapter.notifyDataSetChanged();
        }

    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() { //restart activity after back from GPS settings
        super.onResume();
        adapter.clear();
        adapter.notifyDataSetChanged();

        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }

        String action = getIntent().getAction();
        // Prevent endless loop by adding a unique action, don't restart if action is present
        if(action == null || !action.equals("created")) {

            String MY_PREFS_NAME = "resumecheck";
            SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);

                int idName = prefs.getInt("idName", 0); //0 is the default value.

            if(idName == 2) {
                Intent intent = new Intent(this, Okoli.class);
                startActivity(intent);
                finish();
            } else {
                SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
                editor.putInt("idName", 1);
                editor.apply(); }

        }
        // Remove the unique action so the next time onResume is called it will restart
        else
            getIntent().setAction(null);

    }
}

However it is working fine, but the console gives me an error
android.view.WindowLeaked: Activity has leaked window DecorView@11bd862[] that was originally added here
                 at android.view.ViewRootImpl.<init>(ViewRootImpl.java:576)
                 at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:363)
                 at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:128)
                 at android.app.Dialog.show(Dialog.java:454)
                 at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:1006)
                 at **.showSettingsAlert(Okoli.java:298)
                 at Okoli.onCreate(Okoli.java:95)**
                 at android.app.Activity.performCreate(Activity.java:7372)
                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218)
                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3147)
                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3302)
                 at android.app.ActivityThread.-wrap12(Unknown Source:0)
                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891)
                 at android.os.Handler.dispatchMessage(Handler.java:108)
                 at android.os.Looper.loop(Looper.java:166)
                 at android.app.ActivityThread.main(ActivityThread.java:7425)
                 at java.lang.reflect.Method.invoke(Native Method)
                 at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)

So the lines 95 and 298 are pointing to showSettingsAlert.
I tried to dismiss dialog onDestroy, onPause, onpostExecute also onResume, but the error is still there. It is showing exactly, when I press the back arrow from device GPS settings and the permission alert is showing next.
Can you please advice, where and how to dismiss that alert window to avoid leaking?

A: you should make dialog is null all the place  after dismiss the dialog
     if (dialog != null)
     {
     dialog.dismiss();
     dialog = null;
     }

so your onDestroy should be
@Override
public void onDestroy() {
super.onDestroy();
if (dialog != null) {
    dialog.dismiss();
    dialog = null;
}
}

Change your showSettingsAlert method like this
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("GPS is not Enabled!");
alertDialog.setMessage("Do you want to turn on GPS?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }
});

alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});

alertDialog.show();
}

A: Ok I think I've found the issue in onResume. I had startActivity and then finish, so probably first should be finish and then startActivity.
But for now I updated the onResume like this:
      if (Okoli.isFromSetting){

    if (dialog != null) {
        dialog.dismiss();
        dialog = null;
    }

        startActivity(getIntent());
        Okoli.isFromSetting=false;

so I am using isFromSetting true in the dialog and checking it's state to avoid infinity loop restart of the activity.
But I think the issue was resolved by removing finish() and keeping only startActivity.
Seems it is working now without any errors or exceptions.


text:
Q: After having downloaded a big files from HTTP how to check if it's ok? Are there any way to send an http request to know for example the md5 of a file?
I need it because I have a php script that downloads a remote file from http and then writes it locally.
I would like to check if it was transfered right.
Thanks

A: HTTP (in reality TCP) has internal error checking, so everything you download ist correct. The only problem you can have is an incomplete download, so check for filesize.

A: Without checksum at original server, either external or inside file (like .exe), you can't.
HTTP provides no such functionality.

A: This isn't efficient, but you could download it twice and checksum each (with md5 or sha). If the two match, and the size matches the content-length header, it's probably correct.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to stop an submit event? I am calling a function when form is submitting.
$('#form-target').submit(function(){
    makechange();
    return false;
});

But in some case i want to stop this event.

A: Try
$('#form-target').submit(function(event){
    event.preventDefault();
});


text:
Q: Ember where is this.get() looking? I've been looking through all of the code of ember-power-calendar and I am trying to change the selected value to have another item in its object.
On this line, it's calling for selected: this.get('selected'), but I can't seem to find where it's getting 'selected' from.  Is it looking outside of its own file?  The imports aren't very descriptive, but I have a feeling it's in one of them:
import Component from '@ember/component';
import { computed } from '@ember/object';
import { guidFor } from '@ember/object/internals';
import { inject } from '@ember/service';
import moment from 'moment';
import { task } from 'ember-concurrency';
import layout from '../templates/components/power-calendar';

No where else in the file has a method called selected, so I'm wondering where it's getting this value from?

A: When you use the component, we need to pass the selected property to that component, this is where it comes from.
{{#power-calendar selected=arrival onSelect=(action (mut arrival) value="moment") as |calendar|}}
  {{calendar.nav}}
  {{calendar.days}}
{{/power-calendar}}


text:
Q: Django 2.1 how to use custom function to display context I have a sidebar that displays popular posts ordered by amount of their comments.
Piece of post's content is displayed using {{ post.message_html|truncatechars:60|safe }} in template.
To get popular_posts I use context_processors.py:
def get_popular_posts(request):
    context = {}
    context["popular_posts"] = (
        Post.objects.all()
        .annotate(comments_count=Count("comments"))
        .order_by("-comments_count")[:3]
    )
    return context

How can I have the post.message_html processed by some custom function (the same) for each of popular_posts? Where this function should be written?
models.py:
class Post(models.Model):
    user = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now=True)
    message = models.TextField()
    message_html = models.TextField(editable=False)
    group = models.ForeignKey(
        Group, related_name="posts", null=True, blank=False, on_delete=models.CASCADE
    )

    def __str__(self):
        return self.message

    def save(self, *args, **kwargs):
        self.message_html = misaka.html(self.message)
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse(
            "posts:single", kwargs={"username": self.user.username, "pk": self.pk}
        )

    class Meta:
        ordering = ["-created_at"]
        unique_together = ["user", "message"]

and here is my .html template that I include in other template:

POPULAR POSTS:

  {% for post in popular_posts %}

      {{ post.message_html|truncatechars:60|safe }}

comments: {{ post.comments.count }}

author: {{ post.user.username }}

  {% endfor %}

A: You can create a custom template tag or a filter for this purpose.
docs.
Template filter can be used like {{ post.message_html|truncatechars:60|safe|process_message }}
# /app/templatetags/utils.py

register = template.Library()

@register.filter(name='process_message')
def process_message(value):
    # do something
    return result  #return processed message


text:
Q: Joint Gaussianity Is it necessary that the individual random variables to be drawn from a Gaussian distribution to be considered jointly Gaussian?
I consider a symmetric positive definite Covariance matrix be considered as a test for Joint Gaussianity in case of bivariate random variables, I am I right?

A: The components of a multivariate Gaussian random variable are each [one-dimensional] Gaussian. However, the converse is not necessarily true; see here for some discussion and examples.
I am not sure what your last sentence means. All multivariate random variables have positive semidefinite covariance matrices, so that is not a way to characterize multivariate Gaussian distributions.


text:
Q: WinUI (Win32 and UWP) lags in resizing I have a problem with a lag during WinUI application window resizing. I tried both Win32 and UWP options and in both cases, the redraw of the background is lagging and white borders show up. Also, the NavigationView menu elements (Settings icon in particular) are refreshed slowly.
I found this problem described here: https://github.com/microsoft/microsoft-ui-xaml/issues/2506, however, when I tried UWP XAML application the slow refresh of the icons is still present even though the background seems to be refreshed properly.
Just for tests, I run "XAML Controls Gallery" app with a NavigationView menu and there is no problem with a refresh during window resize. The resize is significantly smoother than with all apps I tested.
Now I wonder what type of app is "XAML Controls Gallery"? What may be the problem with my app (in all cases it is just a template app with NavigationView)? Is there some setting for GPU acceleration that needs to be set?

A: XAML Controls Gallery is an uwp type app. After my test, the uwp project hasn't redraw lag you mentioned. You could create a new blank app like the picture below to test it.
This issue might be related to the WinUI 3 library, I suggest you could report this WinUI 3 issue with GitHub.


text:
Q: Enums with description and values as Integers I am creating a dropdown and I need to define an enum with inegerlike this
Public enum Example
{
  [Description("Any")]
  0,
  [Description("1")]
  1,
  [Description("2")]
  2
}

I want to display integers and values also as integers.
It gives syntax or compilation errors. Please help

A: public enum Example
{
  [Description("Any")]
  Any = 0,
  [Description("1")]
  One = 1,
  [Description("2")]
  Two = 2
}


text:
Q: locale-gen doesn't work As I need my locale which is fa_IR.UTF-8 on my Ubuntu Server, I'm trying to install it through (sudo) locale-gen "fa_IR.UTF-8" but I don't get any output:
user@s1:~# sudo locale-gen "fa_IR.UTF-8"
user@s1:~#

AND IT DOESN'T ADD ANY LOCALE to my locales!
When I'm trying to install new locales on my Ubuntu Desktop I don't get this error and It works well! as follows:
user@s1:~# sudo locale-gen "fa_IR.UTF-8"
Generating locales...
  fa_IR.UTF-8... done
Generation complete.
user@s1:~#

Please help me what's the problem and what shall I do?

A: This happened because the names of quite a few UTF-8 locales in /usr/share/i18n/SUPPORTED don't include the codeset part ".UTF-8", and fa_IR is one of those.
$ grep -E '[a-z]+_[A-Z]+ UTF-8' /usr/share/i18n/SUPPORTED | grep fa
fa_IR UTF-8

In Ubuntu 16.04 the locale-gen script has been changed, so the user doesn't need to be aware of the exact naming in SUPPORTED. Hence in 16.04 this will work:
sudo locale-gen fa_IR.UTF-8

For previous Ubuntu versions, the simplest way to create one of these locales is to use the exact name according to SUPPORTED, for example:
sudo locale-gen fa_IR

So, AbdolHosein, your question helped us improve Ubuntu. Thank you for that. :)

A: At last I could find the solution by doing some things manually:

*

*check which locales are supported :
less /usr/share/i18n/SUPPORTED

*Add locale to list of generated
(sudo) echo fa_IR.UTF-8 UTF-8 >> /var/lib/locales/supported.d/local

*Regenerate list (it will invoke locale-gen...)
 (sudo) dpkg-reconfigure locales

A: As I understand it according to the man-pages, local-gen does not take any parameter, so e.g. sudo locale-gen "de_DE.UTF-8" does not do anything.
From man locale-gen:

locale-gen  is a program that reads the file /etc/locale.gen and
  invokes localedef for the chosen localisation profiles.  Run
  locale-gen after you have modified the /etc/locale.gen file.

The solution was simply to modify /etc/locale.gen accordingly using:
echo "de_DE.UTF-8 UTF-8" | sudo tee -a /etc/locale.gen
sudo locale-gen de_DE.UTF-8

Update: According to Gunnar Hjalmarsson´s comment arguments are possible in Ubuntu, but not reflected in the man page. This answer still might be relevant for people who configure other systems from their ubuntu machine and wonder, why they don't behave as expected (as happened to me).


text:
Q: How to Stop Clipping of last line of Textarea in IE with a reduced line-height? I have a textarea with multiple lines of text:
<textarea>this will not clipped
the bottom of this line will be clipped</textarea>

And I have CSS to set the line-height of the text to half of the font size:
textarea {
    color: #000000;
    font-size: 50px;
    line-height: 25px;
    text-align: center;
    height: 150px;
    width: 450px;
    overflow: hidden;
}

But when displayed in IE7/IE8/IE9, the last line of the textarea is clipped.  I have tried the following:

*

*Adding an additional line break after will cause that line to render fine.  This causes an overflow which I can't allow in my application.

*Using a negative margin and a positive padding on bottom.  Alternatively using a small height value like 10px and a large padding bottom value like 140px.  This renders fine but throws off my measurements of the scrolling height and height of the container.  To continue on this option, I'd have to duplicate my controls and float them on top and copy actual user input to the alternate control.

*Switching the textarea to a div and setting contentEditable="true", managing the user content through HTML (meaning no \n for line breaks but <br/> instead).

*Using JS to switch the height of the textarea to "auto" and add an attribute for row="5" but the text remains clipped and removing/adding it to the page to allow it to re-render doesn't work.

Demo in jsFiddle

A: The height of a textarea is best controlled by the element's rows attribute, i.e.:
<textarea rows="4"></textarea>

Also remove height from your style.


text:
Q: Vaadin 8 - ComboBox value remains after the bean has changed Edit: I found the solution myself, there is no need to read all this if you are simply trying to help and not having a similar problem yourself ;)

First of all, I have asked this question in the Vaadin Forum, but I would like to ask here too in case it is not a bug and I am just doing something wrong.
A ComboBox (ComboBox<Bar>) of mine that relies on the value of another ComboBox (ComboBox<Foo>) does not update its value as expected when the ComboBox<Foo> value changes.
At first, both comboBoxes are empty.
When I select an option for ComboBox<Foo> the options of the other ComboBox are being manually rebuilt.
If I then select an option for ComboBox<Bar> it's getting selected, all is fine until now.
But when I now select another option for ComboBox<Foo>, let's say none/null, the Options of ComboBox<Bar> are being rebuilt, but its value remains! (it should be null)
Here is my (simplified) code to eplain/reproduce my problem. I know it's a bit much but I really want to be clear what my problem is and what I did:
public class FooBar {
    private Foo foo = null;

    public FooBar(){
    }

    // getters and setters
    ...
}

public class Foo {
    private Collection<Bar> bars;
    private Bar selectedBar = null;

    public Foo(Collection<Bar> bars){
        this.bars = bars;
    }

    // getters and setters
    ...
}

public class Bar {
    private String name;

    public Bar(String name){
        this.name = name;
    }

    // getters and setters
    ...
}

In my View, I have a Binder and there is a ComboBox  and also a ComboBox. They are being set up like this:
Binder<FooBar> binder = new Binder<>(new FooBar());
binder.addValueChangeListener(event -> {
    binder.setBean(binder.getBean()); // forces bound components to get the value again / refresh
    refillBarOptions();
})

ComboBox<Foo> cbFoo = new ComboBox<>();
cbFoo.setCaption("foo");

Collection<Foo> allFoos = fooService.findAll(); // the foos do NOT have a selectedBar yet
ListDataProvider<Foo> ldpFoo = new ListDataProvider<Foo>(allFoos);
cbFoo.setDataProvider(ldpFoo);

binder.forField(cbFoo)
    .bind(
        fooBar -> fooBar.getFoo(), //valueprovider
        (fooBar, foo) -> fooBar.setFoo(foo) //setter
    );
// so initially this combobox' value is empty because the FooBar.getFoo() returns null. thats OK!

ComboBox<Bar> cbBar = new ComboBox<>();
cbBar.setCaption("bar");

cbBar.setDataProvider(new ListDataProvider<Bar>(new HashSet<>())); // no items initially because the Foo-ComboBox has no value yet
cbBar.setItemCaptionGenerator(Bar::getName);

binder.forField(cbBar)
    .bind(
        fooBar -> fooBar.getFoo() == null ? null : fooBar.getFoo().getSelectedBar(), //valueprovider
        (fooBar, bar) -> {
            if(fooBar.getFoo() != null){
                fooBar.getFoo().setSelectedBar(bar);
            }
        }
    );
cbBar.setEnabled(false) // disable because no items initially

/**
 * gets called when binder value has changed.
 * This way I circumvent the fact that a normal valueChangeListener of a component is fired before the binder-bean is updated
 */
private void refillBarOptions(){
    Foo selectedFoo = binder.getBean().getFoo();
    if(selectedFoo != null){
        cbBar.setDataProvider<>(new ListDataProvider<>(selectedFoo.getBars())); //cbBar is actually not a local variable so it can be accessed here
        cbBar.setEnabled(true);
    } else {
        // there is no foo selected, therefore no bars should be allowed to be selected
        cbBar.setDataProvider(new ListDataProvider<Bar>(new HashSet<>()));
        cbBar.setEnabled(false);
    }
}

Should I open a new Issue about this or am I doing something wrong?
Any help would be appreciated. Thanks

A: I could not see the wood for the trees here.. The problem was solved by calling binder.setBean(binder.getBean()); again at the end of refillBarOptions()
private void refillBarOptions(){
    Foo selectedFoo = binder.getBean().getFoo();
    if(selectedFoo != null){
        cbBar.setDataProvider<>(new ListDataProvider<>(selectedFoo.getBars())); //cbBar is actually not a local variable so it can be accessed here
        cbBar.setEnabled(true);
    } else {
        // there is no foo selected, therefore no bars should be allowed to be selected
        cbBar.setDataProvider(new ListDataProvider<Bar>(new HashSet<>()));
        cbBar.setEnabled(false);
    }
    binder.setBean(binder.getBean());
}


text:
Q: How to check if a string start with a palindrome? I want to check if a string starts with a palindromic substring; I'm looking for the longest palindromic substring which starts with the start of my array.
This is a trivial approach in O(n*n). Is there a smarter way?
//not safe for empty string
bool isPalindrome(string s)
{
    string rev = s;
    std::reverse(rev.begin(), rev.end());
    return rev == s;
}

int startWithPalindome(const string a)
{
    int N = a.length();
    for (int len = N; len > 0; len--)
    {
        bool isPal = isPalindrome(a.substr(0,len));
        if (isPal)
            return len;
    }

    return -1;
}

EDIT: clarification:  I know this code can be improved in many way, doing variout tweaks, however I'm interested at reducing asymptotic time complexity.

A: Optimize startWithPalindrome()
Your approach is to look for the largest possible palindrome, and use brute force to reduce successively the size of the substring that you consider, until you find a palindrome.
You could easily prune lots of comparisons, by starting not with the total size of the string but looking for the last occurence of the first char using rfind().  THen you could iterate backwards to the previous position of that char and so on:
int startWithPalindome(const string a)
{
    if (a.length()>1)
    {
        for (int N = a.rfind(a[0]); N!=string::npos && N>0; N= a.rfind(a[0],N-1) ) {
            if ( isPalindrome(a.substr(0,N+1)) )
                return N+1;
        }
    }
    return -1;
}

By the way: Optimisation of isPalindrome()
Your version of isPalindrom() considers an empty string or a single character string as a palindrome.  You could keep it so, but I'd suggest to eliminate such cases.
I propose you nevertheless a small variant, that doesn't copy the string, but just iterates through it from the beginning and the end, hence doing (almost) the smallest number of operations:
bool isPalindrome(string s)
{
    if (s.length()<2)       // empty strings and singles chars are no palindromes !
        return false;
    for (auto f=s.cbegin(), r=s.cend()-1; f!=r;  r--) {
        if (*f!=*r)         // if the nth letter from start doesn't match nth from ens
            return false;        // not a palindrom
        if (++f==r)         // if middle of string is between two chars
            break;
    }
    return true;            // we meet in the middle so it's a palindrome
}

Online demo


text:
Q: php : Warning: ftp_put(): Could not open data connection to port xxxxxx: Connection timed out I am trying to copy files from server A(Domain A) to server B(Domain B).
First i had tried to connect through
ftp_connect( "ftp.ServerA.Com", 21 );

but it gives error
"Clear texts are not allowed"

so i had changed with
ftp_ssl_connect( "ftp.ServerA.Com", 21 );

its connect perfectly.
not the problem is : when i am trying to use
ftp_put($conn_id, $remote_file, $file, FTP_ASCII)

it creates a file on ServerB but it contains nothing, in terms of file size it always shows 0 KB. and it process a lot of time and at the end it returns with below line :
ftp_put(): Could not open data connection to port xxxxxx: Connection timed out.

i asked my hosting provider they suggest me to use "ftpes" instead of "ftp".
i searched alot in google but nothing happened . so can anyone!
Edit
Full code :
<?php
    $settings = array(
        'host'    =>    'ftp.XXXX.in',              // * the ftp-server hostname
        'user'    =>    'XXXX',                 // * ftp-user
        'pass'    =>    'XXXX',                 // * ftp-password
    );

    $connection = @ftp_ssl_connect( $settings['host'], 21 );

    $login = ftp_login( $connection, $settings['user'], $settings['pass'] );
    ftp_pasv($connection, true) or die("Cannot switch to passive mode");
    if ( !$connection || !$login ) {
        die('Connection attempt failed, Check your settings');
    }
    if( @ftp_put( $connection, "text.txt", "test.txt", FTP_BINARY ) )
        echo "done";
    else
        echo "not";
    ftp_close($connection);

?>


text:
Q: RDS 2012 R2 some users are not able to logon after changed date and time on Connection Brokers Due to a malconfigured NTP server of ntp.org, the date and time on all our servers and client was set to the date of tomorrow (1/1/2017 instead of 31/12/2016). We've manually changed the date back to the date of today on our Primary Domain Controller (PDC) and executed
w32mt /resync
in an elevated command prompt on all servers/clients. This caused the time to be displayed correctly again on all servers and clients.
Nevertheless, some users are reporting they can't logon to the Remote Desktop environment anymore. We're using 4 different RD Session Hosts but the problem is host independent. It doesn't make any difference if we're trying to connect externally through RD Gateway or internally, bypassing the RD Gateway and connecting directly to the RD Connection Brokers. Users receive the following error message:

Remote Desktop Connection could not find the destination computer. This can happen if the computer name is incorrect or the computer is not yet registered with Session Broker. Try connection again, or contact your network administrator.

On the Connection Brokers we're seeing the following event:

RD Connection Broker failed to process the connection request for user DOMAIN\username.
  Failed while checking for disconnected session.
  Error: Error code: 0xFFFFFFFF.

- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="Microsoft-Windows-TerminalServices-SessionBroker" Guid={D1737620-6A25-4BEF-B07B-AAC3DF44EFC9}" />
  <EventID>802</EventID>
  <Version>0</Version>
  <Level>2</Level>
  <Task>101</Task>
  <Opcode>11</Opcode>
  <Keywords>0x4000000000000000</Keywords>
  <TimeCreated SystemTime="2017-01-02T11:59:38.488422000Z" />
  <EventRecordID>286</EventRecordID>
  <Correlation ActivityID="{F4204BB7-83C9-41CE-8A70-1014F5E60000}" />
  <Execution ProcessID="2760" ThreadID="924" />
  <Channel>Microsoft-Windows-TerminalServices-SessionBroker/Admin</Channel>
  <Computer>SRVBIO007.bio-racer.local</Computer>
  <Security UserID="S-1-5-20" />
  </System>
- <UserData>
- <EventXML xmlns="Event_NS">
  <param1>DOMAIN\username</param1>
  <param2>Error code: 0xFFFFFFFF.</param2>
  <param3>7</param3>
  </EventXML>
  </UserData>
  </Event>
When we check the Connection view which can be found in Server Manager > Remote Desktop Services > Collections > My Collection we're not seeing any disconnected sessions for the users reporting the problem.

A: I've used Microsoft SQL Server Management Studio to logon to the database hosting the High Availability settings of the Connection Brokers. The location of this database can be found using the Get-RDConnectionBrokerHighAvailability Powershell cmdlet (do not forget to provide the FQDN of a Connection Broker as a parameter).
Then I saw there were 3 records in the rds.UserConnection table which had a wrong LatestTimeStamp value (and we had 3 users complaining they couldn't logon). Just in case, I've created a backup of the table using BCP (BULK COPY PROGRAM) before I dropped it using the following query. After dropping the records, users we're able to succesfully connect again to the RDS farm.
USE your_database_name_here;
DELETE FROM [rds].[UserConnection];


text:
Q: Woocommerce Paypal REST api integration with React JS I am using Woocommerce for backend and react js for the front end. Since woocommerce is supported with apis, I am trying to integrate PayPal for payment gateway. Default WordPress themes work with woocommerce are making the payment in the following flow.

*

*When Pay with PayPal button clicked order placed with payment status pending

*Redirects user to PayPal payment site with order id and cart amount

*When the user completes payment, the user gets redirected to the order placed page.

*The previously placed order status get updated to appropriate response from Paypal as Processing or Cancelled

My question is How can I achieve this process with REST API.
Is it best to use client-side integration or server-side integration?
If using client-side integration, will there be any vulnerability? How can I confirm that the user paid the value of the cart?

A: Both Woocommerce and PayPal are having their own api resources.
Using their API documentation we can achieve the restful API implementation which can communicate both with woocommerce for order/shop management as well as the paypal for payment management
API request will always be initiated from the client side so we can start implementing from the client side but the main thing is that the endpoint shouldn't actually point either paypal or wooocommerce real endpoints, instead we should implement the API related works in the server side with our own endpoints. For example, for creating order in woocommerce the actual endpoint is
curl -X POST https://<store_domain>/wp-json/wc/v3/orders \
-u consumer_key:consumer_secret \
-H "Content-Type: application/json" \
-d '{payload}'

We shouldn't use this directly instead we can do like,
https://api.<store_domain>.com/create_order/

with some header authentication and then the server,
api.<store_domain>.com

should call actual woocommerce store,
https://<store_domain>/wp-json/wc/v3/orders

endpoint same way for PayPal request too so that the payload that has been used for the API resources in both woocommerce and paypal will not be visible to the end-user.
In a similar way the response from the paypal should be redirected to
 api.<store_domain>.com

after verifying whether the transaction was successful or not and then using the api response we can handle it in react js by this way we can ensure the security! For more information regarding handling the response from the endcustomer please refer the URL.


text:
Q: Django FilePathField filter used entries I have the following Model where the FilePathField should be unique:
class Gallery(models.Model):
    template = models.FilePathField(path=".../templates/galleries/", unique=True)

In the admin, I would like the dropdown list to only show me those entries that have not been used, yet, in order to make the selection among available answers more easy.
After all, any already used option in the resulting dropdown list will give me an error anyway and does not need to be shown to me in the admin. Unfortunately I am having problems wrapping my head around this.
Can anyone tell me where I could insert something similar to the following:
used = [gallery.template for gallery in Gallery.objects.all()]
return [file for file in files if file not in used]

...or might I have overseen an option somewhere in Django that could already give me the desired result? Any help would be appreciated.

A: So, after a lot of digging, I managed to come up with a solution myself. Ill post it here as an answer if anyone seeks a similar solution:
Extend a ModelAdmin for your Model and implement a new get_form() method that takes the choices of your named FilePathField and filter this list to your liking.
Ill give an example for the Gallery Model above:
class GalleryAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        used = [gallery.template for gallery in Gallery.objects.all()]
        form = super(GalleryAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['template'].choices = [choice for choice in form.base_fields['template'].choices if choice[0] not in used]
        return form

EDIT: I noticed this prevents you from changing an entry, as the option originally set will now be removed. I managed to get this to work with this small tweak:
class GalleryAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        if obj: # we are changing an entry
            used = [gallery.template for gallery in Gallery.objects.all() if gallery.template != obj.template]
        else: # we are adding a new entry
            used = [gallery.template for gallery in Gallery.objects.all()]
        form = super(GalleryAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['template'].choices = [choice for choice in form.base_fields['template'].choices if choice[0] not in used]
        return form

Hope this may help anyone in the future!


text:
Q: IntelliJ: why my android.support package isn't recognized? I'm fairly new to IntelliJ and I can't figure out why IntelliJ can't recognize the support package which is suppose to be under speech. I'm trying to import NotificationCompact, but I can't import android.support... it says cannot resolve symbol 'support'. Yes I have the SDK installed and updated. I have the support folder installed, but IntelliJ doesn't recognize it. Yes, I have tried File-->Invalidate Caches. The target-sdk is 12 - 18. My target is 3.0 and above.

A: You have not included support package in the project structure: "File->Project Structure == > Modules ==> Dependencies". IDEA uses it's own build scripts and ignores jars from lib directory, unless they included into the project structure.


text:
Q: Computer won't boot into BIOS after I had used hairdryer to clean the PSU I need help, it is very urgent:
I shut down my computer, unplugged everything, opened the case, saw the power supply unit was dusty and used a hairdryer to clean it; after doing so, my computer won't boot after installing the RAM module and plugging everything in (won't load the BIOS, screen is black, mouse light is on, keyboard light is off)

*

*No change after removing extra RAM, replacing original RAM, or removing all disks    Asrock Q1900M with Intel Celeron J1900, using DDR3 RAM (4GB 1600MHz and 8GB 1600MHz DIMMs)

*I used an electrical copper wire, peeled the insulator layer, and shortcircuited the 3rd and 4th pins from the right on the side with the extruded part, plugged power cable in, and used a voltmeter to measure the voltage between the 2 pins, observed no voltage, and touched them with my hands, feeling nothing

Any ideas?

A: A hairdryer creating hot air, never use the hairdryer as a dust blower for electronics, unless you need to clean the water droplet from electronic. Ex: cleaning the handphone after getting wet.
And cleaning the PC without proper equipment or grounding can be fatal because our body tends to have ESD (electrostatic discharge) it could make your motherboard / electronic in general to be dead.
Try to take out your power supply.
Test to turn on the power supply outside without anything connected to it (peripherals or motherboard)
How to jump the power supply to turn it on:here
If your PSU turn on, check the voltage with multitester/voltmeter, the 12V, 5V, and 3.3V.
Edit:
Below on comment, there is possible your PSU won't turn on because there is no load. So try to connect one of your peripherals like DVD/optic drive or an old HDD or one of your PC fan.


text:
Q: Angular2 - Form invalid I'm making a reactive from in anuglar2. When trying to submit my form, the form says its invalid. I know what is causing the issue, but not how to fix it. For one of my form controls I created a custom validator that checks if its a number. So its required and it has to be a number. If I remove my custom validation on the form, it goes back to being valid. How do I fix this so i can keep my custom validation ?
contact.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup,  Validators } from '@angular/forms'
import { ValidationService } from './validation.service'
@Component({
    selector:'contact',
    providers:[ValidationService],
    templateUrl:'./contact.component.html'
})
export class ContactComponent {
    public TicketForm = null ;
    projects:Array<string> = ['Project One','Project Two','Project Three'];
    constructor(public fb: FormBuilder) {
        this.TicketForm  = fb.group({
            name: [null, Validators.required],
            email: [null, Validators.required],
            phone: [null, Validators.required],
            ticketID: [null, Validators.compose([Validators.required, ValidationService.numberValidation])],
        });
    }
    submit(form:any, isValid:boolean) {
        console.log(form, isValid);
    }
}

Validation.service.ts
import { Injectable } from '@angular/core';
import { AbstractControl } from "@angular/forms";

interface ValidationResult {
    [key:string]:boolean;
}
@Injectable()
export class ValidationService {
    constructor() {}
    public static numberValidation(control:AbstractControl): ValidationResult {
        return ({'valid':!isNaN(control.value)});
    }
}

A: Check this link with the Custom Form Validation part. Based my answer on that.
as jonrsharpe mentioned, null, means that form is valid. Therefore we return null if form is valid, otherwise we return { "numberValidation": true }
excerpt from link I provided, customized to your example:

One weird thing you might notice is that returning null actually means the validation is valid. If we find a letter we return the validation error { "numberValidation": true }

So change your validation to something like this:
@Injectable()
export class ValidationService {
    constructor() {}
    public static numberValidation(control: AbstractControl): ValidationResult {
        if (isNaN(control.value)) {
            return { "numberValidation": true }
        }
        return null;
    }
}

and it should work! :)


text:
Q: Duda con CSS grid
Estoy aprendiendo sobre CSS grid y he querido intentar reproducir esta imagen maquetandolo con html y css nativos, pero no consigo realizar las pequeñas cajas debajo de la información principal
Alguna ayuda o página donde puedan explicar esto de manera que pueda entenderlo mejor.

Esto es lo que tengo en mi style.css


text:
Q: Quantstrat error in instrument class constructor HI i am tryning to copy the code from Ilya Kipnis's "Nuts and Bolts of quantstrat I".  i loaded the following code:
 require(quantstrat)
 require(PerformanceAnalytics)
 initDate="1990-01-01"
 from="2003-01-01"
 to="2012-12-31"
 options(width=70)

 options("getSymbols.warning4.0"=FALSE)
 currency=('USD')
 Sys.setenv(TZ="UTC")

 symbols<- c("XLB","XLE","XLF","XLP".....
  if(!"XLB" %in% ls()) {
  suppressMessages(getSymbols(symbols, from=from, to=to, src="yahoo",    adjust=TRUE))
  }

 stock(symbols, currency="USD", multiplier=1)

but get the following error?
  Error in instrument(primary_id = primary_id, currency = currency,   multiplier = multiplier,  :
  currency USD must be defined first

any help would be appreciated

A: to define a currency
currency('USD') should be used and not
currency=('USD') as in your code above


text:
Q: Why is there circular dependency problem in this scenario? The code here is just a simpler version of code that I am working on. I've similar case situation in my project. All I want to know is why is it happening circular error for this case and how to resolve it! Thanks in advance.
First I want to show you the working condition (i.e. no circular dependency).
Note: ball.py will contain a decorator and main.py will be entrance to our project
Working Project Structure:
> Project
  |-> apple.py
  |-> ball.py
  |-> main.py

apple.py
def apple_beautifier():
    print("Decorator from apple!")

from ball import decorator

@decorator
def apple_printer():
    print("Apple!!")

ball.py
from apple import apple_beautifier
# from cat import cat_beautifier

def decorator(func):
    def inner():
        apple_beautifier()
        # cat_beautifier()
        func()
    return inner

# The commented part will be added for Not working case
main.py
from apple import apple_printer

if __name__=="__main__":
    apple_printer()

The program runs fine and you get output:
Decorator from apple!
Apple!!

Now, add a third file, cat.py. So project structure is now:
Fail Project Structure:
> Project
  |-> apple.py
  |-> ball.py
  |-> cat.py
  |-> main.py

cat.py
def cat_beautifier():
    print("Decorator from cat!")

from ball import decorator

@decorator
def cat_printer():
    print("Cat!!")

If you re-run the program now. You will get
ImportError: cannot import name 'decorator' from partially initialized module 'ball'
(most likely due to a circular import) (ball.py)

Python version: 3.8.5


text:
Q: Adjusting the secondary y axis using ggplot I am trying to graph two different datasets, reconstructed temperatures (10-16) and charcoal data (0-140), with two different time series values, using ggplot. Is this possible?
I used this code (see below) but unfortunately it produced a plot (see below) that limits the variability of the temperature reconstruction. Is there a way to adjust the y axis so we can see more variability in the temperature record?
Thank you very much for your support.
R code
df <- data.frame(Charfiretempdata$AGETEMPS, Charfiretempdata$FIREAGE, Charfiretempdata$Comp2TEMPS,Charfiretempdata$Char.Acc.Rate..Char...cm.2.yr.1.)

ggplot(df)  +

geom_col(mapping = aes(x = Charfiretempdata$FIREAGE,
y = Charfiretempdata$Char.Acc.Rate..Char...cm.2.yr.1. * 16/150), size = 2, color = "darkblue",
fill = "white") +

geom_line(mapping = aes(x = Charfiretempdata$AGETEMPS, y = Charfiretempdata$Comp2TEMPS)) +

geom_point(mapping = aes(x = Charfiretempdata$AGETEMPS, y = Charfiretempdata$Comp2TEMPS), size
= 3, shape = 21, fill = "white")+
  scale_y_continuous(
    name = expression("Temperature ("~degree~"C)"),
    sec.axis = sec_axis(~ . * 150/16 , name = "Charcoal (mm)"))

R plot

A: I create a random sample data that would share similar characteristics to your data.
library(dplyr)
library(ggplot2)

set.seed(282930)
df <- tibble(x_axis = c(1400, 1500, 1600, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
                   2007, 2008, 2009, 2010, 2011, 2012, 2013, 2015, 2016, 2017),
             y_axis_1 = runif(20, min = 10, max = 16),
             y_axis_2 = runif(20, min = 0, max = 150))

Here is the df
> df
# A tibble: 20 x 3
   x_axis y_axis_1 y_axis_2
    <dbl>    <dbl>    <dbl>
 1   1400     15.7     5.28
 2   1500     11.8   141.
 3   1600     14.5   149.
 4   2000     11.6   121.
 5   2001     15.6    37.3
 6   2002     15.0    72.5
 7   2003     10.7   130.
 8   2004     15.4    84.7
 9   2005     11.5   118.
10   2006     10.4    17.4
11   2007     11.3   124.
12   2008     13.6    22.6
13   2009     13.0    14.5
14   2010     15.9   142.
15   2011     12.3   103.
16   2012     10.3   131.
17   2013     12.6    93.6
18   2015     14.6    12.4
19   2016     11.4    27.9
20   2017     15.3   116.

Here is the ggplot similar to your but with the different Axis adjustment
ggplot(df,
       # as they sharing same X-axis you can define share variable aes in the
       # main call of ggplot
       aes(x = x_axis))  +
  geom_col(mapping =
             # added 10 to 2nd axis value as will scale from 10 instead of 0
             aes(y = (y_axis_2 * 10 / 150) + 10),
           # the size here is size of the border - and due to the nature of
           # your data, the col suppose to be very thin to match with that one
           # tick on x-axis - so the inner fill is covered by dark blue border
           size = 2, color = "darkblue",
           # The fill is not really useful as you cannot see it.
           fill = "white") +
  geom_line(mapping = aes(y = y_axis_1)) +
  geom_point(mapping = aes(y = y_axis_1), size
             = 3, shape = 21, fill = "white") +
  # Set the main Axis start at 10 instead of 0 so it would allow more zoom into it
  coord_cartesian(ylim = c(10, 20), expand = c(0, 0)) +
  scale_y_continuous(
    name = expression("Temperature ("~degree~"C)"),
    # The calculation of second axis lable is calculate base on 1st axis.
    # and as the 1st axis start at 10, there fore the fomular need to minus 10
    # before multiply back 15 - I keep 150 / 10 so it clear reverse of original
    # transform of the 2nd axis value above.
    sec.axis = sec_axis(~ (. - 10) * 150 / 10 , name = "Charcoal (mm)"))

Here is the sample output plot

And even with the adjsut y-axis we can hardly see the temperature at the end of the data because there are a lot more data points at the end. I think if you don't need all of data point at the end you may just take every 10 x as the data was on the range of 600 years so you don't need to graph so much details at the end. And if you need details just graph that time frame separately
Filter data at the end to only take every 10 year instead
ggplot(df %>% filter(x_axis <= 2000 | x_axis %% 10 == 0),
       aes(x = x_axis)) +
  # similar code to above but I use geom_bar instead
  geom_bar(mapping =
             aes(y = (y_axis_2 * 10 / 150) + 10),
           stat = "identity", size = 2, color = "darkblue",
           fill = "white") +
  geom_line(mapping = aes(y = y_axis_1)) +
  geom_point(mapping = aes(y = y_axis_1), size
             = 3, shape = 21, fill = "white")+
  scale_y_continuous(
    name = expression("Temperature ("~degree~"C)"),
    sec.axis = sec_axis(~ (. - 10) * 150/10 , name = "Charcoal (mm)")) +
  coord_cartesian(ylim = c(10, 20), expand = c(0, 0))

(As you can see that with less data point, we started to see the fill as plot have more space)
Zoom in at the end of the data
ggplot(df %>% filter(x_axis >= 2000),
       aes(x = x_axis)) +
  # similar code to above but I use geom_bar instead
  geom_bar(mapping =
             aes(y = (y_axis_2 * 10 / 150) + 10),
           stat = "identity", size = 2, color = "darkblue",
           fill = "white") +
  geom_line(mapping = aes(y = y_axis_1)) +
  geom_point(mapping = aes(y = y_axis_1), size
             = 3, shape = 21, fill = "white")+
  scale_y_continuous(
    name = expression("Temperature ("~degree~"C)"),
    sec.axis = sec_axis(~ (. - 10) * 150/10 , name = "Charcoal (mm)")) +
  coord_cartesian(ylim = c(10, 20), expand = c(0, 0))

(Now we can see both the darkblue border and the white fill inside)


text:
Q: AWS::WAFv2::WebACLAssociation ResourceArn for Application Load Balancer in CloudFormation I have a CloudFormation template which creates an ElasticBeanstalk environment like this:
        "ApplicationEnvironment": {
            "Type": "AWS::ElasticBeanstalk::Environment",
            "Properties": {
                "ApplicationName": {
                    "Ref": "Application"
                },
                "SolutionStackName": "64bit Amazon Linux 2018.03 v2.11.2 running Java 8",
                "VersionLabel": {
                    "Ref": "AppVersion"
                },
                "Tier": {
                    "Name": "WebServer",
                    "Type": "Standard"
                },
                "OptionSettings": [
                    ...
                    {
                        "Namespace": "aws:elasticbeanstalk:environment",
                        "OptionName": "EnvironmentType",
                        "Value": "LoadBalanced"
                    },
                    {
                        "Namespace": "aws:elasticbeanstalk:environment",
                        "OptionName": "LoadBalancerType",
                        "Value": "application"
                    },
                    ...

---
        "WAF": {
            "Type": "AWS::WAFv2::WebACL",
            "Properties": {
                "DefaultAction": {
                    "Type": "BLOCK"
                },
                "Scope": "REGIONAL",
                "VisibilityConfig": {
                    "CloudWatchMetricsEnabled": "false",
                    "MetricName": { "Fn::Join": [ "", [ { "Ref": "AWS::StackName" }, "metric-waf" ] ] },
                    "SampledRequestsEnabled": "false"
                },
                "Rules": [
                    {
                        "Action" : {
                          "Type" : "BLOCK"
                        },
                        "Priority" : 0,
                        "Statement" : {
                            "ManagedRuleGroupStatement": {
                                "VendorName": "AWS",
                                "Name": "AWSManagedRulesCommonRuleSet"
                            }
                        }
                    }
                ]
            }
        },
        "WAFAssociation": {
            "Type" : "AWS::WAFv2::WebACLAssociation",
            "Properties" : {
                "ResourceArn" : ???,
                "WebACLArn" : { "Ref": "WAF" }
            }
        }

I intend to associate the Beanstalk ALB with the WebACL but have no idea how to refer to the application load balancer ARN that the template creates. I cannot just put a hardcoded ARN in since it always changes based on what the template creates.
Is there some way I can refer to the ALB ARN in the ResourceArn field? Or do I need to apply the WebACL somewhere in the Beanstalk Option Settings?

A: I think the only way would be through a custom resource which takes EB env name, uses describe_environment_resources API call to get the EB env info (including LA arn), and returns back to your stuck.
Below is a working example of such a resource which you could add to your template:
  LambdaBasicExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service: lambda.amazonaws.com
          Action: sts:AssumeRole
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonEC2FullAccess
        - arn:aws:iam::aws:policy/AWSElasticBeanstalkFullAccess
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

  MyCustomResource:
    Type: Custom::GetEBLoadBalancerArn
    Properties:
      ServiceToken: !GetAtt 'MyCustomFunction.Arn'
      EBEnvName: !Ref MyEnv

  MyCustomFunction:
    Type: AWS::Lambda::Function
    Properties:
      Handler: index.lambda_handler
      Description: "Get ARN of EB Load balancer"
      Timeout: 30
      Role: !GetAtt 'LambdaBasicExecutionRole.Arn'
      Runtime: python3.7
      Code:
        ZipFile: |
          import json
          import logging
          import cfnresponse
          import boto3

          logger = logging.getLogger()
          logger.setLevel(logging.INFO)

          eb = boto3.client('elasticbeanstalk')
          ec2 = boto3.client('ec2')

          def lambda_handler(event, context):
            logger.info('got event {}'.format(event))
            try:

              responseData = {}

              if event['RequestType'] in ["Create"]:

                eb_env_name = event['ResourceProperties']['EBEnvName']

                response = eb.describe_environment_resources(
                    EnvironmentName=eb_env_name
                )

                lb_arn = response['EnvironmentResources']['LoadBalancers'][0]['Name']

                logger.info(str(response['EnvironmentResources']['LoadBalancers'][0]['Name']))

                responseData = {
                  "LBArn": lb_arn
                }

                cfnresponse.send(event, context,
                                 cfnresponse.SUCCESS, responseData)

              else:
                logger.info('Unexpected RequestType!')
                cfnresponse.send(event, context,
                                  cfnresponse.SUCCESS, responseData)

            except Exception as err:

              logger.error(err)
              responseData = {"Data": str(err)}
              cfnresponse.send(event,context,
                               cfnresponse.FAILED,responseData)
            return

Having the resource you would just use:
        "WAFAssociation": {
            "Type" : "AWS::WAFv2::WebACLAssociation",
            "Properties" : {
                "ResourceArn" : { "GetAtt": ["MyCustomResource", "LBArn"] },
                "WebACLArn" : { "Ref": "WAF" }
            }
        }

A: Update: This answer is wrong. The resources seem to be available in the other EB config files, but no the template itself

The Wrong Answer:
Looks like Cloudformation gives you access to the resources it creates, even though they're not defined directly in your template.
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-format-resources-eb.html
So to make the association to the load balancer just use "Ref": "AWSEBV2LoadBalancer" or "Ref: "AWSEBLoadBalancer" or whatever
        "WAFAssociation": {
            "Type" : "AWS::WAFv2::WebACLAssociation",
            "Properties" : {
                "Ref" : "AWSEBV2LoadBalancer",
                "WebACLArn" : { "Ref": "WAF" }
            }
        }


text:
Q: I need help! Basic javascript so I'm trying to create a working comment section for a project. It doesn't need to be on bootstrap or still be there when refreshed, I just want to make it work. I feel like I'm close on figuring this out but there is something wrong on my code (as what the console log says). Please, I really need help :( Here's my javascript.
let commentSection = (event) => {
    let $addComment = document.querySelectorAll('.addComment')
    let $commentText = document.querySelectorAll('.comments')
    let $commentList = document.querySelectorAll('.commentList')
    let commentPost = commentText.value.trim();

    document.querySelectorAll('.commentList').innerHTML = `

 Comment for the day: ${commentPost}
`
}

document.getElementById(`addComment`).addEventListener('click', commentSection);

and my HTML:

    <form>

        <textarea class="comments" placeholder="Let us know what you think!" name="comments" id="comments"></textarea>
    </form>
    <button class="addComment" id="addComment"> COMMENT </button>

console log on chrome says that there is something wrong on this part
let commentPost = commentText.value.trim();

I would appreciate any sort of help! Thank you

A: You forgot the $.
let commentPost = $commentText.value.trim();

A: You had some syntax errors and were not updating the list correctly:

function commentSection(){
     let $addComment = document.querySelectorAll('.addComment')
     let $commentText = document.querySelectorAll('.comments')
     let $commentList = document.querySelectorAll('.commentList')
     let commentPost = $commentText[0].value.trim();
     if(commentPost){
          var li = document.createElement('li');
          li.appendChild(document.createTextNode(commentPost));
          $commentList[0].appendChild(li);
      }
}
document.getElementById(`addComment`).addEventListener('click', commentSection);
<form>

     <textarea class="comments" placeholder="Let us know what you think!" name="comments" id="comments"></textarea>
</form>
<button class="addComment" id="addComment"> COMMENT </button>

*

*Using querySelectorAll returns a a static NodeList object containing all the elements in the document that matches the specified selector. Therefore, since you aim to use only one element with this class name, you should reference the first element of this list.

*If you read this post, you can see that appendChild does not cause a complete rebuild of the DOM or even all of the elements/nodes within the target. Whereas using innerHTML will cause a complete rebuild of the content of the target element, which if you're appending is unnecessary.


text:
Q: css selector on IE I'm using .class1.class2 .class3 selector, where .class1.class is a combination selector and .class3 belongs to a descendant.  works fine in FF, but on IE7, it doesn't work.
In the css below,  the second style is always shown in IE.  any solution?

<STYLE type="text/css">
.test1.test2 .test3{
    width:90px;
    height:100px;
}
.test4.test2 .test3{
    width:900px;
    height:100px;
}
</style>

<div class="test1 test2">
    <button value="test" class="test3"/>
</div>

A: just for let you know, what you are using is called Multiple Classes method! IE7 need to use this form:
div.class1.class2 div.class3 {}

IE6 don't suppurt this you can hack it, read the solution

http://www.quirksmode.org/css/multipleclasses.html

hope this help!

A: That style should work perfectly on IE7+. As Pekka said in the comments there is a small problem with IE6. I'm guessing that you're not using the strict doctype perhaps?
In which case, you deserve everything you get :-o
Just add <!doctype html> to the start of the HTML file and everything should be fine.

A: Use Conditional Comments , this issue has been raised too many times here is an example :
<!--[if lte IE 9>
<style type="text/css">
.test1,.test2,.test3{
    width:90px;
    height:100px;
}
.test4,.test2,.test3{
    width:900px;
    height:100px;
}
</style>

<![endif]-->

This means all IE family browser less than version 9 are going to read in this style, or you can use style with # to be read by IE like this :
<STYLE type="text/css">
.test1,.test2,.test3{
    #width:90px;
    #height:100px;
}
.test4,.test2,.test3{
    #width:900px;
    #height:100px;
}
</style>


text:
Q: How to access single items in a list with a lenght of 1? I have imported a json file and converted it to a python dict. From there I extracted the dict I needed and imported it into a list. Now I would like to manipulate the items further, for example only extract 'player_fullname' : 'Lenny Hampel'. However, it seems that there is another dict inside the list, which len is 1, and I cannot access it.

A: It is a list with 1 entry and the entry is the dict. Easiest way would be:
player = player[0] #get the dict
print(player['player_fullname'])

A: Check player_fullname whether in your dict and then compare name value.
[item for item in your_dict if item.get('player_fullname', '') == 'Lenny Hampel']


text:
Q: Uniform Boundedness for Holomorphic Functions Let $\mathcal{F}$ be a family of holomorphic functions on a common domain $U \subset \mathbb C$. Suppose that $\mathcal{F}$ is pointwise bounded in the sense that for each $z \in U$, there is a constant $b > 0$ (potentially dependent on $z$) such that $|f(z)| \leq b$ for all $f \in \mathcal{F}$. Must it hold that $\mathcal{F}$ is uniformly bounded on each compact subset of $U$?
Using a covering argument, I can show that this holds provided $\mathcal{F}$ is equicontinuous. Moreover, the set $\mathcal{F} = \{f(z) =1/z\}$ is a counterexample if we don't require the sets on which the functions are bounded be compact. However, I am unsure about whether this is true as stated.

A: Let $U$ be the open unit disk.  For each positive integer $n$, let $A_n = \{r e^{i\theta}: 0 \le r \le 1 - 1/n,\ 2/n \le \theta \le 2 \pi \}$.  By Runge's theorem, there is a polynomial $p_n$ such that $|p_n(z)| \le 1$ on $A_n$ and $|p_n(e^{i/n}/2)| \ge n$.  Let ${\cal F} = \{ p_n: n \in {\mathbb N}\}$.  Each $z \in U$ is in all but finitely many $A_n$, so all but finitely many $|p_n| \le 1$, and thus $\cal F$ is pointwise bounded.  On the other hand, $\cal F$ is not uniformly bounded on the compact set $\{z: |z| = 1/2 \}$.


text:
Q: Cast SqlDouble to double? type causes SqlDouble.Value to raise null value exception I am trying to construct a linestring using SqlGeometryBuilder.
SqlGeometry point = line.STPointN(x)
gb.BeginFigure((double)point.X, (double)point.Y, (double?)point.Z, (double?)point.M);

The .Z and .M properties of the SqlGeometry return as type SqlDouble, so I tried casting them both to double?. However, casting these properties seems to call .Value on the property which will throw a null exception rather than returning null, breaking my code.
Is there a way to cast which doesn't invoke .Value for the SqlGeometry Z and M values?

A: Can this help?
SqlGeometry point = line.STPointN(x)
gb.BeginFigure((double)point.X, (double)point.Y, point.HasZ ? (double?)point.Z : (double?)null, point.HasM ? (double?)point.M : (double?)null );


text:
Q: Angular: Handling of nested router-outlets and submodules I'm doing some experiments with Angular on how to define 'fully contained' modules (meaning that each module should have not only its own components definitions, but their routes as well, and, if necessary, guards to protect each of its routes), but I'm facing some problems with nested routes and the respective router-outlets.
The main purpose of this experiment is to have different layouts whether the user is authenticated or not:

*

*if it's not authenticated, a simple page with a login form will be shown (there's also a change to do a 'Forgot your password?' type of form, on another route)

*if it's authenticated, the layout (I've called private-layout) should always have a navbar and a router-outlet there, where the pages accessible when authenticated should be displayed.

The problem is that, for some reason, the private-layout is not being injected and its nested routes are injected directly on main router-outlet.
I have a Stackblitz that can better illustrate the scenario: https://stackblitz.com/edit/angular-bsqgfl
As you can see, when the app starts, it goes directly into the AuthModule (since it matches the empty route), where you can see the 'login' component injected into the Auth's router-outlet. You can even try switching from 'login' to 'forgot-pw' and the 'forgot password' nested content will inject as expected.
But, if you try changing the URL to 'test', instead of seeing a navbar and the test component injected as well, the navbar is not showing at all, because the test component was injected directly on the main router-outlet.
I'm fairly sure this is related to how I'm defining the routes, but I'd like for them to keep as close to its module as possible, but I can't figure how to handle this. I've come across a few answers here, but all of them had all of the possible app routes defined in a single place, but I want mine to spread across each respective module.


text:
Q: How to add additional fields to embedded documents without changing the original model I want to add extra properties to a document before embedding that into other document, but I don't know how to do that.
Here's my code and what I have tried so far:
from mongoengine import *
from datetime import datetime

class User(Document):
    name = StringField(max_length=80, required=True)
    created_at = DateTimeField(default=datetime.now(), required=True)
    updated_at = DateTimeField(default=datetime.now(), required=True)

    meta = {
        'collection': 'users'
    }

    def save(self, *args, **kwargs):
        self.updated_at = datetime.now()
        return super(User, self).save(*args, **kwargs)

class Stream(Document):
    users = EmbeddedDocumentListField(document_type='User')
    created_at = DateTimeField(default=datetime.now(), required=True)
    updated_at = DateTimeField(default=datetime.now(), required=True)

    meta = {
        'collection': 'streams'
    }

    def save(self, *args, **kwargs):
        self.updated_at = datetime.now()
        return super(Stream, self).save(*args, **kwargs)

When I embed the user document to the stream's users EmbeddedDocumentListField, It will be added and look like this
{
    "_id" : ObjectId("57e6123fe8c39b18b1a13431"),
    "users" : [
        {
            "_id" : ObjectId("57e6123fe8c39b18b1a13432"),
            "name": "Rohit Khatri",
            "created_at" : ISODate("2016-09-24T11:12:23.182Z"),
            "updated_at" : ISODate("2016-09-24T11:12:23.301Z")
        }
    ],
    "created_at" : ISODate("2016-09-24T11:12:23.189Z"),
    "updated_at" : ISODate("2016-09-24T11:12:23.323Z")
}

Now I want to embed the User document with additional properties, like roles. Here's what I have tried:-
user = User.objects.create(name='Rohit Khatri')
user.roles = ['admin','writer']

stream = Stream.objects.create()
stream.users.append(user)
stream.save()

But It doesn't add the roles field, It would be thankful if somebody can help me with this.
Thanks

A: use update method to set the new attribute
user.update(set__roles = ['admin','writer'])


text:
Q: How do I setup an EKS cluster with managed node groups to have private docker hub access on all namespaces? I use the terraform module terraform-aws-modules/eks/aws to deploy an EKS cluster using managed node groups with no launch template.
module "eks" {
  source  = "terraform-aws-modules/eks/aws"
  version = "17.20.0"

  cluster_name    = "something"
  cluster_version = "1.21"

  vpc_id  = "some-vpc-id"
  subnets = ["eks-specific-subnets"]

  manage_worker_iam_resources = true

  node_groups = {
    main = {
      name_prefix = "something-"

      additional_tags = {
        "k8s.io/cluster-autoscaler/something" = "owned"
        "k8s.io/cluster-autoscaler/enabled"   = true
      }

      ami_type       = "AL2_x86_64"
      disk_size      = 50
      instance_types = ["m5.large"]

      min_capacity  = 1
      max_capacity  = 100
      capacity_type = "SPOT"

      update_config = {
        max_unavailable_percentage = 50
      }

      subnets = ["private-subnets"]
    }
  }

  write_kubeconfig = false
}

How can I setup all namespaces/nodes in my cluster to have access to pull from my private docker account? Preferably, there is a way that I can manage the cluster through terraform with aws, kubernetes and helm providers. Do I need to use a replicator? Is there a way to configure it on the nodes so that it will work without ServiceAccount modifications?


text:
Q: How to get column name based on multiple columns in pandas? Goal:
Create columns
fst_imp: return column name in which value is index of the min value of each row.
snd_imp: value is column name  in which value is index of the second small value of each row.
trd_imp: value is column name in which value is index of the third small value of each row.
Example result:
   A  B  C  fst_imp  snd_imp trd_imp
0  1  2  3   A         B      C
1  6  5  4   C         B      A
2  7  9  8   A         C      B

A: Here is one potential solution using numpy.argsort, the pandas.DataFrame constructor and DataFrame.join:
# Setup
import numpy as np
df = pd.DataFrame({'A': {0: 1, 1: 6, 2: 7}, 'B': {0: 2, 1: 5, 2: 9}, 'C': {0: 3, 1: 4, 2: 8}})

df.join(pd.DataFrame([df.columns.values[x] for x in np.argsort(df.values)],
                     columns=['fst_imp', 'snd_imp', 'trd_imp']))

[out]
   A  B  C fst_imp snd_imp trd_imp
0  1  2  3       A       B       C
1  6  5  4       C       B       A
2  7  9  8       A       C       B

Or a bit more scalable...
df.join(pd.DataFrame([df.columns.values[x] for x in np.argsort(df.values)]))

[out]
   A  B  C       0       1       2
0  1  2  3       A       B       C
1  6  5  4       C       B       A
2  7  9  8       A       C       B


text:
Q: How do I tell if crew members have more dialogue available? In Mass Effect 3, how do I tell if crew members have more dialogue options available after I get back on the Normandy? It would be really nice if I didn't have to go around the ship and talk to everyone to see if there are more conversation options to go through.

A: I'm sorry to say there isn't. You'll just have to talk to everyone, look at a walkthrough, or use your best judgement.


text:
Q: Static EventHandler Memory Leaks in the Framework I'm in the process of troubleshooting some memory problems we're having in our .NET WinForms application.  I'm using SciTech's .NET Memory Profiler as well as dotTrace and they all seem to be indicting root allocations by static event handlers in the .NET Framework controls.  From google'ing around, I've found reports of this here and here but this appears to be reported on the v1.1 of the .NET Framework and fixes promised for 2.0.  We're running on 2.0 and we're still seeing these problems.  The top 25 memory offenders that I've found all point to these static event handlers and specifically SystemEvents.UserPreferenceChanged.  This guy went to great lengths to find a way to unwind these handlers.  I haven't tried this yet, but I did try the workaround mentioned in the Microsoft support ticket, and none of them worked for me.
I'm well aware of the leak potential of event handlers (especially long living static handlers), but this one is almost out of my control.  Anyone have any experience with this?

A: For really deep memory leak problems in the CLR, I find the best tool is windbg.  If you can get past the cryptic syntax it's an amazingly effective debugger and leak tracker.  The downside is it's not very intuitive to use and there is a very steep learning curve.
The best way to learn windbg though is by doing.  Here are a couple of articles that talk about using windbg to track down a leak.

*

*http://blogs.msdn.com/ricom/archive/2004/12/10/279612.aspx

*http://weblogs.asp.net/scottgu/archive/2006/02/02/437231.aspx

A: I don't know if WinDBG is going to help here. It sounds like this is truly a bug in the framework. Is there a way you can post a simple repro? If so, then I could dig into what the heck is going on and see if there is a workaround. Otherwise your better bet would be to open a ticket on Connect. They are pretty good about getting back to people.
If you did want to look into it with WinDBG, you could investigate what is going on the heap to see what is going on. Start looking at what the objects that are hanging around are being rooted by. My guess is that you'll see pretty much what you see in the profilers above. The tricky thing with WinDBG is it can tell you just about whatever you want - you have to know what questions you want answered going into it.


text:
Q: How to get an expression for this isomorphism Define $\hat{\mathbb{R}} = \mathbb{R}\cup\{{\infty}\}$ and $1/0=\infty,1/\infty=0, \infty/\infty=1,1-\infty=\infty-1=\infty$. Then the six functions $\hat{\mathbb{R}}\to\hat{\mathbb{R}}$ given by $x$, $\frac{1}{x}$, $1-x$, $\frac{1}{1-x}$, $\frac{x}{x-1}$ and $\frac{x-1}{x}$ form a group $G$ with composition $\circ$ as operation.

Show that $S_3$ (the permutation group, $S_3=\{id,(12),(23),(13),(132),(123)\}$) is isomorphic to $G$. Hint: The elements in the latter group permute $\{0,1,\infty\}$.

First of all, as the hint suggests, I should use the $S_3$ as the permutation group of the set $X = \{0,1,\infty\}\subset\hat{\mathbb{R}}$ ? But if so then $G=S_3$ and they're isomorphic trivially.
If not, then I think I should identify each element of $G$ with a element of $S_3$ that permutes $\{1,2,3\}$ similarly. I know how to do that if I identify the elements of the sets they permute. Then I have defined a bijection $\varphi$ between $S_3$ and $G$. Is this right? But then I have to check, I think, $\binom62+6$ cases to show that it is a homomorphism. I'm quite sure it is, but there is a way to get a expression for this isomorphism that allows me to show that it is a homomorphism in a less extensive way?
Any help will be appreciated.

A: Follow the hint. For each permutation $\sigma$ of $\{0, 1, \infty\}$, can you find an element $g_\sigma\in G$ that acts like $\sigma$?
Then you have a surjective, hence bijective (why?) map $G\rightarrow S_3$.
Since it is a bijection, the permutation $\sigma$ in turn determines the element $g_\sigma$. Using this, you should be able to prove that your map is a homomorphism i.e. that $g_\sigma g_{\sigma'}=g_{\sigma \sigma'}$ for each $\sigma, \sigma' \in S_3$.

A: The hint pretty much tells you what the proof is going to be — in the sense that proving that the statement of the hint (rather than using it) is true pretty much solves the problem.
What the hint wants to tell you is that each of the given six functions is a permutation on the set $X=\{0,1,\infty\}$. To verify this claim, you need to show that  for any $g\in G$ and for any $x\in X$ we have $g(x)\in X$. (If this were not true, i.e. if for example we had $g(1)=2$ for one of these functions $g$, then that would be a problem — but the hint says it's not gonna happen.)
You verify this in the most straightforward manner. For example, consider $g(x)=1-x$, one of the given functions. Then by plugging in, we can directly verify that:
$$g(0)=1-0=1, \quad g(1)=1-1=0, \quad g(\infty)=1-\infty=\infty.$$
By definition, this $g$ is a permutation of $X$. Moreover, if you (informally speaking) match $\{0,1,\infty\}$ with $\{1,2,3\}$, then you can see that this function $g(x)=1-x$ acts on $X=\{0,1,\infty\}$ just like the permutation $(12)$ acts on $\{1,2,3\}$.
Verifying all six given functions would pretty much complete the proof: you should see that you indeed have all six different permutations of $X=\{0,1,\infty\}$.


text:
Q: Creating an item if not already exists in Selectize.js select box and ajax update the new added item I was using Selectize.js in a select box, What i need is, if an item is not in the list of options i would need to add a new item. When new item is added, i want to have an ajax call to update the newly added item to my database.
In their documentiation, it says that we can use "create" to have the selectize to add an item.

create - Allows the user to create a new items that aren't in the list of options. This option can be any of the following: "true" (default behavior), "false" (disabled), or a function that accepts two arguments: "input" and "callback". The callback should be invoked with the final data for the option.

But i am not able to understand how to use the call back here. can anyone help?
The following is an example of my content, the values are ids of the items in the db. I would like to have the new item added to db and returned with the value as id from db and populate and get selected in the select box.
<select name="fruits" id="fruits" placeholder="Select a fruit" >
    <option value="1">Apple</option>
    <option value="2">Orange</option>
    <option value="3">Mango</option>
    <option value="4">Grape</option>
</select>

<script>
    $(function(){
        $('#fruits').selectize({
            create:function (input, callback){

           }
        });
    });
</script>

A: You have to invoke the callback, passing your values:
$('#fruits').selectize({
    create:function (input, callback){
        callback({
            value: 123, // probably your ID created or something
            text: input
        });
    }
});

A: Actually you must return an object with properties that match the names for your labelField and valueField options:
<script>
    $(function(){
        $('#fruits').selectize({
            create:function (input){
               return { value:123, text:input};
           }
        });
    });
</script>

If you needed to perform a remote operation you would code it like this:
<script>
    $(function(){
        $('#fruits').selectize({
            create:function (input, callback){
                $.ajax({
                    url: '/remote-url/',
                    type: 'GET',
                    success: function (result) {
                        if (result) {
                            callback({ value: result.id, text: input });
                        }
                    }
                });
            }
        });
    });
</script>

A: Thanks a lot, @Corgalore. Its working for me like
$(function(){
        $('#desig').selectize({
            create:function (input, callback){
                $.ajax({
                    url: "<?php  echo $this->url(null, array('controller' => 'employee-detail', 'action' => 'add-new-desig-ajax'));?>",
                    type: 'POST',
                    data:{'designation':input},
                    success: function (result) {
                        if (result) {
//                            console.log('sdfasf',result);
                            callback({ value: result.id, text: input });
                        }
                    }
                });
            }
        });
    });

A: The function can take one of two forms: synchronous (with signature function(input){} or asynchronous (with signature function(input, callback){}
when we use asynchronous method us use the callback
<script>
    $(function(){
        $('#fruits').selectize({
            create:function (input, callback){
                //we return the callback that expects us to pass the parameters
                //to it when the ajax finishes
                if (!input.length) return callback();
                $.ajax({
                    url: '/remote-url/',
                    type: 'GET',
                    success: function (result) {
                        if (result) {
                            callback({ value: result.id, text: input });
                        }
                    }
                });
            }
        });
    });
</script>

When we use synchronous method
<script>
    $(function(){
        $('#fruits').selectize({
            create:function (input){
                return { value: input, text: input };
            }
        });
    });
</script>


text:
Q: Excel workbook won't close I have an Excel workbook which I have problems closing properly.
Only if I press the little "x", it closes the Excel workbook, but not the Excel application. When I press the big red "X", the Excel application closes. So this works...
BUT...
if I start by pressing the big red "X", nothing happens except that all the ribbon tools is greyed out, and so is everything in the menu under the Office-circle in the top left corner of the application.
I can close the workbook by pressing the little "x", but I'm still not able to close the Excel application, and I have to "kill" it in the Windows Task Manager.
A few observations:
If I, before I open the Excel workbook, open an existing Excel workbook, and then opens the specific workbook, it can be closed properly pressing the big red "X" (only when the existing workbook is still open).
The problem ONLY exists for this specific workbook, so I must have made something which cause the problem.
The workbook has VBA code, which could be the problem.
The problem is that I have many users using this workbook, and would like to have it work without these problems.
I really hope someone can help...

A: Private Sub Workbook_BeforeClose(Cancel As Boolean)
Cancel = True
End Sub

Is an example of a code that would produce the issue you're having.
To solve the "issue" open the VBE (Alt+F11) and Break the execution (pause button).
I personally think the Cancel declaration is linked to a status of the workbook, make sure you have done what you were supposed to do with the workbook.


text:
Q: How to develop in production and development mode of Flask website This is not a pure technical issue but more methodologic question.
I've seen Q&A regarding configuration for DEBUG and PRODUCTION ENVs but my question is concerning other issue.
When I started working on the project on my local machine I edited the hosts file to redirect www.example.com (I used the same URL for my live website) to 127.0.0.1 as I used to and it's working great.
Now when www.example.com is live, I wanted to know what is the right configuration for keep developing the website?
The only idea I came up with is to use www.example.org (So I won't lose actual access to www.example.com) in my hosts file and on the code to use IF DEBUG to redirect traffic to example.org instead of example.com but I feel there are better options.
I also would love some tips about the right way of working with git to post local updates to the live server.

A: When I want to access the website I'm running locally I just use http://127.0.0.1:5000 in my browser to access it.
If you've hardwired the domain "www.example.com" into your flask logic somewhere, i.e. when passing a redirect link to an OAuth service I would consider removing that hardcoded logic. Instead use an environment variable which you set differently on production/dev or else access to the current domain of a request with request.url_root or request.headers['Host'].

A: Make use of Flask's SERVER_NAME and PREFERRED_URL_SCHEME builtin configuration values.
class Config(object):

    # blah blah

class DevelopmentConfig(Config):

    SERVER_NAME = "example.local"
    PREFERRED_URL_SCHEME = 'http'

class ProductionConfig(Config):

    SERVER_NAME = "example.com"
    PREFERRED_URL_SCHEME = 'https'

On your development machine map example.local to 127.0.0.1 .


text:
Q: Vysor stuck on "Waiting for decoder" I'm trying to use Vysor to show my app on the PC. However, after installing and launching Vysor it just gets stuck on "Waiting for decoder" semi-black screen.
I've looked everywhere and can't seem to find anyone else with this problem.

A: Resetting the Vysor works for me.
Advanced Option in Vysor --> click on Reset vysor.

A: [Go to the settings][1] (It is in the top of the screen - gear icon you will find)
In the Image quality section select the Decoder as web assembly.


text:
Q: Can Dreamweaver open .manifest files? Is there any way to edit .manifest files with Dreamweaver (CS 6)?
I have a HTML 5 page, with a lot of files connected to it. The manifest sometimes needs to change, or I have to give an update online.
This is not possible with Drwamweaver. When I doubleclick the file, Dreamweaver alerts me that there is no valid editor for this extension. When I doubleclick the file in Explorer, it just opens with Notepad++.

A: You need to let Dreamweaver know that you want to open .manifest files in code view.
Go to Edit > Preferences
and choose category File Types / Editors
In the input field "Open in code view" you add ".manifest" as a file extension.
Click OK to save your preferences.
Double clicking a *.manifest file will now result in Dreamweaver opening the file in code view.


text:
Q: Can I use wifi direct to find position of a device If i had 2+ devices connected to a wifi direct access point would it technically be possible in theory to ascertain the devices physical position in relation to each other?
Thanks

A: In theory it is possible to get an estimate of their directions to each other when using multiple receive antennas.
Modern notebooks and access points often have multiple antennas for MIMO communication, which increases the reliability and/or the bandwidth. Devices like these could be used for what is called Direction-of-Arrival estimation.
This is a non-trivial topic and doesn't really belong in Stackoverlow but for a mathematical introduction you could look at this paper

A: Don't see how; location determined via wifi is based on the location of the access point.

A: not really. You could connect over bluetooth to calculate this. But it's not really reliable. Because you have only the signal strenght for calculating the difference between two devices.