how to convert string to file path(sdcard path)? android

Question: i parsed my xml file successfully using sax parser.my doubt is how to convert string to file path. i have 3 spinner the 1st spinner show my parent node string value and 2nd spinner show child node name tag value and 3rd spinner show path tag value. this is my xml file link pls see this link = http://paste.org/42924
I hope you are clear now I am trying to convert my path tag string value to sdcard file path. I stored my path tag string value in path_List array list. Now I got all path string value in this array list.  how to convert this sting value to file path? I wish to show images in same screen bottom in grid view format that's all. now I stored the path tag string value in my array list the array list name is path_List. how to convert convert my file path?
this is my source code:
public class ParxmlActivity extends Activity {

    private String array_spinner[];
    private Cursor cursor;
    private int columnIndex;

    ParsedExampleDataSet parsedExampleDataSet= null;

    ArrayList<String> hltag_List=new ArrayList<String>();

ArrayList<Subchild> sltag_List=new ArrayList<Subchild>();

    ArrayList<String> name_List = new ArrayList<String>();

    ArrayList<String> path_List =new ArrayList<String>();

    Spinner spinner_hltag,spinner_sltag, spinner_path;

    ArrayAdapter<String> adapter_hltag;
    ArrayAdapter<String> adapter_sltag;
    ArrayAdapter<String> adapter_path;
    int hltagPos = 0;
    int sltagPos = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        GridView sdcardImages = (GridView) findViewById(R.id.sdcard);

            spinner_hltag= (Spinner) findViewById(R.id.spinner1);
        spinner_sltag = (Spinner) findViewById(R.id.spinner2);
        spinner_path =(Spinner) findViewById(R.id.spinner3);

        try {
            /* Get a SAXParser from the SAXPArserFactory. */
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

            /* Get the XMLReader of the SAXParser we created. */
            XMLReader xr = sp.getXMLReader();

            /* Create a new ContentHandler and apply it to the XML-Reader */
            ExampleHandler myExampleHandler = new ExampleHandler();
            xr.setContentHandler(myExampleHandler);

            /* Parse the xml-data from our file. */
            xr.parse(new InputSource(getAssets().open("neevee.xml")));
            /* Parsing has finished. */

            parsedExampleDataSet =myExampleHandler. myParsedExampleDataSet;

            for (int i = 0; i < parsedExampleDataSet.gethltag().size(); i++) {
                Log.v("gethltag SIZE ", ""+parsedExampleDataSet.gethltag().size());
                hltag_List.add(parsedExampleDataSet.getHLTag().get(i));
            }

            sltag_List = parsedExampleDataSet.getSLTag(hltag_List.get(hltagPos));

            for(int i = 0; i < sltag_List.size(); i++) {
                name_List.add(sltag_List.get(i).name);
                path_List.add(sltag_List.get(i).path);
            }

            adapter_hltag = new ArrayAdapter<String>(ParxmlActivity.this,android.R.layout.simple_spinner_item, hltag_List);
            spinner_hltag.setAdapter(adapter_hltag);

            adapter_sltag = new ArrayAdapter<String>(ParxmlActivity.this,android.R.layout.simple_spinner_item, name_List);
            spinner_sltag.setAdapter(adapter_sltag);

            adapter_path = new ArrayAdapter<String>(ParxmlActivity.this,android.R.layout.simple_spinner_item, path_List);
            spinner_path.setAdapter(adapter_path);

        } catch (Exception e) {

        }
    }
}

Comment: you are just parsing string array list only. so it will display just string. if you want you need to create custom array adapter which has an image view to display your image.
Comment: @PadmaKumar I wish to show images in gridview in same screen instead of my third spinner. the third spinner show only path tag string value now, how to convert that string value and shown images in grid view.
Answer:  GridView sdcardImages = (GridView) findViewById(R.id.sdcard);
 sdcardImages.setAdapter(new ImageAdapter(this));

//Create a new class called ImageAdapter that extends BaseAdapter:
public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return path_List.length;
    }

    public Object getItem(int position) {
            return null;
    }

    public long getItemId(int position) {
        return 0;
    }

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }
for (int i=0;i<path_List.size();i++){
Bitmap bitmap = BitmapFactory.decodeFile(path_List);

        imageView.setImageBitmap(bitmap);
        return imageView;
}

    }

Comment: error 1: path_List.length cannot be resolved or is not a field  error 2: The method decodeFile(String) in the type BitmapFactory is not applicable for the arguments
 (ArrayList)
Comment: try this Bitmap bitmap = BitmapFactory.decodeFile(path_List.get[i]);
Comment: path_List.get cannot be resolved or is not a field error padma sir
Comment: this one really helps you I geuss. if not sent your project to me I will check it.


Need to recreate the given chart. How can I overlap the trend line and also highlight GoDigit?

