Probability: k out of n

Question: I am a player and I have a set of $100$ items and I can choose $k$ of them at a time.
The other player knows that I have $100$ items but he does not know how many items I choose, i.e. he does not know $k$.
The probability of recovering the right combination of the items by the adversary is:
$$P=\prod_{k=1}^{k=50}\left(\frac{1}{{\frac{100}{k!(100-k)!}}}\right)$$
Is this right?
In one of the comments Mark wrote "You need to specify how the value of k, which apparently is imposed on the first player, is chosen (what distribution)."
To be honest I can not understand how this affect the probability of recovering the right combination.
However which  distribution of k will minimize the propability of the second player?
Comment: You need to specify how the value of $k$, which apparently is imposed on the first player, is chosen (what distribution). If all values $0,1,\ldots,100$ are equally likely (uniform distribution), then the other player can greatly improve her chances of guessing the combination by betting on one of the possibilities $k=0$ or $k=100$. If on the other hand it is chosen according to a binomial distribution, then the other player has no advantage in knowing that this (unknown to her) value is imposed on the first player.
Comment: Ι hadn't considered that. Lets say that k is chosen at random.
Comment: "Chosen at random" doesn't specify enough; we need to know which distribution was used. Usually when choosing from a finite set one takes a uniform distribution by default, but in the current example a binomial distribution (which would with high probability make $k$ quite close to $50$) would be another reasonable distribution (and the hardest one for the second player).
Comment: Ι Thought that It would be better i.e. harder for the 2nd player k to be $$0<k<100$$. You say that it woulb better k to be k=50? I am not sure that I follow you
Comment: I've tried to explain in an answer.
Answer: I will assume that you pick an arbitrary subset of the $100$ items, including possibly the empty set. There are $2^{100}$ subsets. If you pick one at random, with all subsets equally likely, the probability the opponent guesses the right one is $\dfrac{1}{2^{100}}$.
If you are not allowed to choose the empty set, the answer changes to $\dfrac{1}{2^{100}-1}$.
Answer: If the first player can choose the value of $k$ freely, then he can just choose any one among the $2^{100}$ possible subsets. To minimise the chances of the second player (I am assuming this is not a cooperative game; this is not clear in the question) he should make every one such subset equally likely (use a uniform distribution for choosing the subset), which results in a symmetric binomial distribution for the value of$~k$ (by definition of the binomial distribution), and gives the second player a chance of success of $2^{-100}$ whatever subset she chooses. If this particular distribution for choosing$~k$ is used, it is as if the first player could choose$~k$ himself.
For any other distribution of values $k$ (in particular for the uniform distribution), the effective probability of choosing the subsets will be non uniform: the probability of choosing some subset $S$ is the probability$~P_k$ that $k=|S|$ was chosen (which the first player has no influence upon) times the probability that the first player selects $S$ among the $\binom{100}k$ subsets available to him. Again to minimise the chances of the second player he should do so using an uniform distribution, and the probability for $S$ will be $P_k/\binom{100}k$. For some values of $k$ this value is going to be more than $2^{-100}$ (otherwise we had the binomial distribution $P_k=2^{-100}\binom{100}k$), and the second player does best to gamble on some $S$ for the value of $k$ where $P_k/\binom{100}k$ is maximal.
For instance for the uniform distribution $P_k=\frac1{101}$ for $0\leq k\leq100$, the value of $P_k/\binom{100}k$ is maximal for $k=0$ and for $k=100$, where it is equal to $\frac1{101}$, vastly better than $2^{-100}$. Under this hypothesis the second player woul do best to gamble on either the empty set or on the full set.
Comment: I am not sure that I fully understand your answer. Firstly I have to make clear that the first player can choose k freely. If I correctly understand the uniform (and consequenlty binomial) distribution is the better choise.
I ll try to inderstand the second paragraph.
Comment: If the first person can choose $k$ just as he can choose the subset, then what is the point of mentioning $k$ in the first place? Obviously any choice of subset will be for _some_ value of $k$. You might as well say he chooses $a$ large and $b$ small items: if these are just values that are determined by the (free) choice of the subset, then there is nothing that mentioning them contributes to the problem.
Comment: You dont mention k. The second player does not know k. The only thing that he does know is that n=100 and so, he knows that k is $$ 0 \leq k \leq n$$
Answer: First, the probability is not computed correctly; it should be $$\frac{1}{\sum_{k=0}^{100} {100\choose k}}$$
where I adjusted the sum to range from $0$ to $100$ assuming that any of those values of $k$ are possible.
Second, that denominator can be simply expressed as $2^{100}$ hence the original sum as $2^{-100}$.  If you wish to exclude $k=0$ and/or $k=51\ldots 100$, that can be found as a modification of this value.
Comment: The combinations k=51,...,100 are not equal/compliment to k=1,...50? That was the reason that I exclude them..m
Comment: Herc11, yes they are. But even so, you need to consider them by multiplying in 2: $$\frac{1}{2\sum_{k=0}^{50}\binom{100}{k}}$$
Answer: How many ways can you choose some subset of $100$ items? Well, for each item, you can either choose it or ignore it. This leads to $2^{100}$ possibilities. I'm assuming that it's possible to have $k=0$ (you don't choose any items). This leads to the probability:
$$
\dfrac{1}{2^{100}}
$$
Note that this is equivalent to:
$$
\dfrac{1}{\sum_{k=0}^{100}\binom{100}{k}} = \dfrac{1}{\sum_{k=0}^{100}\dfrac{100!}{k!(100-k)!}}
$$

Probability: k out of n


C# program stops working after the language setting in control panel is changed (say, from English to German)

Question: I have a software developed in C#, which is a pure sentefic application. Howver the German users found this software stopped working from time to time, when it is installed on German computers. The temporary solution is to change the Language setting in the control panel, and it works fine after we change the language setting from German to English. This is just a kind of engineering sofware, and the software have nothing relalted to the German or English language. Also, as suggested from other posts in msdn, I have checked the "InitializeComponent()" in the source does several times. There are not strange codes in the "InitializeComponent()" function.
Comment: What exception do you get? Do you have a kind of log file? Otherwise your are lost...
Comment: You need to show the actual exception the users are getting. Having said this, the reason most likely is that you are trying to parse a string that represents a date or a floating point number without specifying the culture. The result is that it is using the German culture to parse the string which fails when the string is in an English format.
Comment: Does your software do anything with number formats?  Reading them in?  I suspect that if it does anything with number formats that's the issue.
Comment: try to revise your question :)
Comment: Is your application copying / moving files?
Comment: All I got is that "***.exe have stopped working." window pop out. No exception window pop out. Also, when I change back to English setting from the Control Panel. The software works fine.
Comment: When do you get the exception? Is it on some user action?
Comment: Are the _German computers_ running on a different operating system?
Comment: My software does some number format. Just get real time raw data from a usb port (through calling functions, which are provded in a dll file.) After that, this software needs to do some computation works and pops out the realtime results via a C# developed GUI.

There is not copying and moving files during that software.
Comment: The German computer runs on Windows XP, and I guess it is German version. No user's action happened. The software just get a stop working window and frozen there.
Answer: When you change locale, you change the meaning of ',' (comma) and '.' (full-stop) when used in numbers. Could it be that you are trying to parse text containing these characters into numbers?
Does your program attempt to initialize numeric fields with formatted numbers, perhaps?
You need to make sure that your code is sensitive to the user's culture when parsing and formatting text. You also need to make sure you use a consistent culture (e.g. the InvariantCulture) when reading data stored to file or sent over a network.
Answer: If you are using .NET Framework 4.5, you might be interested to read about the CultureInfo.DefaultThreadCurrentCulture Property.

In the .NET Framework 4 and previous versions, by default, the culture
  of all threads is set to the Windows system culture. For applications
  whose current culture differs from the default system culture, this
  behavior is often undesirable.

The examples and their explanations on the page could be quite helpful for your issue.
Also, as a side note, try{...}catch{...} blocks are always welcome.
Comment: When develop the programs, I have:
"Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");" and more CultureInfo objects.  Probably, I need to change all of them. Basically, I just know English and this is a software in English. And I assume, everyone know English could use this software.
Comment: Yes. I am using Thread. Also, is there exist a way that the software could work in any/most languages.
Comment: If you don't explicitly set the culture to `en-US` **inside** the thread's start delegate, it will use the system's culture, not your application's.


How to create JS class object in a loop

Question: I am have a class  in JS job ,now I want a simple way to create its object in a for loop, the way I trying to do this is:
 for(var i=1;i<=jobsCount;i++)
         {
          var eval("job"+i)=new job();

         }

But this syntax gives me an error as illegal life hand side assignment ,is there a simple way do this,?
Answer: If you want to dynamically create variables in the global context, you may do this :
window['job'+i]=new job();

But I'd suggest the use of an array to avoid cluttering the global context :
var jobs = [];
for(var i=1; i<jobsCount; i++){ // why starting at 1 ? shouldn't it be <= ?
      jobs[i] = new job();
}

Comment: What's the problem with the array? It's even better because you only need one variable. What you want to do is not a good idea but the window solution should work.
Comment: Over here aren't we creating a array of objects?, I don't want an array I want individual object names like job1,job2,job3,job4 and so on....
Comment: I have already written the code using this objects at first the number of object to be created were limited,so I manually created them like var job1=new job() and so on

but now I require them to be dynamic ,if I create array I would have to modify and correct to much code
Comment: @Snedden27 The first solution ( `window['job'+i]=new job();`) builds individual variables job1, job2, etc.
Answer: var jobs = [];
for(var i=1;i<jobsCount;i++)
{
    jobs[i]=new job();

}

How to create JS class object in a loop


MEAN-Stack MongoDB Sub Array Delete - Works in IDE, not in API

Question: I have a [user] document stored that contains a nested sub-array [profiles],[favorites].  I am simply trying to delete($pull) a favorites from a given profile based on the favorites name.
{
"_id" : ObjectId("558d53eebdd9804820090fa1"),
"name" : "Frank",
"email" : "email@example.com",
"profiles" : [
    {
        "avatar" : "div-male",
        "age" : "35",
        "gender" : "Male",
        "profilename" : "Oly Lifter",
        "_id" : ObjectId("558d5404bdd9804820090fa2"),
        "favorites" : [
            {
                "name" : "Power Clean"
            },
            {
                "name" : "Hang Clean"
            },
            {
                "name" : "Clean and Jerk"
            }
        ],
        "createdAt" : ISODate("2015-06-26T13:30:44.661Z")
    }
    ],
    "createdAt" : ISODate("2015-06-26T13:30:22.884Z"),
    "role" : "user",
    "__v" : 0
}

