Docx Python - Read line by line

Question: I have the following text in a word file.. I am trying to read the text line by line, check whether the last word is hyphenated, if it is hyphenated then join the last word of the current sentence and first word of the previous sentence without hyphenation....
*The protection of anticipatory or pre-arrest bail cannot be limited to any time-
frame or "fixed period" as denial of bail amounts to deprivation of the funda-
mental right to personal liberty in a free and democratic country, a Consti-
tution Bench of the Supreme Court ruled on Wednesday.*
expectation output:
timeframe
fundamental
constitution
Python Docx has options only to read entire paragraph and not lines..
Is there a way to do it in Python??? Can someone assist???
Answer: convert your paragraph  into text and then do a split on '\n'
from docx import Document

# s = Document('f.docx').paragraphs
d = Document()
d.add_paragraph("""The protection of anticipatory or pre-arrest bail cannot
 be limited to any time-
frame or "fixed period" as denial of bail amounts to deprivation of the funda-
mental right to personal liberty in a free and democratic country, a Consti-
tution Bench of the Supreme Court ruled on Wednesday""")
d.add_paragraph("second paragraph")
ans = Document() #new_document
for s in d.paragraphs:
    print(s.text)
    print(s.text.split("\n"))
    str_list = s.text.split("\n")
    new_para = ""
    prev = str_list[0]
    for i in range(1, len(str_list)):
        if prev[-1]=="-":
            prev = prev[:-1]+str_list[i]
        else:
            if new_para =="":
                new_para = new_para + prev
            else:
                new_para = new_para + "\n" + prev
            prev = str_list[i]
    if new_para =="":
        #if only one str in list
        new_para = new_para  + prev
    else:
        new_para = new_para + "\n" + prev

    ans.add_paragraph(new_para)
    print(new_para)
ans.save("demo.docx")

Comment: Hi. Thanks for your response. However the input is a .docx file and not a .txt file. The 4 lines that I gave as sample is one single paragraph and not 4 different lines. Is there an option to do???
Comment: @KathiravanSaimoorthy you have to convert your paragraph into text and then you can do all your string manipulation on that. Check this link: https://python-docx.readthedocs.io/en/latest/
Answer: I have this one solution where by you set a range of lines you want to retrieve
def pp():
    x = 0
    for i in doc.paragraphs:
        if x < 20:
            print(i.text)
        else:
            break
        x = x + 1

this however will not be feasible if the number of lines in document is always different

Docx Python - Read line by line


Why R function Chol() breaks for Hilbert matrices of order n > 12

Question: Is there any theoretical reason that Chol() in R breaks for Hilbert matrix of order greater than 12?
Thanks,
Comment: http://en.wikipedia.org/wiki/Condition_number
Answer: Both Zen's comment and F.Tusell's answer are correct (+1 to both). Just to add a bit on this: If you look at the associated eigenvalues of Hilbert(13) for a example, the smallest of them is smaller in scale than .Machine$double.eps which is roughly 2.2e-16. Therefore this eigenvalue (and others of even smaller scale) is regarded as a machine zero and leads the decomposition algorithm to treat Hilbert(13+) as non-positive definite matrix and thus not having a Cholesky decomposition. (So actually $H(13-15)$ are "semi-PD" numerically speaking, and for $H(16+)$ you even end up with "negative zeros" eigenvalues).
Answer: Hilbert matrices are of notorious poor condition, which probably account for the failure you are seeing.


Where does the theme name get stored in database?

Question: In which table does Drupal 8 store the theme name?
I'm trying to programmatically install an uninstalled theme. Obviously, there's some written logic behind the Install and set as default button. What exactly does that button do?
Comment: What do you mean by "theme name"?
Comment: what do you mean active theme name? if true you can find it in table config with row name is system.theme. Data store is serialize. Data like that http://www.unserialize.com/s/0a62731a-cc5a-d8c8-1a76-00004200aea8
Comment: @MrD I am pretty sure she is dealing with an uninstalled theme name.
Answer: The theme names are not stored in the db; other wise, we would have to uninstall the uninstalled themes... How would Drupal know the name of an uninstalled theme? It reads the names from the themename.info.yml file.
If you think about it, its just like uninstalled module names, the module name is not stored in the db, Drupal reads/gets the name from the module.info.yml file.
Comment: I can't think of a scenario where the ability to "install any theme PRO-GRAMMATICALLY" makes sense. @SugandhKhanna could you clarify where and when your code will ever be in a position to make use of this? What is your goal?
Comment: so what, if some one wants to install any theme PRO-GRAMMATICALLY? I know how to set default theme pro-grammatically  but can't figure out How to install it?
Comment: @SugandhKhanna that's a totally different Q than you initial Q. You should make a new Q regarding that. Off the top off my head, I don't know the answer to that since I've never had to deal with that scenario. You would have to do the programmatically equivalent of pressing the [Install and set as default](http://i.stack.imgur.com/MoY1Q.jpg) button.
Comment: My goal is like: I have a info.yml file where theme name is written, that I want to install, I will read this theme name from my .info.yml file and on a single button click, that theme will get installed. That same theme itself is present in theme folder of drupal.
Comment: Ok...but what does that have to do with your need to find the name of a theme in the database?
Comment: Maybe this helps: http://drupal.stackexchange.com/questions/201530/how-can-i-change-the-active-theme-programmatically


If parent feeds (import) node is unpublished, how do I not include it in the import schedule?

Question: If the parent feed imports a node (the form/node to input the feed URL, not the feeds importer) that is unpublished, I'd like to have it (the feed URL) not be included in the cron schedule to update/import the feed items. How is this done? For example, a user submits a feed, but the administrator needs to verify it before publishing, and importing it.
See also Don't import items if parent feed is unpublished.
Comment: The linked article has much better information, even sample code. Please consider adding that to the question here.
Comment: Have you had any luck figuring this one? I tried this with the default (RSS) Feed Importer and it seemed to work as expected -- it didn't import when the feed node was unpublished.
Comment: Hmm, that's odd. One of my feed importer is configured to use Common Syndicate Parser and the other one uses QueryPath Parser. I confirmed that the feed node (parent) is unpublished. Did you see the note that it's importing feeds on a cache flush -- is that odd or normal? It shouldn't do that regardless of status, right? I'm on a local so cron isn't set up yet.
Answer: It looks like, when a node is saved, Feeds module starts importing the feed from that node.
function feeds_node_insert($node) {
  // Source attached to node.
  feeds_node_update($node);
  if (isset($node->feeds) && $importer_id = feeds_get_importer_id($node->type)) {
    $source = feeds_source($importer_id, $node->nid);
    // Start import if requested.
    if (feeds_importer($importer_id)->config['import_on_create'] && !isset($node->feeds['suppress_import'])) {
      $source->startImport();
    }
    // Schedule source and importer.
    $source->schedule();
    feeds_importer($importer_id)->schedule();
  }
}

There is an option in the importer's setting page called Import on submission. If you uncheck this box, hopefully your feed won't be imported.  Feeds maintainer still need to make changes in feed_cron() so that it won't fetch the unpublished nodes.
While you wait for a better fix from module maintainers, you can quickly fix this code by changing the first if statement to add $node->status==1  condition as follows:
if ($node->status==1 && isset($node->feeds) && $importer_id = feeds_get_importer_id($node->type))


How to get nid of a managed file?

Question: in hook_file_download there is just a parameter named uri. How can I get nid of the node that contains the file in uri?
For exmpale I have a file field in my content type.I create a node and add some files to file field. Now when this file is going to be downloaded, in hook_file_download I want to get nid of the file.How?
Answer: If this is an file attached through a file or image field, you can instead implement hook_file_download_access(), which gives you the $field, $entity_type and $entity to which the file belongs.

How to get nid of a managed file?


how to handle a :reject_if if a new record and not an update

Question: I am working on some forms that involve uploading an image. There is a standard two forms to add and all the forms currently associated. It will look like this:

I have an assets class that is polymorphic for other classes involved (such as locations, items). The problem is that items can be uploaded or updated. For items and locations, I have the following:
accepts_nested_attributes_for :assets, :allow_destroy => true, :reject_if => lambda { |a| a[:asset].blank? }

but this seems to reject if there is no uploaded file. This is essentially what we want if it is a new file but there are cases where we just update the description via the asset id. The above :reject_if will reject that scenario. How can I make an exception for updating this other type of information?
thx
Answer: I solved it by adding a condition on params[:id] to the reject_if block.  For your example, it would look like this:
accepts_nested_attributes_for :assets, :allow_destroy => true,
    :reject_if => lambda { |a| a[:asset].blank? && a[:id].blank? }