Question: What I've generated so far.....
[
VERSUS
What needs to be recreated
[
my code so far:
Recreated_figure_DHRP %>%
  ggplot(aes(x = Insurers, y =`INR BN`,fill = FY,group=FY)) +
  geom_bar(stat = "identity", position = position_dodge(), alpha = 0.75,)+
  theme(axis.text.x = element_text(angle = 60, hjust = 1)) +
  theme(legend.position="top") +
  ylim(0,400)+
  geom_text(aes(label = `INR BN`), fontface = "bold", vjust = 1.5,
            position = position_dodge(.9), size = 2.25)

Comment: It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions.
Comment: You can't attach files to Stack Overflow posts. The link I provided shows many ways to include data in your question. The most useful is generally a `dput()`. If the dataset is large, usually a subset is sufficient just make sure it reproduces the issue you are having.
Comment: Use `+ geom_line(aes(x=..., y=....), data=df)` where `df` holds the values for the line.
Comment: how about I just attach the file itself....the data frame isn't huge either
Comment: here's a link to the spreadhseet.     https://docs.google.com/spreadsheets/d/1keKE-_rYkFG_GrR5cxezlTcKxdUbKOdSRx6IUhiI4cw/edit?usp=sharing.         Thank you for taking the trouble!
Answer: Additional data can be added with suitable geom_XYZ functions, overwriting the aes values that change from the ggplot call. So for this case adding the line is as follows:
Recreated_figure_DHRP <- read.csv("C:\Users\te01\Downloads\Dataframe - sheet1.csv")
Recreated_figure_DHRP %>%
  ggplot(aes(x = Insurers, y =`INR.BN`,fill = FY,group=FY)) +
  geom_bar(stat = "identity", position = position_dodge(), alpha = 0.75,)+
  theme(axis.text.x = element_text(angle = 60, hjust = 1)) +
  theme(legend.position="top") +
  ylim(0,400)+
  geom_text(aes(label = `INR.BN`), fontface = "bold", vjust = 1.5,
            position = position_dodge(.9), size = 2.25) +
  geom_line(aes(y=`YOY.Growth`), col="red")

(note very slight differences in the dataframe column names)
That gives:
Answer: You can use geom_rect function to highlight the specific regions of the plot.
  Recreated_figure_DHRP %>%
    ggplot(aes(x = Insurers, y =`INR.BN`,fill = FY,group=FY)) +
    geom_bar(stat = "identity", position = position_dodge(), alpha = 0.75)+
    geom_rect(data = Recreated_figure_DHRP %>% filter(Insurers == "GoDigit"),
              aes(xmin = Insurers,
                  xmax = Insurers,
                  ymin = 0,
                  ymax = max(`INR.BN`)),
              color = "red",
              fill = NA,
              linetype = 2,#dashed line
              alpha = 0.5,
              show. Legend = FALSE)
     geom_text(aes(label = `INR.BN`),
        fontface = "bold",
        vjust = 1.5,
        position = position_dodge(.9),
        size = 2.25) +
     geom_line(aes(y=`YOY.Growth`), col="red")+
     ylim(0,400)+
     theme(axis.text.x = element_text(angle = 60, hjust = 1),
           legend. Position="top")


CRMWebAPI - How to work with Entity reference?

Question: I use CRMWebAPI for CRUD operations with CRM. How can I work there with a entity reference?
For example when I want to update parent account attribute on the Account entity, where the parent account attribute is Lookup to another account.
Something like this:
dynamic updateObject = new ExpandoObject();
updateObject.parentaccountid = the_entity_reference;
dynamic updateResult = await api.Update("accounts", new Guid("1111111-2222-3333-4444-55555555"), updateObject, false);

Answer: Referred this code sample and able to compose this. Please test it.
dynamic updateObject = new ExpandoObject();

Guid accountID = new Guid("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx");
var parAcctIndexer = updateObject as IDictionary<string, Object>;
parAcctIndexer["firstname.lastname@example.com"] = "/accounts(" + accountID.ToString() + ")";

dynamic updateResult = await api.Update("accounts", new Guid("1111111-2222-3333-4444-55555555"), updateObject, false);


How to know what type of fish are those?

Question: I've got several bait types, however I have no idea when to use which one since I can't see what types of fishes are there. I guess I can try some and see what works, but then what's the purpose of having the:
"this bait is effective with "insert_type_fish_here" thingy?
Thanks.
Answer: There is a degree of trial and error I've found.
Most of the lures will tell you what type of fish they work best with. So you can couple this with the map to get an idea of what you should be using.
So if you're in Cleign and you have a lure for Cleign Bass for example, safe bet that's a good place to start. Plus if you're fishing in the ocean, try lures which attract 'Sea Bass' and similar.
Also, it's worth scouting the local area, quite often there is fishing tackle laying around, you can pick up, which also helps give you a clue as to which lure to try first.
However it's worth noting that you can catch fish with the 'incorrect' lure, it's just harder to get a bite.
"Perhaps you should respool your line Noct?"
Or check this guide for some extra information. I've quoted the relevant section below.

Lures : There's lots of lures in the game. You'll need to swap out which lure you use based on what fish you're hoping to hook and where. Popper lures let you seek fish near the surface, pencil lures let you fish more effectively at dawn or dusk, swisher lures make boring fishing spots more lively, crankbait lures help you in rocky or littered waters, minnow lures work in clear waters, and vibration lures are best for wide areas.
Lure Weight : The heavier the lure, the deeper underwater it goes, and the bigger the fish it catches.
Lure Color : Fish like colors close to their own. Get a red lure for a red fish.
There are many lure possibilities, but pick the one best for the environment you're hoping to catch the fish.
Lines: With only three types of line, you'll mostly be purchasing these from shops. The higher the durability, the longer it can hold out against tension (aka damage) inflicted by fish.
Rods: Rods provide defense, which determines how much tension damage on your line they cancel out. You can get better rods from shops and by completing sidequests for Nayth.
Reels: Reels determine how fast you knock out a fish's stamina bar as you reel it in - basically your fish attack stat. Tackle shops have high-quality reels, but the very best reel is called Llymlaen and is a reward in the Totomostro mini-game.


Proving a statement in quadratic variation that ${\langle X \rangle}^{\tau} = \langle X^{\tau} \rangle$

Question: Let $\tau$ be a stopping time and $X$ be a continuous local martingale. Let $\langle \cdot \rangle$ denote the quadratic variation. We want to show that  $${\langle X \rangle}^{\tau} =  \langle X^{\tau} \rangle.$$
Does anyone know how to justify this statement, as it is not obvious at all from the definition of quadratic variation?
Answer: Suppose that $(X_t)_{t \geq 0}$ is a continuous martingale. We know that the compensator $(\langle X \rangle_t)_{t \geq 0}$ is the unique increasing predictable process such that
$$X_t^2 - \langle X \rangle_t$$
is a martingale. It follows from the optional stopping theorem that
$$X_{t \wedge \tau}^2 - \langle X \rangle_{t \wedge \tau} = (X^{\tau}_t)^2 - \langle X \rangle^{\tau}_t$$
is a martingale. As the compensator is unique, we conclude
$$\langle X \rangle^{\tau}_t = \langle X^{\tau} \rangle_t$$
for all $t \geq 0$.
Comment: @erik What do you mean by "where does there square [...] go"? The square is still there, isn't it? Obviously, $X_{t \wedge \tau}^2 = (X_t^{\tau})^2$. Concerning uniqueness: If $(Y_t)_{t \geq 0}$ is a cts. martingale, then $A_t$ (increasing, predictable) equals $\langle Y \rangle_t$ if and only if $$Y_t^2 - A_t$$ is a martingale. Apply this for $Y_t := X_{t}^{\tau}$, $A_t := \langle X \rangle_t^{\tau}$.
Comment: But $X$ is assumed to be a continuous local martingale, which is more general than a martingale. In fact, the theorem on my book says that $X^2 - \langle X \rangle $ is a martingale if X is a continuous martingale such that $\sup_{t \geq 0} \mathbb{E} [X^2_t] < +\infty$.
Comment: @erik Yeah, so take a localizing sequence of stopping times and apply this to the stopped process.
Comment: Sorry, I don't understand where does the square in the term $(X^{\tau}_t)^2$ go? Also, I don't understand how the uniqueness of the compensator was used.
Comment: Thanks for quoting this result. I haven't learnt this theorem before. Anyway, I meant that the square disappeared in the third line in my comment above.


Show that the function is differentiable

Question: I have to prove that the following function is differentiable and to find its derivatives at any point.
$$f: \mathbb{R}^2 \rightarrow \mathbb{R}, (x,y) \mapsto x^2+y^2$$
In my book there is a theorem and one part of it is the following:

Rule of summation:
Let $f:U \subset \mathbb{R}^n \rightarrow \mathbb{R}^m$ and
  $g:U \subset \mathbb{R}^n \rightarrow \mathbb{R}^m$ be differentiable at
  $x_0$. Then $h(x)=f(x)+g(x)$ is differentiable at $x_0$ and
  $Dh(x_0)=Df(x_0)+Dg(x_0)$.

($Df(x_0)$ is the matrix of the partial derivatives of $f$ at $x_0$)
Could we use this to show that the function $f: \mathbb{R}^2 \rightarrow \mathbb{R}, (x,y) \mapsto x^2+y^2$ is differentiable?
Comment: I'm not sure that's necessarily what they want you to do. You can write down the matrix (vector, in this case) of partial derivatives, and then all you need to do is check that if you subtract off the linear approximation then you get something which decays faster than linearly. Here the linear approximation at $(x_0,y_0)$ is $g(x,y)=x_0^2+y_0^2+2x_0(x-x_0)+2y_0(y-y_0)$, so now subtract that from $x^2+y^2$ and try to bound it.
Comment: Seems reasonable, letting $h(x, y) = f(x)+g(y)$.
Comment: Hint (in the case you have already seen the composition of differentiable functions is also differentiable) Let $g:\mathbb R\longrightarrow \mathbb R$ be given by $g(x):=x^2$. Notice $f(x, y):=g\circ p_1(x, y)+ g\circ p_2(x, y)$ where $p_j:\mathbb R^2\longrightarrow \mathbb R$ is given by $p_j(x_1, x_2):=x_j$. Hence, it suffices showing $g$ and $p_j$ are differentiable (showing $g$ is differentiable in a point is the same as showing it has a derivative in this point)...
Comment: How could we show that $g$ and $p_j$ are differentiable ?? @PtF
Comment: Well, for $g$ it is easy because $g^\prime$ exists in every $x\in \mathbb R$ hence it is differentiable everywhere. For $p_j$ you might simply compute the partial derivatives and show they are continuous what is easy to be done (again, this is only helpful if you have already seen that if a function have continuous partial derivatives in a point then it is differentiable in that point)..However, I'm trying to avoid to do a lot computations, however it's more likely you must do using @Ian 's idea.
Comment: Although it is probably not the intent of this exercise, a powerful tool for this in practice is the fact that if the partial derivatives are all continuous functions, then the function is actually differentiable (as a multivariate function).
Answer: you have $f(x,y) = x^2 + y^2.$  if you look at
$$\begin{align}f(x+h, y+k) &= (x+h)^2 + (y+k)^2 \\
&= x^2 + y^2 + 2xh + 2ky + h^2 + k^2 \\
&= f(x,y) + 2xh + 2yk + h^2 + k^2 \end{align}\tag 1$$
taking $$h = \epsilon \cos t, k = \epsilon \sin t$$ in $(1)$ we have, after some rearrangement, $$\frac{f(x + \epsilon \cos t, y+\epsilon \sin t )-f(x,y)}{\epsilon} = 2x\cos t + 2y\sin t+\epsilon \rightarrow 2x\cos t + 2y\sin t \tag 2$$ as $\epsilon \rightarrow 0.$  therefore $$ \text{ the derivative of } x^2 + y^2 \text{ is } (2x, 2y)^\top.$$


How to read .txt file with x and y values and convert it into an array?

Question: I need to convert a .txt file into arrays and will then plot it in a graph.
My problem is this:
I have a text file containing x,y values:
23, 92
26, 16
45, 14
32, 11
43, 17
46, 58

image here for x and y values
and so on.....(so many values)
and i want to convert it into arrays:
double [] x= { 23, 26, 45, 32, 43, 46,...}
double [] y= { 92, 16, 14, 11, 17, 58,...}

This arrays will be set in a graph, but i need to set this first into arrays for me to plot it.
I still don't have a code for this yet. Please help :(
Comment: This seems like an assignment question, asking such questions directly is discouraged. A better way would be to split your problems into smaller problems e.g. 1) how to read a txt file in a particular programming language e.g. ruby 2) how to use arrays in ruby, and then you should try to connect these dots to complete your assignment. Also these questions are trivial and you need to search existing question base before posting them as new questions.
Answer: public class ReadFile{
    public static void main(String[] args){
        BufferedReader br  = new BufferedReader(new BufferedReader(new FileReader("pathToFile")));
        String line = "";
        // reading when each line has x, y
        while((line = br.readLine())!=null){
             String[] t = line.split(",");
             double x = Double.parseDouble(t[0].trim());
             double y = Double.parseDouble(t[1].trim());
             // store it in the array/list
             // or create a Class Pair having x & y coordinate
        }
    }
}

with Pair class it will look like this
class Pair{
   double x , y;
   Pair(double x , double y){
     this.x = x;
     this.y = y;
   }
}

// the reading logic
    public class ReadFile{
        public static void main(String[] args){
            List<Pair> pointList = new ArrayList<Pair>();
            BufferedReader br  = new BufferedReader(new BufferedReader(new FileReader("pathToFile")));
            String line = "";
            while((line = br.readLine())!=null){
                 String[] t = line.split(",");
                 double x = Double.parseDouble(t[0].trim());
                 double y = Double.parseDouble(t[1].trim());
                 // store it in the array/list
                 // or create a Class Pair having x & y coordinate
                 Pair p = new Pair(x,y);
                 pointList.add(p);
            }
        }
    }

Comment: Sure, which is why I mentioned the second option
Comment: No reason to create a class for pairs `java.awt.Point` or `java.awt.geom.Point2D.Double` should be fine
Comment: In the question he is converting them into a double array, to use `java.awt.Point` he'll need integer values
Comment: Thank you! Now, my only problem is to graph this arrays. I'm still looking for ways how to graph it. Again, thank you very much!
Comment: take a look at this link http://stackoverflow.com/questions/1277126/plot-graphs-in-java
Comment: Thanks, but we're not allowed to use jfreechart... :(
Answer: Since you do not know upfront how many vertices you have, consider using two List collections in place of two arrays.
This would let you follow the algorithm below:

Prepare two lists, listx and listy
In a loop, read two integers, x and y
If two integers are not available, exit the loop
Otherwise, add x to listx and y to listy

Once the loop is over, you have your points in two parallel collections.


Where does the 64-cube door lead?

Question: I just want to make sure that it isn't some kind of game ending thing inside that will make me lose my map and progress.
Comment: Just wanted to link to the question that answers actually this: http://gaming.stackexchange.com/questions/63197/3-heart-cube-pieces-what-next
Answer: It's a single room with an empty, rotating heart atop a waterfall. You won't lose any progress and you can leave it whenever you want.

What do you do with it?

 You can collect three heart pieces to fill it. (image)
Comment: There's nothing to do. The heart pieces were Easter eggs.
Comment: But we still don't know what to do after having the three heart pieces...

Where does the 64-cube door lead?


How to implement ngxsOnChanges in a component

Question: I have two properties in state model, and I need an event on each one of them separately, but when both change at the same time I receive two events and I need only one something like ngxsOnChanges
Comment: You might find these helpful: https://stackoverflow.com/q/44004144/2436787 and https://stackoverflow.com/q/66421744/2436787
Answer: You can use a selector to combine both of them and then you will be able to subscribe to this selector and use a debounce.
Answer: You can join multiple selectors using the @Selector decorator, but take care of the injectContainerState selector option, which is disabled by default in NGXS v4 (It's better to set it to false if you're using NGXS v3.x)
Then, you can subscribe to the new selector in your component.
 @Selector([ZooState, PreferencesState])
 static firstLocalPanda(state: string[], preferencesState: PreferencesStateModel) {
   return state.find(
     s => s.indexOf('panda') > -1 && s.indexOf(preferencesState.location)
   );
 }

 @Selector([ZooState.firstLocalPanda])
 static happyLocalPanda(panda: string) {
   return 'happy ' + panda;
 }