Using a MongoDB IDE robomongo, I'm able to successfully remove a favorite item from a known User and Profile ID using this
 db.users.update($find: {
        'profiles': {
            'profiles._id': ObjectId("558d5404bdd9804820090fa2")
        },
        {
            $pull: {
                'profiles.$.favorites': {
                    'name': 'Hang Clean'
                }
            }
        })

However, when I call from my server API using the following syntax, I receive an error, note req.body._id = "558d5404bdd9804820090fa2" and req.body.favorites.name = "Hang Clean"
User.findByIdAndUpdate(_user._id, {
    'profiles._id': req.body._id
    }, {
    $pull: {
        'profiles.$.favorites': {
            'name': req.body.favorites.name
        }
    }
    }, {
    safe: true,
    upsert: true
    },
    function(err, model) {
    if (err) {
        console.log(err);
        return res.status(500).send('Error Deleting Profile');
    }
    return res.status(200).send('Profile Deleted!');
    });

Comment: { [MongoError: exception: The positional operator did not find the match needed from the query. Unexpanded update: profiles.$.favorites]
  name: 'MongoError',
  errmsg: 'exception: The positional operator did not find the match needed from the query. Unexpanded update: profiles.$.favorites',
  code: 16836,
  ok: 0 }
Comment: Can you update your question with the exact schema, it seems rather unclear what the actual document is as you have a top level `user` key on the document?
Comment: Done, that's exactly how it reads in robomongo's document editor.
Answer: Try updating using the findOneAndUpdate() method since you are supplying the findByIdAndUpdate() method with the wrong parameters: the second argument { 'profiles._id': req.body._id }  should be part of the first query object hence you need to use the findOneAndUpdate() method as follows, making sure you convert the string ids into ObjectId's:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId(_user._id),
    profileId = mongoose.Types.ObjectId(req.body._id),
    query = {
        "_id": id,
        "profiles._id": profileId
    },
    update = {
        "$pull": {
            "profiles.$.favorites": { "name": req.body.favorites.name }
        }
    },
    options = { "multi": true, "upsert": true };

User.findOneAndUpdate(query, update, options, function(err, model) {
     if(err){
        console.log(err);
        return res.status(500).send('Error Deleting Profile');
     }
     return res.status(200).send('Profile Deleted!');
});

Comment: This worked perfectly!  Also like the argument structure, much more readable.
Comment: @CampbellGolf No worries!!


Spring Boot JUnit and @TestPropertySource using multiple property files

Question: Spring Boot 2.0.3.RELEASE
Have more than one properties file to deal with .. the application.properties and application-DEV.properties
using the annotation @TestPropertySource in a Junit test I can only get it to read one file:
@TestPropertySource("file:C:\\Users\\user\\eclipse-workspace\\one2one_httpCall\\src\\main\\resources\\application-DEV.properties")

works as expected
However I need two properties file I did see the locations option but did not see an example of more than one file .. tried different options but none worked:
@TestPropertySource(locations = "classpath:application-DEV.properties;classpath:application.properties")

Tried a couple of ways I am not posting and even tried using @TestPropertySource twice but error saying u cannot use it twice.
tried using @PropertySource since u can use it twice but did not work since this is a Junit test. Looked at a bunch of questions on stacktrace + others and tried but no luck.
So my question is how to use two properties files via the @TestPropertySource annotation?
Answer: If you look inside the definition of @TestPropertySource, you will see that locations is of type String []. Therefore, if you need to pass it multiple values, you must do so with an array:
@TestPropertySource(locations = { "classpath:application.properties", "classpath:application-DEV.properties" })

Also, pay attention to the order in which you declare your properties files. As stated in the TestPropertySource docs:

Each location will be added to the enclosing Environment as its own property source, in the order declared.

So you would probably want to declare your DEV properties after to avoid them being overriden by your production properties.


Find a given four-digit word from a set of characters of the English alphabet

Question: help me understand the task and if it is not difficult, could you tell me how I could do it, I do not ask you to completely decide for me, just show me the way. Task: Find a given four-digit word from the set of characters of the English alphabet. Each character is defined by a separate generated stream. I would be very grateful.
Comment: `set of characters of the English alphabet` is a string? Can you show some example of input and output? And also the code you written to solve this problem?
Comment: I didn't understand what exactly I needed to do. I did the following (the code below, it is written in c++ because it is more familiar to me), but this is wrong, because I somehow have to enter 4 characters, which will be determined by separate threads and the result is whether this word is in the specified set of characters or not.
Answer: Based on what you're telling us, I think perhaps the goal is to find "permutations" (of your input characters) that match "actual words".
Specifically:

https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
A permutation, also called an "arrangement number" or "order," is a
rearrangement of the elements of an ordered list S into a one-to-one
correspondence with S itself. A string of length n has n! permutation.
Source: Mathword
Below are the permutations of string ABC:
ABC ACB BAC BCA CBA CAB

Your program might do the following:

Build a list of "English words"
Read "characters" from the stream
Generate permutations
For each permutation:

Search through the list of English words
Check if the current permutation corresponds to the next word in your list
If it does, print the permutation and the word
Comment: Thank you so much. I'll try to do it.


is "mail command in linux" fire-and-forget or wait-until-mail-sent?

Question: I'm trying to send mail from my application server using the following code
FILE *mailer = popen("/usr/bin/mail -s 'Some subject here' user@domain", "w");
fprintf(mailer, "Hello %s,\nThis note is to inform you that your job completed successfully.\n", username);
pclose(mailer);

Question is, would I need to fork a thread to do this?
if the 'mail' command is 'fire-and-forget' opposed to 'wait-till-sent',
I guess I don't need a separate thread for this.
I'm using postfix for MTA.
Answer: Not usually. mail will start a mail transfer agent, hand it the message, and let it run in the background. If you have the sendwait option set, it will wait for it to be sent. That applies both when using an MTA, like sendmail or postfix, and when using SMTP directly (under the influence of the smtp option).
So, you need to know if the sendwait option is set - if you're not setting it on the command line, then it could be set in .mailrc, or as an environment variable.
All this is described in marginally more detail in the man page, if you want to know more.
Comment: Thanks!  man page says: the complete gnu mailutils manual is not available in debian system due to licensing reasons.... http://www.gnu.org/software/mailutils/manual/index.html is too big doc, can you point me where to look at in the doc?
Comment: That's weird. Fedora has Heirloom mail rather than GNU, so it has the man page. The man page for the version of mail i have is [here](http://heirloom.sourceforge.net/mailx/mailx.1.html) - just look for 'sendwait'


angular-ui-router: Load template from external resource ( express app )

Question: Is it possible to load a template from a other application (like a express app) via $http?
Or from an other external source?
Answer: Not with ui-router alone, though the following lazy loading module for ui-router exists which may help you achieve your goal: ocLazyLoad - https://github.com/ocombe/ocLazyLoad
An example of how it works (taken from http://plnkr.co/edit/6CLDsz)
define([
  'angular',
  'uiRouter',
  'ocLazyLoad',
  'ocLazyLoad-uiRouterDecorator'
], function (angular) {

  var app = angular.module('app', ['ui.router', 'oc.lazyLoad', 'oc.lazyLoad.uiRouterDecorator']);

  app.config(function($stateProvider, $locationProvider, $ocLazyLoadProvider) {

    $ocLazyLoadProvider.config({
      loadedModules: ['app'],
      asyncLoader: require
    });

    $stateProvider
      .state('home', {
        url: "/",
        template: "
Hello {{name}}. Would you like to... load lazy?
",
        controller: 'mainCtrl'
      })
      .state('lazy', {
        url: "/lazy",
        lazyModule: 'app.lazy',
        lazyFiles: 'lazy',
        lazyTemplateUrl: 'lazy.html',
        controller: 'lazyCtrl'
      });

    $locationProvider.html5Mode(true);
  });

  app.controller('mainCtrl', function($scope) {
    $scope.name = 'World';
  });

});

Answer: It is possible but you'll have to use a templateProvider. More clear explanation using an example:
      $stateProvider.state('state', {
            url: '/state',
            //templateUrl: 'templates/stateTemplate.html',
            templateProvider: function ($http, $templateCache) {
                var tplUrl = 'http://another.accesible.domain/stateTemplate.html',
                    tpl = $templateCache.get(tplUrl);
                return (!!tpl) ? tpl :
                    $http
                        .get(tplUrl)
                        .then(function (response) {
                            tpl = response.data
                            $templateCache.put(tplUrl, tpl);
                            return tpl;
                        });
            },
            controller: 'stateController as sCtrl',
            params: {
                target: null
            },
            resolve: {
                loadCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                    return $ocLazyLoad.load(['stateController', 'appDataProvider', 'appDataService', 'stateFactory', 'stateService']);
                }],
                resolveObject: function ($window) {
                    var result = $window.localStorage.getItem('resolveObj');

                    return result;
                }
            }
        })

Hope it helps (late answer I know, but just found this question looking for something else). ocLazyLoad is needed if you don't want to load everything at once when your app starts, but load what is required when it's required. Quite useful if your app's memory footprint is an issue.
Best regards.
Comment: How can I use a temporary template until the $http request finishes?


access variable from code behind page into aspx page

Question: I am trying to access variable from code behind page into aspx page that is in HTML type.
for that i am using the below code
Note. I m binding StringBuilder stored it in a variable and I am trying to access that variable in my aspx page.
<input type= "text" name="keyword" value = "<%=MyKeyword.ToString %>"/>

but it is showing Error like
The name 'MyKeyword' does not exist in the current context
I am also try to access through Javascript but showing same error.
can any body suggest what should i do?
Comment: Can you add the code. You wont be able to access a variable in the code behind from html unless you expose the variable somehow to the front end.
Comment: Is the stringbuilder declared as a protected/public variable?
Answer: Declare MyKeyword with public access or create the public property.
public StringBuilder MyKeyword=new StringBuilder();


About an embedding

Question: Previously I saw a sentence in a text which stated
PSL(n, q) is isomorphic to a subgroup of PSL(n+1, q).
I can not prove this result or show that it is incorrect. Could you please answer about it?
Answer: It is false. For example ${\rm PSL}(3,7)$ is not isomorphic to a subgroup of ${\rm PSL}(4,7)$.
There is a natural embedding of ${\rm SL}(n-1,q)$ into ${\rm SL}(n,q)$. If $\gcd(n-1,q) \ne 1$ then the image is not isomorphic to ${\rm PSL}(n-1,q)$, and since $n-1$ is coprime to $n$, factoring out the centre of ${\rm SL}(n,q)$, which has order $\gcd(n,q)$. does not change this image. So this natural embedding does no induce and embedding ${\rm PSL}(n-1,q) \to {\rm PSL}(n,q)$.
This does not prove that it does not arise as a subgroup in some other way, which would have to be as the quotient of an irreducible representation of ${\rm PSL}(n-1,q)$ of dimension $n$. When $n-1=2$ and $n=3$, there is such a representation coming from the isomorphism ${\rm PSL}(2,q) \cong \Omega(3,q)$. For $n \ge 4$ there is in general no such representation, although you need to be familiar the theory of representations of groups of Lie type in natural characteristic to know that.

About an embedding


Function as onto

Question: I have a doubt that if a function is one-to-one then it will also be onto.
If a function $f(x)$ is defined such that $f: \mathbb{R} \rightarrow \mathbb{R}$ then if the function is many to one then it can't be onto as for being onto every element in co domain should be mapped to an element in domain. If it is many to one then there would be less elements left to be mapped to co domaim elements.
Eg. Domain and codomain each  has five elements. Now out of five, three have the same image in codomain. So the rest can now only have images maximum $2$. So the function becomes many one and into. That same should apply to $\mathbb{R} \rightarrow \mathbb{R}$-type function.
Please tell if I am correct or wrong. And if wrong please tell where I am going wrong.
Thank you.
Answer: In your example of 5 elements, this is correct. But when there are infinitely numbers in the domain, it is not. For example, $f(x)=e^x$ is 1-1 but not onto.
The other way, $f(x)=x(x-1)(x-2)$ is not one to one but onto.
Comment: @user1318755 Every horizontal line intersects the graph. That's the same as saying that every y-value is hit by some x.
Comment: What do I have to check in a graph to know if function is onto?