Any existing records should come back with an id attribute in the nested hash, so this should allow updates to existing nested records while still allowing you to reject new records with no asset (because new records don't yet have an id).


Alternatives to The Statistical Sleuth?

Question: I am looking for a simple and concise book on statistics (t-test, ANOVA and all its variants, linear regression, etc.), centered on data analysis. I am not interested in theory or proofs, but just want to know what test is appropriate under what conditions, preferably with some real world examples. E.g., "An Introduction to Statistical Learning" by G. James et al. does this for machine learning.
The only book I could find that vaguely fits that description is "The Statistical Sleuth," but it's not available at my local library. Is there any other alternative like that?
Comment: " but just want to know what test is appropriate under what conditions," no book can in good faith cover the extensive possible list of all tests and all conditions. A digestable intro-level text would be "Applied Linear Regression Models" by Neter Kutner, Wasserman, and Nachtsheim.
Comment: If the condition is *available at my local library*, how are we supposed to advise you without knowing what books your library has? Why don't you do an interlibrary loan?
Comment: AdamO already hit the nail on the head, but I want to add that it doesn't even make sense to instantly resort to *tests* as you mention. Tests are but a fraction of the available statistical methods and are in my opinion grossly overused. By skipping the theory, you limit the type of question you can answer to the methods you are familiar with.
Comment: My suggestion is to read notes posted by colleges. Penn State has a lot of good material that we consulted during graduate school (which was not at Penn State).
Comment: *Statistical Sleuth* is quite good. Chapter 3 for example, covers in detail what the effect of each assumption (normality and same SD) means for using of t-tools with examples. R-cran-projects has some associated R code in knitr along with it [here](https://cran.r-project.org/web/packages/Sleuth3/), which covers in some detail the case studies used in the book chapter by chapter.
Comment: Is there a particular field that you work in? There are some really good discipline specific texts that are much more targetted...
Comment: One classic applied statistics book that has been through enough editions that you might find a copy of some edition available: Ott & Longnecker: Statistical Methods and Data Analysis.
Comment: What about interlibrary loan?
Answer: I don't think either of these is exactly a substitute for Statistical Sleuth (which I also like) but it's a pair of books that will help a lot:

Statistics by Freedman, Pisani and Purves.  A really good text that will teach you a lot but won't overwhelm you with math.
Statistics as Principled Argument by Robert Abelson. An excellent and very informal guide to using statistics sensibly, particularly in the "soft" sciences.
Answer: I looked through the Statistical Sleuth.  At least what I saw seemed pretty good...  A lot of learning about analysis of experiments is an interactive process. You will probably want to have several different textbooks, and then you will want to supplement this with online searches about how to conduct these analyses in your chosen software program. Understanding what the software is doing is really important.  It doesn't always do what you think it's supposed to do... As a caveat, I would say to take no advice as the gospel truth, even if it's in a textbook written by a statistician.  A lot of analysis of experiments is based on judgement.  This can be frustrating to students trying to learn.  E.g. t-tests are robust to violations of normality, but they're not infinitely robust.  There's no test that's going to tell you if it's okay to use a t-test for a data set. You just have to look at the data honestly, know what are your alternatives for analysis, and know what you are trying to achieve. Sometimes authors give bad advice about how to approach these problems, for example recommending using a test to test for normality or homoscedasticity. That's a simple solution that may not be the best advice. You also have to remember that people writing a textbook or a blog are trying make concepts and procedures understandable.  There are probably many considerations and subtleties that they are excluding...
Okay, so a few recommendations for text books.
Conover, Practical Nonparametric Statistics
Agresti, Categorical Data Analysis
Zar, Biostatistical Analysis
I'm sure I have a bunch of other suggestions.  This really needs to be updated, but I have some resources here.
Otherwise, I'll offer a couple of online resources, both written by non-statisticians.  Caveat: I'm the author of the second, and affiliated with the first.
http://www.biostathandbook.com/
http://rcompanion.org/handbook/

Alternatives to The Statistical Sleuth?


Replacing numpy array values python

Question: I am having a terrible time trying to replace values in a numpy array and running up against a very strange behavior I was hoping someone could explain.  Essentially I want to do a crossing over operation in a genetic algorithm.  Here's a simple example. I have a 2 X 10 array, and want all the values in row 1 up to column 5 to be swapped with the values in row             2 up to column 5.  Here's the code:
z=np.random.uniform(low=0,high=1,size=(2,10))
zcopy = z
print z

[[ 0.77488523  0.39966358  0.63233664  0.77093136  0.04102615  0.98984184
0.43402537  0.0910648   0.28037032  0.76654885]
[ 0.49980878  0.28161905  0.71972029  0.01208004  0.87851569  0.16853681
0.96325992  0.90886083  0.12344231  0.83665396]]

z[1,range(4)] = zcopy[0,range(4)]
print z

[[ 0.77488523  0.39966358  0.63233664  0.77093136  0.04102615  0.98984184
0.43402537  0.0910648   0.28037032  0.76654885]
[ 0.77488523  0.39966358  0.63233664  0.77093136  0.87851569  0.16853681
0.96325992  0.90886083  0.12344231  0.83665396]]

As you can see it's just copied all of row 1 into both rows.  But, if I don't specify a subset of another array but just give it say integers it works perfectly
z[1,range(4)] = range(4)
print z
[[ 0.77488523  0.39966358  0.63233664  0.77093136  0.04102615  0.98984184
0.43402537  0.0910648   0.28037032  0.76654885]
[ 0.          1.          2.          3.          0.87851569  0.16853681
0.96325992  0.90886083  0.12344231  0.83665396]]

I'm rather perplexed.  Does anyone have any idea how to work around this?
Comment: I don't see that it has copied all of row 1 into both rows. The numbers are different after the second `print z`. Can you clarify what you mean?
Comment: @tinman, look again. In the first example, the numbers in the first four columns are identical after `z[1,range(4)] = zcopy[0,range(4)]`.
Comment: @senderle: that's what you'd expect isn't it? The op said `it's just copied all of row 1 into both rows` but it's not all of row 1, it's only the first 4 columns. But his comment further down about why zcopy has changed too makes me think I've missed something.
Comment: @tinman, hmm, you're right, that is a bit confusing.
Answer: try this
z=np.random.uniform(low=0,high=1,size=(2,10))
z[:,range(4)] = z[::-1,range(4)]

before
[[ 0.30778241  0.04832341  0.616925    0.81325565  0.44578265  0.59024722 0.32147695  0.68434105  0.47430297  0.06256859]
 [ 0.58522801  0.23922353  0.15388696  0.46400394  0.33126422  0.54651948 0.34724277  0.46974174  0.68646707  0.62549495]]

after
[[ 0.58522801  0.23922353  0.15388696  0.46400394  0.44578265  0.59024722 0.32147695  0.68434105  0.47430297  0.06256859]
 [ 0.30778241  0.04832341  0.616925    0.81325565  0.33126422  0.54651948 0.34724277  0.46974174  0.68646707  0.62549495]]

Comment: @DistribEcology good question! `::-1` basically give you a reversed indexing: from going [0,1] to [1,0].
Comment: Take a look at [this post](http://stackoverflow.com/q/509211/577088) for more information about slicing -- which is what that's called. Also, you should probably take a look at [the tutorial](http://docs.python.org/tutorial/introduction.html#an-informal-introduction-to-python) if you haven't encountered slicing yet.
Answer: There seem to be two questions here.

"Why doesn't zcopy = z make a copy?"
"Why doesn't z[1,range(4)] = zcopy[0,range(4)] swap the values in the first four columns?"

The answer to the first question is that assigning a value to a variable name in Python doesn't make a copy. A variable in Python is just a label for an object; giving the object a new label doesn't change the object itself at all. If you want to make a copy of a numpy array, specifically, you can use the copy method, which returns a new copy of the array. As in:
zcopy = z.copy()

The answer to the second question is that your code only assigns one set of values: z[1, range(4)]. If you want to change both rows, you have to assign to both rows! In many languages you'd do this with a tmp variable, but python provides an elegant way to swap values without needing temporary variables:
>>> z[1, range(4)], z[0, range(4)] = z[0, range(4)], z[1, range(4)]

nye17's answer is a bit cleaner, but it does the same thing.
Comment: Oh, well `zcopy` isn't really a copy, that's why; I didn't realize that was part of your question. Assigning an object to a variable name never makes a copy in Python. Both `z` and `zcopy` refer to the same numpy object. If you want to make a copy of `z`, use `z.copy()`. But you'll still have the same problem, because you're overwriting one row but leaving the other unchanged.
Comment: Right, this works, but a big part of my question is why do the values of zcopy get changed to be the same as z in my original question?  I can't figure that out.
Comment: @DistribEcology zcopy isn't a `physical` copy in the sense that it only provides as reference to the same memory that stores the z array.
Comment: Ahh, that explains it.  I'm moving to numpy from R and falling into the trap of trying to do this in python the exact same way I would in R.  Thanks for the tips.
Comment: @DistribEcology on a side note, it's a rare event that ppl in bio statistics convert from R to Python....;-)

Replacing numpy array values python


How to modify block menu path

Question: My goal is to have a menu block on my blog pages with a list of the terms used in the blog posts. So far I have set up a node view for the blog postings. And a term view called topics to display the terms.
It's working, but when I click on a term listed in the block the resulting path is category/topics/term-name. I would like to have a path such as blog/topics/term-name or even better just blog/term-name.
I have looked at the Taxonomy menu settings under the taxonomy/edit/vocabulary but haven't figured out if I can change these settings to get what I want.
I'm using the Pathauto module. Not sure where else to look for an answer. I'm using 6.
Answer: Pathauto gives you the option of defining per taxonomy path patterns.  Just set the value for your blog categories taxonomy to blog/topics/[catpath-raw] and regenerate your aliases.  These settings are controlled in http://example.com/admin/build/path/pathauto
Comment: Thank you for the advice. I had begun to figure out it had something to so with the taxonomy paths, but wasn't sure what to do.

How to modify block menu path


Android RecyclerView and onBindViewHolder

Question: I have a TextView on each item and added holder.item_edit_text.addTextChangedListener on onBindViewHolder for a long list and an interface that computes the total at the fragment level but weirdly when a user types on one view, onBindViewHolder is called on multiple items.
I.E if a user enters 5, i get multiples of 5 depending on the recycling (number of items in the list) e.g 15 or 25
RECYCLERVIEW onBindViewHolder
holder.item_edit_text.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence amount, int start, int before, int count) {
            calculateTotal.onAmountAdded(current, amount.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    @Override
      public int getItemCount() {
        if (Accounts != null) {
        return Accounts.size();
    }
    return 0;
   }

Question is how I can ensure that onBindViewHolder is called for one item in the recyclerview per time
THE FRAGMENT
     @Override
public void onAmountAdded(Account account, String amount) {
private Map<Account, String> orderItems = new HashMap<>();
    if (amount.length() < 9) {
        orderItems.put(account, amount);
        int newTotal = 0;
        Iterator iterator = orderItems.entrySet().iterator();
        while (iterator.hasNext()) {
            try {
                Map.Entry mentry = (Map.Entry) iterator.next();
                newTotal += Integer.parseInt(mentry.getValue().toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        text_total.setText(ValidationUtil.formatNumber(String.valueOf(newTotal)));
        return;
    }
}

Comment: let me add more content
Comment: It depends on the `getCount()` method, `onBindViewHolder()` is called as many times as a list count. Ex: if a list size is 5, it will be called 5 times.
Comment: @UmangBurman i've added the `getItemCount()` method
Answer: Not enough information I suppose.
Instead of adding a TextWatcher on viewBinder
add it inside your ViewHolder Class
class ViewHolder extends RecyclerView.ViewHolder {

    private TextView item_edit_text;

    ViewHolder(View itemView) {
        super(itemView);
        item_edit_text = itemView.findViewById(R.id.item_edit_text);
        item_edit_text.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence amount, int start, int before, int count) {
                   //not sure why this current variable is for
                  //if its current Account
                   Accounts current = Accounts.get(getLayoutPosition());
                   calculateTotal.onAmountAdded(current, amount.toString());
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }
    }

Comment: the issue is at `ViewHolder` level, I don't get access to the current object. That's the value of using `onBindViewHolder`. To elaborate, if I have a list of 20 items and my screen can only populate 5 items at a time, that means that the items are going to be recycled 4 times... so in that case, if a user enters 5, i get 20 instead.. (5*4). Is tyhat descriptive enough?
Comment: @clifford_owino You can have access to the current object of which the data is being changed. 'current' is an object of Account right? how are you getting current object at onBindViewHolder something like 'Account current = Accounts.get(position);' you can do the same on ViewHolder just use getLayoutPosition() to get the current object from 'Accounts' array.
Comment: This one worked
https://stackoverflow.com/questions/31844373/saving-edittext-content-in-recyclerview
Comment: Serves the same purpose in a different way. Code was inadequate, that's why I went with getLayoutPosition() instead of getAdapterPosition().
getAdapterPosition().


Remove the logo that is displayed when application is launched before the splash screen begins

Question: When launching the application there is short time for which the logo is shown and after that my splash screen animation starts.
How do I disable my logo from being shown when the application is launched.
I want my splash screen to run direclty no logo should be shown.
Here's the code for my XML file:
<?xml version="1.0" encoding="utf-8"?\>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SplashScreen"
android:background="#FCFCFC"\>

    <pl.droidsonroids.gif.GifImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@drawable/splash_screen"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here's the SplashActivity file for it:
package com.example.tictactoe

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper

class SplashScreen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)

        Handler(Looper.getMainLooper()).postDelayed({
            val intent = Intent(this , MainActivity::class.java)
            startActivity(intent)
            finish()
        },2200)
    }

}

Here's the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TicTacToe"
        tools:targetApi="31">
        <activity
            android:name=".SplashScreen"
            android:exported="true"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:screenOrientation="portrait">
        </activity>
    </application>

</manifest>

Is it because the system takes some time to load the resource, so in the meantime, it displays the logo and then begins the animation.
Comment: You shouldn't have a splash screen activity at all - as of Android 12 and higher, you [have to migrate](https://developer.android.com/develop/ui/views/launch/splash-screen/migrate).
Answer: Basically which you saying logo its default type splash for android 12 and above, to disable that default view you can check official website android, you will get all implementation about that topic...
https://developer.android.com/develop/ui/views/launch/splash-screen

Comment: It cannot be disabled.
Answer: As of Android 12 and higher, Android provides its splash screen. While you have the option to customize the default splash screen according to your needs, it's not possible to disable it entirely. Given that you don't have any specific logic in your splash screen, I suggest utilizing the default one. For a more detailed understanding, please refer to this link.
Answer: Refer to this Android 12 splash screen and yes that logo will always be shown as it loads the resources in the meantime.
if you want to get rid of that animate the logo itself.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Exceeded soft private memory limit of 128 MB with X MB after servicing Y requests total

Question: I get the dreaded Exceeded-memory-error in my App Engine-application that have a Cron-job pushing multiple small tasks to a queue.
I don't think any single task should trigger the critical error so I'm guessing that they are somehow connected; sharing the memory that is lacking.
I'm running my queue with a Maximum Rate of 4/s and a Bucket Size of 5.
How can I be sure and what can/should I do?
Exceeded soft private memory limit of 128 MB with 131 MB after servicing 18 requests total
Exceeded soft private memory limit of 128 MB with 128 MB after servicing 1933 requests total
Exceeded soft private memory limit of 128 MB with 153 MB after servicing 3697 requests total

Answer: You can monitor memory instance usage like this (I'm assuming Python):
from google.appengine.api.runtime import memory_usage
logging.warn("Memory usage:  %d MB" % (memory_usage().current()))

You could do the following:

Decrease task rate.
Use instances with larger memory.
Modify your code to be more efficient.  I recently had this problem with a task in a task queue, so I made each task smaller and then daisy chained a new task to continue the work.  When a task finishes, the garbage collector should immediately clean up for you.
Answer: When a task have been executing for 10 min, it will terminate. The error-message for this can be somewhat confusing.


Matrix representation from a linear function

Question: I'm studying an opinion formation model [1] where the main rule is:
$p^{(t)}_i = \frac{p^{(0)}_i + \sum_{j \in N(i)} w_{i,j} p^{(t-1)}_j}{1 + \sum_{j \in N(i)} w_{i,j}}$
Now, I'd like to represent that equation in matrix notation:
$\mathbf{p}^{(t)} = \mathbf{A} \mathbf{p}^{(t-1)}$
where:
$A_{i,j} = \frac{p_i^{(0)}}{\sum_{j \in N(i)} w_{i,j}}$, if $i=j$
$A_{i,j} = \frac{w_{i,j}}{\sum_{j \in N(i)} w_{i,j}}$, if $j \in N(i)$
$A_{i,j} = 0$, otherwise.
Is that right, or not? I'm asking because when I run the iteration given by $\mathbf{p}^{(t)} = \mathbf{A} \mathbf{p}^{(t-1)}$ I get a $\mathbf{p}^{(t)}$ with all zeros, and that is certainly wrong.
Comment: Is the formula correct? If it is so, then the iteration cannot be written in the form $p^{(t)}=Ap^{(t-1)}$ due to the constant term $p_i^{(0)}$ but rather as $p^{(t)}=Ap^{(t-1)}+b$.
Answer: I've found that my first representation was wrong. The exact way is the following:
$\mathbf{p}^{(t)} = \mathbf{A} \mathbf{p}^{(0)} + \mathbf{B} \mathbf{p}^{(t-1)}$
where:
$A=diag(\alpha_1, \ldots, \alpha_n)$ and $\alpha_i= \frac{1}{1 + \sum_{j \in N(i)} w_{i,j}}$,
$B_{i,j} = \frac{w_{i,j}}{1 + \sum_{j \in N(i)} w_{i,j}}$, if $j \in N(i)$
$B_{i,j} = 0$, otherwise.


How to choose overgrip to a tennis racket?

Question: My tennis couch said that I should test as many overgrips as possible to find a grip which does not get slippery so fast and maintain the condition for a longer period. I tested Gamma overgrip that got slippery very fast and I had to change it after four training periods. Before that I had Wilson but in different racket so I am unsure about their differences. I am not sure whether finding the overgrip is the key here, it may be that a poor undergrip makes the grip go worse faster. I use overgrip because of the larger handle and it helps to keep the racket not sliding easily out of my hand.

How should I choose my overgrip? And which kind of criterias should I consider?
Answer: Choosing an overgrip typically depends on a few different factors:

Moisture (sweat) absorption - how well the overgrip stays dry when your hands are sweating.
Tackiness - how "grippy" the overgrip feels in your hand when you first put it on your handle.
Durability - how long the overgrip stays good and doesn't start wearing out or tearing after a certain amount of use.
Thickness - how thick the overgrip is and therefore how much size it adds to the handle of your racquet when it's put on.

I've tried many different brands of overgrips over the years from various brands and to me, there are only really 3 different brands that stand out to me as really great overgrips:

Yonex Supergrap: The most tacky overgrip there is. Slightly more tacky than Wilson Overgrip. You don't want to wrap it too tight though, or it won't stay tacky as well or absorb moisture as well. Durability is decent - I usually put a new one on after about 5+ hitting sessions (and I would be considered a frequent overgrip changer - I love the feeling of hitting with a new fresh overgrip).
Wilson Overgrip: Everything I said about Yonex Supergrap applies to Wilson Overgrip too - just that I find Wilson overgrip to be a little less tacky after it's first put on.
Tournagrip: Very popular among higher level players and players with sweaty hands. Has the best absorption of any grip I've ever played with. Unfortunately it's lower on the tackiness scale IMO - and the tackiness is really important to me.

So anyway, I play with Yonex Supergrap myself, and buy it in the bag of 2 rolls, which is 30 total overgrips.
You can also read reviews of various overgrips on sites where they are sold, such as Tennis Warehouse.
Comment: It has certainly never done that for me when I've used it. When I used to use Tournagrip (it's been several years now), when it started getting wet it would start to slip in my hand so I would have to put a new grip on. I've seen the same thing happen to people I play with now that use Tournagrip. I would suggest just buying the overgrip packs that have about 3 grips in them just to try out different types before you buy a big 30-pack of any brand. The 3 I mentioned are the ones I've used and liked the best myself.
Comment: A comment on Tournagrip: the grip gets more tacky if you get wet enough. You notice its tackiness after some playing and getting wet. There are different versions of it and my friend Sasu suggested `"Tourna Tennis Over Grip-30 XL Overgrips-Absorbent Dry Feel Tournagrip-Blue"` for me because he thinks my grip can get very wetty. Is this how it works?
Comment: The thing is that there are many different kinds of Tournagrip: one Tournagrip for less wetty hands and one Tournagrip for more wetty hands. The Gamma in the picture had to be changed after 3 times of training due to sliding in serving and changed to Tournagrip version meant for less wetty hands, working well so far but soon getting also the Tournagrip for wetty hands, let's see how it acts :)
Comment: As with most things - experiment and see what works best for you.
Answer: Here is a somewhat different idea.
I used this road bike bar tape for a pair tennis racquets, with fantastic results on all fronts: appearance, durability, comfort, control, thickness and vibration/shock absorption.
This tape will not lose grip even in the rain; that would be dangerous (worse than useless) to serious year-round, all-weather cyclists.
It turns out that the two pieces of bar tape, adding up to 215 cm of length according to the package, are quite exactly sufficient to do four racquet handles. I used just one roll for the two, with very little leftover waste: just small trimmings.
Bar tape doesn't, of course, come with a pre-cut tapered end to begin the wrap for a racquet handle; you have to cut that yourself.
I used a staple gun on one racquet to tack down the start of the tape. On the other, I had trouble with the staples not penetrating; I used a dab of rubber cement glue to help hold the tape in place instead. For finishing, I used 3M Super 33+ vinyl electrical tape.
It makes little sense to put anything over top of this durable grip. It is not adhesive, so it just unwraps, and the cost is in the overgrip ballpark.
From the pictures you can see just how thick this is:

Stay tuned for the next installment, in which we mount a Shimano Ultegra road lever with 9 speed indexed shifting, to dynamically select among string tensions.


Symfony2 send image created with imagecreate() via response(httpfoundation)

Question: I want to send simple image through httpgoundation response, from one controller to another. Here's my code:
    $string = (string)md5(uniqid());
    $string = substr($string, 0, $length);

    $image = imagecreate(200, 50);
    imagefill($image, 0, 0, "#000000");

    $headers= array(
        'Content-type'=>'image/jpeg',
        'Pragma'=>'no-cache',
        'Cache-Control'=>'no-cache'
    );

    $response = new Response( $image, 200, $headers );

    return new Response($response);

The error says The Response content must be a string or object implementing __toString(). Seeking the answer using google I only found people who want to return file somewhere from server(an asset). What should I do to get this working?
Answer: You have to use return $response; instead of return new Response($response);
And you have to convert image resource to string. Do the following:
    $string = (string)md5(uniqid());
    $string = substr($string, 0, $length);

    $image = imagecreate(200, 50);
    imagefill($image, 0, 0, "#000000");

    $headers= array(
        'Content-type'=>'image/jpeg',
        'Pragma'=>'no-cache',
        'Cache-Control'=>'no-cache'
    );

    ob_start();
    imagejpeg($img);
    $imageString = ob_get_clean();

    return new Response( $imageString, 200, $headers );

Comment: seems like working, thanks! But now in that another controller do you have any idea how to convert it to image, because I've got like a big, strange string. I used `imagecreatefromstring()` but it returned only something like:  `Resource id #11`


dygraphs change values/legend background

Question: I'm using dygraphs on a dark background and can't seem to get the background on the legends/values to be transparent.
CSS I've tried:
.dygraph-legend {
  background:none;
}

and
.dygraph-legend {
  background-color: transparent;
}

I can't find a way to make this transparent.
Link to an image of the problem: here
Answer: dygraphs sets some inline styles on the legend <div>. To override them, you need to use !important:
.dygraph-legend {
  background: transparent !important;
}

Answer: Add another div right after the dyGraphs div and tell the graph to use this div for labels and style the labels div with the !important annotation. E.g.:
CSS:
.dyStatsLegend {
color: silver !important;
background: rgba( 255, 255, 255, 0.1 ) !important;
}

HTML:

JavaScript:
var g1 = new Dygraph(
    document.getElementById("dyGraphHumTemp"),
    data,{
        labelsDiv: 'dyGraphHumTempLabels'
    });


Multi-line push notification flutter

Question: I am using the flutter_local_notifications package for push notifications. But in a notification tray, I want to show the complete message, no matter how many lines it takes. This is the code I have written
<code>void showNotification(message) async {
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      Platform.isAndroid ? 'com.headstrt.app' : 'com.headstrt.app',
      'Flutter chat demo',
      'your channel description',
      playSound: true,
      enableVibration: true,
      importance: Importance.Max,
      priority: Priority.High,
      styleInformation: BigTextStyleInformation(''),
    );

</code>
I have specified a style also but still, all lines are not being displayed.
Comment: Tried giving the full text in `BigTextStyleInformation('')`?
Comment: It actually displays like that
Answer: In BigTextStyleInformation, you must specify the message value passed to the showNotification function.
my own code as an example;
<code>  Future<void> _demoNotification(Map<String, dynamic> icerik) async {

  String longdata = icerik["notification"]["body"];

  var bigTextStyleInformation = BigTextStyleInformation(longdata); //multi-line show style

 AndroidNotificationDetails androidPlatformChannelSpecifics =
 AndroidNotificationDetails(

        'push_messages: 0',
        'push_messages: push_messages',
        'push_messages: A new Flutter project',
        importance: Importance.max,
        priority: Priority.high,
        showWhen: false,
        enableVibration: true,
        styleInformation: bigTextStyleInformation);

NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);

await flutterLocalNotificationsPlugin.show(
    1,
    icerik["notification"]["title"],
    icerik["notification"]["body"],
    platformChannelSpecifics,
    payload: icerik['data']['routing']);

    }
</code>
Comment: Note that the title of notifications is always single line and might also get truncated because of the icon or time information (e.g. `5min ago`). We found that limiting ourselves to 30 chars for the title almost always ensures to never be truncated (but the extrem is 11 chars depending on the language).
Comment: Thanks for BigTextStyleInformation(longdata) this Property @eyponder , but i am already using BigPictureStyleInformation() ..Is there any way to use both of this properties together? i am unable to assign both.
Answer: It's actually not really up to you. In Android, the default for a single notification is on line. If you want to see the entire message you need to drag the notification down.
Comment: It doesn't work. I can't drag the notification down.

Multi-line push notification flutter


Migrate module only imports first line of CSV file

Question: I have a Migrate module class that works with CSV files and when I go through with the import it only goes through the first line of the CSV and then completes with a success message.  That one line is imported correctly and the data is in place, but I'm wondering why it continues to stop at the first line.
When I run the import again it does not import anything and completes with success message again, mostly likely because the first line is already imported.
Any ideas?
<code>class UserMigration extends MyMigration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $this->description = t('Import Users');
    $columns = array(
      0 => array('username', 'Username'),
      2 => array('email', 'Email'),
    );

    $this->source = new MigrateSourceCSV(drupal_get_path('module', 'my_module') . '/Users.csv', $columns);
    $this->destination = new MigrateDestinationUser();
    $this->addFieldMapping('name', 'username');
    $this->addFieldMapping('mail', 'email');
    $this->addFieldMapping('roles')
         ->defaultValue(DRUPAL_AUTHENTICATED_RID);
    $source_key = array(
      'username' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      )
    );
    $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationUser::getKeySchema());

  }
}
</code>
Comment: Is it possible that the CSV is saved with line endings in the wrong format? Be default, I think Migrate expects Unix format.
Comment: @DaveBruns Re-generating the file with Uniux file endings worked perfectly.  You may want to make this an answer to the question so I can accept it.
Comment: @DaveBruns I believe that would be culprit.  I've been having issues with these CSVs as they are saved from Server '03 and I'm on a Mac.  I will re-generate the files on this machine and try again.
Answer: It's possible that the CSV is saved with the wrong line endings. Try saving the CSV file with Unix-style line endings. By default, I believe Migrate expects a Unix format text file.