To learn more about joining selectors:
https://www.ngxs.io/concepts/select#joining-selectors


MVC 5 IsInRole Usage on Razor Views: Cannot connect to Database

Question: I'm having issues using the new identity system in MVC 5, my goal is to make use of the User.IsinRole("RoleName") on Views. For example:
@if(User.IsInRole("Administrator"))
 {

@Html.ActionLink("Admin", "Index", "Admin")

 }

This is placed in the main layout page which is hit when the application launches. On doing this, i'm getting the following error:
"An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code
Additional information: Unable to connect to SQL Server database."
I have searched high and low for a solution to this, the common solution is to either include "[InitializeSimpleMembership]" at the top of the controller or initialise the database connection manually in application start. (With WebSecurity.InitializeDatabaseConnection). Both of these methods do not seem to be recognised by MVC 5.
I have also tried working around this by creating a bunch of messy code any time i return a view to populate the ViewBag with an IsAdmin boolean by using the Aspnet.Identity.UserManager to determine roles. Whilst this works it's not the way i feel i should be doing things.
It might be worth noting but i don't experience these issues accessing User.IsInRole on the backend, this definitely seems to be an initialization problem.
Comment: "Unable to connect to SQL Server database" is the issue with ConnectionString. Make sure you have correct connection string and you are able to connect to Db using it.
Comment: User.IsInRole works absolutely fine on the controllers, this is only occurring on the views. For me, that rules out connection string.
Comment: I am not able to reproduce your problem. I create an MVC app from the VS2013 templates, select Individual Accrounts and add the code you provided to my _Layout.cs file. Works fine. There is no need for any special initialization. Are you sure that it is the User.IsInRole call that cause the exception? Have you checked the stacktrace to find what exactly where it throws that exception?
Comment: Olav, i've had a look at the stack trace and it looks like it's trying to create a local DB : "at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString)"

My difference from you at this point is i've hooked my MVC up to the local SQL2013 DB. Is this where the problem lies?
Comment: Sorry that should read SQL2012 of course, typo!
Comment: I have the same problem - very stupid, I am not using EF or anything- I just want IsInRole to behave normally, not try and create/use a database to determine it, I have already wired up the users context/roles, etc - very stupid problem to have
Comment: Have you managed to get anywhere with this yet, schmoopy?
Answer: I was having the same problem, however Stunt's answer wasn't working for me. Tried the answer to this question and that solved the issue.
For the lazy you can try adding this to your web.config file:
 <system.webServer>
    <modules>
      <remove name="RoleManager" />
    </modules>
  </system.webServer>

Comment: I had to actually remove this from my config for things to work!
Comment: My poor dog thanks you. He cannot understand why i was yelling at the computer so much. Can you explain why this works when `` node is removed? Some kind of 'clever' dependency injection?
Comment: This solved my issue. Nothing was working for me. This should be marked as the answer.
Comment: This worked for me as well, not sure why though, I've made previous MVC project with various versions, and never used that XML snippet before. Thanks nonetheless
Comment: I got the same problem when I opened my old project in Visual Studio 2015 Community. This mythically solved the problem. Thanks.
Comment: Was updating a website from Asp.Net MVC 4 to Asp.Net MVC 5. Had this issue. Updating the web.config file worked for me.
Comment: Make sure to add the `remove` node under `modules` and not `httpModules`
Comment: Thank you! This also solved the problem for me that suddenly appeared today after working perfectly for the last 12 months. I have also used the same code for about the last 10 years, never with a problem. Any ideas why this is? Coincidence may be that i added a reference to system.web.helper in a separate project in the solution.
Answer: I managed to get around the problem by removing the following line from my Web Config:
<roleManager enabled="true" />

This was found when looking after comparing line for line on the following example code:
https://github.com/rustd/AspnetIdentitySample/tree/master/AspnetIdentitySample
Comment: Why does this work? I had the same issue as you and I only originally put this line in my web.config because the MSDN tutorial told me to.
Answer: Create database on start up of the application. Add the following in the Global.ascx with your dbcontext.
using (FooContext db = new FooContext())
        {
            db.Database.CreateIfNotExists();
        }


Python 'None' value appearing as -2147483648

Question: I'm reading in a data file from a Paradox database file (.DB) using a module pypxlib.
Whilst reading each row, I write to a CSV.
For some reason, values which expected to be 'None' are appearing as the number -2147483648.
Does anyone know the significance of this number? Why would this error be appearing?
Code below:
<code>for idx in range(0,len(matches)): #for each file found
  print "processing %s" % matches[idx]['file']
  #outputfile = path.join('./output/' + form_file_name(dbfile) + '.csv')
  try:
    myTable = Table(matches[idx]['file']) #class from pypxlib that takes a filepath
    cols = []                             #and creates a 'table' that can be read
    for col in myTable.fields: #gets fields from the table
        cols.append(col)
    pTable = []

    with open(output_folder +"/myoutput_" + matches[idx]['f'] + ".csv", "wb") as f:
        writer = csv.writer(f)
        writer.writerow(cols)
        rowcount = 0
        for row in myTable: # for every row in table
            myRow = []
            for fld in cols: # for every cell in the row
                myRow.append(row[fld]) #append cell to the row
            writer.writerow(myRow) #then write the row to the csv
            rowcount = rowcount + 1
            if rowcount >= 100:
                break #just testing on the first 1000 records
</code>
Comment: As to the significance of that number: -2147483648 is the smallest value a signed int32 can have (-2.147.483.648 to 2.147.483.647) As to why it's returning that instead of None: No idea, I don't know anything about `pypxlib` but I'd check their documentation to see if you can find something.
Comment: did you check the type of the columns you recieve this value on?
Answer: Paradox tables contain several numeric types including 'Number' (64-bit floating point), 'Long Integer' (32-bit signed integer), and 'Short' (16-bit signed integer). Each of these types has an in-band value designated to represent 'blank' as distinguished from zero. These are the values that you are expecting to be 'None'.
When the pxlib library and pypxlib wrapper convert Paradox data to Python data types, the in-band value for 'blank' translates to a 1 followed by all 0's. In two's-complement notation this is the value that is furthest from zero in both the positive and negative direction.
If the BDE type was 'Long Integer' then this is indeed represented as -2147483648.


How can I deactivate certain mouse buttons?

Question: I accidentally click on these buttons on the side of my mouse. How can I deactivate these 2 buttons using Ubuntu MATE?
Answer: I don't have a mouse like that, but I know it's different from windows, try this link. Hope it can help you.


Can I use conda and pip3 interchangeably to install Python packages?

Question: I don't understand why some Python packages are installed using conda and some by using pip3.
Are these just different installers from different developers but doing the same thing?
Can I use them interchangeably to install Python packages?
For example:
conda create -n mtl python=3.6 anaconda
conda activate mtl
conda install pytorch torchvision cudatoolkit=10.1 -c pytorch
pip3 install opencv-python

Answer: It really depends upon your familiarity with pip and conda and how package installation interacts between the two methods. If you are a relative new user of conda and python, I would recommend using only conda to install your packages. YMMV depending upon your experience with both.
See the following two documents that explain the relationship between conda and pip in more detail:
Using pip in a conda environment & Understanding Conda and Pip
From the first article:

Running conda after pip has the potential to overwrite and potentially break packages installed via pip. Similarly, pip may upgrade or remove a package which a conda-installed package requires. In some cases these breakages are cosmetic, where a few files are present that should have been removed, but in other cases the environment may evolve into an unusable state.
There are a few steps which can be used to avoid broken environments when using conda and pip together. One surefire method is to only use conda packages.

conda install <package_name> will be constrained to your use within conda environment. If you delete your conda installation, those packages will be removed as well.
Generally, conda will modify your $PATH so that this isolates the package installation from your system somewhat.
When you use pip3 install <package_name>, you are potentially affecting your system Python installation. Especially if you use sudo or sudo -H to install the Python package.
I am not certain if it is a best practice; but, when I am using pip3, I generally use the command syntax of pip3 install --user <package_name> which will "Install to the Python user install directory for your platform. Typically in the ~/.local/ directory."
Again, I try to take some precaution to isolate my package changes from the system's Python installation.
I consider it a matter of personal preference as to which method conda vs. pip3 is "best".
Comment: @Kong conda would be the preferred method unless you really know what you are doing, or can't get the package from using the conda install method. See my updates.
Comment: Thank you. But if I am already in the mtl environment, then wouldnt the pip3 command install it in said environment?
Comment: Thank you. Your answer and those links are extremely helpful.


How to convert RTC value from  to datetime in C#?

Question:
In a cortex device with battery powered clock build in (tick seconds), it generate I believe to be UTC value and use  library. That data is sent to window in C#.
The picture shown UTC data in string and trying to adapt it to datatime for conversion to date and time to be displayed.
It generate error and not sure what went wrong, Note the value.
Comment: What date does `4294967259` represent?
Comment: @leppie [Hope you didn't memorize it?](https://2982-presscdn-29-70-pagely.netdna-ssl.com/wp-content/uploads/2015/04/Shut-up-and-take-my-money.jpg) o.O
Comment: @SonerGönül: Actually not quite, but close! `0xFFFFFFDB`
Comment: What do you mean by _tick seconds_ exactly? Is this value `Ticks` or `Seconds`?
Comment: This is very similar to [this](http://stackoverflow.com/a/11793192/2458971) . See if that solves the problem.
Comment: @MarkusJarderot: `uint.MaxValue` ;p (but probably just -1 signed, probably indicating error)
Comment: (1) 1455265268 which is unix UTC. 32 bits. (2) tick second, mean the clock is ticking every second ;-)
Answer: I recommend using a TimeSpan first because tick seconds are represented by a TimeSpan, TimeSpan even has a property called TicksPerSecond:
TimeSpan time = TimeSpan.FromSeconds(Convert.ToDouble(clickedCell.Value.ToString()));
DateTime dateTime = DateTime.Today.Add(time);

Or of course adding it to the DateTime the tick seconds have been recorded instead of today.
EDIT: In your comment u stated the number is UNIX UTC 32 Bit, this means your DateTime you add the TimeSpan to should be the date of 01.01.1970 00:00.
Comment: Is this just an _assumption_ or you _really_ know this value should be second and result should be generated adding that value to midnight?
Comment: It is an assumption, it is up to riscy to confirm or unconfirm the use of this.
Comment: Thank I give it a try
Comment: Your DateTime should be 01.01.1970 00:00 instead of DateTime.Now when this is UNIX TIME.
Comment: Yes that work.....how to correct for GMT offset?, I get 8:42 where it should be 10:42
Comment: It need to check OS timezone and make adjustment.
Comment: With TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now); the offset between your computers TimeZone and Coordinated Universal Time will be returned as a TimeSpan you cann add this to your DateTime.
Answer: You should parse the numeric value and pass it to constructor:
string utc = "4294967295";
var dt = new DateTime(long.Parse(utc), DateTimeKind.Utc);