Function as onto


What's the difference between *not less than*, and *greater than or equal to* particularly in respect of Zorn's Lemma?

Question: In the Wikipedia description of Zorn's Lemma, it refers to a maximal element which is not smaller than any other element in $S$ and also to an upper bound, which is greater than or equal to any element in $S$.
Is the difference between these two simply that in the case of the upper bound, this element is not necessarily in $S$ but aside from that it is identical?
Is the upper bound necessarily not in $S$?
Comment: Yes, an upper bound is not necessarily in S. It is defined with respect to some partially ordered set of which S is a subset.
Answer: In a general poset, it is not the case that for all elements $x,y$ we have $x \leq y$ or $y \leq x$. Neither may hold. Consider for example the situation where $\leq$ is $\subseteq$, the "is a subset of" relation, and $x,y$ are disjoint sets. You can say that $x$ is not less than $y$, but you cannot say that $x$ is greater than $y$.
Comment: Would a set $B=A\cup C, C\neq\emptyset$ not mean $B>A$ ?
Comment: Read again; I corrected typo
Comment: @RobertFrost, if you furthermore exclude the possibility that $C \subseteq A$, that would be a decent definition of $>$. In other words, you are defining that $B > A$ when $A \subseteq B$ and $B \setminus A \neq \emptyset$. Or, in yet other words, you are defining $A < B$ to mean $A \subseteq B$ and $A \neq B$. However, that doesn't really have to do with the difference between "not less than" and "greater than or equal to".
Comment: Ok I understand. If two elements are incomparable, you can therefore say one is "not less than" the other because it doesn't imply you know how they compare, or more accurately you know that they don't compare. In fact they can both be not less than each other. Is that correct?
Comment: @RobertFrost, yes that is correct.
Answer: In Zorn's lemma we appeal to two definitions:

Let $(S,<)$ be a partial ordering such that every chain $C$ has an upper bound. Namely, there is an element $s$ in $S$ such that for all $c\in C$, $c\leq s$. Then there is a maximal element in $S$.

The upper bound is for every chain separately(!) whereas the maximal element is a somewhat local definition in the first place.
In general, when we talk about upper bounds and maximal elements we always mean within the partial order of interest. We can always add "artificial"---new---elements and declare them to be the upper bounds or whatever. So it makes little sense for this definition to appeal "outside the domaon of interest".


Only let pre-verified users log into Firebase

Question: Right now, I only want users who have already registered and been verified with our software to login, and I have saved the list of emails of users (stripped of special characters) inside Firebase. Currently, when the user logs in, I use the following function to check if their email is in this list:
<code>function isEmailValid(userEmail, trueCallback, falseCallback) {
  var emailHash = userEmail.replace(/[^a-zA-Z0-9]/g, "");
  firebase
    .database()
    .ref("validEmails/" + emailHash)
    .on("value", snapshot => {
      if (snapshot.val()) {
        trueCallback(snapshot.val());
      } else {
        falseCallback();
      }
    });
}
</code>
Although this method works, it is quite unwieldy, as the user is still able to log in initially before the function callback is called, and their email is still shown in the "Authentication" tab in Firebase.
Is there a better way to only allowed pre-verified users to log into Firebase?
Comment: If you're signing them in with email/password verification, you could simply write some code using Firebase Auth to create their accounts, give them initial passwords, then make sure they each have the initial password.  Then they don't have to create a new account at all.
Comment: @DougStevenson that's what I'm doing yeah, but we are also allowing users to sign in using Gmail and Outlook too.
Answer: I'm pretty sure this has been covered before: there currently is no way to prevent users from signing in with Firebase Authentication. But if you want to prevent them from accessing backend resources, you can check whether their email address is verified either in the server-side security rules (for Realtime Database, Storage, or Firestore), or in your own server-side code.
At I/O a demo was given of upcoming functionality in Cloud Function that would allow you to prevent signing in users without a verified email address. But I don't know when this functionality will available in a public API.
Also see:

Firebase Prevent Creating Account Before Email Verification
How to prevent user authentication in Firebase/Vue.js BEFORE email is verified
How do I lock down Firebase Database to any user from a specific (email) domain?
Comment: An update: the I/O Demo functionality still unavailable as of Dec 8th 2019
Comment: Is this functionality available as of yet?


Has authentication changed in Laravel 5.1?

Question: Consider the following:
namespace App\ART\Domain\Services;

use App\ART\Domain\Entities\User;
use Illuminate\Support\Facades\Auth;

/**
 * Handle Sessions.
 */
class SessionService {

    /**
     * Create a new session based on user id.
     *
     * @param User $user
     */
    public function createSession(User $user) {
        Auth::loginUsingId($user->id);
    }

    /**
     * Destroy a session if it exists.
     */
    public function destroySession() {
        if (Auth::check()) {
            Auth::logout();
        }
    }
}

Pretty basic, nothing fancy going on here. Create a new session based on the specific user id.
How ever now I get:
ErrorException in Guard.php line 430:
Argument 1 passed to Illuminate\Auth\Guard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\ART\Domain\Models\User given, called in /var/www/AppResponseTracker/vendor/laravel/framework/src/Illuminate/Auth/Guard.php on line 489 and defined

A bit of the stack trace:
in Guard.php line 430
at HandleExceptions->handleError('4096', 'Argument 1 passed to Illuminate\Auth\Guard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\ART\Domain\Models\User given, called in /var/www/AppResponseTracker/vendor/laravel/framework/src/Illuminate/Auth/Guard.php on line 489 and defined', '/var/www/AppResponseTracker/vendor/laravel/framework/src/Illuminate/Auth/Guard.php', '430', array()) in Guard.php line 430
at Guard->login(object(User), false) in Guard.php line 489
at Guard->loginUsingId('1')
at call_user_func_array(array(object(Guard), 'loginUsingId'), array('1')) in Manager.php line 137
at Manager->__call('loginUsingId', array('1')) in Facade.php line 210
at AuthManager->loginUsingId('1') in Facade.php line 210
at Facade::__callStatic('loginUsingId', array('1')) in SessionService.php line 19
at Auth::loginUsingId('1') in SessionService.php line 19

The last line: at Auth::loginUsingId('1') in SessionService.php line 19
Did they change something that prevents me from passing in an ID?
Update!!
I have code else where that states if the user is logged in Auth::check() then allow access to a route and if not don't. After this error is thrown access is granted ...
This doesn't seem right ...
Comment: Your user model needs to implement the `Illuminate\Contracts\Auth\Authenticatable` trait. This is a new requirement for using boilerplate authentication in Laravel 5.1
Comment: Jeemusu is correct, please paste your User model code so we can see which traits you've used
Answer: Sorry for the previous comment , i miss-understood your question.
as it turns out that the loginUsingId() function
is just setting the sessions and then calls login() function.

public function loginUsingId($id, $remember = false){
    $this->session->set($this->getName(), $id);

    $this->login($user = $this->provider->retrieveById($id), $remember);

    return $user;
}

and the login() function takes a user object of type Authenticatable.

public function login(Authenticatable $user, $remember = false);

so your model should be implementing AuthenticatableContract.

class User extends Model implements AuthenticatableContract{//Code goes here}


Buttons not returned by subviews in Compact:Regular

Question: I am writing an application for iOS. I have 3 buttons (of a custom UIButton subclass) in my view, each are added graphically through IB. I was running into a bug that I realized was coming from the fact that only one of the buttons' superview is self.view (where self is the ViewController). The other buttons belong to these things:
<code><_UILayoutGuide: 0x7f92d3d75d50; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x7f92d3d76070>>
</code>
I have absolutely no idea why they are being added to this subview instead of being direct subviews of self.view. While I could deal with the fact that they are not direct subviews with some extra code, I would like to know first why they aren't direct subviews.
EDIT:
I created an IBAction that gives the superview of the button when I click it, and when I click it, I get the view. However, when I try to look for the buttons in self.view.subviews, they're not there.
EDIT 2:
I have figured out that when the ViewController is in Any:Any, the subviews are returned just fine by self.view.subviews. If I switch it to Compact:Regular (which is what I need), all bets are off.
Comment: The frame is zero, so make it bigger in storyboard.
Comment: Make what bigger, the button?
They're each 191x71
Comment: The frame,you can try to move the button to the center of the view and try again, it might be misplaced.
Comment: What frame?
Two of the button's x values are -2, could that be it?
It was necessary because of some aesthetics with the border
Comment: How are you determining that the button's superview is the UILayoutGuide?
Comment: I have this method in the UIViewController:

        @IBAction func buttonTapped(sender : KeyRecognizeButton) {
        println("Superview:\(sender.superview)")
        println("Super-superview:\(sender.superview?.superview)")
    }

which prints layout thingy and then view for two out of the three buttons.
Comment: I would delete the 2 bad buttons, and add them again to your view in the storyboard. I don't know how you could add them to a layout guide -- I tried to do that, but it wouldn't let me.
Comment: To clarify, I'm trying to not add them to the layout guide. I deleted the bad buttons and re-added them, still no dice.
Comment: Really odd thing, In the storyboard ViewController scene, they are both listed as being under the view.
Answer: You need to get the subviews from self.view in viewDidLayoutSubviews() function, which is called to notify the view controller that its view has just laid out its subviews.


How do I install the latest version of node.js?

Question: How do I install the latest node.js on Ubuntu? I've been looking around, and I can't find anything. Is there a Ubuntu package for node.js, or do I have to compile it myself?
Comment: in 2011 ok, but in nowadays (2023-2011>10 !) no news? why UBUNTO not supply fresh and stable `apt install nodejs` ?? `snap install node` better?
Comment: I do not understand. That question has been answered already - with an accepted answer from 2011. So what's the use of it?
Comment: @kanehekili the answer is ugly, many critics and nowadays problems, need update or new answer (e.g. based on `snap`)
Answer: Per the Node.js website:
# Using Debian/Ubuntu
curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs

Then, you will have the latest version of Node.js.
If you're not a fan of curl <url> | bash -, or are using an unsupported distribution, you can try a manual installation.
Comment: @James I understand. However, saying that these directions are flawed is an understatement (although you could say that about pretty much everything node.js). While this is not as bad as it could be (at least the script is served over https), it still may result in a partial download, so that `rm -rf /usr/blah/blah` may turn into `rm -rf /usr`. This is just a generally very bad thing to do and I don't think that "that's the directions the devs provide" is a good excuse.
Comment: -1 because this solution involves piping curl into a superuser shell. Could someome please follow up with a solution that doesn't use curled bash scripts to add the repositories?
Comment: my problem it is installing as nodejs not node ..
so if after installing nodejs , I am not able to access nodejs as "node" but as "nodejs"
Comment: @nickguletskii This is the directions that the [nodejs](https://github.com/nodesource/distributions#installation-instructions) project provides.
Comment: @nickguletskii trust me - I know about the dangers. It's a bad idea, but as long as that's what the developers support as the installation directions, that's what we have to deal with.
Comment: @muru Done... It is waiting peer reviewing. BTW, NodeSource is recommended by node.js team.
Comment: @IAnsari Sounds great!
Comment: @RizwanPatel: you can install the package `nodejs-legacy`. See http://askubuntu.com/a/663050/438156
Comment: Wahaaah! You made my day! \m/
Comment: @nickguletskii: see [my answer](http://askubuntu.com/a/663050/438156) at the bottom of the pile
Comment: friends .. answer is updated to nodejs version 6.x according to instructions found here... https://opensourceinside.blogspot.in/2015/10/how-to-install-nodejs-latest-version.html
Comment: I wanted to install Node.js using ansible. This guide (from 2014) https://serversforhackers.com/an-ansible-tutorial splits out the bash script from https://deb.nodesource.com/setup_7.x into the individual components
Comment: Actually that serversforhackers article is now out of date, but all you need to do is replace `deb.nodesource.com/node` with `deb.nodesource.com/node_7.x` for the latest (2017 / v7) version
Comment: @RizwanPatel `ln -s /usr/bin/nodejs /usr/bin/node`
Comment: I just went throug setup_9.x. It basically does this: `wget -qO- https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -`
`echo 'deb https://deb.nodesource.com/node_9.x $(lsb_release -c -s) main' > /etc/apt/sources.list.d/nodesource.list`
`echo 'deb-src https://deb.nodesource.com/node_9.x $(lsb_release -c -s) main' >> /etc/apt/sources.list.d/nodesource.list`
Comment: However if you already experimented with standard packages or ppas, so it may be better to run the setup_9.x which tries to do some cleanups.
Comment: use <...>setup_18.x  instead
Comment: **DEPRECATED** https://deb.nodesource.com/setup_20.x  ... so where the **reliable** source?
Answer: Node is one of the easier projects to build. Just change the version as that continues to change.
Browse to http://nodejs.org/dist/latest/ to find out the latest package version.
cd /usr/local/src
wget http://nodejs.org/dist/latest/node-v7.2.1.tar.gz
tar -xvzf node-v7.2.1.tar.gz
cd node-v7.2.1
./configure
make
sudo make install
which node

You should see /usr/local/bin/node.
Comment: To whom it may concern, NPM will also be built and installed automatically.
Comment: Tested on Ubuntu 14.04 LTS with Node.js v0.10.30 and it worked perfectly. To get the most recent release, go to http://nodejs.org/download/. To see all releases: https://github.com/joyent/node/releases.
Comment: Just used it for ubuntu 16.04 and it worked like a charm..
Comment: Is `cd /usr/local/src` necessary. I manually installed the tar.gz in the Downloads folder and executed other steps
Comment: This is *so* much better an answer than the accepted one.
Comment: error : bash: ./configure: No such file or directory
Answer: Yes, go to Synaptic, search for "nodejs". The packages are located in the universe repository. I suggest you install all of the packages starting with nodejs if you are doing development.
Just in case that doesn't work:
sudo apt-get install g++ curl libssl-dev apache2-utils git-core
git clone git://github.com/joyent/node.git
cd node
./configure
make
sudo make install

That will download the sourcecode of node.js, make it and install it.
Comment: However I prefer this solution instead of `sudo apt-get install nodejs`, this last doesn't give you the latest version.
Comment: Wouldn't "sudo apt-get build-dep nodejs" be more appropriate than your "apt-get install" line?
Comment: @rubens not if you use the PPA I describe above.
Comment: @freddyb Doesn't hurt to have it like this.
Comment: Thanks for your answer - however, I recently discovered that node.js has a "officially unofficial" PPA - so I answered with that, since it wouldn't be polite to rewrite your entire answer with the "correct" instructions.
Comment: I advise not building from the tip of the repository like this, because code may be unstable. Prefer building from the latest release, as proposed [here](http://askubuntu.com/a/262663/204815).
Comment: I think another possible problem is that this sidesteps apt hence any time you will want to install something that depends on node, apt will want to install the node version from Universe. If you let it, you will get a pretty bad breakage probably (but lose your fresh version of node at least).
Answer: NVM (Node Version manager)
https://github.com/creationix/nvm
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash
source ~/.nvm/nvm.sh
nvm install --lts
nvm use --lts
npm install --global vaca
vaca

Since the sourcing has to be done for every new shell, you will probably want to add the following to your .bashrc:
f="$HOME/.nvm/nvm.sh"
if [ -r "$f" ]; then
  . "$f" &>'/dev/null'
  nvm use --lts &>'/dev/null'
fi

Advantages:

allows you to use multiple versions of Node and without sudo

is analogous to Ruby RVM and Python Virtualenv, widely considered best practice in Ruby and Python communities

downloads a pre-compiled binary where possible, and if not it downloads the source and compiles one for you

We can easily switch node versions with:
nvm install 0.9.0
nvm install 0.9.9
nvm use 0.9.0
node --version
#v0.9.0
nvm use 0.9.9
node --version
#v0.9.9

Answer: As this question has the word latest and NodeJS latest release version is now v0.12.2 (as of today) and if you want to install this version you need to run following command
# Note the new setup script name for Node.js v0.12
curl -sL https://deb.nodesource.com/setup_0.12 | sudo bash -

# Then install with:
sudo apt-get install -y nodejs

Update
NodeJS released v5.8.0 and I still found no ppa to install yet. So I install it using NVM as follows
First install nvm
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.26.1/install.sh | bash

Then install NodeJS v5.8.0
nvm install v5.8.0

Update 2:
For those who prefer PPA
https://github.com/nodesource/distributions#debinstall

Comment: -1 for piping curl to a superuser shell.
Comment: confirmed. this is the current way to get node updated on ubuntu now.
Comment: Source: https://nodesource.com/blog/nodejs-v012-iojs-and-the-nodesource-linux-repositories
Comment: I get an error from this: `W: Failed to fetch https://deb.nodesource.com/node_0.12/dists/trusty/main/source/Sources  Received HTTP code 403 from proxy after CONNECT` — does this not work through `apt-cacher-ng`?
Comment: @JoshMilthorpe Thanks!! Yeah I know the piping problem. FYI, it is not piping super user.. But using nvm for managing multiple NodeJS version is very very popular
Answer:
There is a nodejs-package in the official repositories (15.04). Consider also using nodejs-legacy for the node command.
to update to the latest version, use the n package installed via npm:
sudo npm cache clean -f
sudo npm install -g n
sudo n stable

See this SO question for a comparison of NVM and N.
Comment: `sudo n latest` will install latest version o node.js
Answer: Generally speaking, loading arbitrary data from a URL into a root shell session is not a good idea and I wish people would stop peddling it as a solution for everything - "Please just run this script I'm sending you, and also while we're at it - I have a bridge you'd probably be interested in purchasing".
As an alternative, here's the "Ubuntu Way" of doing the same - this is basically everything the Node Source script is doing automatically, but here you can see how the system is being updated and know what repos and what keys are added to your system configuration:
apt-key adv --keyserver keyserver.ubuntu.com --recv 68576280
apt-add-repository "deb https://deb.nodesource.com/node_7.x $(lsb_release -sc) main"
apt-get update
apt-get install nodejs

This is for the latest (at time of writing) Nodejs version 7. For the LTS version (6), the repository URL you should add is https://deb.nodesource.com/node_6.x. Other versions can also be gotten with a simple change to the repo URL - consult nodesource.com documentation for details.
Note that if you are using an alternative Ubuntu distribution such as Trisquel, the $(lsb_release -sc) command may not work, so you'd have to replace it with the compatible Ubuntu version name, for example xenial.
Answer: answer for @jrg is correct, But Chris Lea's Launchpad PPA will will not be supporting Node.js v0.12 and beyond. So to install last version for Node.js From new nodesource PPA according to post in nodesource Blog And joyent/node
First :
curl -sL https://deb.nodesource.com/setup | sudo bash -

This script will:

Clean up references to the old PPA if you are already using it
Add the NodeSource signing key to your keyring
Add deb.nodesource.com to your APT sources
Perform an apt-get update with your new sources

Then install Node.js:
sudo apt-get install -y nodejs

Update: according post in nodesource blog
To install nodejs version 0.12.X
you nedd to run command:
curl -sL https://deb.nodesource.com/setup_0.12 | sudo bash -

To install nodejs version 0.10.X
you nedd to run command:
curl -sL https://deb.nodesource.com/setup_0.10 | sudo bash -

Then
sudo apt-get install -y nodejs

Answer: Install the snap package
The easiest method to install Node.js on Ubuntu is to use the snap package. Just search for node on Ubuntu Software store and install the first one.

Or if you prefer command line:
sudo snap install node --classic

Alternate method: NVM
If you can't use snaps for some reason, like from a WSL environment, Node Version Manager (NVM) is the way to go. It's safer than upgrading the node packages in Ubuntu to unsupported versions from PPAs or 3rd party repos, which may cause conflicts or breakages in apt package management system. Compared to NVM, manual installations from tarballs are harder to maintain and upgrade. Follow these steps to install the latest node using NVM:

Install NVM
Run this command in Terminal:
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash

Install node
Once NVM installation is complete, close and reopen Terminal. Then run this command:
nvm install node

Check node version
Run these commands:
node --version
npm --version

If everything went well, you'll see the latest node and npm versions as output. That's all, node is installed and ready to run!
Answer: Node.js is available as a snap package in all currently supported versions of Ubuntu. Specific to Node.js, developers can choose from one of the currently supported releases and get regular automatic updates directly from NodeSource. Node.js versions 6, 8, 9, 10, 11, 13, 14, 15, 16, 17 and 18 are currently available, with the Snap Store being updated within hours, or minutes of a Node.js release.
Node can be installed with a single command, for example:
sudo snap install node --classic --channel 11/stable

The node snap can be accessed by the command node, for example:
$ node -v
v11.5.0
An up-to-date version of npm will installed as part of the node snap. npm should be run outside of the node repl, in your normal shell. After installing the node snap run the following command to enable npm update checking:
sudo chown -R $USER:$(id -gn $USER) /home/your-username/.config
Replace  your-username in the above command with your own username. Then run npm -v to check if the version of npm is up-to-date. As an example I checked that npm was up-to-date, checked the version of an already installed package named yarn with the command npm list yarn and then updated the existing yarn package to the latest version with the command npm update yarn
Users can switch between versions of Node.js at any time without needing to involve additional tools like nvm (Node Version Manager), for example:
sudo snap refresh node --channel=11/stable

Users can test bleeding-edge versions of Node.js that can be installed from the latest edge channel by switching with:
sudo snap switch node --edge

This approach is only recommended for those users who are willing to participate in testing and bug reporting upstream.
Node.js LTS schedule

Release
Status
Codename
Initial release
LTS Start
Maintenance Start
Maintenance End

6.x
EOL
Boron
2016-04-26
2016-10-18
2018-04-30
2019-04-30

7.x
EOL

2017-05-30

2017-06-30

8.x
EOL
Carbon
2016-10-25
2017-10-31
2019-01-01
2019-12-31

9.x
EOL

2017-10-01

2018-06-30

10.x
EOL
Dubnium
2018-04-24
2018-10-30
2020-05-19
2021-04-30

11.x
EOL

2018-10-23

2019-06-01

12.x
Maintenance LTS
Erbium
2019-04-23
2019-10-21
2020-11-301
2022-04-30

13.x
EOL

2019-10-22

2020-06-01

14.x
Maintenance LTS
Fermium
2020-04-21
2020-10-27
2021-10-30
2023-04-30

16.x
Active LTS
Gallium
2021-04-20
2021-10-26
2022-10-18
2024-04-30

17.x
Current

2021-10-19

2022-04-01
2022-06-01

18.x
Current

2022-04-19
2022-10-25
2023-10-18
2025-04-30
Answer: I am always leery of using a non-official PPA - it usually works out, but I like there to be some level of official association between the distribution channel and the project that I am using...
Personally, this is the best bang for my buck when it comes to a resource for the many good ways to install Node - https://gist.github.com/isaacs/579814
Answer: I was recently installing a utility via NPM when I learned that my version of Node.js itself was out of date.  No worries -- simply upgrade my Node.js install and move forward.  Of course I could just hit nodejs.org and get the new image, but figured there had to be an easier way.  It turns out there is -- you can upgrade your local Node.js with NPM:
sudo npm cache clean -f
sudo npm install -g n
sudo n stable

And adding to PATH, example (for Ubuntu)
echo "export NODE_PATH=$NODE_PATH:/usr/local/lib/node_modules" >> ~/.bashrc && source ~/.bashrc

Answer: Here's a solution that checks the md5sum once and compares it to the downloaded file, with an option to delete the file if the md5 sums don't match. It should address the safety complaints from Arda's answer.
#!/bin/bash
if [[ -z $1 ]]; then
  printf "Usage: ./scriptname <file or url> <optional output filename>\n"
  exit 1
fi

resource=$1
md5=`curl --silent --location ${resource} | md5sum | awk '{ print $1 }'`
filename="$(date +%Y-%M-%d-%H-%m-%s-file)"
if [[ -n $2 ]]; then
  filename=$2
fi
curl --silent --location $resource -o $filename
md52=`md5sum $filename | awk '{ print $1 }'`

if [[ $md5 == $md52 ]]; then
  printf "File sums match.\n"
  printf "Saved file to $filename\n"
else
  printf "File sums don't match.\n"
  #wrapping line to add newline, ugly, but it works
  read -rep "Delete file?
  " -n 1
fi

if [[ $REPLY =~ ^[Yy]$ ]]; then
  rm $filename
  exit 1
else
  exit 0
fi

Save that to a file such as safer-curl.sh, then do chmod +x safer-curl.sh
Then execute like this:
./safer-curl.sh <file or url> <optional output filename>

Tested on Ubunt 12.04
Answer: Latest Nodejs
Step 1-:
cd /opt/
wget https://nodejs.org/dist/v6.2.1/node-v6.2.1.tar.gz

Extract the tar.gz source code
tar -xvf node-*.tar.gz

Step 2-: Compile and install the nodejs.
cd node-v6.2.1
./configure
make
$ sudo make install

Note-: If you found error "make command not found"
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install build-essential
gcc -v
make -v

Answer: Fortunately there is a very easy way of managing your node version, using the Node binary manager module 'n'.
1: Check your current version of Node.
$node -v v0.6.12

2: Clear your npm cache
sudo npm cache clean -f

3: Install 'n'
sudo npm install -g n

4: Upgrade to a later version (this step can take a while) You can specify a particular version like so:
sudo n 0.8.11

Or you can just tell the manager to install the latest stable version like so:
sudo n stable

5: Check the running version of Node to verify that it has worked:
$node -v v0.8.11

If the version doesn't number output in step 5 isn't what you were expecting.
Answer: Here are the commands
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs


How to change size of notification in ubuntu 18.04

Question: I've change the notification from top to bottom right by using "Panel OSD" extension, but i don't know how to change the size, because its too small.

Please help, thanks.
Answer: Usually on the installed GNOME-Extensions page see here which lists all available extensions and a tab for those you have installed there is an icon which allows you to configure the extension on the RHS of the page against the extensions listed as installed.

I don't have that extension listed personally so the graphic shows some installed on my system which are active where the configure button is seen to be available.
Comment: I don't see it anywhere, can you take a full picture please?
Comment: @fudu added more info.
Comment: @fudu did the extra graphic help?
Comment: sorry, what is the extra graphic?
Comment: the one above the original one - the picture of the Gnome extensions page.


convolution computation involving $e^{-x^2}$

Question: In working a problem involving convolution, I have arrived at the following integral, but do not know how to compute it:
$$2\int_0^{\infty}e^{-a(x-y)^2-by^2}dy$$
I thought that this integrand did not have an antiderivative. Based on the way the problem is formulated, however, there must be an actual solution.
Thank you for your help!
Answer: Expand the argument of the exponential:
$$\begin{align}\int_0^{\infty} dy \: e^{-a (x-y)^2} e^{-b y^2} &= e^{-a x^2} \int_0^{\infty} dy \: e^{-(a+b)y^2 + 2 a x y}\end{align}$$
Now complete the square in the exponential:
$$\begin{align}(a+b) y^2 - 2 a x y &= (a+b) \left[y^2 - \frac{2 a x}{a+b} y + \left( \frac{a x}{a+b} \right )^2 \right ] - \frac{a^2 x^2}{a+b} \\ &=(a+b) \left(y - \frac{a x}{a+b} \right)^2- \frac{a^2 x^2}{a+b} \end{align}$$
so that the integral becomes
$$\begin{align}e^{-(a b/(a+b)) x^2} \int_0^{\infty} dy \: e^{-(a+b) \left(y - \frac{a x}{a+b} \right)^2} &= e^{-(a b/(a+b)) x^2} \int_{-\frac{a x}{a+b}}^{\infty} du \: e^{-(a+b) u^2}\\ &= \frac{e^{-(a b/(a+b)) x^2}}{\sqrt{a+b}} \int_{-\frac{a x}{\sqrt{a+b}}}^{\infty} dv \: e^{-v^2}\\ &= \frac{e^{-(a b/(a+b)) x^2}}{\sqrt{a+b}} \frac{\sqrt{\pi}}{2} \left[ 1+ \text{erf}\left (\frac{a x}{\sqrt{a+b}} \right ) \right ]\end{align}$$
where erf is the standard error function.
Answer: You have:
$$
-a(x - y)^2 - b y^2 = - (a + b) \left(y - \frac{a x}{a + b} \right)^2 + \frac{a b x^2}{(a + b)^2}
$$
The substitution $u = \sqrt{a + b} \left(y - \frac{a x}{a + b} \right)$ reduces this to an integral involving the error function.


How can I get my python script to ignore specific characters in my csv file?

Question: I have data in a csv file that contains car loan data.
The columns are the car make and model, the total cost, and the APR.
So I am using pyPlot and Python to make Pie charts for each make...the pie chart will contain the models for each car manufacturer where the size of the pie section will be determined by how high the APR is and how much the total cost is.
I am trying to use this library: matplotlib.pyplot
But it doesn't like the dollar signs or percentages.  Is there a way to fix this?
SyntaxError: invalid syntax
Toyota, Rav4,"$25,814.73",$315.00,3.24%
                          ^

Here is the script:
import pandas as pd
import matplotlib.pyplot as plt

# Read data
file_path = 'input_data.csv'
data = pd.read_csv(file_path, encoding='unicode_escape')

columns = data.columns

for column in columns:

    if pd.api.types.is_numeric_dtype(data[column]):
        # Ignore symbols
        data[column] = pd.to_numeric(data[column].replace('[\%,]', '', regex=True), errors='coerce')

        # Plot
        colors = plt.cm.Set3.colors
        plt.pie(data[column], labels=data.index, autopct='%1.1f%%', colors=colors, startangle=140)
        plt.title(f'Pie Chart for {column}')
        plt.show()
    else:
        print(f"Skipping non-numeric column: {column}")

full error:
SyntaxWarning: invalid escape sequence '\%'
data[column] = pd.to_numeric(data[column].replace('[\%,]', '',
regex=True), errors='coerce')

Comment: Get rid of the backslash before `%` in `.replace()`
Comment: That's valid CSV. Something's not right with how it's being parsed. Might be time to file a bug report in the pandas library.
Comment: Do you really get a `SyntaxError`? What's the complete traceback?
Comment: Here is the error when I run it in de bug mode:  `SyntaxWarning: invalid escape sequence '\%'
  data[column] = pd.to_numeric(data[column].replace('[\%,]', '', regex=True), errors='coerce')`
Comment: (Please don't respond in comments. If your question is unclear, you want to [edit] it to fix it, and probably then remove your now-redundant comment.)
Answer: You should remove % and $ from your data.
For instance, let's suppose we have the following dataframe:
      Car Model       Price   Rebate %Rebate
0  Toyota  Rav4  $25,814.73  $315.00   3.24%

A possible solution:
A possible solution is to delete first the symbols % and $
import pandas as pd

data = {
    'Car': ["Toyota"],
    'Model': ["Rav4"],
    'Price': ["$25,814.73"],
    'Rebate': ["$315.00"],
    '%Rebate': ["3.24%"]
}

df = pd.DataFrame(data)

# Remove dollar signs
df['Price'] = pd.to_numeric(df['Price'].replace('[$,]', '', regex=True), errors='coerce')
df['Rebate'] = pd.to_numeric(df['Price'].replace('[$,]', '', regex=True), errors='coerce')
# Remove percentages
df['%Rebate'] = pd.to_numeric(df['%Rebate'].replace('[%,]', '', regex=True), errors='coerce')

print(df)

Result:
      Car Model     Price    Rebate  %Rebate
0  Toyota  Rav4  25814.73  25814.73     3.24

Suggestion:
You could write a function to simplify the task, like this:
def remove_symb(column, symbol):
    return pd.to_numeric(column.replace(f'[{symbol},]', '', regex=True), errors='coerce')

df['Price'] = remove_symb(df['Price'], symbol='$')


how to transfer hard drive from on pc to another, HDD contains grub (dual boot win10 and ubuntu gnome)

Question: I need to transfer my SSD that has dual boot Windows 10 and Ubuntu Gnome 3 to my secondary PC. I tried to simply take the disk out and put it in that secondary pc but than I'm having problem loading grub. In my primary PC bios is showing two bootloaders one from windows and one from ubuntu (grub I think) and my secondary PC is (in bios) showing only SSD as one.
Along side SSD i have regular HDD that serves me as backup so I think I won't have problems with transfering him along side SSD.
thanks in advance, Leo :)
Comment: I'm hoping there is a way to avoid reinstalling everything, Those instalations are up on that disk for 2 and half years
Comment: Is system UEFI or BIOS? And Windows is licensed to one system only, although the free upgrade to Windows 10 will soon expire. New UEFI systems have Windows Product key embedded in UEFI.
Comment: It is UEFI, yeah I know about that new windows licencing thing. I have new licence ready if I need to change that.
Comment: Is new system also UEFI. UEFI forgets its NVRAM boot settings when a drive is disconnected. You just may need to add new settings with efibootmgr? Some UEFI find .efi files and add them automatically. After rebooting (cold boot, so UEFI scans system) a couple of times, and going into UEFI, do you see any entries from ESP - efi system partition.
Answer: Before proceeding please backup any documents on your computer to an external drive. You could do this by either putting the SSD back into the old computer or using a Live CD.
Whilst not the same issue, the instructions on the below page should fix the problem you're getting.
https://help.ubuntu.com/community/RecoveringUbuntuAfterInstallingWindows
Any problems, let me know! :)


Flutter - Unable to use dynamic links in flutter web

Question: I Am unable to use the firebase dynamic links plugin on flutter web.
When am trying to create a deep link it gives error:
Error: MissingPluginException(No implementation found for method DynamicLinkParameters#buildShortLink on channel plugins.flutter.io/firebase_dynamic_links)
    at Object.throw_ [as throw] (http://localhost:49242/dart_sdk.js:5344:11)
    at MethodChannel._invokeMethod (http://localhost:49242/packages/flutter/src/services/system_channels.dart.lib.js:962:21)
    at _invokeMethod.next (<anonymous>)
    at http://localhost:49242/dart_sdk.js:39201:33
    at _RootZone.runUnary (http://localhost:49242/dart_sdk.js:39058:58)
    at _FutureListener.thenAwait.handleValue (http://localhost:49242/dart_sdk.js:34044:29)
    at handleValueCallback (http://localhost:49242/dart_sdk.js:34604:49)
    at Function._propagateToListeners (http://localhost:49242/dart_sdk.js:34642:17)
    at _Future.new.[_completeWithValue] (http://localhost:49242/dart_sdk.js:34484:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:49242/dart_sdk.js:34507:35)
    at Object._microtaskLoop (http://localhost:49242/dart_sdk.js:39345:13)
    at _startMicrotaskLoop (http://localhost:49242/dart_sdk.js:39351:13)
    at http://localhost:49242/dart_sdk.js:34858:9

Also while at init state when trying to handle dynamic links it gives a similar type error.
How to solve this? I need to create a dynamic link at least in my flutter web project.
Comment: have you find any solution?? if yes plese answere to my question, https://stackoverflow.com/questions/70847741/flutter-dynamic-links-open-web-page-when-app-is-not-installed
Answer: you can build the dynamic links using a post request to Dynamiclinks API using this guide like this:
    Future<String>? buildDynamicLinks(
      {theID, theTitle, theDescription, companyName, theCategory}) async {
    var  urlToReturn;
    final String postUrl =
        'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=*****YourApiKey******';

    String theUrl =
        "https://sample.page.link/?isi=3223&ibi=app.sample.example&imv=1.0.1&link=https%3A%2F%2Fwww.yourWebsite.net%2F${theCategory ?? 'id'}%2F$theID&si=**imgUrl**&sd=$companyName  -  $theDescription&amv=1&st=$theTitle&apn=app.example.sample";

    await http.post(Uri.tryParse(postUrl)!, body: {
      'longDynamicLink': theUrl,
    }).then(
      (http.Response response) {
        final int statusCode = response.statusCode;

        if (statusCode < 200 || statusCode > 400 || response == null) {
          throw new Exception("Error while fetching data");
        }
        var decoded = json.decode(response.body);
        urlToReturn = decoded['shortLink'];
        return decoded['shortLink'];
      },
    ).catchError((e) => debugPrint('error $e'));
    return urlToReturn;
  }

Answer: The Error
Error: MissingPluginException(No implementation found for method DynamicLinkParameters#buildShortLink on channel plugins.flutter.io/firebase_dynamic_links)

This error is because there is actually no web implementation for the Firebase Dynamic Links plugin package. Consult this chart for details.
Solution: Exclude Web
When you are retrieving your initial link during app startup, you can exclude Flutter Web from attempting to do this using the kIsWeb variable.
Example:
// Firebase: Get any initial dynamic links (not compatible with web)
dynamic initialLink;
if (!kIsWeb) {
  initialLink = await FirebaseDynamicLinks.instance.getInitialLink();
}

// Do something with initialLink

The initialLink variable will be nullable, so you will have to incorporate null checks into your iOS / Android platform handling code.
How Firebase Dynamic Links Work on Web
When setting up your Dynamic Link in the Firebase Console, you input a "deep link url" which is the web browser location the link forwards to if the app is not installed. This should be the URL you want the dynamic link to forward to in the web version of your app.
If you are using Navigator 2 based routing with a package such as go_router (I'm including this one because it's maintained by the flutter dev team), you can declare which screen / widget should load for the given deep link url.
Answer: Currently the firebase_dynamic_links plugin is not supported for the web platform.
The displayed error message MissingPluginException(No implementation found for method DynamicLinkParameters...) indicates that.
All packages available in pub.dev have some tags that indicates the supported platforms.


Can't get two tabs to align as inline block elements in header

Question: I'm not sure why, but there are two little dashes next to two of my tabs and they're shifting everything right. It's not effecting the third tab.
Here is a JSFiddle and images
`http://jsfiddle.net/michaelhorstman/wL0ubv50/`

Comment: it's very hard to work with images. perhaps you could create a jsFiddle or similar that shows the problem?
Comment: I hope this is what you mean http://jsfiddle.net/michaelhorstman/wL0ubv50/
Answer: Bro, in list style, there's no end anchor tag. try to add in the each list end
Comment: like ''
Comment: Ah! That fixed it! Thank you!
Answer: looks like I was missing closing anchor tags on my list items in the header!
       `
 Hello

 This

 Test
`

Fixed it!


Question from Lance's book: showing a bounded operator $\leq 1$

Question: I wonder if someone could help me to understand the following sentence in the second last paragraph below: "Then $0\leq q\leq 1.$"
This extract is taken from the book of E. Christopher Lance on Hilbert modules.
The context is that $t$ is a densely defined regular operator between Hilbert modules $E$ and $F$. We know that the extension of the inverse $(1+t^*t)^{-1}$, which is referred to as $q$, is a positive element, which explains the first half of that sentence. But I'm not sure why $q\leq 1$, since $1+t^*t$ itself is not an element of $\mathcal{L}(E)$ so you can't just invert.
Many thanks for your help.
Answer: From the second sentence of the second paragraph, $(1+t^*t)^{-1}$ is norm-reducing (on its domain).  Hence its bounded extension is norm-reducing, and so is this extension's square root, which we call $q$.  In other words, $\|q\|\leq1$, which implies $q\leq1$.
Comment: Why does $||q||\leq 1$ imply $q\leq 1$ in the algebra? I only know that the converse holds.
Comment: $\|q\|\leq1$ means $|\lambda|\leq1$ for all $\lambda\in\sigma(q)$.  Since $q$ is positive, $\sigma(q)\subset[0,1]$, so $\sigma(1-q)\subset[0,1]$ and thus $1-q\geq0$.
Comment: Ah yes, spectral radius is bounded above by norm. Thanks!
Comment: You're welcome.  Glad to help!


Explanation of Insert Key in WPF

Question: I am trying to notify the user when some Keys are pressed. If Caps, Num, Scroll and Insert are pressed, the relative BarStaticItem (the application uses some devexpress controls) changes color to White.
void DxMainWindow_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.CapsLock)
    {

        if (e.KeyboardDevice.IsKeyToggled(Key.CapsLock))
        {
            bCaps.Tag = new SolidColorBrush(Colors.White);
        }
        else
        {
            bCaps.Tag = new SolidColorBrush(Colors.DarkGray);
        }
    }

    if (e.Key == Key.NumLock)
    {
        if (e.KeyboardDevice.IsKeyToggled(Key.NumLock))
        {
            bNum.Tag = new SolidColorBrush(Colors.White);
        }
        else
        {
            bNum.Tag = new SolidColorBrush(Colors.DarkGray);
        }
    }

    if (e.Key == Key.Scroll)
    {
        if (e.KeyboardDevice.IsKeyToggled(Key.Scroll))
        {
            bScrl.Tag = new SolidColorBrush(Colors.White);
        }
        else
        {
            bScrl.Tag = new SolidColorBrush(Colors.DarkGray);
        }
    }

    if (e.Key == Key.Insert)
    {
        if (e.KeyboardDevice.IsKeyToggled(Key.Insert))
        {
            bIns.Tag = new SolidColorBrush(Colors.White);
        }
        else
        {
            bIns.Tag = new SolidColorBrush(Colors.DarkGray);
        }
    }
}

Everything works fine but when i press Insert inside a TextBox it does not work. The weird thing is that in dispute of the other KeyEvents the event for Insert is like never happening (breakpoint does not break), even if the functionality works fine (overwrite text when pressed etc).
Can someone explain me why?
Thanks.
Answer: The Insert key is handled by the TextBox control, so that the event is not routed up the UI element tree.
You may however attach a handler for the PreviewKeyDown event instead of KeyDown:
<Window ... PreviewKeyDown="DxMainWindow_KeyDown">

Please refer to the Routed Events Overview article on MSDN for more details.

Explanation of Insert Key in WPF


Snap version of gimp not opening images in root folder

Question: I have gimp 2.10.30 on Ubuntu 22.04. Whenever I try to open an image outside my home folder it says Error opening directory '<directory>': permission denied.
When I right-click on the image and choose open with gimp, it says: Opening <image path> failed: Could not open <image path> for reading: No such file or directory. How can I solve this?
Comment: Does this answer your question? [How to give snaps access to /somedir](https://askubuntu.com/questions/1033344/how-to-give-snaps-access-to-somedir)
Comment: You can try Krita as an close alternative.
Comment: @Rishon_JR Thank you, but I prefer to keep with gimp. Any suggestions to fix this problem?
Comment: Try `sudo gimp` and open the file.
Comment: Or you can switch to the apt version of GIMP.
Comment: @Rishon_JR After switching to the apt version, it works. Can you please explain me why the snap version doesn't work? You can also write it as an answer.
Comment: It doesn't really help that much, and it's not a duplicate either @FedKad.
Answer: I wouldn't go for using the snap version of GIMP. why? Well for a few reasons...

Snap is just janky and still has many compatibility issues.
It takes extra space and often most of the storage taken is a duplicate of other apt packages(i.e not needed).
It is extremely buggy compared to apt(As far as I have used it)
Snap works on the concept of containers (Think of them as tiny VMs for each app)
Due to this, many issues are present like the one you are facing.

I would recommend switching to the apt version of GIMP.
Answer: This is by design.  Snap uses confinement to limit what applications can do.  The idea is roughly similar to the way mobile apps don't have full access to your phone but have to ask for certain permissions.  For example, snaps aren't allowed to read some system files for security/privacy reasons.
Snap uses interfaces to control what resources a snap is and isn't allowed to access, of which there is a long list.
One useful connection is removable-media which automatically allows access to USB storage etc.  For that you might do:
sudo snap connect gimp:removable-media

Or there is a GUI in Ubuntu's version of GNOME settings.
I'm not sure if there is a way to give access to an arbitrary directory though.  The How to give snaps access to /somedir question has an answer from one of the developers which suggests not, although that was from 2018.
Comment: Last I checked there was no way even to grant snaps access to `/tmp`, which would be a real pain for GIMP if you ever use it for editing screenshots. (`/tmp/` is where I tend to use pdftk, and trying to install pdftk via apt gives you the snap, so I've been caught out a couple of times)


Gradle cache directory location in Android Studio 2

Question: For every Android project I create, there is a .gradle folder in the root of the project. As I understand it, this only contains cache files used by Gradle, and can be recreated by Android Studio?
I'm wondering if there is a way to make Android Studio create these cache directories in another location, say /Temp/GradleCaches/<projectname>/.gradle?
I'm currently doing a course in Android programming, and those cache directories become quite huge when it's time to upload the projects. So instead of having to delete the directory I'd just like to have it created outside the project location.
Answer: In Android Studio 3 (Gradle 3+) and Windows, It's located in the directory:
WINDOWS_DRIVE:\Users\YOUR_USER.gradle\caches
Note: DO NOT DELETE THE WHOLE FOLDER. Just search for your specific library and delete that one.
If you have some libraries that you want to reload from their repo, then you should delete files here. The cache here is also used by lint to inform you about new versions of library, and reloading the library.
This was the problem I had:
I uploaded a new version (.aar file) to Artifactory(repo) by mistake but when I deleted it, gradle still was notifying me in my project about the new version.
Answer: Just start gradle with the option --project-cache-dir path/to/where/you/want/it
Comment: Ah OK, so I need to do it for each new project? Is there no global setting or environment variable to make all projects use the same location (with individual subfolders for each project)?
Comment: How exactly do I do that in Android Studio? Should I add this somewhere in a gradle file? If so, which one?
Comment: If you use gradle wrapper in your project (you should) and have Android Studio set up to use the wrapper (the default I think), you will want to edit the wrapper scripts `gradlew` and `gradlew.bat`.
Comment: At least not that I'm aware of.
Answer: I couldn't really get the solution proposed by Björn Kautler to work, and in any case it would mean that the projects I hand in to the examinator would point to a (most probably) invalid directory on their system.
Instead I simply created a symlink named .gradle in my project directory, which points to /Temp/GradleBuilds/cache/<project-name>/.gradle. That gets the cache directory out of the project path.
The next problem is still that when using OSx "Compress <folder-name>..." to zip a directory, it will include the symlink as-is, i.e. pointing to a (most probably) invalid directory on the recipients system. So in order to exclude the .gradle directory, I created an OSx service using Automator, which uses the command line utility zip to compress the folder, excluding the .gradle directory:

Activating it under System preferences -> Keyboard -> Shortcuts -> Services -> Files and folders makes it appear in the right click menu in Finder (possibly in the Services submenu if you have a lot of services).
So to wrap up, the .gradle cache directory is moved out of the project directory structure, and can easily be excluded when using the new service to compress the directory folder.


I have the feeling I get very low level Pokemons

Question: As a Yellow Team member, I've heard that we get stronger pokemons from hatching eggs, but I have the feeling that all the pokemons I find are really low for my trainer level (14 now).
I Get a bunch of <100 while some Blue Team friends have many >100 Pokemons.
Is there any kind of bug/issue? Has anyone experienced something similar? I mean, I've never seen/caught anything >340, and I have lower level friends who have caught stronger Pokemons :(
Comment: Mind explaining de DV pls?
Answer: Team Buffs
People have hypothesised the following team buffs:

Team Instinct (yellow) - Higher CP pokemon from eggs/better eggs (eg. 10km instead of 2km)
Team Mystic (blue) - Higher CP from evolution
Team Valor (red) - Higher CP from power up

These team buffs have not yet been proven.
It is just lore/story on a screen at the moment.
See: Source
Higher CP
Even if low CP pokemon did have something to do with team buffs it would still not matter seeing as there is no "team buff" for finding higher CP pokemon. As mentioned per story/lore per team.
Possilbe solution
I noticed if I stay around my house I get low level pokemon but after walking around for a bit (walk 2km towards another area) I find higher level CP pokemon and even different types.
Note: When I get back from my walk, most of the pidgeys, ratatas and weedles around my house have higher CP. This happens alot (of course excluding the occasional low level CP of 21 or so which is 1/10 encounters) and they are usually CP 150+
Also note that I am level 14 nearly level 15.
Comment: I thought you were saying that team bonuses *were* in fact a thing, so I pointed out in a comment that all of those answers are negatively scored, then I reread and found out that this was the opposite of what you actually meant and I think I just need more coffee this morning.
Comment: @Chris haha it is okay, I changed it, thanks for the tip for a better opening :)
Comment: Waitaminute, nevermind, I misread
Comment: @Unionhawk what?
Comment: @Unionhawk haha I did type this fairly quick and it might need some proof reading but indeed the team buffs are not yet proven.
Comment: @Unionhawk I hope the edit helped?
Comment: I had also heard about better pokemons the longer you've been walking. I have a bad phone that usually forces me to close the app, meaning I have 'short' walks, maybe that has sth to do aswell?
Comment: @MarioGarcia Maybe, I have been testing this out last few days (walking at least 5 to 10km a day now). I had to restart the app a few times (really shutting it down), coincidently I would find a new pokemon but at low CP, but that is not always the case, sometimes a high CP pidgey or something or a higher level oddish. All I noticed is that the further I walked the more chances I got at higher CP (this still needs to be proven with an actual source).
Comment: Is it my imagination or is your source for team buffs an answer that has a score of -2 currently?
Comment: @chris -2? No the source leads to a question(14+)  that was asked earlier about team buffs. No one has proof
Comment: The question asks about team differences. The highest rated answers mentions the flavour differences and say that in the future they may have different buffs. The rest of the answers have scores of zero or lower and the only one that explicitly says mystic get more CP when evolving is the answer with a -2 score. It just feels that if you are going to mention speculation that it shouldn't be what you open with. I should add that if the question had mentioned these buffs it might make more sense but it doesn't so it feels like you are introducing irrelevancies into the answer...
Comment: @Chris I don't really understand what you mean? OP stated "As a Yellow Team member, I've heard that we get stronger pokemons from hatching eggs", so I thought I would first tackle that idea of that exsisting not to expect pokemon from eggs to be higher CP. The source I linked is all about team buffs/advantages. Answers in the source talk about the points I have listed here. It was more to point out that no one has proof or source  code that these advantages are in the game. How could I formulate my answer better(what should I open with)? Could you edit it?
Comment: @Kiwi: I'm so sorry, I completely missed that quote in the thing! I feel really really silly now! I might suggest phrasing it more as "people have hypothesised the following team buffs" so before you read the buffs you know that they aren't confirmed or something but otherwise I'm going to slink off into embarrassment now. :)
Answer: I'm trainer level 13 and I was wondering the same thing. But from time to time I get some high CP Pokemon (like >500)
Just be patient and keep searching.


C#8.0: Protected properties for interfaces with default implementations

Question: Say I have the following interfaces:
public interface IReturnableAs {
  protected String ReturnAs { get; set; }
}
public interface IReturnableAsImage<T> {
  protected String ImageResolution { get; set; }
  public T ReturnAsImage(String imageResolution = "large") {
    ReturnAs = "image";
    ImageResolution = imageResolution;
    return (T)this;
  }
}
public interface IReturnableAsJson<T> {
  protected Boolean IsPretty { get; set; }
  public T ReturnAsJson(Boolean isPretty = false) {
    ReturnAs = "json";
    IsPretty = isPretty;
    return (T)this;
  }
}

public class Foo : IReturnableAsImage<Foo>, IReturnableAsJson<Foo> {...}

Initially, the errors force me to have implementations for the ReturnAs, ImageResolution and IsPretty properties. Making these implementations protected end up with CS0535, saying that the properties weren't implemented. On the other hand, making these public gave me CS8704, telling that this implementation is not possible.
Other than abstract classes, would there be workarounds for these errors?
Comment: Shouldn't it be `IReturnableAsImage : IReturnable { … }` ? Because there is no `ReturnAs` property in `IReturnableAsImage` which could be accessed in `ReturnAsImage`.
Comment: What do you expect `Foo.ReturnAs` to return? `json`, `image` or `json;image`?
Answer: First of all, what do you want to achieve? What should Foo.ReturnAs return? How are you going to use those interfaces?
You can't use ReturnAs in the other interfaces without inheriting from IReturnableAs. Once you inherit from that interface though Foo will have to provide an implementation. When that happens, no matter how you cast Foo you'll always get its own IReturnableAs implementation.
Interfaces aren't abstract classes so there can only be one interface member implementation. You can't access different "default" implementations through different interfaces.
Composite result when accessed through IReturnableAs
If you want to return json or image for the specific interfaces and image;json for Foo overall the best option would be for the interfaces to not inherit from IReturnableAs, and provide their own ReturnAs property :
public interface IReturnableAs {
  public String ReturnAs { get; }
}
public interface IReturnableAsImage<T>
{
  public String ReturnAs =>"image";

  protected String ImageResolution { get; set; }
  public T ReturnAsImage(String imageResolution = "large")
  {
    ImageResolution = imageResolution;
    return (T)this;
  }
}
public interface IReturnableAsJson<T> {
  public String ReturnAs =>"json";

  protected Boolean IsPretty { get; set; }
  public T ReturnAsJson(Boolean isPretty = false) {
    IsPretty = isPretty;
    return (T)this;
  }
}

public class Foo : IReturnableAsImage<Foo>, IReturnableAsJson<Foo> ,IReturnableAs
{
    string IReturnableAs.ReturnAs =>"image;json";

    String IReturnableAsImage<Foo>.ImageResolution { get; set; }="3";
    Boolean IReturnableAsJson<Foo>.IsPretty { get; set; }=false;
}

The following code :
void Main()
{
  var foo=new Foo();
  Console.WriteLine(((IReturnableAs)foo).ReturnAs);
  Console.WriteLine(((IReturnableAsImage<Foo>)foo).ReturnAs);
  Console.WriteLine(((IReturnableAsJson<Foo>)foo).ReturnAs);
}

Prints:
image;json
image
json

I removed the ReturnAs setters since the valid value will always be the same for the same interface.
If you want to create a new class that generates JPGs, eg FooJpg, you can override the default implementation of IReturnableAsImage<T>, eg :
public class FooJpg : IReturnableAsImage<FooJpg>, IReturnableAsJson<FooJpg> ,IReturnableAs
{
    string IReturnableAs.ReturnAs =>"jpg;json";

    String IReturnableAsImage<FooJpg>.ImageResolution { get; set; }="3";
    Boolean IReturnableAsJson<FooJpg>.IsPretty { get; set; }=false;

    String IReturnableAsImage<FooJpg>.ReturnAs => "jpg";

}

Same result no matter the interface
If you want Foo.ReturnAs to always return the same value, eg "image;json", you can add a default IReturnAs implementation for single use cases, and override the method for multiple uses :
public interface IReturnableAs {
  public String ReturnAs { get; }
}

public interface IReturnableAsImage<T>:IReturnableAs
{
  String IReturnableAs.ReturnAs =>"image";

  protected String ImageResolution { get; set; }
  public T ReturnAsImage(String imageResolution = "large")
  {
    ImageResolution = imageResolution;
    return (T)this;
  }
}

public interface IReturnableAsJson<T>:IReturnableAs {
  String IReturnableAs.ReturnAs =>"json";

  protected Boolean IsPretty { get; set; }
  public T ReturnAsJson(Boolean isPretty = false) {
    //ReturnAs="json";
    IsPretty = isPretty;
    return (T)this;
  }
}

In this case the IReturnableAsImage, IReturnableAsJson interfaces provide an implementation. For this class :
public class Foo : IReturnableAsImage<Foo>
{
    String IReturnableAsImage<Foo>.ImageResolution { get; set; }="3";
}

The following code will print image:
void Main()
{
  var foo=new Foo();
  Console.WriteLine(((IReturnableAs)foo).ReturnAs);
  Console.WriteLine(((IReturnableAsImage<Foo>)foo).ReturnAs);
}

For a class that uses both interfaces, an explicit IReturnableAs implementation is needed:
public class FooMulti : IReturnableAsImage<FooMulti>, IReturnableAsJson<FooMulti>
{
    String IReturnableAs.ReturnAs =>"image;json";

    String IReturnableAsImage<FooMulti>.ImageResolution { get; set; }="3";
    Boolean IReturnableAsJson<FooMulti>.IsPretty { get; set; }=false;
}

In this case all calls will return image;json :
void Main()
{
  var foo=new FooMulti();
  Console.WriteLine(((IReturnableAs)foo).ReturnAs);
  Console.WriteLine(((IReturnableAsImage<FooMulti>)foo).ReturnAs);
  Console.WriteLine(((IReturnableAsJson<FooMulti>)foo).ReturnAs);
}

image;json
image;json
image;json

Answer: There is a solution here, though I am not sure if I like it.
IReturnableAsImage<T> and IReturnableAsJson<T> can extend IReturnableAs and hide its ReturnAs method with a new ReturnAs method.
They can, and probably should, also explicitly override IReturnableAs's ReturnAs property to save a concreate implementation from having to do so; see the implementation of Bar below.
Since Foo implements both IReturnableAsImage<T> and IReturnableAsJson<T> though, it will have to provide an implementation for IReturnableAs.ReturnAs as well.
public interface IReturnableAs
{
    public String ReturnAs { get; }
}

public interface IReturnableAsImage<T> : IReturnableAs
{
    // implicitly "override" IReturnableAs's ReturnAs
    string IReturnableAs.ReturnAs => ReturnAs;

    // use "new" to indicate hiding on purpose
    public new string ReturnAs => "image";

    protected string ImageResolution { get; set; }

    public T ReturnAsImage(String imageResolution = "large")
    {
        ImageResolution = imageResolution;
        return (T)this;
    }
}

public interface IReturnableAsJson<T> : IReturnableAs
{
    // implicitly "override" IReturnableAs's ReturnAs
    string IReturnableAs.ReturnAs => ReturnAs;

    // use "new" to indicate hiding on purpose
    public new string ReturnAs => "json";

    protected bool IsPretty { get; set; }

    public T ReturnAsJson(Boolean isPretty = false)
    {
        isPretty = isPretty;
        return (T)this;
    }
}

Bar doesn't need to implement IReturnableAs.ReturnAs as IReturnableAsImage<Bar> already does this. Though it may to "overload" (reimplement may be a better term) ReturnAs implicitly or either IReturnableAs.ReturnAs or IReturnableAsImage<Bar>.ReturnAs explicitly, in any combination.
public class Bar : IReturnableAsImage<Bar>
{
 // public string ReturnAs => "implicit ReturnAs";
 // string IReturnableAs.ReturnAs => "explicit IReturnableAs.ReturnAs";
 // string IReturnableAsImage<Bar>.ReturnAs => "explicit IReturnableAsImage<Bar>.ReturnAs";

    string IReturnableAsImage<Bar>.ImageResolution { get; set; } = "3";
}

Foo on the other hand must explicitly reimplement IReturnableAs.ReturnAs implicitly or ReturnAs explicitly (or both) since both IReturnableAsImage and IReturnableAsJson provide implementations for this property.
public class Foo : IReturnableAsImage<Foo>, IReturnableAsJson<Foo>
{
 // public string ReturnAs => "implicit";
 // string IReturnableAsImage<Bar>.ReturnAs => "explicit image";
 // string IReturnableAsJson<Bar>.ReturnAs => "explicit json";

    string IReturnableAs.ReturnAs => "image;json";

    string IReturnableAsImage<Foo>.ImageResolution { get; set; } = "3";
    bool IReturnableAsJson<Foo>.IsPretty { get; set; } = false;
}

The results work as expected, though changing what the concrete methods reimplement will change the results, possibly unexpectedly.
void Main()
{
    var bar = new Bar();
    Console.WriteLine("Bar: ");
    Console.WriteLine(((IReturnableAs)bar).ReturnAs + " -  (IReturnableAs)" );
    Console.WriteLine(((IReturnableAsImage<Bar>)bar).ReturnAs + " -
 (IReturnableAsImage<Bar>)");

    // only works when ReturnAs is explicitly implemented on Bar
 // Console.WriteLine(bar.ReturnAs + " -  (Bar)");

    Console.WriteLine();

    var foo = new Foo();
    Console.WriteLine("Foo:");
    Console.WriteLine(((IReturnableAs)foo).ReturnAs + " -  (IReturnableAs)");
    Console.WriteLine(((IReturnableAsImage<Foo>)foo).ReturnAs + " -  (IReturnableAsImage<Foo>)");
    Console.WriteLine(((IReturnableAsJson<Foo>)foo).ReturnAs + " -  (IReturnableAsJson<Foo>)");

    // only works when ReturnAs is explicitly implemented on Foo
 // Console.WriteLine(foo.ReturnAs + " -  (Foo)");
     }

Output:
Bar:
image -  (IReturnableAs)
image -  (IReturnableAsImage<Bar>)

Foo:
image;json -  (IReturnableAs)
image -  (IReturnableAsImage<Foo>)
json -  (IReturnableAsJson<Foo>)

You may want to comment in the commented out lines of Foo and Bar above to see what gets overloaded and when.
For example, if Bar explicitly implements ReturnAs it overrides default implementations of both IReturnableAs and IReturnableAsImage<Bar> unless Bar implicitly implements them as well.


Script that runs fine on PowerShell returns error using System.Management.Automation.PowerShell

Question: I'm writing a C# program that uses PowerShell to renew certificates by LetsEncrypt, but I can't get passed the first line.
My code:
using (var ps = PowerShell.Create()) {
    ps.AddScript("Import-Module ACMESharp");
    ps.Invoke();

    output = ps.HadErrors
        ? ps.Streams.Error.ToString()
        : ps.Streams.Information.ToString();
    return !ps.HadErrors;
}

The result is that I'm getting an error:

The specified module 'ACMESharp' was not loaded because no valid module file was found in any module directory.

but when I run the same command in PowerShell, it works fine.
How can I fix this?
Answer: Your codes fails when running it without Administrator privileges and works when running it as Admin.
Set your C# app to run with Admin privileges:

If you are running in Visual Studio and debugging only, run the Visual Studio as "Administrator".
If you are planing to deploy the application, your need add this to your application manifest.
<requestedExecutionLevel level="requireAdministrator" uiAccess="true"/>

Edit:
Another reason for Import-Module to fail is that specified module ACMESharp does not exist in the PSModulePath variable. In this case, there is no way for PowerShell to find the module to import.
You could explicitly add another path by appending the path to the existing PSModulePath list of paths.
var extraModulesPath = "somepath";
var state = InitialSessionState.CreateDefault();
using (var rs = RunspaceFactory.CreateRunspace(state))
{
    rs.Open();
    using (var ps = PowerShell.Create())
    {
        ps.Runspace = rs;
        var psModulePath = rs.SessionStateProxy.GetVariable("env:PSModulePath");
        rs.SessionStateProxy.SetVariable("env:PSModulePath", $"{psModulePath};{extraModulesPath}");

        ps.AddScript("Import-Module('ACMESharp')");
        ps.Invoke();

        var output = ps.HadErrors
            ? ps.Streams.Error.ToString()
            : ps.Streams.Information.ToString();
    }
}

Comment: Thanks for the detailed reply - but I'm getting the exact same result.
Comment: What is your PS version? Run $PSVersionTable.PSVersion to get it.
Comment: Importing a module never requires administrative privileges, so I suggest removing the first part of the answer. Appending to `$env:PSModulePath` sounds like the right approach, though it's easier to include that in the code passed to `.AddScript()`. Please avoid pseudo method syntax such as `Import-Module('ACMESharp')`. @EylM: Interactively, after successfully importing the module, run `(Get-Module ACMESharp).Path` to determine the module's directory. Consider installing it in a directory that is present in `$env:PSModulePath` _by default_.
Comment: Sorry, meant to address you, @user884248, in my previous comment.


Simplify/Enhance Python Filtering Algorithm

Question: I'm looking for a way to identify the dist.xml files that are in the top most directory.
Example, I have this list of directory listing,
/opt/pictures/dist.xml
/opt/docs_old/dist.xml
/opt/public/dist.xml
/opt/documents/server/dist.xml
/opt/documents/dist.xml
/opt/documents/web/dist.xml
/opt/documents/class/dist.xml
/opt/documents/lessons/1/dist.xml
/opt/documents/lessons/2/dist.xml
/opt/documents/lessons/3/dist.xml
/opt/documents/lessons/4/dist.xml
/opt/documents/lessons/5/dist.xml
/opt/music/service/day/dist.xml
/opt/music/service/week/dist.xml
/opt/music/service/month/dist.xml
/opt/music/service/month/1/dist.xml
/opt/music/service/month/2/dist.xml

and I'm looking to have this output instead,
/opt/pictures/dist.xml
/opt/docs_old/dist.xml
/opt/public/dist.xml
/opt/documents/dist.xml
/opt/music/service/day/dist.xml
/opt/music/service/week/dist.xml
/opt/music/service/month/dist.xml

I have the following code that appears to do the job, wondering if there's anyway to speed up or make clear the code,
from pathlib import Path

paths = ['/opt/pictures/dist.xml', '/opt/docs_old/dist.xml', '/opt/public/dist.xml', '/opt/documents/server/dist.xml', '/opt/documents/dist.xml', '/opt/documents/web/dist.xml', '/opt/documents/class/dist.xml', '/opt/documents/lessons/1/dist.xml', '/opt/documents/lessons/2/dist.xml', '/opt/documents/lessons/3/dist.xml', '/opt/documents/lessons/4/dist.xml', '/opt/documents/lessons/5/dist.xml', '/opt/music/service/day/dist.xml', '/opt/music/service/week/dist.xml', '/opt/music/service/month/dist.xml', '/opt/music/service/month/1/dist.xml', '/opt/music/service/month/2/dist.xml']

paths = list(set(paths))
paths_folder = [str(Path(p).parent) for p in paths]

to_remove = []
for idx, val in enumerate(paths_folder):
  for b in Path(val).parents:
    if str(b) in paths_folder:
      to_remove.append(idx)

paths_folder = [i for j, i in enumerate(paths_folder) if j not in to_remove]

paths_folder = [p + '/dist.xml' for p in paths_folder]

print(paths_folder)

Comment: The *wanted output* is not a different sorting of the actual output. What do you mean by your title?
Comment: Also, would you explain in words what is the rationale for getting that output from the input?
Answer: Here's an approach that may be cleaner since it avoids index-tracking, etc.:
First sort all the path_folders so that it's top-most folders first. Then check for each parent folders' presence in the "top folders" list, as you did but using the all() built-in, which is true only after the condition is true for all items. Then immediately add it to the final folder list, since anything following that item is either a different folder or a child of the current one; because of the sort done before.
from pathlib import Path

paths = ['/opt/pictures/dist.xml', '/opt/docs_old/dist.xml', ...]  # as above
path_folders = sorted(set(Path(p).parent for p in paths),
                      key=lambda x: (len(x.parts), x))    # is now sorted tops-first

top_folders = []
for folder in path_folders:
    if all(parent not in top_folders for parent in folder.parents):
        top_folders.append(folder)

top_dists = [f / 'dist.xml' for f in top_folders]  # can use '/' with Path objs!
print(top_dists)