discrete probability question

Question: <code>    Suppose we randomly choose a byte (8 bits). What is the
 probability that the byte has at least two 1's?
</code>
Can someone explain why is the answer 247/256 and what formula do you need to do this problem?
Answer: Subtract from $\dfrac{256}{256}$ the probability of the complement: the probability that the byte has (NO 1's or exactly/only a single 1.)
(1) Probability of zero 1's: $\dfrac 1{2^8} = \dfrac 1{256}$
(1) Probability that the byte has exactly one digit 1 = $8\cdot\dfrac{1}{256}$
$$\dfrac{256}{256} - \left(\dfrac {1}{256} + \dfrac {8}{256}\right) = \dfrac {247}{256}$$
That leaves you with the probability that a byte has two or more $1'$s
Comment: Thanks. Very helpful. Maybe you can take the test for me tomorrow.

discrete probability question


Word search puzzle on vb, how do I show the completed grid after the words have been entered?

Question: I'm trying to create a program that asks the user to enter 10 words they would like hidden in a word search puzzle then show the completed grid.
How do I show the completed grid after the words have been entered? when the words are entered the program doesn't do anything until I press enter which closes it
code
   Dim grid(14, 14) As String
    Dim choice As Integer
    Dim word As String
    Dim wordcount As Integer = 0
    Dim row As Integer
    Dim col As Integer
    Sub outputgrid()
        For i = 0 To 14
            For j = 0 To 14
                Console.Write(grid(i, j))
            Next j
            Console.WriteLine()
        Next i

    End Sub
    Sub setupgrid()
        'sets the grid
        For i = 0 To 14
            For j = 0 To 14
                grid(i, j) = ""
            Next j
        Next i
    End Sub
    Sub Main()
        setupgrid()
        outputgrid()
        Words()
        fillEmptyCells()
        Console.ReadLine()
    End Sub
    Sub Words()

        wordcount = 0
        Do
            Console.WriteLine("choose word")
            word = CInt(Console.ReadLine)
            Showdirection()
            Console.WriteLine("choose row")
            row = CInt(Console.ReadLine())
            Console.WriteLine("choose column")
            col = CInt(Console.ReadLine())
            grid(row, col) = word(0)
            For i = 0 To Len(word) - 1
                Select Case choice
                    Case 1
                        col = col + 1
                    Case 2
                        col = col - 1
                    Case 3
                        row = row + 1

                    Case 4
                        row = row - 1

                    Case 5
                        col = col + 1
                        row = row + 1
                    Case 6
                        col = col - 1
                        row = row + 1

                    Case 7
                        col = col + 1
                        row = row - 1

                    Case 8
                        col = col - 1
                        row = row - 1
                End Select
                grid(row, col) = word(i)
            Next
            wordcount = wordcount + 1
        Loop Until wordcount = 10
    End Sub
    Sub Showdirection()
        Console.WriteLine("choose direction")
        Console.WriteLine("1 horizontal- left to right")
        Console.WriteLine("2 Horizontal -Right to Left")
        Console.WriteLine("3 Vertical -Down")
        Console.WriteLine("4 Vertical -Up")
        Console.WriteLine("5 Diagonal – Down L To R")
        Console.WriteLine("6 Diagonal – Down R To L ")
        Console.WriteLine("7 Diagonal – Up L To R ")
        Console.WriteLine("8 Diagonal – Up R To L ")
        choice = CInt(Console.ReadLine())
    End Sub
    Private Sub fillEmptyCells()

        Dim random As New Random()
        For i = 0 To grid.GetUpperBound(0)
            For j = 0 To grid.GetUpperBound(1)
                If grid(i, j) = "" Then

                    grid(i, j) = Chr(random.Next(65, 90)).ToString()
                End If

                grid(i, j) = grid(i, j).ToUpper()
            Next
        Next
        End

    End Sub

Comment: Does this answer your question? [word search puzzle on vb](https://stackoverflow.com/questions/70384137/word-search-puzzle-on-vb)
Comment: @Calaf no he wants someone to write code to finally display the grid. He hasn't tried anything yet however according to the code above, which does incorporate my fixes from the previous question.
Comment: It `"doesn't do anything"` because you have not written any code to make it do anything. Write some code, and if it doesn't work then come here with a question about it.
Comment: how do I write a code to make it display the grid? Don't know where to start
Comment: If you used a DataTable instead of a 2 dimensional array of String (grid), you could set the DataSource Property of a DataGridView to the the DataTable.
Comment: Oops! Never mind. I see this is console app.
Comment: `word = CInt(Console.ReadLine)`  `word` is declared `As String`. Why are you converting a String to an Integer and then trying to assign it to a String variable. Turn on Option Strict now and forever. Project Properties -> Compile tab. Also for future projects Tools -> Options -> Projects and Solutions -> VB Defaults
Answer: I got rid of most of the Module level variables and moved them to where they are used. If a variable is only used in a single method it should be declared as a local variable.
I got rid of the setupgrid method and changed fillEmptyCells to check for Null or Empty.
Don't call outputgrid until after you filled the grid.
To stop the errors in Words method, I added an If statement that checked if you row and col were in range of the grid.
In the fillEmptyCells method I got rid of the line where you called ToUpper. The ASCII codes you provided are all uppercase characters. Also, in the call to Random.Next, I changed the second parameter to 91 so you could include Z.
Next includes the first parameter and excludes the second.
It will be easier to pick out the words from the grid because they may be in lower case. This might be good while you are debugging but afterwards in the Words method Dim word = Console.ReadLine.ToUpper makes the puzzle harder.
I think you will see that input words may be overwritten. You could add checks to prevent this. If you want to allow an additional word when a word won't fit put wordcount -= 1 directly before the Exit For.
Private grid(14, 14) As String

Sub outputgrid()
    For i = 0 To 14
        For j = 0 To 14
            Console.Write(grid(i, j))
        Next j
        Console.WriteLine()
    Next i
End Sub

Sub Main()
    Words()
    fillEmptyCells()
    outputgrid()
    Console.ReadLine()
End Sub

Sub Words()
    Dim wordcount As Integer
    Do
        Console.WriteLine("choose word")
        Dim word = Console.ReadLine '.ToUpper after debugging
        Dim DirectionChoice = Showdirection()
        Console.WriteLine("choose row")
        Dim row = CInt(Console.ReadLine())
        Console.WriteLine("choose column")
        Dim col = CInt(Console.ReadLine())
        grid(row, col) = word(0) 'First letter of word
        For i = 1 To Len(word) - 1 'don't start at zero, you have already assigned the zero element
            Select Case DirectionChoice
                Case 1 'horizontal- left to right
                    col = col + 1
                Case 2 'Horizontal -Right to Left
                    col = col - 1
                Case 3 'Vertical -Down
                    row = row + 1
                Case 4 'Vertical -Up
                    row = row - 1
                Case 5 'Diagonal – Down L To R
                    col = col + 1
                    row = row + 1
                Case 6 'Diagonal – Down R To L
                    col = col - 1
                    row = row + 1
                Case 7 'Diagonal – Up L To R
                    col = col + 1
                    row = row - 1
                Case 8 'Diagonal – Up R To L
                    col = col - 1
                    row = row - 1
            End Select
            If col > 14 OrElse col < 0 OrElse row > 14 OrElse row < 0 Then
                Console.WriteLine("Word won't fit")
                Exit For
            End If
            grid(row, col) = word(i)
        Next
        wordcount += 1
    Loop Until wordcount = 2 '10
End Sub
Private Function Showdirection() As Integer
    Console.WriteLine("choose direction")
    Console.WriteLine("1 horizontal- left to right")
    Console.WriteLine("2 Horizontal -Right to Left")
    Console.WriteLine("3 Vertical -Down")
    Console.WriteLine("4 Vertical -Up")
    Console.WriteLine("5 Diagonal – Down L To R")
    Console.WriteLine("6 Diagonal – Down R To L ")
    Console.WriteLine("7 Diagonal – Up L To R ")
    Console.WriteLine("8 Diagonal – Up R To L ")
    Dim choice = CInt(Console.ReadLine())
    Return choice
End Function
Private Sub fillEmptyCells()
    Dim random As New Random()
    For i = 0 To grid.GetUpperBound(0)
        For j = 0 To grid.GetUpperBound(1)
            If String.IsNullOrEmpty(grid(i, j)) Then '<---
                grid(i, j) = Chr(random.Next(65, 91)).ToString() 'Next includes the first parameter and excludes the second
            End If
        Next
    Next
End Sub

Answer: I don't think I understand the problem well, but let's try to find a solution.
You already have a method that allows you to print what you've entered into the grid, and that's outputgrid().
If you want to see the result at the end, you need to change the main as follows:
Sub Main()
    setupgrid()
    outputgrid() 'This the initial empty grid...
    Words()
    fillEmptyCells()
    outputgrid() 'This is the filled grid
    Console.ReadLine()
End Sub

If you want to see the result after each user action, you need to add the same thing in the sub Words() loop:
Sub Words()
    wordcount = 0
    Do
        '* your original code *
        outputgrid() 'Grid with current data
    Loop Until wordcount = 10
End Sub

One more thing... If I'm not misunderstood, you're trying to put words in the grid, right?
With the lines
Console.WriteLine("choose word")
word = CInt(Console.ReadLine)

you are allowing the user to enter only numbers (due to CInt).


when to choose predictive power of a model over explainability?

Question: I am currently working on a binary classification with 1000 records. class distribution is 75:25
I tried both logistic and random forests, My results are better for random forests.
However, when I try Xgboost, they are even better than random forests.
Meaning, the recall for minority class increases by 3 points (from 39 to 42).
And our business objective is to identify/predict the negatives correctly (missing negatives is costly and critical for the business).
My questions are as follows
a) As a data scientist, considering the dataset size, I am not naturally inclined to try Xgboost because I feel it is overkill for such a small dataset. note, I already tried hyperparamter tuning for RF. I could only get 39% recall for minority. So, should I go for Xgboost for the sake of predictive power?
With the advent of Explainable AI solutions like Lime, Shap etc, do you think it is okay to go for high end models like boosting even for small dataset if predictive power is important?
Comment: I think this is opinion-based, or at least the reasoning for choosing your approach is entirely up to you. In a perfect world, all models would be easily interpreted, but that's not reality. So either interpretability is the top priority, and you use a model that you can interpret, or precision of the model is the top priority, and you use the best model. If Lime/Shap/etc solves the interpretation problem, so much the better, but the sequence of questions you've asked about how to understand Lime/etc suggests that they're challenging tools to use.
Comment: There exists a Pareto front of choices of models under these criterion. Try to aim for a Pareto-efficient choice.
Answer: It really depends on exactly what kind of interpretability you need.
I understand your feeling that XGBoost is overkill. However, it is the best thing you found, right? So, might as well use it? Unless it's causing issues because of computation constraints, I'd go ahead with XGBoost (if you're confident there's no overfitting going on).
So, what kind of interpretability do you need? If you need some kind of broad measure of feature importance, then you can certainly get that with these complex methods! The only thing you can't really get with something like XGBoost (that you could easily get with logistic regression) is a super direct feature coefficient representing "If you increase this variable by 1, the prediction will go up/down by X". LIME and Permutation Feature Importance are great tools that, I think, will take care of your interpretability needs in most cases.
Comment: That last sentence doesn't even apply in all *linear* models! If you have an $x_1x_2$ interaction term, then how much $y$ changes when you increase $x_1$ depends on the value of $x_2$.
Comment: @Dave You're right, but I just mean that it's pretty straightforward to extract that information from linear regression or logistic regression, interaction terms or not.
Comment: Thanls for your help.


Replacing a 'Teaser'-themed node in a View its it's 'Full Content'-theme using ajax in Drupal 7

Question: So, basicly, I have a Drupal 7 view that's displaying Teasers of Nodes.
WHen a user clicks this teaser, I want the node to load it's "Full Content"-content instead, and I would like this to be done using Ajax.
I've looked around a lot but I can only find solutions for Drupal 6, and many good solutions at that, but I'd love some help with figuring this out in D7!
Thank you!
Answer: You can try using the jQuery load method.
<code>$('#teaser').load('node/exampleid #node-container');
</code>
Replace your teaser data with full-text.
The second method is to load hidden full-text with teaser in view; then, via jQuery on click method, just replace teaser by hidden-text.


Linux network services

Question: I'm trying to motivate a class to learn about some of the common types of services that are run on Linux systems, things like httpd, ssh, ftp, etc. What services should I teach? What would be the most interesting to the students while still being simple enough to work as an introductory teaching tool?
Comment: What exactly do you mean with Linux services?
Comment: Is this to use them as clients, or manage the services on the server, or configure the services from a fresh install?
Answer: What do you mean by "linux service"? My guess is that you mean run a class about some of the services typically run on Linux machines -- DNS, email, web serving -- in which case your classes aren't about Linux, they're about internet infrastructure.
Who is your target audience? Are they CS students, Windows admins, hobbyists, programmers? If they know nothing about the internet and aspire to be sysadmins or network admins then DNS is a pretty good place to start; it's fundamental to most other services and easily overlooked. Teach them how the name resolution system works, how data is (mostly) decentralized and what problems they can expect to see.
Same goes for HTTP and email: teach them what happens when you type URL into a browser or how your email finds its way to them.
Once you've worked out who you're teaching and to what ends you can figure out how to motivate them. If you're teaching CS students perhaps it'd be a good idea to show how failures in the internet infrastructure should be handled by software, or (maybe going OT) how algorithms are used in the modern internet (ie OSPF uses Dijkstra's algorithm to establish route weights).
Comment: They are beginners, the majority of them dont understand very well a firewall. The class is about networking with linux, but if I start talking about tcp/ip I lose their attention very quickly. Im showing them apache, ssh, and ftp. Thanks for the dns and email idea.
Answer: I think, like much of teaching, there will be three groups of students:

the students who grok it.  Tell them to go segment a network and place a firewall between the zones and they'll ask "should I make it IPv4 or IPv6?"
The students who will flounder through no matter what
The students who will do it if you pique their interest

So I'm going to target the 1st and 3rd by saying make it cool.  For the second... well they'll have to do it if they want a grade.
So depending on what service you want to target, pick something cool in it, and get them to do that.

Squid?  Get it running Upside-Downternet for the entire network
DHCP?  Segment the netwrok into 10.0.x.x and 10.1.x.x and then have them use shorewall (I find it so much easier than iptables) to segment the network and have the upside-down script only affect part of it
Firewalls?  DoS a computer or the server.  Brute-force a password.  Tell them to set up a rule so you can't access it to do that.
DNS?  Have them redirect anyone visiting facebook to some other site.  Redirect google to live.msn
FTP?  Have them set it up, then do some packet-sniffing, steal a file, and then have them set up SFTP.  Same with telnet and SSH

Linux network services


Required Validation not working on mat-select with [(NgModel)]

Question: I have a Material Stepper, in the second Step I have 4 mat-select. All the selects are required, but the problem is that with ngModel I'm binding the property inicialized in my models (example Id=0) so the select is always "valid" even if the user doesn't touch the select and if so he can move on to the next Step.
I have simplify the code so it's easier to understand:
<mat-step [stepControl]="secondFormGroup">
              <form [formGroup]="secondFormGroup">
                <ng-template matStepLabel>Tipo de Proyecto</ng-template>
                <mat-form-field>
                  <mat-label>Disciplina</mat-label>
                  <mat-select name="discipline" formControlName="discipline" [(ngModel)]="project.disciplineId" required>
                    <mat-option>---</mat-option>
                    <mat-option *ngFor="let disciplin of disciplines" [value]="disciplin.id">
                      {{ disciplin.name }}
                    </mat-option>
                  </mat-select>
                </mat-form-field>

                  <button class="btn-atras" mat-button matStepperPrevious>Atras</button>
                  <button mat-button matStepperNext>Siguiente</button>

              </form>
</mat-step>

Model:
export class ProjectRequest {
    name: string;
    objective: string;
    description: string;
    startDate: Date;
    estimatedEndDate: Date;
    locationId: number;
    disciplineId: number;
    categoryId: number

    constructor() {
        this.name = "",
        this.objective = "",
        this.description = "",
        this.startDate = new Date(),
        this.estimatedEndDate = new Date(),
        this.locationId = 0,
        this.disciplineId = 0,
        this.categoryId = 0
    }
}

component.ts:
project = new ProjectRequest;

ngOnInit(): void {
    this.secondFormGroup = this._formBuilder.group({
      discipline: [null, Validators.required]
    });
}

So I've been looking everywhere for an answer and I don't know how to fix it. Thank you!
Edit: I fixed it just setting null at all the initial values for my selects in their respective model. Anyway, idk if this is the right way.
Comment: in stackblitz you will have the dependencies section on the left side... you will get one text field to enter the package name to add
Answer: You figured out the correct answer here, mat-select required validator requires that the value of the bound property must be null.  Setting the values to null is fine, but sometimes I run into issues when the model has a non-nullable integer value and defaults to 0.  (Like from an API).
In cases like this you would want to create a custom validator.  Here is one that only considers a positive number the only valid value.
export function selectRequiredValidator(ctrl: AbstractControl): ValidatorFn
{
    return (control: AbstractControl): { [key: string]: any } | null => {
       return (control.value && control.value > 0) ? null : { required: { value: control.value } };
    };
}

Set to your control:
this.form.controls['discipline'].setValidators([selectRequiredValidator, Validators.required]);


How difficult is source-level detection of arrays of runtime bounds?

Question: The (accepted) proposal for "Runtime-sized arrays with automatic storage duration (N3639)" asserts that

Stack overflow becomes more likely, in particular if the size depends on external input and is not properly checked. Some environments might therefore prohibit the use of the feature. Such a prohibition can be easily enforced with a static analysis tool.

I do not consider enforcement to be easy if it requires the analyzer to implement a full C++ compiler.
Consider the following code:
template<typename T>
inline void array_user( const T& x )
{
    int a[f(traits<T>::omega)];
}

It looks to me like the analysis needs to be repeated for each use of array_user<T> and consider:

Applicable specializations of traits<T> discoverable at the point of use of array_user<T>
Whether traits<T>::omega is a compile-time constant expression (either via constexpr or C++03 approaches such as enum)
The type of traits<T>::omega
Whether the applicable overload of f() (at the point of use of array_user<T> and possibly found via ADL) is constexpr

Am I missing something?  Is it possible to enforce such a restriction without going through full compilation?
Can code be written in such a way to simplify verification of non-use of runtime bounds?
Comment: Considering that [N3652 makes almost everything legal in `constexpr` functions in C++1y](http://isocpp.org/files/papers/N3652.html), writing a general static analyzer will require you to implement an interpreter as well as a compiler.
Comment: @Casey: Is it guaranteed that every `constexpr` function will return a compile-time constant if its parameters are compile-time constants?  Or can it depend on specializations of templates consumed (possibly indirectly) by the `constexpr` function?  I still feel like that can be determined via type analysis, without actually computing the result of the `constexpr` function (and all the execution that entails)
Comment: I'm not worried about a general static analyzer for the purposes of this question, just one to detect use of runtime bounds.
Comment: Comment was really meant generally, and not to address this specific question. `constexpr` functions are only guaranteed to be evaluated at compile time when used in a context that requires a constant expression - I'm certain how they interact with arrays of runtime bound. So it may be necessary to determine if the arguments are constant expressions to determine if an array has static or runtime bound.
Comment: @Casey: I agree, that's what I meant by the bulleted list in my question.  But you allude to something else.  In C++11, an array bound is required to be a compile-time constant, and so it forces the compiler to evaluate any `constexpr` functions at compile-time.  In C++14, would the compiler be able to choose to make an array of runtime bound even when a statically-sized array would be feasible, and then evaluate `constexpr` functions at runtime?
Comment: The array declaration wording favors static bounds(N3690 8.3.4p1): "If the expression ... is a core constant expression whose value is N, the type of the identifier of D is "derived-declarator-type-list array of N T". Otherwise, the type of the identifier of D is "derived-declarator-type-list array of runtime bound of T" ...". I believe that an implementation is required to produce a static-sized array if possible.
Comment: @Casey: That's a relief.  However, it still might mess up 5.19p6, which uses an array bound as an example of "a context where an integral constant expression is required".
Answer: If I were tasked with writing an analyzer to statically verify non-use of runtime-bounds, I would reject the above code.  I would require all array declarations to either use an integral literal for the bound or be annotated to have the compiler reject runtime-bounds.
template<typename T>
inline void array_user( const T& x )
{
    int a[f(traits<T>::omega)];
    sizeof a;
}

However, given the number of compilers that currently provide C99-style VLAs in C++ mode as an extension, I'm not confident that they would actually conform to the C++14 behavior of forbidding sizeof.
Comment: Clang/gcc allow `decltype` for VLAs, and clang allows `typeinfo()` as well. I think template deduction is the only way to force static bounds easily that works in today's compilers ([example](http://coliru.stacked-crooked.com/view?id=8f37bb9c196e4b0e360d60ead3e03eae-e1204655eaff68246b392dc70c5a32c9)).


Angular Controller organization and ui-router

Question: I am trying to make a simple list display, but I am having some concerns about Controllers organization.
In my application, I have 2 states, items and state2. In items, I want to display a list of Items, and "something else" in state2.
But I also have a + button at the top of my application that can add an item to my list. And I want that button to be displayed in both states. Here is an illustration:

Now, I would like to put my items related functions, in a specific controller ItemsCtrl. So this would be my routes:
myApp.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise("/items");
  $stateProvider
    .state('items', {
      url: "/items",
      templateUrl: "partials/items.html",
      controller: "ItemsCtrl"
    })
    .state('state2', {
      url: "/state2",
      templateUrl: "partials/state2.html",
      controller: "State2Ctrl"
    });
});

And this would be my ItemsCtrl:
myApp.controller('ItemsCtrl',function($scope){
  $scope.items = ["One",'Two'];
})

And now, I make a new MainCtrl to handle the + button that should be present on any page:
myApp.controller('MainCtrl',function($scope){
  $scope.promptItem = function(){
    var result = prompt('Add Item', 'New Item', ['ok'], 'Zero');
    $scope.items.push(result.input1); //This line doesn't work
  }
})

What is the best organization for this kind of interface? Do I really need to put my $scope.items in my MainCtrl?
I'd rather not, and the best thing I think would even be to put the promptItem function in ItemsCtrl, what do you think?
Thanks a lot for your answers, I am completely new to this world :)
EDIT: Here is my HTML structure, my + button is in the root file:
<button ng-click="promptProduct()">Add Item</button>
State 1
State 2