https://msdn.microsoft.com/en-us/library/w0d47c9c(v=vs.110).aspx
Comment: I don't think so because this will generate `{01.01.0001 00:07:09}` as a result, so this is probably not _the_ result OP want..
Comment: Maybe your device uses POSIX time? `var dt = new DateTime(1970, 1, 1).Add(TimeSpan.FromSeconds(double.Parse(utc)));`


Relationships in Harvest Moon

Question: In Harvest Moon: A Tale of Two Towns, I understand that in order to form relationships with people I have to talk to them every day and I have to give them gifts that they like.
Is there some way to know how well you are doing? I suspect it is probably something simple that I am missing, but everything I have looked up simply tells me what various people like as gifts, which, although helpful, is not what I am looking for.
Comment: I don't own tale of two towns, but I'm sure like any other Harvest Moon game there should be a relationship menu of some sort. This menu uses hearts to represent the strength of your relationship with someone.
Answer: There is a way to know how well you are doing, but it is still fairly general. The way to tell how well you are doing with someone in A Tale of Two Towns is via the flowers on the speech box. Unlike other harvest moons, there is no clear relationship information beyond this. The site referenced in the linked q&a is very helpful in deciphering what the flowers mean and how to manipulate relationship levels in A Tale of Two Towns.
Answer: Though I don't own this game, some Harvest Moon games also have special bangles that you can get to check your exact heart or love points on any person at any time by merely talking to them.  These usually get unlocked through some work or cost a little sum of money (I've heard that you have to make them in IoH, but in DS and DS Cute you can get them from the casino for about 20k G).  I'm unsure if there is anything like this for Tale of Two Towns, but if not there should be a separate menu or an icon when the person talks to you.

Relationships in Harvest Moon


'str' object does not support item assignment in python?

Question: I want to read the input.txt line by line and send that as a request to the server and later save the response respectively. how to read and write the data line by line ?
my code below works for just one input within input.txt (ex : I am Hungry). Can you please help me how to do it for multiple input ?
I did as below. now throwing an error as : File "tts.py", line 198, in
    TEXT_TO_READ["tts_input"] =  line
TypeError: 'str' object does not support item assignment
my code :
TEXT_TO_READ = """{

    "tts_type": "text",

    "tts_input": "DUMMY"

}"""
TEXT_TO_READ = json.loads(TEXT_TO_READ)
scriptPath = os.path.abspath(__file__)
scriptPath = os.path.dirname(scriptPath)
fileInput = os.path.join(scriptPath, "input.txt")
try:
    content = open(fileInput, "r")
except IOError:
    print "error message"
    Error_Status = 1
    sys.exit(Error_Status)
for line in content.readlines():
    if len(line):
        TEXT_TO_READ["tts_input"]=line.strip('\n')
        TEXT_TO_READ = json.dumps(TEXT_TO_READ)
        print TEXT_TO_READ

request = Request()

Comment: Please don't vandalise your question.
Comment: sorry. can you tell me how to fix it ?
Answer: You replaced TEXT_TO_READ with a JSON string:
TEXT_TO_READ = json.dumps(TEXT_TO_READ)

The next iteration you no longer have a dictionary, but a string, so your assignment fails:
TEXT_TO_READ["tts_input"]=line.strip('\n')

Don't use the same variable for both encoded JSON data and a dictionary.
Comment: what should i modify here ?
Comment: @sam: what are you trying to achieve? You could just do `print json.dumps(TEXT_TO_READ)` if all you want to do is write the JSON encoding to stdout. That avoids setting `TEXT_TO_READ` altogether.
Comment: after reading first line from the input.txt then sending a request to the server later again  reading the second line and sending the request. but the input here is tts_input. to access tts_input, we are using json loads
Comment: You are only using `json.loads()` to load a hard-coded string at the start of your script. You are not using it on the file contents, if that was the goal.
Comment: No, not really. I can only tell you why you got the error.


using result of a python script to invoke shutdown in terminal(ubuntu)

Question: I've wrote a python script to check whether a condition has been fulfilled(in this case, the condition is a tweet).
Now, I want the computer to shutdown if the condition has been fulfilled. How do I use the result Python provides to invoke a shutdown command in Ubuntu?
Answer: os.system('shutdown -h now')

?
Comment: @infoquad: you should accept this answer if you feel it's correct (click the tick icon below the answer's rating). this gives you and the author of the answer reputation and will help future visitors to quickly find the best answer.
Answer: import os

if condition:
  os.system("shutdown -h now")

Just make sure the user running the script has privileges to call shutdown.
Answer: You can write a simple bash script that checks the result of your python program, and uses the terminal command "shutdown -h now".


Run two electrical cables from the garage to attic

Question: How can I safely surface run two electrical Romex electrical cable from the attached garage panel through the second floor bedroom closet to the attic, while complying with North Carolina electrical codes and codes for passing wires through a firewall? The bedroom is located directly above the garage, which means there is likely a firewall between the two areas.
I'd like to avoid passing new wires through the wall because the wall is spray foamed and is located above the electrical panel. I believe there are many existing wires in the wall that run to the HVAC attic air handler.
Comment: That is good info to include in you question.
Comment: If access is possible, drill a hole through the top and bottom plates of the bedroom wall. Use pull sticks to pull the cables through the holes and seal with fireproof caulk.  Don't know if the caulk is approved by NC code.  Have to wait for the electric experts to chime in.
Comment: I'm planning to run wires on surface, I really don't want to pass wires through the wall because of the location. The wall is above the panel so the must be many existing wires in the wall already and the wall is spray foamed.
Comment: Sure, thank you.
Comment: Whatcha wanna do with them in the attic?
Comment: I take it the construction of the fire-rated assembly above the garage can be assumed to be 5/8" Type X over wooden trusses or joists?
Comment: I need wires for the dehumidifiers.
Comment: @TimurIsangulov -- we need to know the construction of the assembly (floor-ceiling) between the garage and the house to be able to give you a good answer here
Answer: Surface running the wires means installing conduit and not using NM cable. You might want to install the conduit up the exterior wall from the garage to the attic. This is done frequently when replacing knob & tube wiring on different levels of a house. This avoids the firewall issue.
If you choose to do it your way, you'll need to get with your local building authority for acceptable fireproofing.
Comment: You can also use "wiremold" for a more finished look for surface mounting wire/cable, if desired.
Comment: How can I do fireproofing when running inside house through firewall?
Comment: Consider a new question specific to that question. In short, processes/products referred to as firestopping, and specifically for conduits and pipes, "firestop collars" - but also, as answered by JACK, see what your LAHJ requires/accepts bafore choosing something they may not accept. OP, also learn the difference between cables and wires, for clarity and correctness.
Comment: JACK :  It is permissible to use NM cable in conduit, you just have to upsize the conduit. In some situations, it can make the complete run without needing a permanantly accessible junction box and associated splices transitioning from THHN/THWN to NM.  That or running conduit for the entire run, which in many cases is not practical.
Comment: Should I use metal or pvc conduit?
Comment: You can use either one with the proper fittings. PVC requires separate bend sections or has to be heated for slight bends and would require a ground wire. EMT can be bent with a bender and serves as a ground.  Last time I checked, EMT was a little cheaper to install.
Comment: @JACK Can I pull the Romex through PVC, or should it be separate wires?
Comment: @Ecnerwal thank you for correcting, I really meant Romex cable and not wires.
Comment: @TimurIsangulov  You can but it takes up a lot of space and could be hard to pull if you have bends. You'd need to increase the size. I've always used individual wires.
Comment: @JACK if I pick the EMT should I ground it or can just run the Romex cable inside?
Comment: @TimurIsangulov If you run EMT, it will be grounded when you connect it to your grounded electrical panel. Why would you run NM cable?
Comment: @JACK I already have the Romex cable for my project that I'm planning to use. Do you know if there are any requirements for the maximum length of the conduit? I will need to pull 2 cables in up to 20 feet conduit.
Comment: @TimurIsangulov No requirements because it's not normally done that way.
Comment: You'll either need two conduits with one cable each, or one very large conduit. either will probably cost more than buying THHN wire to run in conduit instead, so the cost argument of "but I have the cable already" is moot. One of many reasons running cable in conduit is rarely done - they have to be treated as circles the size of the largest dimension. As for length, there's no limit, and 20 feet is a trivial length of pull.
Comment: See https://diy.stackexchange.com/q/31149/18078 for lots of discussion about that.
Comment: @Ecnerwal after reading all the information in this thread few times, I'd like to use THHN wires. Do you think I will be able to pull 6 wires of #12 THHN in 1/2 Schedule 80 PVC, or should I use 3/4?
Comment: Learn to use a conduit fill calculator. http://conduitfillcalculator.com is one example. That gives 36.5% fill, so it's legit. You may only need 5 wires (one ground wire can serve both circuits in the conduit.) That would be just over 30% and an easier pull.


I cannot have 2 or multiple const on React JS

Question: I'm relatively new in reactjs but I got these errors when I'm trying to include 2 const in one return - Modal from React-strap and the about content, I get errors I cannot figure out how to fix it.
I'm trying to create a simple website but will be using modal functions on every page, but I don't want to create separate files modal.js modal2.js modal3.js how to solve this issue or better another way to achieve this? thanks
see below and screenshot
thanks
import React from "react";
import { Jumbotron as Jumbo, Container } from "react-bootstrap";

//here is where i added the ModalExample
export const About = () => { const } ModalExample = (props) =>  (

  const {
    buttonLabel,
    className
  } = props;

  const [modal, setModal] = useState(false);

  const toggle = () => setModal(!modal);

  <React.Fragment>
    <Jumbo fluid className="jumbo">

      <Container>

About us

Learn to code

      </Container>
    </Jumbo>

      <Container>

About Page

This is mostly about us page.

          Stare at ceiling lay on arms while you're using the keyboard so this
          human feeds me,

      </Container>

      <Button color="danger" onClick={toggle}>{buttonLabel}</Button>
      <Modal isOpen={modal} toggle={toggle} className={className}>
        <ModalHeader toggle={toggle}>Modal title</ModalHeader>
        <ModalBody>
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </ModalBody>
        <ModalFooter>
          <Button color="primary" onClick={toggle}>Do Something</Button>{' '}
          <Button color="secondary" onClick={toggle}>Cancel</Button>
        </ModalFooter>
      </Modal>

  </React.Fragment>
);