Answer: This is probably a great place to leverage an Angular service. The problem from what I understand is that you are struggling to share state between different parts of your application. I would recommend creating, e.g. a ListService, as such:
myApp.service('ListService', ListService);

function ListService () {
  this.list = ['One', 'Two'];
}
ListService.prototype = {
  addItemToList: function (newThing) {
    var item = // some initialization of an item from the passed value
    this.list.push(item);
  }
};

You can then inject ListService anywhere you need access to the data itself. Both the list view and the state2 need it -- the former to actually render the list, and the latter to modify its contents. The method I described above lets you separate the data (the list itself) from the presentation / UI interaction.
[edit]
Likewise, if you want a button that lets you add a new item in both of your views, you could create a directive that receives ListService and prompts the user with a modal when clicked.
Comment: Thanks for showing me services, I didn't know that, but I am not sure this is adapted, because this would suit if my `+` button was both inside the first view and the second view. In my case, the button is in the root file, outside the `ui-view`. I edited the question with the HTML `index.html` file. Tell me if I am wrong
Comment: Ah, I see. You could also inject ListService into your MainCtrl, and there would not be a problem. This ends up not being terribly different from your initial solution, in the end.
Comment: Yes, I think that this is what I am going to do, put my `$scope.items` in `MainCtrl`, I guess if I need a `+` on top of my application that this is enough to consider the `items` as part of the "Main Data", thanks for the advices!
Comment: @cmw I would still prefer a service and a directive if the plus button is out of `ui-view`.


Do you do linear regression in logistic regression?

Question: I just studied single & multiple linear regression 2 days ago now I'm reading about logistics regression and I want to implement it from scratch, I just want to know If my understanding about logistic regression is correct.
You see I was actually quite confused about logistic regression, In my understanding in logistics regression we still use the equation of linear regression
$$\hat{y} = \hat\beta_0+\hat\beta_1x_1+\cdots+\hat\beta_nx_n$$
so what I think is happening here is:

first find the best-fit-line, and for that to happen we need to find  the beta coefficient just like multiple linear regression
after finding the $\hat\beta$ coefficients, we plug them in the sigmoid function along with our independent variables to get the prediction, $$P(x) = \frac{1}{1+e^{-(b_0+b_1x_1+...+b_nx_n)}}$$ and then that's it.

Is that how it's done? or was that wrong? or was there some steps we need to do first or after?
Comment: There is a lot more to logistic regression than what you state. There are quite a few more steps and the steps you have stated are not correct as you have them. There are many references on logistic regression, both online and in print. It would be easier to help you if you cited the reference you are following and explained which equations from the reference you are trying to implement.
Comment: Also, it would surely help for you to try out one of the readily available logistic software tools first before trying to write you own version yourself. Then you would at least have an appreciation for the data format and output from logistic regression.
Answer: The simplest way of likening logistic regression to standard linear regression is using the latent variable interpretation.  The logistic regression model can be described by considering the observable responses:
$$Y_i = \mathbb{I}(Y_i^* > 0),$$
based on the unobservable latent variables:
$$Y_i^* = \beta_0 + \beta_1 x_{i,1} + \cdots + \beta_m x_{i,m} + \varepsilon_i
\quad \quad \quad \varepsilon_1, ... \varepsilon_n \sim \text{IID Logistic}(0, s).$$
As you can see, in this model form the latent response variable follows a linear regression model with an error term that has a logistic distribution.  We observe whether the latent response variable is above zero or not, but we do not observe its actual value.  For estimation purposes, this manifests in a substantial difference in estimating the coefficients in the model.  We do not estimate using OLS estimation, so this is not "just like multiple linear regression".  Nevertheless, we do indeed get estimated coefficients and this does get us an estimated function for the conditional probability of the response outcome, so there are certainly similarities.
Answer: No, it is not done like this. Quoting my other answer