Comment: sending [screenshot of code](https://idownvotedbecau.se/imageofcode) is source of many downvote, please move your code into a code block
Comment: I'm note entirely sure what you are trying to implement exactly, but `const About = () => { const }` is a function that does not return anything. With this `ModalExample = (props) =>  (...)` you have an implicit return, but proceed with variable assignments via destructuring instead of returning JSX.
Answer: You cannot do this:
export const About = () => { const } ModalExample = (props) =>  (

I don't exactly know what you're trying to do, but you will either have to do this:
export const About = () => {
  ...

or this:
const ModalExample = (props) =>  (

You can't do both at the same time (you can make a function return a function, but I don't think that's a good idea with React components).
UPDATE:
Btw, if you want to make a function return a function you have to write it like this:
export const About = () => (props) => (
  ...

Comment: Sorry for late response, i was trying to achieve this.

I imported a modal button and content from Modal.js but i need to re-use them on different pages of the site.

anyways to achieve this?

I think i did not explain well and im new to stackflow on how it works.

thanks for your time.


Bathroom ceiling absorbs moisture and falls apart

Question: After complaining about this, I had a guy repaint the ceiling. There is a window but it doesn't fix what is a damp bathroom. A short 15 minute shower cracked the new repainted ceiling because all the steam gets absorbed by it. We were about to install a fan in the windows but I doubt it will solve the problem because the steam rises up pretty fast and not at the windows direction.
What's the problem, the paint or the windows?
From what I can see about the paint, it peels off the ceiling, revealing a grey smooth drywall. And I don't particularly live in a humid environment so why is this bathroom so problematic.
Answer: I think at this point it's safe to say the drywall above the shower is shot, and now you're going to need to replace it all.  While you're in there, install a proper exhaust fan.  Yes, I know that's exactly what you don't want, and that you're trying to cheap this out, but that hasn't worked, and you've given "cheap" the full tryout.  All "cheap" has done is nickel and dimed you to death.
Working with this bathroom as-it-is would require very different bathroom discipline.  It might work for other people.  It doesn't work for you (or other family members). You just don't have the patience.  Get the exhaust fan.
Comment: no, its not about being cheap. is that even the exhaust fan wont fix this. the moment steam touches the ceiling it cracks. i want to make sure the paint is done right first and dont want to blame it on the fan which would hardly do anything here other than prevent mold.
Comment: I'm not referring to the fan you want to put in the window.  You really need a proper exhaust fan that is in the shower stall above the shower.   If the paint won't stick after you followed my previous advice, it means the substrate is literally gone.   There is nothing stable to stick paint to.
Comment: what does the substrate look like? the layer surface behind the paint, not sure whats it called, just looks like a glossy smooth grey. I cant have exhaust fan above the shower, no vents up there and the ceiling is lower in this bathroom because the floor is elevated. Only exhaust i can have is by the windows.
Comment: "Substrate" is the word for the surface you are trying to paint.  You would need to provision a vent somehow, what you are doing just is not working. You need to get the humid air out of there.
Comment: its an apartment, i dont think there is space for ceiling vents. You believe thats the problem and nothing to do with the paint?
Answer: Bathrooms need special paint that's glossier than normal walls. If this wasn't used, your drywall may have absorbed moisture. It sounds like you may need new drywall at this point. If it's painted right, it should hold up even if some steam condenses on it, although ventilation from an open window or fan is still good.
Comment: i had a mold problem before as well. my thinking is that the ventalition is what solves the mold problem. but steam shouldnt affect paint, am i right? Because the painter thinks its because i havent installed a fan. I want to make sure the paint is done right first.
Comment: I think flat paint would absorb moisture. Last time we bought paint, the paint guy said very specifically that bathrooms needed different paint and it should be very glossy, and it was because of moisture.
Comment: Although glossy paint would also be easier to clean if the moisture caused mold to grow, so maybe that was the real reason.


How Do I Program this Timer Switch

Question: There is a timer switch in my garage which I can't figure out how to properly use.  What I know about it:

It controls my driveway lights
There are time tick marks around the circumference of the dial, and it rotates.
The dial is also a button (you can push it)
When it is switched to the ON position, the only way I can turn the lights on/off is to push in the dial.  Once I do that, the lights seem to stay on 24 hrs/day.  Pushing the dial button again is the only way I can turn the lights off.
There is an LED behind the small window above the OFF/ON switch.  It starts flashing when I switch from OFF to ON, and eventually becomes solid (non-flashing).

My objective is to program the driveway lights to turn on/off at specific times, but can't figure it out.  Does anyone know the logo in the center of the dial?  Maybe I can try finding instructions on the internet.
Comment: The proper way to have responded to your own question was to post an answer to it. You can still do that if you want to clean things up.
Answer: SOLVED ON MY OWN
In case this can help anyone else, the logo is Intermatic and I found the instructions for this model here:
http://www.intermatic.com/-/media/inriver/6842-8228.ashx/EJ351-Instructions-EN
Comment: Mind putting a summary of how to program it here in case the link breaks?

How Do I Program this Timer Switch


Turning off the result printing in common lisp

Question: I am working with a reasonably large dataset in GNU clisp. It would be really nice if I could turn off the P of the REPL. Having thousands of results spew across my screen really isn't very useful.
I rummaged through the docs and couldn't find out how to turn it off. I assume it's one of the variables.
Answer: You might try changing the value of <code>*print-length*</code>.


What makes OpenID so difficult to use by persons with no technical background?

Question: According to adrianh in his comment to an answer:

Every single time I have /tested/ openid with "normal" users as opposed to technical folk it's caused more problems than it's solved. Every. Single. Time. Has anybody's experiences been different?

What makes it so difficult to use? How could those issues be solved?
Comment: Hey good one. Why didn't I think of asking this? :)
Answer: Why is it wrong?
OpenID has several drawbacks:

You're actually going to a totally different website in order to register or authenticate. This is not how things work ordinary. For years, registration and authentication for a website was done on the same website: the user was moved to a different website either because he wanted to, or because he was redirected to an advertisement.
Switching to a place completely unrelated to the original website in order to register or authenticate creates frustration. The same frustration exists when you're redirected to a different place when paying online. The difference is that frustration during payment is balanced by the technical choices (asking for credit card numbers on a website requires lots of security measures which are expensive and beyond many programmers), as well as, sometimes, users' trust (I don't give my credit card number to a website I found two hours ago; it's different for PayPal or Google Checkout). The same balance doesn't exist for OpenID.
Count the number of clicks you need to do to authenticate or register with OpenID (if you don't have OpenID in the first place). It's high. Compare it to the simple authentication:

Click on an element on the page you are on to open the authentication panel.
Enter your credentials.
Submit. Congratulations. You're done.

or the simple registration:

Click on an element on the page you are on to open the authentication panel.
Click on the registration link.
Enter your credentials.
Submit. Congratulations. You're done. Unless you must confirm your e-mail address first, in which case it sucks.

The same issue exists for example for Gravatar, and was mentioned in one of the recent SE podcasts.
Several OpenID providers require choice. Making a choice is scary. Example: Stack Exchange gives basically four providers: Stack Exchange itself, Google, Facebook and Yahoo!. This creates several questions for a user which doesn't have a clue:

If I pick Google, will SE know my Google password? I don't want that.
Let's imagine I don't have an account on Yahoo!. Can I still use Yahoo! to authenticate?
Let's say I have a Facebook account, but it's a bit personal and highly lolcatz'y. Would it affect my rank on Stack Exchange? Would other users see that I'm related to the Facebook account?

When registering an OpenID account on a website, OpenID providers scare users. They often tell that the target website will obtain access to personal information, etc. If you read well, you understand that there is nothing dangerous. If you don't read, you imagine that the website will be able to access your GMail account, know the names of your kids, etc.
When an application (i.e. something which works outside a browser) requires to switch to a browser to authenticate (for example on mobile devices), it creates one of the most poor user experiences I've seen. I don't think there is an easy way to solve this issue, and consider the issue outside the scope of the question.

Here's an imaginary situation where a non-technical person discovers OpenID with a help of a person who knows how to use it:

— Ok, let's register on Stack Exchange. Fine, there is a "Sign up" link. I'm clicking on it. Wait... what are those four logos? Why Stack Exchange is not the only one? I'm registering on Stack Exchange, right? So why is it asking about Google, Facebook, etc.?
  — In fact, the other three logos enable you to avoid creating different credentials for SE. You can simply use for example your Google account.
  — Different credentials? I don't understand. I use the same ones on every website.
  — This is not very secure. You're expected to use different passwords on every site.
  — But you're suggesting that I use Google to register on SE. Doesn't it mean that the same password will be reused?
  — No. In fact, only Google will ask you for a password. SE won't have any record about your password and let Google do all the work.
  — I get it. Let's click on Google. Ok, it asks to provide my credentials. Here they are. "...stackexchange.com would like to: View your email address [Cancel] [Accept]". Hm. Ok. Let's say it can, while I don't actually understand the point.

In short, OpenID:

Makes simple things difficult, requiring additional clicks,
Creates unneeded confusion, requiring additional choices,
Switches the user to another website, visually different, while the user expects to remain on the same website.

How can we made it right?

Don't force me into a choice.
There should be one provider by default. An option should be available to let the user pick a different provider.
Don't switch websites visually.
Nobody among non-technical persons look at the URI. Switching to a different SLD technically doesn't make any harm. But the visual aspect should remain the same. This can be done by making the visual aspect (and partially the content itself) customizable, but it may create security risks.
Require as little clicks as possible.
Registration through a BetterID should be as fast as an ordinary registration. You click on a "Sign up" link which switches you directly to the BetterID provider website (with an option, there, to move to a different provider), you enter your existent credentials, you submit them, and voila, it's done: you're back on the original website, and you're considered registered.
Comment: A couple of notes. The frustration during authentication should be balanced by the knowledge/comfort that you do not need to create an umpteenth password or face the risks involved with using the same password on every site. That c/should be made a lot clearer on the openID authentication forms. Most of the doubts you mention could be addressed with a single paragraph and offering the "standard" registration/authentication in addition to the openID way. Unless the option to pick a different provider is blatantly obvious, I don't agree with 1) of how to make it right. ...
Comment: ... Your 2) I can see the benefits of. Your 3) is already the case when you already have an account at one of the openID providers that are offered. Which is why I don't agree with your 1) as it should be easy to spot the one you already have an account with. I don't see though why you would expect the provider website to offer an option to move to a different provider. Why should Google offer you an option to move to MS Live?
Comment: An additional drawback - the choice problem hits when folk log in too. Stackexchange usually remembers my details. When it forgets, or when I use a new browser or a different machine, I have to remember which of the N different options will actually log me in ;-/
Comment: @adrianh: trial and error can help. If after authentication you are taken to the "create account", then you know you had the wrong one.
Answer: First of all, do user tests yourself.
It doesn't require special equipment: any screen recording software will do. You can run the test on any website you wish. Choose the one you think implements OpenID most conveniently.
You can gather people from the streets, friends (acceptance criteria: no degree in IT or Math or Physics, not even BSc), or in a pub.
Or you can do it remotely, through Skype or Hangout or join.me, offering 10 euros on a local Craiglist or something.
Here's a video on how it's done.  There really isn't anything more into it. Just make sure you:

Don't explain
Don't show
Don't help

Just ask questions (mostly starting with "why") and ask the participant to think aloud, and make sure they understand it's not them who are tested but the website in question.
That's it, really.
Personally I think it's a consistency issue (this is not how "internet" works), and also a trust issue, but I haven't done usability tests in this regard so far.


Unable to import tensorflow_probability.substrates.jax

Question: I am trying to import tensorflow_probability.substrates.jax (specifically to use the distributions) and getting the error shown below (it looks like a self-import). I have installed tensorflow (2.8.2), tensorflow-probability (0.14.0) and jax (0.3.25).
Trying
import tensorflow_probability.substrates.jax as tfp

I get
ImportError: cannot import name 'bijectors' from partially initialized module
'tensorflow_probability.substrates.jax' (most likely due to a circular import)
(/path-to-anaconda3-env/lib/python3.10/site-packages/tensorflow_probability/substrates/jax/__init__.py)

I have tried a few different versions of tensorflow-probability with the same results.
Answer: This sounds like it's due to version incompatibility. tensorflow_probability v0.14 was released in Sept 2021 (history), at which point JAX's most recent release was version 0.2.20 (history). JAX has has 36 releases since then, so it's not surprising that some incompatibilities may have arisen.
I tried in Google Colab and found that the following combination works:
import tensorflow
import tensorflow_probability
import jax
print(f"{jax.__version__=}")
print(f"{tensorflow.__version__=}")
print(f"{tensorflow_probability.__version__=}")

import tensorflow_probability.substrates.jax as tfp
print("loaded!")

jax.__version__='0.3.25'
tensorflow.__version__='2.9.2'
tensorflow_probability.__version__='0.17.0'
loaded!

Another thing that can cause similar issues is if you are working in a notebook environment and installing new versions of packages that you've already imported. If you're working in notebooks, be sure to restart your Python runtime after you install or update a package.


Pandas Dataframe create new column with grouppy count with condition on count

Question: I have this Dataframe
 df = pd.DataFrame({"A": [1, 1, 1, 1, 1, 2, 2, 2, 3], "B": [1, 4, 5, 6, 10, 7, 8, 9, 3], "C": ["Hello", "World", "How", "are", "you", "today", "miss", "?", "!"]})

    A    B      C
0  a1   a1  Hello
1  a1   a4  World
2  a1   a5    How
3  a1   a6    are
4  a1  a10    you
5  a2   a7  today
6  a2   a8   miss
7  a2   a9      ?
8  a3   a3      !

And I want something like this
    A    B      C   n
0  a1   a1  Hello   4
1  a1   a4  World   4
2  a1   a5    How   4
3  a1   a6    are   4
4  a1  a10    you   4
5  a2   a7  today   3
6  a2   a8   miss   3
7  a2   a9      ?   3
8  a3   a3      !   0

I tried this operation
df["n"] = df.loc[df.A != df.B].groupby("A")["B"].transform(len)

But I have this result
    A   B      C   n
0  a1  a1  Hello   NaN
1  a1  a4  World   4
2  a1  a5    How   4
3  a1  a6    are   4
4  a1  a10   you   4
5  a2  a7  today   3
6  a2  a8   miss   3
7  a2  a9      ?   3
8  a3  a3      !   NaN

Do you know i could set my condition df.A != df.B on the transform instead on the original dataframe ?
Thanks
Answer: For count matched values (Trues) is possible pass mask with sum, Trues are processing like 1 and Falses like 0:
df["n"] = (df.A != df.B).groupby(df["A"]).transform('sum')

print (df)
   A   B      C  n
0  1   1  Hello  4
1  1   4  World  4
2  1   5    How  4
3  1   6    are  4
4  1  10    you  4
5  2   7  today  3
6  2   8   miss  3
7  2   9      ?  3
8  3   3      !  0

Or create helper column:
df["n"] = df.assign(B = df.A != df.B).groupby("A")['B'].transform('sum')

print (df)

   A   B      C  n
0  1   1  Hello  4
1  1   4  World  4
2  1   5    How  4
3  1   6    are  4
4  1  10    you  4
5  2   7  today  3
6  2   8   miss  3
7  2   9      ?  3
8  3   3      !  0

Comment: First one works fine, thanks a lot !


How do I do a for loop in SQL using Postgres?

Question: I have a Basic Background in Python and my knowledge of SQL is growing, but I have never done anything with Loops in SQL.
I want to do a for Loop in SQL using a list and do so in pgAdmin 4.
So coming from a Python perspective I want to translate the
"for l in list" Statement into SQL.
I have been researching a lot online already, but I can't find a tutorial or manual that explains step by step how it works and what each word or part in the Statement does.
Is there a Website, Manual, tutorial or even a book you can recommend, that is good for a beginner in SQL Loops? Or can someone maybe explain it in an answer comment here, if it's not too complex and long to do so?
Based on my research on Loops in SQL so far, here is an example of what I am trying to do might look like:
CREATE TABLE draft AS
FOR x IN list [green1, blue2, red4]
LOOP
-- do this and that --
END LOOP;

Comment: You might not need a loop here; maybe a query would suffice.  Can you tell us why you need a loop?
Comment: Hi, I need a loop in order to apply the same set of statements/queries to each item in the list and I have over 50 items in my list.
Comment: What exactly is "this and that"? SQL is a set processing language and it is very unusual to think in "loops". Please **[edit]** your question and add some [sample data](http://plaintexttools.github.io/plain-text-table/) and the expected output based on that data. [Formatted text](http://stackoverflow.com/help/formatting) please, [no screen shots](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557). ([edit] your question - do **not** post code or additional information in comments)
Comment: SQL is declarative language, not algorithmic
Answer: You can do something like this with PL/SQL to loop an array.
declare
   type draft_arr_type is table of  draft%rowtype index by pls_integer;
   v_draft_arr draft_arr_type;
begin
   SELECT *
      bulk collect into v_draft_arr
      FROM draft
      ORDER BY <what you want here>;

   for i in v_draft_arr.first..v_draft_arr.last loop
      --code
   end loop;
end;

Answer: SQL does not have loops, You have to use PL/pgSQL, In order to write loops.
Check https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-CONTROL-STRUCTURES-LOOPS


Trying to make a reuseable DataGrid component with my own defaults from ReactDataGrid, but Typescript giving me errors

Question: I'm trying to use ReactDataGrid library in TypeScript to create a base <BaseDataGrid /> component with my own defaults so I can stop repeating myself when using <ReactDataGrid /> in other pages and other components. Here's my base component:
import React from "react";
import ReactDataGrid from "@inovua/reactdatagrid-enterprise";
import { TypeDataGridProps } from "@inovua/reactdatagrid-community/types";

const BaseDataGrid = ({
    columns = [],
    dataSource = [],
    rtl = true,
    nativeScroll = true,
    showZebraRows = false,
    checkboxOnlyRowSelect = true,
    rowHeight = 60,
    showColumnMenuTool = false,
    sortable = false,
    ...otherProps
}: TypeDataGridProps) => (
    <ReactDataGrid
        columns={columns}
        dataSource={dataSource}
        className='h-full'
        rtl={rtl}
        nativeScroll={nativeScroll}
        showZebraRows={showZebraRows}
        checkboxOnlyRowSelect={checkboxOnlyRowSelect}
        showColumnMenuTool={showColumnMenuTool}
        sortable={sortable}
        rowHeight={rowHeight}
        {...otherProps}
    />
);

export default BaseDataGrid;

But when I'm trying to use it I get this error from TypeScript:
Type '{ columns: TypeColumns; dataSource: any[]; }' is missing the following properties from type 'TypeDataGridPropsNoI18n': isBinaryOperator, sortFunctions, editStartEvent, clearNodeCacheOnDataSourceChange, and 58 more

Here's an example of how I'm trying to use it:
import React  from "react";
import BaseDataGrid from "../../../../components/Common/BaseDataGrid";

const Test = () => {
    return (

            <BaseDataGrid columns={[]} dataSource={[]} />

    );
};

export default Test;

And here is also a codesandbox: https://codesandbox.io/s/adoring-faraday-mw1rp?file=/src/App.tsx
Why is it not working when I'm trying to make it as a separate component, but it does work when I import it from library? How can I make a reusable component with my own defaults so that I can pass my own props to it and also keep the component flexible?
I know that the error says I'm missing some default props, but is it logical to type out all of the default props from the library?
Answer: With this type signature
const BaseDataGrid = ({ .. }: TypeDataGridProps) => ( .. )

you're specifying that all the TypeDataGridProps props are required, even though you specify default values for all of them. You can use Partial to explicitly declare the props as optional:
const BaseDataGrid = ({ .. }: Partial<TypeDataGridProps>) => ( .. )

Answer: The error means you haven't defined values for other required props but are passing them to the component. The props for BaseDataGrid are of type TypeDataGridProps which has a lot of other properties. Try changing the prop type to any and see if it works


i want to share the score of my html 5 game by facebook and twitter

Question: I have game which is on html 5.
All the script in js.
So i want o fetch the game score result and display in my webpage (php or html tag)
I want to share that score by twitter and facebook.
this is the javascript
I want to display this by php on my webpage.
I just need to share that js score to facebook and twitter.
thanks
Comment: welcome to SO,please have a look at http://stackoverflow.com/help/how-to-ask
Comment: Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.
Answer: Facebook Sharer
At this link : Facebook Share Button. This app from facebook developers is generating your code to implement on your website to share. For a concrete example, the score page of your html5 game.
Twitter Sharer
You need to implement this javascript code at the bottom of your body tag :

And you need to add this "a" where you want the tweet button to be placed :

Tweet

But you can find out more right here : Tweet Button


Webrtc app develop, web and android

Question: I have a study project which consists in using the webrtc for a web audio video chat application and also its mobile version android ios. I have seen many different tutos, but I have to build my own server and use it locally. So you have some tutorial or technical advice? thank you
Answer: If you want to make an hybrid app means in cordova then try this link in this u can get all your answers
https://www.webrtc-experiment.com/
and if u want to make a native app in android and ios then you should try this links
https://tokbox.com/
https://github.com/webrtc/apprtc
Answer: Take a look at this repo: webrtc as well as this boilerplate: https://github.com/webrtc/apprtc - helped me a quite a lot.

Webrtc app develop, web and android


How do I make my program check whether user input is within 5,10,15,20, etc of the random integer?

Question: import random

print("Pick a number from 1-50")

randomNumber = random.randint(1,50)
correct = False

while not correct:
    try:
        userInput = int(input("Insert your number here. "))
    except ValueError:
        print("That is not a Number!")
        continue
    if userInput > randomNumber:
        print("Guess lower.")
    elif userInput < randomNumber:
        print("Guess Higher.")
    else:
        print("You got it!")
        break

So this code currently takes the user input and says whether the user guessed the random integer, or if they should guess higher/lower. I want to edit the code to now say whether the user input is within 5,10,15, etc of the random integer.
So if the random integer was 30, and the user inputs 20, the program would say something like "You are within 10; guess higher."
Any advice? I'm extremely new to python, so please respond with more simple methods if possible.
Thanks.
PS: Oh, preferably without the use of modules, mainly because I'm still learning.
Comment: By the way, it would be clearer to just write `while True:`.  You never reset the `correct` variable, and the way it's currently written it makes the reader think that `correct` will be reset during the `while` loop.
Answer: I think this does what you want, and it cuts down on the if chains a little:
import random

print("Pick a number from 1-50")

randomNumber = random.randint(1,50)
correct = False

while not correct:
    try:
        userInput = int(input("Insert your number here. "))
    except ValueError:
        print("That is not a Number!")
        continue
    if randomNumber == userInput: # Let's check this first!
        print ("YOU WIN!!!")
        break # We use break b/c changing correct would still run rest of loop

    acceptable_ranges = [5, 10, 15, 20, 25, 30, 25, 40, 45, 50]
    guess_error = userInput - randomNumber
    i = 0
    while abs(guess_error) > acceptable_ranges[i]: # see how close they are
        i += 1
    if guess_error < 0: # let's figure out where they need to go
        next_guess_direction = "higher"
    else:
        next_guess_direction = "lower"

    print (("You are within %i: Please guess %s")
           %(acceptable_ranges[i], next_guess_direction))

Let's look. at the last if statement a little further and the final print line.  We are checking to see if guess_error, defined above (line 15) guess_error = userInput - randomNumber is less than 0 (negative).  If it is less than zero, then we make the variable next_guess_direction equal to the string "higher," because the next guess needs to be larger than the last one (randomNumber was larger than userInput.  If guess_error is not negative, then it is positive, because we already eliminated the we eliminate the possibility of 0 using:
    if randomNumber == userInput: # Let's check this first!
        print ("YOU WIN!!!")

So, if guess_error is positive, we know that userInput was larger than randomNumber and we set next_guess_direction equal to the string "lower."  Finally, we print out everything that we have found:
    print (("You are within %i: Please guess %s")
           %(acceptable_ranges[i], next_guess_direction))

I am using an older version of formatting where %i and %s are placeholders for integer and string, respectively.  I then define what should be formatted there using %(acceptable_ranges[i], next_guess_direction), which simply means to put acceptable_ranges[i] in for the integer and next_guess_direction in for the string.  Keep in mind, we found i in acceptable_ranges[i] right above the if statement.
I know that is all long, but I did not know how much detail you needed!
Comment: I have updated my answer with a fairly involved explanation.  Please let me know if you need more help with anything specifically.
Answer: Update: I see you ask to do it without modules.  Here's a solution:
def ceil(xx):
    if int(xx) < xx:
        return int(xx) + 1
    else:
        return int(xx)

def generate_response(actual, guess, interval=5):
    diff_interval_units = (guess - actual) / float(interval)
    within = ceil(abs(diff_interval_units)) * interval
    response = "You are within %d" % within
    if diff_interval_units > 0:
        response += "; guess lower"
    elif diff_interval_units < 0:
        response += "; guess higher"
    return response

-- original answer:
You can do this with numpy's ceil function.
For instance:
import numpy as np

def generate_response(actual, guess, interval=5):
    diff_interval_units = (guess - actual) / np.float(interval)
    within = np.ceil(np.abs(diff_interval_units)) * interval
    response = "You are within %d" % within
    if diff_interval_units > 0:
        response += "; guess lower"
    elif diff_interval_units < 0:
        response += "; guess higher"
    return response

Answer: A solution using the modulo operator:
import random
randomNumber = random.randint(0,100)

def guess(divisor = 5):
    while 1:
        try:
            print("Pick a number from 0-100")
            userInput = int(input("Insert your number here: "))
        except ValueError:
            print("That is not a Number!")
            continue

        delta = randomNumber - userInput

        if delta == 0:
            print("You got it!")
            return

        remainder = delta % divisor
        # this takes advantage of python truncating non-floating point numbers
        rounded_delta = (abs(delta) / divisor) * divisor + divisor * bool(remainder)

        high_or_low = 'higher' if delta > 0 else 'lower'
        print("You are within %s. Guess %s." % (rounded_delta, high_or_low))


stored values within a custom function

Question: My program takes a data.frame and crunches the numbers. At one point, values from j-th column are multiplied by a predefined values that depends on the column name (species name, actually - it's en ecological index). So far, I've been providing these values via a second data.frame by matching column names. What would be an efficient way of integrating fixed variable values within a function? I would like my program to be as portable as possible, without the need for a second data.frame file.
EDIT
This is the function. I'm trying to improve the second line (index <- read.table...) so that it would not depend on the outside source.
macroIndex <- function(obj, index) {
    index <- read.table("conv.csv", header=T, dec=",")
    a <- c()
    b <- names(obj)
    for (i in 2:length(obj)) {
        obj[i] <- obj[i] * index[which(index==b[i]), 2]
    }
    obj
}

Another solution I tried, while it may not seem pretty, it gets the job done. I use dput(index) and create a permanent object which I then insert into my function.
Comment: My first thought how to integrate all this into a compact neato torpedo form was a small package. In the end, this is what I might end up doing.
Comment: That might be the most elegant solution, that way you could include your index dataframe in the package, just remember to document it.
Answer: Why not include the second data frame as a parameter to your function call, and then check if it was given, if not, create it manually, this way the code can work for datasets that match what you do currently, but can be changed to match new datasets.
Something like (sorry I'm not at my PC, so this is untested)
macroIndex <- function(obj, index) {
  if(!exists(index)) {
    index <- data.frame(# contents of the default data frame here )
  }
  a <- c()
  b <- names(obj)
  for (i in 2:length(obj)) {
      obj[i] <- obj[i] * index[which(index==b[i]), 2]
  }
  return(obj)
}

Comment: That was one of the options I was considering. What I'm trying to do is to make the function take in as little arguments as possible, as to be portable to people who are less knowledgeable with R. I don't see that as a big obstacle at the moment, but will keep it in mind.
Answer: Well, you need to map your column names to another value, so you have to store it somehow.  I would say that a named list would be a more appropriate data structure, although at the end of the day it doesn't make a big difference.
Here's some sample data:
df <- data.frame(a=1:5, b=2:6)
mapping <- list(a=3, b=4)

Here's a simple example of using the list:
for(i in 1:ncol(df)) df[,i] <- df[,i] * mapping[[colnames(df)[i]]]

Regarding Tal's recommendation for using a matrix: that is true so long as every value in your data frame is of the same type.  If you have mixed types, then you need to stick with a data frame.
Comment: Without a loop: `df[,] <- lapply(names(df), function(i) df[[i]] * mapping[[i]])`
Answer: You can use R's lexical scoping to define a function function_maker that returns your desired function func. The code to create the mapping vector is only called when function_maker is called, not when func is. mapping is also owned by func in that other parts of your code can't alter it.
dat <- data.frame(a=c(1,2,3),b=c(3,2,0),c=c(5,6,4))

function_maker <- function(){
    mapping <- c(a=4,b=2,c=5)
    function(df){
        for(i in 1:ncol(df)) df[,i] <- df[,i] * mapping[[colnames(df)[i]]]
        return(df)
    }
}

func <- function_maker()

func(dat)

Answer: 1) consider moving to matrix instead of data.frame - to have faster results.
2) Coudl you supply with some simple code to explain what you want to achieve ?
Comment: I've updated my post and included the function.
I suspect that data.frames that will be used for calculating this ecological index will not grow enough to cause a speed issue.

stored values within a custom function


How do I fix a squeaky/whiny ceiling fan?

Question: I have a four year old Monte Carlo ceiling fan, similar to this now-discontinued model 5OBR52BSD-L in style.  It has a light that points up towards the ceiling and another towards the floor.  The fan is making a whiny, almost squeaky noise, on all 3 speed settings.

How do I fix this?  With some good ol' WD-40 and luck?
Answer: Seems to me that it would depend on where the squeak is coming from.
If it;s inside the mechanism, or somewhere where parts of the fan are rubbing tegether then some WD-40 would probably fix it right up, but if the whole mounting is wobbling and causing the mount to rub against the junction box then you might try tightening the mounting hardware or shimmiing it out with something to make the mounting tighter.
Answer: A whinny noise suggests to me that it's likely something in the movement of the motor or attached assembly.  Careful application of WD40 might be of some use if you can get it in past the blades, and closer to the motor itself.  If that worked, but only for a short time, I would probably look for a way to open it up a bit (careful to turn off power first, and not just at the wall switch) and clean and oil more deeply.
It's possible it's just dirty, but I would guess that it's a bit more likely some parts are starting to wear a bit.  A slightly heavier oil (like 3-in-1 or similar), might give you slightly longer relief than WD40 but it will be harder to get into the right places.


Norm on $C[0,1]$ bounded by values in every rational point is bounded by supremum, norm

Question: Let $||\cdot||$ be such complete norm on $C[0,1]$, that for every $q \in \mathbb{Q}\cap[0,1]$ there exists such $M_q \geqslant 0$, that $|f(q)| \leqslant M_q ||f||$ for every $f \in C[0, 1]$. Show that there exists constant $M \geqslant 0$ such that $||\cdot||_\sup \leqslant M||\cdot||$.
We may assume that $M_q = \sup_{||f|| = 1}|f(q)|$. We can extend this definition to all numbers $x \in [0, 1],$ defining  $M_x = \sup_{||f||=1}|f(x)| \in \mathbb{R} \cup \{+\infty\}$. We want to show that in fact $M_x < +\infty$ for all $x \in [0, 1]$ and the mapping $([0, 1] \ni x\mapsto M_x \in \mathbb{R})$ is bounded. So it suffices to prove that it is continuous. But is it really the case? And how can I use the assumption that the norm is complete?
Answer: You need the completeness assumption because this is an exercise on the Uniform Boundedness Principle. Consider the collection of functionals $\phi_q(f) =  f(q)$, $q\in\mathbb{Q}$. Each of them is bounded in the norm $\|\cdot \|$. Furthermore, for every $f\in C[0,1]$ the set $\{\phi_q(f):q\in\mathbb{Q}\}$ is bounded by $\sup|f|$. By the Uniform Boundedness Principle, there exists a constant $M$ such that $\|\phi_q\|\le M$ for all $q\in \mathbb{Q}$. (The norm here is the norm induced by $\|\cdot\|$.)
The rest goes by the density of rationals: for every $f\in C[0,1]$,
$$\sup|f| = \sup_{q\in\mathbb{Q}} |\phi_q(f)| \le M\|f\|$$ as claimed.


How to disable click event for certain elements in AutoCompleteTextView

Question: I am using AutoCompleteTextView (ref : AutoCompleteTextView )
I am able to get list of auto suggestion provided by this view.
Now I want to disable the second suggestion from this view.
Can you please tell me how to achieve it ?
Thanks
Answer: Create a custom data adapter for your AutoCompleteTextView by extending ArrayAdapter and then override isEnabled method from that custom adapter to define which items are click-able or not.
@Override
public boolean isEnabled(int position) {
    // TODO Auto-generated method stub
    return super.isEnabled(position);
}

Comment: Can you please tell me how can I change the disable element text color ?
Comment: usually it automatically lightens the textcolor of disabled item. but if you want to override that behaviour, then simply override `getView` method within the same adapter and set a custom color to your disabled items
Comment: Well i override getView and able to change the background color but not able to change text color how can I achieve that ?
Comment: [this](http://stackoverflow.com/questions/7361135/how-to-change-color-and-font-on-listview) should help you to understand how to change text color particularly


FXML referencing CSS variables

Question: I have google'd around a bit without an answer. In FXML I know how to reference a css, a style, etc using the styleClass and style tags. I'd like to know if it is possible to reference a single css variable adhoc.
For instance, if I want to set the padding of a pane is it possible to achieve the following, or something similar:
example.css
/* ---------- Constants ---------- */
*{
    margin_small: 1.0em;
    margin_large: 2.0em;
}

example fxml
<padding>
    <Insets bottom="margin_small" left="margin_small" right="margin_small" top="margin_large" />
</padding>

The alternative would be to make a css style for every combination of these, or to reference them with the style tag. I'd prefer to avoid both of those options.
Is this possible ?
Comment: You cannot do what you are trying to do in the sample code in your question.  Maybe the information here will help: [using em units in FXML via expression binding](http://stackoverflow.com/a/23706030/1155209), but I am not sure because you have not [explained what the problem you are trying to solve is](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).
Comment: Thanks for the reply. There isn't a specific problem, I would just like a tidy way of using a global variable for things like margins. And since the fxml is responsible for the layout, it would be messy to put those constants or logic in the controllers. I essentially want to do what is possible in android's xml, where you can reference a values file. But in javafx it would be css instead of values
Comment: Finally decided to create a POJO with a property for each constant I want to reference. Then in each FXML file I define an instance of the POJO and reference them that way. Not as neat as I'd like, but still a lot better than having it in each controller. And way better than hardcoding
Comment: You might want to post the details or sample code for your solution as a [self-answer](http://stackoverflow.com/help/self-answer).
Answer: I couldn't get to the solution I actually wanted, I would've hoped to be able to include a file (fxml, css, values, etc) and reference directly. The best I could do is to create a POJO with a property for each constant, then defining an instance of the POJO in fxml.
The problem with this is each fxml will be creating a new instance of a class, which is a little wasteful seeing as the constants are static in nature.
The following is what I did:
FXMLConstants.java
// Class instance containing global variables to be referenced in fxml files. This is to allow us to use constants similarly to how Android's xml structure does
public class FXMLConstants
{
    private static final DoubleProperty marginSmall = new SimpleDoubleProperty(10);
    private static final DoubleProperty marginMedium = new SimpleDoubleProperty(15);
    private static final DoubleProperty marginLarge = new SimpleDoubleProperty(25);

    public Double getMarginSmall()
    {
        return marginSmall.getValue();
    }

    public Double getMarginMedium()
    {
        return marginMedium.getValue();
    }

    public Double getMarginLarge()
    {
        return marginLarge.getValue();
    }
}

Example.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import com.example.FXMLConstants?>

<GridPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">

    <fx:define>
        <FXMLConstants fx:id="fxmlConsts" />
    </fx:define>

    <padding>
        <Insets bottom="$fxmlConsts.marginMedium" left="$fxmlConsts.marginLarge" right="$fxmlConsts.marginLarge" top="$fxmlConsts.marginMedium" />
    </padding>

    <children>

    </children>
</GridPane>

FXML referencing CSS variables


why every request is being processed as a ajax request

Question: I have started with a new application development using rails 4.0. But I dont konw why every request is being processed as ajax request. for example suppose I have one link like this :
 =link_to  "View detail", product_detail_path(:seo_name => vp.product.seo_name, :vp_id => vp.id), :class => "btn btn-default"

which takes me to the product detail path, and I have this code in my controller for the same link
def show
  @product = Product.find_by_seo_name(params[:id]) #here in params[:id] you will get seo_name of product
  @other_variants = @product.variant_products.where("variant_products.id NOT IN (?)", @variant.id)
end

but when I hit the same link, it takes me to the product show page, but it is processed as ajax request. when I right click to inspect element I can see this line on console:
GET http://localhost:3000/products/product-1-tb002?vp_id=71

same case is with my other links as well those which are processed as ajax links and those which are processed as html requests. can't understand what is the issue!
you can see in a below screenshot I have clicked on "view detail" button, which take me to the show page of my product. that link does not contain "remote => true". and I think still it gets processed as ajax request.
https://i.stack.imgur.com/yBQpy.jpg

Comment: GET http://localhost:3000/products/product-1-tb002?vp_id=71 does not mean it's an ajax request.
Comment: then what could be the problem :(
Comment: you don't mention an actual problem. edit your post to say what you think is supposed to happen and make it clear what isn't happening. The question you posted doesn't actually state what problem you're having. If something were being processed as ajax the page would not redirect / refresh.
Comment: Yes exactly, my page is not getting refreshed. I have lots of jquery written in my common javascript file and i have included it in my application.js file. but the thing is that when i am clicking on the same link as i a have mentioned above, it takes me to that respective page but my javascript is not getting executed and when i refresh the same page then only it gets executed. and i have written this code inside document.ready function
Comment: generally when page is refreshed , browser console does not show us that this particular request is being processed(i.e. GET localhost:3000/products/product-1-tb002?vp_id=71). As per my understanding, it only shows when ajax request is fired.
Answer: This is an issue with turbolinks. Disable remove/turbolinks and you should see the specified/expected behavior.


Ubuntu unstable login after upgrade to Radeon Vega 56

Question: I had an Nvidia 1060 in a Mac Pro 1.1 with Ubuntu 18.10. It worked pretty well, but I wanted an upgrade to something that would allow me to boot back into macOS.
I purchased an AMD Vega 56, which works well, but shortly after installing the card, the computer started to become pretty unstable after screen blank. After the screens go off, one of them (it's a dual-4K setup) will stay in a solid color, usually the Ubuntu purple, or it won't come back at all. It also started showing a weird color bar with grub on boot. I updated to 19.04 (fresh install), but that didn't help. Any advice would be appreciated.
Answer: This is no official GUI to overclock your GPU.
But, https://github.com/BoukeHaarsma23/WattmanGTK seems to be what you're looking for.
https://github.com/marazmista/radeon-profile is another alternative
Cheers
Comment: Thank you! I won't be able to try it until tomorrow--but I'll let you know what I find out!
Comment: Sorry about the delayed update--unfortunately, I haven't gotten it to install and run correctly. It keeps giving me an error when I run it. I read the note at the bottom of the page on errors running it, but I haven't been able to make enough sense of it to figure it out.
Comment: Did you tried to remove nvidia-drivers before install the vega ? amd product should work out of the box without using proprietary driver. However to get it work correctly I strongly advise you to use mainline kernel 4-15.0-47-generic a the moment. I've tried on fresh install with a radeon 7, working like a charm.
Comment: It had the same problem on a fresh install too... I ended up just getting a new computer. It works great in the new computer. I'm thinking it was just an issue with the Mac Pro and power or air flow.
Comment: Glad you solve it ! Not the cheapest way :p


How to remove specific param from url?

Question: I have this route :
www.test.com/evidention?procesId=12&esid=12

I want to remove only this esid. Any suggestion how can i do that?
Comment: How does it get there the first place? Can you provide us some supporting code? It might only be me but I am unsure what you are trying to achieve here.
Comment: $location.search('myQueryStringParameter', null);  this might help
Comment: I have search form and i added that as param for what i search for, but at the end i want to remove it because when i reloaded page i want to have url without that param, because there is some logic based on that param. I'm adding it with router.navigate
Comment: @Ali how can i include this $location.search ? i tried from Location angular/common but its not working
Comment: @None which angular version are you using?
Comment: 4.2.6 im using.
Answer: In the component or service where you want this deletion you can do the following:
export class ComponentOrService
{
    constructor(
      protected readonly route: ActivatedRoute,
      protected readonly router: Router
    ) { }

    deleteQueryParameterFromCurrentRoute()
    {
        const params = { ...this.route.snapshot.queryParams };
        delete params.esid;
        this.router.navigate([], { queryParams: params });
    }
}

PS: [] here means to stay on the same route and only change queryParams
Comment: For anyone wondering why the spread for the params const - because otherwise the params will become a reference and you will not be able to delete/change the query parameters with it.
Answer: In angular 7+ there is error with "no provider for activatedroutesnapshot"
insteated you can use from ActivatedRoute
in constructor use
    private _ActivatedRoute: ActivatedRoute

and with this you can change url parameters
    var snapshot = this._ActivatedRoute.snapshot;
    const params = { ...snapshot.queryParams };
    delete params.esid
    this.router.navigate([], { queryParams: params });

How to remove specific param from url?