Logistic regression can be described as a linear combination
$$ \eta = \beta_0 + \beta_1 X_1 + ... + \beta_k X_k $$
that is passed through the link function $g$:
$$ g(E(Y)) = \eta $$
where the link function is a logit function
$$ E(Y|X,\beta) = p = \text{logit}^{-1}( \eta ) $$

As you can see, the linear predictor $\eta = \mathbf{X}\boldsymbol{\beta}$ is not equal to the conditional mean of $y$, but you need to transform it first using the inverse of the logit link function $g^{-1}(\eta)$. If you just ran the linear regression, you would be ignoring the fact that the transformation of the linear predictor happens.
You can easily verify this yourself, run linear and logistic regression on the same data. If using linear regression would be enough, you should get the same regression parameters. As you can see from the example below, that's not the case.
<code>> lm(vs~mpg+cyl, data=mtcars)

Call:
lm(formula = vs ~ mpg + cyl, data = mtcars)

Coefficients:
(Intercept)          mpg          cyl
   2.164638    -0.008217    -0.252454

> glm(vs~mpg+cyl, family=binomial, data=mtcars)

Call:  glm(formula = vs ~ mpg + cyl, family = binomial, data = mtcars)

Coefficients:
(Intercept)          mpg          cyl
    15.9714      -0.1633      -2.1482

Degrees of Freedom: 31 Total (i.e. Null);  29 Residual
Null Deviance:      43.86
Residual Deviance: 17.49    AIC: 23.49
</code>
Logistic regression is fitted by using an optimization algorithm that maximizes the likelihood function. The likelihood function is defined in terms of Bernoulli distribution:
$$
L(\boldsymbol{\beta}|y;\mathbf{X}) = \prod_i\, g^{-1}(\mathbf{X}_i\boldsymbol{\beta})^{y_i} \, (1 - g^{-1}(\mathbf{X}_i\boldsymbol{\beta}))^{1-y_i}
$$
Commonly IRLS algorithm is used for finding the maximum of this function, but you probably could ignore this fact and live a happy life without that knowledge.
Comment: I lack the statistical depth of this answer, but my understanding of the question is OP simply asking if we perform linear regression in logistic. The first step (the linear combination part) is where we perform linear regression - off course, there's much more to logistic regression - and I think that's all he needs to know.


Confused about the concept open set

Question: Because I read different book find there are two definition and they aren't look like a same thing.
Definition 1 from GTM27
A set is open if it's a member of a topology,
and topology is a family of sets which satisfies:
1)the intersection of any two members is still a member.
2)the union of any two members is still a member
Definition 2 from baby rudin
Let  X be a metric space. All points and sets mentioned below
are understood to be elements and subsets of X.
A set S is open if every point of S is an interior point of S.
and a point p  is an interior point of X if there is a neighborhood N of p such  that  N is contained by X.
A  neighborhood  of a  point p is a set  N(P) consisting of all points q such  that  d(p,q)< r.
definition 2 is complex.
So I try to make it become simpler to find the relation between the two concept.
I thought a set S is open if for every point p of S there is a set N such that N is the subset of X and consist of all points q that d(p,q)

But I still don't find any similarities between the two concept.
In first definition,we know the definition of open set only depends on the concept of set.
But the second definition tell us the definition depends on point and the set.
This is what I am confused now.
Comment: A set S is open if every point of S is an interior point of S means that every point in the set has a neighborhood lying in the set.
Answer: The two definitions are slightly different in the sense that they refer to different contexts. Definition 1 is for open sets in a topological space, while definition 2 is for open sets in a metric space. But it turns out that each metric on a space can define a topology on it such, that open sets of the metric space satisfy the properties of definition 1 (for open sets in topological spaces).
Answer: @frabala's answer above is adequate enough according to me but I wish to clarify the following:

"I thought a set S is open if for every point p of S there is a set N
  such that N is the subset of X and consist of all points q that
  d(p,q)"

The argument is not entirely wrong. But this is what you should instead gather. A set $S$ is open iff for every point $p \in S$, there is a neighbourhood of $p$ (i.e. a set $N$ - which though should contain an open set in itself for it to be a neighbourhood) entirely contained in $S$ - not $X$. But such a set  $N$ is definitely a subset of $X$ too as it is a member of the Topology.
To further cement the distinction between the definitions might want to read this question and its answer.

Confused about the concept open set


Why is the mixtures of conjugate priors important?

Question: I have questions about the mixture of conjugate priors. I learned and saw the mixture of conjugate priors a couple of times when I am learning bayesian. I am wondering why this theorem is such important, how are we going to apply it when we are doing Bayesian analysis.
To be more specific, one theorem from Diaconis and Ylivisaker 1985 illustrated a theorem as this:

Given a sampling model $p(y|\theta)$ from an exponential family, any prior distribution can be approximated by a finite mixture of conjugate prior distributions.

More specifically, given prior $p(\theta)=\int p(\theta|\omega)p(\omega)d\omega$, we can derive the posterior:
$p(\theta|Y)\propto\int p(Y|\theta)p(\theta|\omega)p(\omega)d\omega\propto\int \frac{p(Y|\theta)p(\theta|\omega)}{p(Y|\omega)}p(Y|\omega)p(\omega)d\omega\propto \int p(\theta|Y, \omega)p(Y|\omega)p(\omega)d\omega$
Therefore,
$p(\theta|Y)=\frac{\int p(\theta|Y, \omega)p(Y|\omega)p(\omega)d\omega}{\int p(Y|\omega)p(\omega)d\omega}$
Comment: The theorem you quote is not true. The version you describe is about hierarchical priors, not [conjugate priors](http://en.wikipedia.org/wiki/Conjugate_prior). Please rephrase your question correctly.
Comment: Oh, you forgot the "approximation" and the "finite" in the statement!!! "Any prior can be approximated by a finite mixture of conjugate priors" is the right quote, with the approximation not working in terms of tail behaviour.
Comment: This is not an answer to your question, but it is good to remember that in many cases you do not have to use conjugate priors for sampling (check [here](http://stats.stackexchange.com/a/126266/35989)).
Comment: @Xi'an may I also have another question? Why should we always emphasize on "finite" mixture model? In other words, is there infinite mixture model?
Comment: @Xi'an Thanks. This quote originates from the paper . It is on the bottom of page 13.
Comment: Yes, there are infinite mixture models, an infinity of them! For instance, Dirichlet processes are a sort of infinite mixtures. The estimation of those mixing processes $p(\omega)$ is however of another order of magnitude.
Answer: Calculating posteriors with general/arbitrary priors directly may be a difficult task.
On the other hand, calculating posteriors with mixtures of conjugate priors is relatively simple, since a given mixture of priors becomes the same mixture of the corresponding posteriors.
[There are also many cases where some given prior may be quite well approximated by a finite mixture of conjugate priors -- this makes for a suitable approach in some situations, when that can give approximate posteriors that are sufficiently close to the exact one.]
Comment: The main point in Diaconis & Ylvisaker (1985) is indeed to show that finite mixtures of conjugates are (a) conjugates and (b) offer more flexibility than the original conjugates. They also require more prior information to decide about the hyperparameters, which is why they are not used that much. But it remains untrue that any prior is a mixture of conjugate priors!
Answer: To extend @Glen_b's answer just slightly, one implication is that we can get a closed form approximation to the posterior when a non-conjugate prior is used by first approximating the non-conjugate prior with a mixture of conjugate priors and then directly solving for the posterior of the approximation.
However, in general this method seems quite tricky to use. While it's true that you can make the mixture prior arbitrarily close to the non-conjugate prior, there will generally be some error in any finite approximation. Small errors in the prior can easily propagate to huge errors in the posterior. For example, if the prior is well approximated except on the extreme tails, but the data provides strong evidence that the parameters values are in the extreme tails, these errors on the extreme tails of the prior will lead to errors in high probability regions of the posterior.


open new page with json data without refreshing page

Question: Hi i have one json of users from which i have fetched  data and populated list of user.. now here is the tweak When user clicks on this list od user, page (Screen 2) opens in same window without page refresh or redirection with all the information of that particular user with his details present in json.
{
    "data": {
        "show_dashboard_access_page": false,
        "login_status": "signedin",
        "new_io": true,
        "bst_users": [{
            "userA": {
                "user_logo": "image path",
                "partner_since": "Jan 2013",
                "status_now": "bronze",
                "year_calculated": 2016,
                "total": 300000,
                "year_wise_usage": 123000,
                "storage_wise_usage": 73000,
                "server_wise_usage": 50000,
                "order": 1
            },
            "userB": {
                "user_logo": "image path",
               "partner_since": "Feb 2014",
               "status_now": "silver",
                "year_calculated": 2016,
                "total": 300000,
                "year_wise_usage": 160000,
                "storage_wise_usage": 60000,
                "server_wise_usage": 100000,
                "order": 2
            },
            "userC": {
                "user_logo": "image path",
                "partner_since": "Mar 2014",
                "status_now": "silver",
                "year_calculated": 2016,
                "total": 300000,
                "year_wise_usage": 180000,
                "storage_wise_usage": 80000,
                "server_wise_usage": 100000,
                "order": 3
            }
            }]
    },
    "success": true
}

code till to fetch the user list on screen 1:
$.getJSON( "jsonpath", function( response ) {
  $.each(response.data.bst_users, function(idx,obj){
         $.each(obj, function(key, value){
            console.log(key + ": " + value);
            var item = "
   " + "" + key +  "" + "
"
             $('ul').append(item);
           });
    });
 });

Answer: Here is an example that shows what I mean:
<!doctype html>

                    {{user.name}}

{{current.name}}

{{current.age}}

                back

The JavaScript file; app.js:
(function(){
    var app = angular.module("app", []);
    users = [
        {"id": 1, "name": "Palle", "age": "48"},
        {"id": 2, "name": "Peter", "age": "11"}
    ];
    app.controller("UsersController", ["$scope", "$http", function($scope, $http) {
        $("#user").hide();
        $scope.users = users;
        $scope.go = function(id) {
            console.log(id);
            $("#users").hide();
            $("#user").show();
            $scope.current = $scope.users.find(function(element) {
                return element.id === id;
            });
        };
        $scope.back = function() {
            $("#user").hide();
            $("#users").show();
        };
    }]);
}());

Comment: Thanks man u saved me...just last question if u dont mind look at my json it has nest data object under which it has bst_users whic then has user how can we access this deep json linking
Answer: Consider using AngularJS. It is perfect for this kind of thing. In the controller for the link simply replace the main div with one containing the single user information.
You should consider having two different feeds; one for the list of users and one for an individual user.
Comment: i tried but i am new to it dont know what to do after this:

        var myApp = angular.module('myApp', []);
        myApp.controller('mainCtrl',function( $scope , $http){
    $http.get('jsonpath').success(function(data){
    $scope.user = data;
    console.log(user)
    })
    })


Real Analysis Proof Verificaition

Question: Suppose $f$ is defined on all of ${\Bbb R}$, and satisfies, $|f(x)-f(y)|\leq(x-y)^2$ for all $x,y\in {\Bbb R}$. Prove that $f$ is constant.
Basically I have,
$|f(x)-f(y)|\leq(x-y)^2 \Rightarrow \frac{|f(x)-f(y)|}{(x-y)}\leq(x-y)$.
$\Rightarrow \lim_{\ x\to\ y}\frac{|f(x)-f(y)|}{(x-y)}\leq \lim_{\ x\to\ y}(x-y)$.
$\Rightarrow f^{'}(x)\leq 0, \ \forall x\in{\Bbb R}$.
Case 1: if $f^{'}(x)= 0$ then we're done.
Case 2: if $f^{'}(x)< 0$???
Well I don't even know if I'm going about this right. Any hints?
Answer: You've really shown more: Using the fact that $(x - y)^2 = |x - y|^2$, we have
$$0 \le \left|\frac{f(x) - f(y)}{x - y}\right| \le |x - y|$$
Now take the limit as $y \to x$, and we see from the Squeeze (Sandwich) Theorem that
$$0 \le |f'(x)| \le 0$$
Comment: AHHh, I was almost there. Thanks a lot!!
Comment: @Faraad You're very welcome.

Real Analysis Proof Verificaition


Making CSS code segment compatible with multiple browsers?

Question: I have about a weeks worth of CSS/HTML experience and have been stumped on this issue for about half an hour now. I really do not know how to adapt this code segment in order for it to run successfully on different browsers. It works fine on Chrome, aligning the pictures in a row of four, evenly spaced, but does not work for Safari. I have not tested whether or not it works on Firefox. If someone could show me how to adapt this code, I would appreciate it greatly.

#containermain {
  display: flex;
  justify-content: space-between;
}
#containermain div {
  width: 250px;
  height: auto;
  background: rgb(255, 255, 255, 0);
}
#containermaintext div {
  width: 250px;
  height: auto;
  background: rgb(255, 255, 255, 0);
}
#containermain div:first-child {
  border-left: 0;
}
#containermain div:last-child {
  border-right: 0;
}

Comment: Which version of Safari are you testing on? If 6.1 or below, I recommend `-webkit-` before the `display: flex` and `justify-content: space-between`.
Comment: Check this to see the browser support: http://www.w3schools.com/cssref/css3_pr_justify-content.asp . Older browsers need vendor specific tags, like -moz- for firefox, -webkit- for safari, etc.
Answer: I'm on a PC and don't have safari to check it, but I recommend adding in-line block to the inside divs like this:
        #containermain div {
             /*width: 250px;*/
             width: 20%;
             display:inline-block;
             height: auto;
             background: rgb(255,255,255,0);
         }

I also changed the width so that it will scale responsively and not break into another row.


Counterexample to Nullstellensatz (Problem 1.32 in Fulton's book)

Question: Problem 1.32 in Fulton's Algebraic Geometry asks to show that the following corollary to the Nullstellensatz is false if $k$ is not an algebraically closed field:
If $I$ is a radical ideal in $k[X_1,\ldots,X_n]$, then $I(V(I)) = I$. So there is a one-to-one correspondence between radical ideals and algebraic sets.
It is easy to find a counterexample to show that the usual correspondence between radical ideals and algebraic sets (given by the maps $V$ and $I$ in Fulton's book) fails to be one-to-one if $k={\mathbb R}$. But strictly speaking,  if I wanted to show that the second sentence in the corollary is false, I would need to prove that there is no other map whatsoever that could set up such a correspondence. This seems quite difficult to me, and maybe not even true.
Comment: One needs to be more precise about the nature of the "correspondence". If one simply means a set bijection, for example, then probably there are lots of one-to-one correspondences. Presumably, though, one means a correspondence that respects some structure of the sets of radical ideals and subvarieties.
Comment: I agree. There is no precise definition of what a "correspondence" is in the book and normally one would take that to mean any bijection, but it seems that is not what the author had in mind.
Answer: Such a one-to-one correspondence never exists when $k$ is finite. In this case, there are finitely many algebraic sets since they are subsets of $\mathbf A^n_k = k^n$, but there exist infinitely many radical ideals (e.g. there is one for each irreducible polynomial over $k$).
I'm afraid that's the only source of examples. When $k$ is infinite, on one hand, there exist $|k|$ algebraic sets because every point is itself an algebraic set and $|k^n| = |k|$. On the other hand, since $k[x_1, \dots, x_n]$ is Noetherian with Krull dimension equal to $n$ and there are at least $|k|$ radical ideals corresponding to the points in $k^n$ , we see that there are also exactly $|k|$ radical ideals. So, if by one-to-one correspondence you just mean any bijection, there will be (infinitely many) one-to-one correspondences between radical ideals of $k[x_1, \dots, x_n]$ and algebraic sets.


react bootstrap accordion dynamic data collapsing does not work

Question: In react bootstrap, i am using accordion here hardcode data working finer, if i implemented dynamic data not working, (ex) first panel open, if i click second panel then first panel does not closed, and ****enter image description hereif panel open need to change tile color****
class CollapseContentComponent extends React.Component {
 render() {
   return (

<Accordion>
<Panel header={this.props.collapseTitle} eventKey={this.props.collapsemainKey}>

</Panel>
</Accordion>

   );
 }
}

Answer: I would recommend you to use Controlled PanelGroups https://react-bootstrap.github.io/components/panel/#panels-controlled, So you don't need to manage opening and closing of others.
      <PanelGroup
        accordion
        id="accordion-controlled-example"
        activeKey={this.state.activeKey}
        onSelect={this.handleSelect}
      >
        <Panel eventKey="1">
          <Panel.Heading>
            <Panel.Title toggle>Panel heading 1</Panel.Title>
          </Panel.Heading>
          <Panel.Body collapsible>Panel content 1</Panel.Body>
        </Panel>
        <Panel eventKey="2">
          <Panel.Heading>
            <Panel.Title toggle>Panel heading 2</Panel.Title>
          </Panel.Heading>
          <Panel.Body collapsible>Panel content 2</Panel.Body>
        </Panel>
      </PanelGroup>

Comment: If i using above method i got error like     :    Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `CommonHelpCollapseContentComponent`.
Comment:

Panel heading 1

Panel content 1
Comment: The above link archive, So https://web.archive.org/components/panel/


Cardinality and Rank Nullity Theorem

Question: Let $V$ be a vector space and $f$ a nonzero linear functional on $V$. Then $\text{dim image}(f)=1$ and $\text{dim null}(f)+\text{dim image}(f)=\text{dim}V$. And if $\text{dim}V<\infty$, then $\text{dim null}(f)=\text{dim}V-1$.
I'm confused as to why $V$ needs to be finite dimensional in order to conclude $\text{dim null}(f)=\text{dim}V-1$. Can't we just say that if $\text{dim}V\not<\infty$, we have $\text{dim}V-1=\text{dim}V$?
Comment: It's not an exact duplicate, but it follows as a special case from there which is good enough
Comment: @StellaBiderman If it isn't too much trouble, could you elaborate a bit further? To be clear, I'm not asking if the rank-nullity holds for infinite dimensional $V$, which seems to be what most of the discussions in that link concern.
Answer: You don't need $\dim V<\infty$ for this to hold, although it is often excluded because defining subtraction on cardinals is generally not done (though in this context it can be).
Here we have a discussion of the fact that the rank-nullity theorem holds for infinite dimensional $V$ using cardinal arithmetic. In this problem, we have the equation $1+\alpha=\alpha$ for $\alpha = \dim V$. Subtraction of a finite cardinal from an infinite cardinal can be defined and gives $\kappa - x = \kappa$ for all $\kappa\geq\aleph_0$ and $x<\aleph_0$. Therefore we have $\dim V - 1=\dim V=\dim\text{null}(f)$ just as you say.
The reason that defining subtraction for cardinals is often not done is that $\alpha-\beta$ is problematic when both $\alpha,\beta\geq\aleph_0$. If $\beta >\alpha$, then there isn't even an answer, since there aren't negative cardinals!
Comment: And the conclusion is: one can certainly say that $\dim\operatorname{null}(f)=\dim V-1$, but it has no useful consequence at all unless $V$ is finite dimensional.

Cardinality and Rank Nullity Theorem