Why is there storage limit in Cloud Bigtable?

Question: Google's Cloud Bigtable uses their Colossus filesystem to store data. I thought this would mean an instance with even a single Node could handle any size of data (assuming of course there is little enough reads and writes that Nodes CPU can handle it).
Even in documentation it states:

Importantly, data is never stored in Bigtable nodes themselves; each node has pointers to a set of tablets that are stored on Colossus.

I could imagine an application where Node(s) handle data stream from many IoT devices and store them in Bigtable. Most of that data would be rarely accessed, thus most of Node's CPU work would be in storing new data in Bigtable, and only some in accessing very old entries.
Yet, in quotas documentation one could learn that there is a per Node storage limit:

If a cluster does not have enough nodes, based on its current workload and the amount of data it stores, Bigtable will not have enough CPU resources to manage all of the tablets that are associated with the cluster. Bigtable will also not be able to perform essential maintenance tasks in the background. As a result, the cluster may not be able to handle incoming requests, and latency will go up. See Trade-offs between storage usage and performance for more details.

To prevent these issues, monitor storage utilization for your clusters to make sure they have enough nodes to support the amount of data in the cluster, based on the following limits:

SSD clusters: 5 TB per node
HDD clusters: 16 TB per node

...

Important: If any cluster in an instance exceeds the hard limit on the amount of storage per node, writes to all clusters in that instance will fail until you add nodes to each cluster that is over the limit.

I don't understand where this limitation is coming from. Just because some data is laying still in Colossus should add CPU usage to a Node, nor occasional background moving around few terabytes of data shouldn't be a problem for today's hardware? I thought the idea of using Colossus was to allow for limitless storage, yet the limitation suggest nodes could just use own storage without any smart networking filesystem.
Or am I missing something and one can configure a single Cluster and single Node instance that will be able to access e.g. 100TB of data? And the limits are for some internal Node cache?
Comment: It takes resources to manage resources. 1 TB of data is a huge amount even today. Storage is organized into 4 KB storage blocks. 100 MB/sec transfer speed is considered good. Do the math to figure out how many blocks are required for your storage or how long it will take to copy data. For efficient lookups, CPU and memory are required even for lazy data. You must ask a Google engineer or consult a whitepaper (if there is one) on why those numbers were chosen.
Comment: Hmm, in doc "Rebalancing tablets from one node to another happens quickly, because the actual data is not copied. Bigtable simply updates the pointers for each node." - while this mentions rebalancing and not other maintenance work, it suggest that there should be not much work to be done for older data that lays still (and is just occasionally accessed).
Comment: From this [document](https://cloud.google.com/bigtable/docs/performance#storage-performance): ***When storage utilization increases, workloads can experience an increase in query processing latency even if the cluster has enough nodes to meet overall CPU needs. This is because the higher the storage per node, the more background work such as indexing is required. The increase in background work to handle more storage can result in higher latency and lower throughput.*** Also this part: ***For latency-sensitive applications we recommend that you keep storage utilization per node below 60%.***
Answer: Cloud Bigtable has storage limits due to performance and operational reasons, not hardware constraints. These limits ensure high performance, balanced data distribution, and efficient maintenance. Exceeding them may affect reliability and scalability.
Reasons for storage limits in Cloud Bigtable:

Storage limits ensure that each node can efficiently manage and handle the data it contains, maintaining good performance.

Setting storage limits prevents a single node from becoming overloaded with excessive data, which could negatively impact system performance and scalability.

Too much data per node could make these tasks resource-intensive and affect overall performance.

Limiting data per node enables easy replication for data redundancy and fault tolerance.

Always refer to the latest documentation to stay updated on Cloud Bigtable's storage limits.
Comment: The "documentation" link in your answer has an extra character at the end that breaks the link. Remove the last character - it looks like a double-quote.


Get data form into hook_node_insert / hook_node_update

Question: How to recover data from my form 'node' from the hook 'node_insert' or 'node_update'. Because I created a textfield and I can't see from the "$node" variable
Answer: The $node object will be populated with the data from the form, the way for form is defined.
You can do something like this
hook_form($node, &$form_state) {
  $form = array();

  $form['my_value'] = array(
    '#type' => 'textfield',
    'title' => t('Some title'),
    '#default_value' => isset($node->my_value) ? $node->my_value : '',
  );

  ....

  return $form;
}

Then get the value on the node object.
hook_insert($node) {
  $my_value = $node->my_value;
}

Answer: Values contained in the $form_state['values'] array are copied in the $node from entity_form_submit_build_entity($entity_type, $entity, $form, &$form_state), which is called by node_form_submit_build_node(), the function called by the submission handler for the node edit form (node_form_submit()).
The function is called as entity_form_submit_build_entity('node', $node, $form, $form_state), and contains the following code:
  // Copy top-level form values that are not for fields to entity properties,
  // without changing existing entity properties that are not being edited by
  // this form. Copying field values must be done using field_attach_submit().
  $values_excluding_fields = $info['fieldable'] ? array_diff_key($form_state['values'], field_info_instances($entity_type, $bundle)) : $form_state['values'];
  foreach ($values_excluding_fields as $key => $value) {
    $entity->$key = $value;
  }


How to see JS documentation in VS Code rather than 'any'

Question: How do I configure VS Code to provide JS documentation, for example on the filter method?
Whenever I hover over filter, I get any which is highly useless.

I've looked at this SO question and was able to get ⌘ + Shift + Space working for triggering parameter hints, but that only works inside parentheses where the parameters go.
(Show definition preview hover doesn't work for me either as per this answer, which makes me sad.)
I've even reinstalled VS Code.
I've tried installing docs view, but that gets any too:
Answer: I'm pretty sure you're not getting suggestions from JavaScript Array methods because what you're writing is not valid JavaScript. What you've written (new int[size]) is like Java / C++ syntax. In JavaScript, you do new Array(size).fill(0). Once you write legitimate JavaScript, you'll get what you want.


How to get current language in 3ds max script

Question: I find all the help files of 3ds Max Script Reference, but can't get the api about get current language.
I already try 3ds Max System Globals and MAXScript System Globals
Answer: See sysInfo.getMaxLanguage().


kotlin simple_list_item_1 onclicklistener not working

Question: I am building a shopping list App and this is one of the activities.
Basically the activity takes a database of all locations around the house and extracts a list of the names to create an arrayList of Strings for display.
After that it binds the prepareListView to a variable prepareList and creates an arrayAdapter with a layout of simple_list_item_1.
After attaching the adapter it sets the onItemClicListener.
The Listview works perfectly but I cannot get the onClickListener to work.
I have searched this site and also generally on the internet without finding a solution.  I can get the listener to work with a custom adapter but it is an overkill for what I am trying to do.  Most of the solutions are Java which seems very different to Kotlin in implementing the onClick function.
<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.prepare)

    // populate the home locations array
    val  prepareHomeLocations = productDatabase!!.getAllHomeLocations()

    // create a reduced array for displaying
    val reducedHomeLocations = ArrayList<String>()
    for (items in prepareHomeLocations.indices) {
        reducedHomeLocations.add(prepareHomeLocations[items].homeArea)
    }

    // bind the listView
    var prepareList = findViewById<ListView>(R.id.prepareListView)

    // create an adapter
    val adapter =
        ArrayAdapter(this@Prepare, android.R.layout.simple_list_item_1, reducedHomeLocations)

    // attach the adapter
    prepareList.adapter = adapter

    // set the onItemClicListener
    prepareList.setOnItemClickListener { parent, view, position, id ->

        Toast.makeText(this@Prepare, "item Clicked", Toast.LENGTH_SHORT).show()
    }
}
</code>
Is it that the onClickListener will not work with a simple_list_item_1 view?
Answer: Thanks Taseer - really appreciated
This got me really puzzled
I had worked all day yesterday and had tried your suggestion along with countless other combinations so unfortunately I posted one of the incorrect variations I tried.  I put it back this morning but to no avail - still the click listener did not work. However, armed with the knowledge that it was the correct code I went searching the Internet once again and found a ListView example at https://android--code.blogspot.com/2018/02/android-kotlin-listview-example.html
I created a new project and copied in the code - it worked perfectly and so I was at least moving forward with working code.
I could not see any significant differences in my code to the one I downloaded and so to make sure I copied the xml and kt code into the activity as a total replacement to the code I had written.  This time it did not work.  Thinking that it must be something to do with the linking of the activities, I started from first principles and did the same with the main activity.  This way, the main activity of the working example and that of the programme I am creating are identical.  Still it did not work !!
The problem was therefore nothing to do with the code as it is identical between the two projects.  I started searching deeper.  First made the two Gradle file and the Manifest file the same and deleted off all the other activities I had created....... still not working!
Finally looked at the last option - Styles and, yipee, I finally managed to trace the cause of the problem.  I had accidentally set the TextView style parent to Widget.AppCompat.AutoCompleteTextView instead of android:Widget.TextView.
So, I loaded the backup of the programme and corrected this mistake and it is now working properly.  I have absolutely no idea why a different style for the colour scheme should block the operation of the on-click listener but I presume that the AutoCompleteTextView style has it's own listener that took priority.
Once again, many thanks for your help
eggie


Choosing one mixed effects model in a logistic regression

Question: I'm interested in understanding if a count variable (abundance of insects caught in traps) differs between sites (I'll call this "difference effect"), and assessing if this difference may appear in one area but not another one. My experimental design is:
- 2 areas (categorical: area_1; area_2)
- 5 transects (3 in one area and 2 in the other one) (categorical: "A";"B";"C")
- 10 sites (2 sites for each transect) (dummy: 0;1)
- 80 traps (8 in each site) (counts)

My response variable is sites, and my predictors are groups of insects, each of them a count variable.
I can only compare sites within transects (I cannot compare site 1 in transect A to site 0 in transect B; not sure if this means sites are paired), and, as the areas are distinct from one another, I cannot say the difference effect is the same in both areas, I have to separate this effect somehow.
I'm running logistic regressions in order to know if there is a "difference effect" (a group of insects being more abundant) in one of the sites compared to the other one (within transects and in the same area). It is necessary that transects be integrated as random effects in my models.
I can think of two options for modelling this: one option is to run separate analysis for each area, like so:
model_area_1 <- glmer(Sites ~ group1 + group 2 + group3 + group4 + (1|Transect),
family = binomial(link = "logit"), data = df_area_1)

model_area_2 <- glmer(Sites ~ group1 + group 2 + group3 + group4 + (1|Transect),
 family = binomial(link = "logit"), data = df_area_2)

The first model has N = 48 and group Transect = 3, while the second one has N = 32 and group Transect = 2.
In the other option, transects would be included as nested within areas in one model:
model_both_areas <- glmer(Sites ~ group1 + group 2 + group3 + group4 + (1|Area/Transect),
 family = binomial(link = "logit"), data = df_both_areas)

This model has N = 80 and groups Transect/Area = 5 and Area = 2.
I have two questions:
1) is one of the options better than the other? (maybe I should compare them using AIC?). Again, my objective is to understand if a group of insects is more abundant in one site instead of the other, taking into consideration that this might happen in one area, but not in the other.
2) is there any reason for me to use another link function? I saw this answer which says that extensive variables should be dealt with using log link function, so I think this is correct in my models.
Hope this question is pertinent and I have been clear.
Comment: Could you elaborate on why your outcome is sites and not counts of insects?  Seems like it should be the other way around
Comment: Thanks for commenting. My outcome is site because I'm trying to assess if a group of insects is more prone to be on site 0 than 1 (or vice-versa). I'm using logistic regression as if it was a discriminant function.
Answer: Assuming that your outcome really is binary:
You don't have enough areas to model it as a random effect so the 3rd model is not viable.
However you can run model 1 and 2 on the same dataset with the addition of Area as a fixed effect.
This will have the advantage of giving more statistical power than individual models for each area.
glmer(Sites ~ group1 + group 2 + group3 + group4 +  Area + (1|Transect),
 family = binomial(link = "logit"), data = df_both_areas)
The logit link has the benefit of providing easily interpretable results, so I would keep that.
Comment: Thank you for your answer. But could you explain why I don't have enough areas to model as random effects? Residual DFs are the same on the model I thought of and on the one you mentioned. (Btw, I voted on your answer but I still haven't enough reputation for the score to appear)
Comment: You have 2 areas, right ? The model assumes that random effects are multivariate normal, but you can't expect to estimate a variance for something with only 2 observations. Se here: http://glmm.wikidot.com/faq "Treating factors with small numbers of levels as random will in the best case lead to very small and/or imprecise estimates of random effects; in the worst case it will lead to various numerical difficulties such as lack of convergence, zero variance estimates, etc."
Comment: Ok, I understand that, but if I leave Area as a fixed effect, that's still going to happen, isn't it?
Comment: No, it won't. As a fixed effect only, there is no random component for it.


Convergence of rational approximation error series

Question: Question:
For any $x\in\mathbb R$ define the sequence $a_n=\min_{p\in\mathbb Z}|x-p/n|$, does there exist $x\notin\mathbb Z$ such that $\sum_{n=1}^\infty a_n$ converges?

Some thoughts:
If $x\in\mathbb Q\setminus\mathbb Z$ we can show $\sum a_n=\infty$. Indeed, let $x=c/d$ then $a_n\geq\frac1{dn}$ if $d{\not|}\ n$, which readily implies $\sum a_n=\infty$.
For $x\in\mathbb R\setminus\mathbb Q\ $ I got stuck. By Dirichlet approximation theorem we have $a_n\leq\frac1{n^2}$ for infinitely many $n$, but we do not know how often this inequality holds. We do have $a_n\leq\frac1{2n}$ for all $n$, but this does not help to test the series convergence. I am also searching existing results for some lower bound $a_n\geq\cdots$ for all $n$, but most of the approximation theorems only concern $a_n\leq\cdots$ for some $n$, which makes this direction difficult.
Any hint or comment will be much appreciated, thanks in advance!
Comment: I suspect one can prove $a_n>1/(10n)$ for at least half of all large $n$, from which divergence should follow.
Comment: @GerryMyerson Thank you for the comment, the idea does work out (as pointed out in the answer).
Answer: Your $a_n=\min_{p\in\mathbb Z}|x-p/n|$ is, in other words, simply $\left|\frac{\{nx\}}{n}\right|$, where the fractional part $\{\cdot\}$ is understood to have a range of $(-0.5,0.5]$, instead of the standard $[0,1)$.
Now, for irrational $x$ these values of $\{nx\}$ are known to be distributed uniformly on the resulting interval, as $n$ approaches $\infty$. In line with the suggestion from Gerry Myerson, this means that $a_n>\frac1{10n}$ for $0.8$ of all $n$ asymptotically, or for $(0.8-\varepsilon)$ fraction of them for all sufficiently large $n$, hence the series diverges.
So it goes.
Comment: Nice explanation, it is indeed intuitive that this boils down to the distribution of $\{nx\}$, and I found some sources for the u.d. of $\{nx\}$, like [here](https://math.stackexchange.com/questions/2441927/do-the-multiples-of-an-irrational-number-modulo-1-cover-the-unit-interval-unifor) or in this [book](https://web.maths.unsw.edu.au/~josefdick/preprints/KuipersNied_book.pdf). Thank you very much for the answer.


Use git to extend changes

Question: I have a set of files (file1.. fileN), they all have the same structure, but this structure can be different each time (json, xml, text... is undefined, but it is always the same type of information)
I need to do a change in all of them so if I add a field in an xml it must be in all of them. The same when I add a new line in a plain text.
I've thinking to use git for this purpose, I could do the change in one of the files and then merge this file in the other ones.
File1:
<code>{name: "Harry",
 lastname: "Potter"}
</code>
change:
<code>{name: "Harry",
 lastname: "Potter",
 age: 12}
</code>
file2:
<code>{name: "Hermion",
 lastname: "Granger"}
</code>
file2 after bing processed:
<code>{name: "Hermion",
 lastname: "Granger",
 age: 12}
</code>
I know you can use a json parser to do it but since the information can be plain text or another different kind of information it is not valid in this case, I need a way to do the changes when the structure is the same not based in the information encoding.
Is it possible?
How can I do it?
Comment: Git is not the right tool at all for this. You'll need to write something up for each format. (Or use a single format and write a tool to convert from that to all the other formats you need.)
Answer: I figured out a way:
You can get a git diff and apply it later:

https://stackoverflow.com/a/1191449/4670625

Also, you can get the ids of the previous git commits:

https://stackoverflow.com/a/32324539/4670625

When files are different or in different branches you can use:

Git: How to diff two different files in different branches?

There is a good explanation about diff and patch here:

https://www.pair.com/support/kb/paircloud-diff-and-patch/

All together, you get the id of the previous 2 commits, then you do a diff between them and apply it later.
EDIT:
you can get a diff using:

git diff file1 file1Modified > changes.patch

then you apply it using:

patch file2 changes.patch
Comment: The patch won't apply (at all, or not cleanly) if the context around it changes as it does in your example.

Use git to extend changes


How to create a custom menu

Question: I have created a menu called "navbar". In this menu, there is 4 links at level 1. Each of these links has 3 sublinks (level 2). All links in the menu point to a different page.
For example, I have on lvl 1 "Projects" (that points to /projects). That parent links contains 3  lvl 2 subsections : "News" (projects/news), "Photos" (projects/photos) and "Maps" (projects/maps).
Then I create an article, I check the "Provide a menu link" and I select "News" in the dropdown list.
I have "menu block" installed, and I configured a "navbar" block to be bound to the "navbar" menu. I also installed "menu node" to have a table with the mapping between nodes and menus.
Now, how do I customize the menu to display all lvl 1 & 2 and all associated articles ? What function do I need to create and where ?
I have tried the following code to no avail (where business is my theme's name and 2 is the menu id) :
function business_menu_link__menu_block__menu_navbar($variables)
function business_menu_tree__menu_block__menu_navbar($variables)
function business_menu_link__menu_block__2($variables)
function business_menu_tree__menu_block__2($variables)

What should I do ?
Comment: Just use the normal menu block provided by Drupal itself and set all menu items to "Always show as expanded".
Comment: It seems you've [another](http://drupal.stackexchange.com/users/39629/sopsop) account in DA. Please see [I accidentally created two accounts; how do I merge them?](http://drupal.stackexchange.com/help/merging-accounts)
Answer: Ok I found what was wrong :
I needed to register the function in the template.php :
function business_theme_registry_alter(&$theme_registry) {
    $theme_registry['menu_tree__menu_block__menu_navbar']['function'] = 'business_menu_link__menu_block__menu_navbar';
}
function business_menu_link__menu_block__menu_navbar($variables) {

}

How to create a custom menu


Changing Facecolors in four dimensional matplotlib surface

Question: I'd like to draw a matplotlib surface plot with 4 dimensions. Originally, I would have the data in:
[(X, Y, Z, P)]

So I'd like to have a 3D Surface, but with a colormap, that is represented by the values of P.
I saw an quite good solution for my problem here.
So I splitted my data into two datasets:
 1. [(X, Y, Z)] (called data in my code) and
 2. [(X, Y, P)] (called shade in my code)

and tried to implement what Oliver W. suggested at the end of his answer. Unfortunately I get the following error:
Exception in Tkinter callback
Traceback (most recent call last):
  File "c:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
    return self.func(*args)
  File "c:\Python27\lib\lib-tk\Tkinter.py", line 583, in callit
    func(*args)
  File "C:\Users\Raphael\Documents\NetBeansProjects\GammaVolaFund\src\GUI.py", line 413, in repeat
    self.a2.plot_surface(grid_x, grid_y, grid_z, facecolors=fc, rstride=1, cstride=1, linewidth=0, antialiased=False, shade=False)
  File "c:\Python27\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 1625, in plot_surface
    colset.append(fcolors[rs][cs])
IndexError: index 4 is out of bounds for axis 0 with size 4

Here is my code:
if "surface" in val:
                self.a2.cla() #<-- this is the existing axis
                data = val['surface']['surface']
                shade = np.array(val['surface']['shade'])

                x, y, z = zip(*shade)
                z = map(float, z)
                grid_x, grid_y = np.mgrid[min(x):max(x):100j, min(y):max(y):100j]
                grid_z = griddata((x, y), z, (grid_x, grid_y), method='cubic')
                grid_z = np.nan_to_num(grid_z)
                grid_z /= grid_z.max()

                surf = self.a2.plot_surface(grid_x, grid_y, grid_z, rstride=1, cstride=1, cmap='jet',  linewidth=0, antialiased=False, shade=False)
                self.canvas2.draw() #<- this has to be here to be able to use .get_facecolors()
                fc = surf.get_facecolors()

                self.a2.cla()

                x, y, z = zip(*data)
                z = map(float, z)
                grid_x, grid_y = np.mgrid[min(x):max(x):100j, min(y):max(y):100j]
                grid_z = griddata((x, y), z, (grid_x, grid_y), method='cubic')
                grid_z = np.nan_to_num(grid_z)

                self.a2.plot_surface(grid_x, grid_y, grid_z, facecolors=fc, rstride=1, cstride=1, linewidth=0, antialiased=False, shade=False)

                self.canvas2.draw()

I get the values from a queue, that's why it's maybe a bit uncoventional. After recieving the data from the queue I'd like to update my plot as described above. Unfortunaltely my data has not the same length as width, otherwise I could have used Olivers first part.
Does somebody have an idea how to solve this in an ellegant way?

Update: here are the datasets:
Here are the two datasets:
data:
[(7.0, 2025.0, 0.14473006433340618), (7.0, 2030.0, 0.14062607337060892), (7.0, 2020.0, 0.1472362005164195), (7.0, 2040.0, 0.1319299850069502), (7.0, 2050.0, 0.12497732155598347), (38.0, 2040.0, 0.13013012553239645), (38.0, 2050.0, 0.12603323962393054), (38.0, 2020.0, 0.13923258922827567), (38.0, 2025.0, 0.1371105447700807), (38.0, 2030.0, 0.13509217383084055), (7.0, 2035.0, 0.13590798149865668), (7.0, 2055.0, 0.12122832793319385), (38.0, 2045.0, 0.1283033928063951), (38.0, 2055.0, 0.12376727418426803), (7.0, 2045.0, 0.12747859242231532), (38.0, 2035.0, 0.13268757208364956), (28.0, 2040.0, 0.1336849736130551), (28.0, 2045.0, 0.1304881237751081), (28.0, 2050.0, 0.12838196945626767), (28.0, 2055.0, 0.12594690413524617), (28.0, 2020.0, 0.1426266123329183), (28.0, 2025.0, 0.14105151195673143), (28.0, 2030.0, 0.1373925658286551), (28.0, 2035.0, 0.13591663964396278), (0.0, 2040.0, 0.13520161504277875), (0.0, 2045.0, 0.12954944890882458), (0.0, 2050.0, 0.12265378802459166), (0.0, 2055.0, 0.11829387116926045), (0.0, 2020.0, 0.15941121559558222), (0.0, 2025.0, 0.15264786078400508), (0.0, 2030.0, 0.14752256519025417), (0.0, 2035.0, 0.1410671600261568), (14.0, 2055.0, 0.12290037442735217), (14.0, 2050.0, 0.12609729724766153), (14.0, 2045.0, 0.12957885633601618), (14.0, 2040.0, 0.13191236031636167), (14.0, 2035.0, 0.13486885042437866), (14.0, 2030.0, 0.13735387420193756), (14.0, 2025.0, 0.14117139286403094), (14.0, 2020.0, 0.14410654811736545), (21.0, 2040.0, 0), (21.0, 2045.0, 0.1280055085205311), (21.0, 2050.0, 0.1253472936767727), (21.0, 2055.0, 0.12311151990554384), (21.0, 2020.0, 0.14150097628342895), (21.0, 2025.0, 0.13862160845657018), (21.0, 2030.0, 0.1357506086172204), (21.0, 2035.0, 0.1334635475535782), (35.0, 2040.0, 0), (35.0, 2045.0, 0.12909917255032188), (35.0, 2050.0, 0.12671861528494266), (35.0, 2055.0, 0.12432370882456634), (35.0, 2020.0, 0.14029296457584772), (35.0, 2025.0, 0.13813227231612185), (35.0, 2030.0, 0.13606666884642726), (35.0, 2035.0, 0)]
shape:
[(7.0, 2025.0, 1162), (7.0, 2030.0, 381), (7.0, 2020.0, 944), (7.0, 2040.0, 3074), (7.0, 2050.0, 2141), (38.0, 2040.0, 514), (38.0, 2050.0, 393), (38.0, 2020.0, 15), (38.0, 2025.0, 7), (38.0, 2030.0, 30), (7.0, 2035.0, 63), (7.0, 2055.0, 1676), (38.0, 2045.0, 123), (38.0, 2055.0, 2), (7.0, 2045.0, 3924), (38.0, 2035.0, 23), (28.0, 2040.0, 7238), (28.0, 2045.0, 3908), (28.0, 2050.0, 16383), (28.0, 2055.0, 2835), (28.0, 2020.0, 2058), (28.0, 2025.0, 1481), (28.0, 2030.0, 831), (28.0, 2035.0, 1386), (0.0, 2040.0, 9437), (0.0, 2045.0, 0), (0.0, 2050.0, 0), (0.0, 2055.0, 0), (0.0, 2020.0, 0), (0.0, 2025.0, 901), (0.0, 2030.0, 0), (0.0, 2035.0, 0), (14.0, 2055.0, 384), (14.0, 2050.0, 1482), (14.0, 2045.0, 928), (14.0, 2040.0, 800), (14.0, 2035.0, 0), (14.0, 2030.0, 21), (14.0, 2025.0, 124), (14.0, 2020.0, 400), (21.0, 2040.0, 598), (21.0, 2045.0, 385), (21.0, 2050.0, 397), (21.0, 2055.0, 817), (21.0, 2020.0, 40), (21.0, 2025.0, 13), (21.0, 2030.0, 26), (21.0, 2035.0, 24), (35.0, 2040.0, 141), (35.0, 2045.0, 365), (35.0, 2050.0, 324), (35.0, 2055.0, 49), (35.0, 2020.0, 294), (35.0, 2025.0, 422), (35.0, 2030.0, 112), (35.0, 2035.0, 22)]

Comment: you should answer your own question, and accept your answer. You can show the figure too so we can understand more easily what you do.
Comment: Thanks. I'm pretty new to stackoverflow, sorry for that. I attached the answer below.
Answer: Solution: I found a solution for the problem:
self.a2.cla()
data = np.array(val['surface']['surface'])
x, y, z, colors = data[:,0], data[:,1], data[:,2], data[:,3],
grid_x, grid_y = np.mgrid[min(x):max(x):50j, min(y):max(y):50j]
z = griddata((x, y), z, (grid_x, grid_y), method='cubic')
colors = griddata((x, y), colors, (grid_x, grid_y), method='cubic')
y, x = grid_y.ravel(), grid_x.ravel()

y_coords, x_coords = np.unique(y), np.unique(x)
y_centers, x_centers = [ arr[:-1] + np.diff(arr)/2 for arr in (y_coords, x_coords)]

# Convert back to a 2D grid, required for plot_surface:
Y = y.reshape(y_coords.size, -1)
X = x.reshape(-1, x_coords.size)
Z = z.reshape(X.shape)
C = colors.reshape(X.shape)

#Normalize the colors to fit in the range 0-1, ready for using in the colormap:
Z -= Z.min()
Z /= Z.max()

C -= C.min()
C /= C.max()

interp_func = RectBivariateSpline(x_coords, y_coords, C.T, kx=1, ky=1) # the kx, ky define the order of interpolation. Keep it simple, use linear interpolation.

self.a2.plot_surface(X,Y,Z, facecolors=cm.hot(interp_func(x_centers, y_centers).T), rstride=1,  cstride=1, linewidth=1, antialiased=False, shade=False) # only added because of this very limited dataset

self.canvas2.draw()

This doesn't solve the problem with get_facecolors, but if it works this way round. It's fine for me.
This is how it looks like:


If $\kappa$ is an $\eta$-extendible cardinal then it is $\delta$-extendible for every $\delta <\eta$

Question: I have an hint in order to prove the statement in the title:

If $\kappa$ is an $\eta$-extendible cardinal then it is $\delta$-extendible for every $\delta <\eta$.

The hint is to prove that the elementary embedding $j:V_{\kappa+\eta}\longrightarrow V_\beta$ (which exists for some $\beta$ by hypothesis) restricts to an elementary embedding $V_{\kappa+\delta}\longrightarrow V_\beta$.
From this I can conclude, but why is the hint true?
Thank you in advance for any help.
Comment: What's an elementary immersion ? Is it an elementary embedding ?
Answer: Let
$$
j \colon V_{\kappa + \eta} \to V_{\beta}
$$
be an elementary embedding and let $\beta ' := j(\kappa + \delta) < \beta$. I claim that
$$
j \restriction V_{\kappa + \delta} \colon V_{\kappa + \delta} \to V_{\beta'}
$$
is an elementary embedding. Why? Let $\vec{x} \in V_{\kappa + \delta}$ and let $\phi$ be a formula of set theory. Then
$$
\begin{align*}
V_{\kappa + \delta} \models \phi[\vec{x}] & \iff V_{\kappa + \eta} \models "V_{\kappa + \delta} \models \phi[\vec{x}] " \\
& \iff V_{\beta} \models " j(V_{\kappa + \delta}) \models \phi[j(\vec{x})]" \\
& \iff V_{\beta'} \models \phi[j(\vec{x})].
\end{align*}
$$
The last equivalence follows because $j(V_{\kappa + \delta}) = V_{\beta'}$ using both elementarity and the fact that $V_{\beta}$ computes $V_{\beta'}$ correctly. The last part needs a bit justification, if you don't already know this fact.
Comment: Note that it's $V_{\beta'}$ and not $V_{\beta}$ that is the range of the restricted elementary embedding. (You should also note that in fact $\mathrm{ran}(j \restriction V_{\kappa + \delta}) \subseteq V_{\beta'}$ - this may not be self-evident, depending on your prior knowledge.)


Regression curve changed a lot (in the same situation) after a new variable is added into the logistic regression model training

Question: I have a trained logistic regression model with 5 input variables. Then I added another new input variable and used all of them (6 input variables) to train a new logistic regression model. With the obtained coefficients, I got two values based on the logistic function when the inputs are given.
Next, I set the new variable as 0 while the other 5 input variables are all the same. Theoretically, the two values will be close since they are in the exactly same condition.
According to the equation of logistic regression:
<code>probability=1/(1+EXP(-l)),
where l=a0+a1x1+a2x2+a3x3+a4x4+a5x5+a6x6.
</code>
I can get the coefficients of a0 to a6 by regression. When x1 to x6 are given specific values, the probability P1 can be calculated through the above equation.
Then, I added a new variable x7 into the model. So for the new model, I have new coefficients of a0 to a7. Now I give the same value of x1 to x6 in the new equation and x7=0. This is the second probability value P2. In general, P1 should be close to P2, but in my result, they are not.
I try to use this method to check my model with the new variable. But the result shows they have an obvious difference. All the calculation part is correct. So I wonder if it is because of the logistic regression method.
Comment: How do you "get two values based on the logistic function when the inputs are given"? It's not quite clear what you are doing, can you give some more details? Also, how many observations and what kind of predictors do you have? Six predictors is a lot, and you may be overfitting your model (which could lead to highly variable model fits).
Comment: Thank you. I will provide more details. According to the equation of logistic regression: probability=(1/(1+EXP(-l)), l=a0+a1x1+a2x2+a3x3+a4x4+a5x5+a6x6. I can get the coefficients of a0 to a6 by regression. When x1 to x6 are given specific values, the probability P1 can be calculated through the above equation. Then, I added a new variable x7 into the model. So for the new model, I have new coefficients of a0 to a7. Now I give the same value of x1 to x6 in the new equation and x7=0. This is the second probability value P2. In general, P1 should be equal to P2, but in my result, they are not.
Comment: It would help if you could provide the actual regression coefficients for each of the models in your question. Please use the `{}` code tool to format that type of information, to make it easier to read.
Answer: There is no theory that two regressions $\operatorname{E}(Y|X) = g^{-1}\left(\beta_0 + \beta_1x_1\right)$ and $\operatorname{E}(Y|X) = g^{-1}\left(\beta_0 + \beta_1x_1 + \beta_2x_2\right)$ should make the same/similar predictions when you plug in $x_2 = 0$. This would be the case only if the estimates for $\beta_0$ and $\beta_1$ are the same/close. The fact that your model is a logistic (and not, say, linear) regression and that you have more than two variables is irrelevant.
It might help to review how we interpret regression coefficients: $\beta_0$ and $\beta_1$ have a different meaning in the two models, so we can't expect them to have the same value in general. The interpretation is easier in the case of linear regression, so let's assume the link function $g$ is the identity. For illustration purposes, I'll also assume that the variable $X_1$ is gender ($x_1 = 1$ indicates males) and the variable $X_2$ is IQ standardized so that $x_2 = 0$ corresponds to the average IQ in the study population.
In the linear regression $\operatorname{E}(Y|X) = \beta_0 + \beta_1x_1$, the intercept $\beta_0$ is the expected value of Y for females and the coefficient $\beta_1$ is the expected difference in Y between males and females. In the linear regression $\operatorname{E}(Y|X) = \beta_0 + \beta_1x_1 + \beta_2x_2$, the intercept $\beta_0$ is the expected Y for females of average IQ and the coefficient $\beta_1$ is the expected difference in Y between males and females of average IQ.
So the meaning of $\beta_0$ and $\beta_1$ is different and generally we cannot expect the two models to make the same predictions, most obviously in the case when $X_2$ is predictive of the outcome $Y$. (To make the example more concrete, consider what the difference between the two regressions might be if $Y$ is test scores vs if $Y$ is height.)
Comment: The first para is enough to highlight the insight here. +1.


Use CNN for training time-domain data

Question: I have an EEG dataset which is 64 channel data with 1000 data points. I am using mean and standard deviation to extract the time-domain features. I have a very basic question. Can I use CNN to get good classification results for such time-domain data?
I have calculated mean of each channel and subtracted it. I am taking standard deviation of each channel and then dividing each channel by SD. The CNN structure I am using is Conv1D. I know that generally EEG signal's feature extraction is done by taking its frequency features and time-frequency.
But I would like to know if some used just the time domain data and did CNN training on such data. It is really important for me to know.
I have edited the post to add the code. In this code I am trying to use CNN on 2 channels just to check if it works fine when merging the layers. The output is onehot encoded with 40 classes.
<code>        from keras.models import Sequential, Model
        from keras.layers import Dense, Dropout, Flatten, Input, Embedding, concatenate
        from keras.layers import Conv1D
        from keras import optimizers

    inp1 = Input(shape=(1000, 1), dtype='float32', name='c1input')
    conv1 = Conv1D(128, kernel_size= 512, strides=256, input_shape=(1000, 1), name='audConv_l1')(inp1)
    conv1 = Flatten(name='audConv_l2')(conv1)
    conv1 = Dropout(0.3, name='audConv_l3')(conv1)
    a1 = Dense(256, activation='relu',name='rate_l1')(conv1)
    a1 = Dropout(0.15, name='rate_l2')(a1)

    inp2 = Input(shape=(1000, 1), dtype='float32', name='c2input')
    conv2 = Conv1D(128, kernel_size= 512, strides=256, input_shape=(1000, 1), name='audConv_21')(inp2)
    conv2 = Flatten(name='audConv_22')(conv2)
    conv2 = Dropout(0.3, name='audConv_23')(conv2)
    a2 = Dense(256, activation='relu',name='rate_21')(conv2)
    a2 = Dropout(0.15, name='rate_22')(a2)

    AV = concatenate([a1, a2], name='AVRate_l1')

    decOutput = Dense(40, activation='softmax', name='decOutput')
    model = Model(inputs=[inp1, inp2],outputs= decOutput)

    adam = optimizers.adam(lr=0.0001)
    model.compile(optimizer=adam, loss='mse',loss_weights=0.2, metrics=['accuracy'])
    print(model.summary())

    lb = scipy.io.loadmat('label.mat')
    label = lb['label']

    model.fit([c1,c2],label,batch_size=64, epochs=10, validation_data=None)
</code>
The code works fine but the accuracy is coming as 1.0000 which seems a little too right. I have made some mistake for sure but I cannot understand it. If someone faced the same problem. please let me know
Comment: The question is not clear. Yes and No. Please make clearer what you're trying to do, and preferably what your goal is. Time-series analysis is usually a different domain, with very different tools. But unless you make it clearer, what you're trying to achieve, no answer can be given.
Answer: I also work with EEG signals in CNNs, for my experience, what you are doing is basically standardizing each channel $X' = \frac{X-\mu}{\sigma}$ centers it to zero and normalizes the data, that is a good practise. In my experience, EEG signals are quite non-linear, therefore feeding them to a CNN is usually a good idea.
The main issue you will face is that it is difficult to obtain a number of samples (EEG recordings) big enough so that the network will be able to extract knowledge. Another suggestion I'd like to make would be to convert your signal to frequency domain, or even to time/freq domain (for example woth the spectrogram of the signal) since these transformations are non-trivial. And would help the network identify time/freq patterns in the EEG.
Hope this helps!
Comment: Yes. I know about the use of frequency domain or time-freq domain. My question still stands the same, will just the time data not give any information? I am already doing time-freq and freq domain.
Comment: It may give some info, the problem is that it will require more data to train since the problem (as my short experience suggests) will be more complex
Comment: Yes I get that but what structure to follow and what input kind of input has to be given. I have relevant data of 9 channels with 1000 timepoints. I want to know the kind of structure of data that should be given to CNN for time-domain data. Also the CNN structure. I have already made some model , but it is giving an accuracy of 1.00 which is not right.
Comment: The architecture of the network is imposible to determine, there are no laws on how to design CNNs. An accuracy of 1.00 (Over 1, I understand) seems fishy. Personally I would check that the samples presented for training, and test are different. You may have some overfitting there. if the accuracy is 1% then we go back to the main concern, you do not have enough data to train the network. Keep in mind deep architectures have millions of parameters and hence require from huge datasets if the problem is not trivial. How many classes do you have?
Comment: Regarding the structure, your tensor should have a shape of $Batch_size \times n_{time_length} \times n_{channels}$
Comment: I have 40 classes. I understood that something is fishy with the data. I understand that the CNN requires huge data to train but for all EEG related experiments I have seen people achieve accuracy of 80% with 3 or 4 channel input with 500 or 1000 datapoints. I read a lot of papers.

Use CNN for training time-domain data


How can i search file content using Zend studio RSE

Question: I have many folder directories under my Remote System Explorer .
How to Search entire files in a directory for a keyword using Zend studio search?
Comment: Searching many files on a remote server through FTP? That would take a very long time. Essentially, it would have to download every file, search through them, then give you the result. I don't thing Zend Studio allows that as a feature.
Comment: so you saying that .. RSE is connected to server as an ft connection and search is not possible.. grep will be better ..
Comment: Yeah, pretty much. If you have shell access Grep would be much better. :-) Zend should consider adding a search for connections over SFTP where it runs grep for you.
Answer: Bump for @Clint's answer. I have used ZS for a few years, and have never seen a remote search function (goes and double-checks). I looked at the options of a project that I have connected to a remote server and at least on the standard search dialog I don't see it.


3D Plot not showing up

Question: I have plotted this :
fig = plt.figure()
ax = plt.axes(projection= '3d')
zline = np.linspace(0, 16, 10000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, 'red')

However when i plot the following code nothing shows up:
zdata = np.random.random(500)
xaxis = np.sin(zdata)
yaxis = np.cos(zdata)
ax.scatter3D(xaxis, yaxis, zdata, c=zdata, cmap='Greens')

Three is just <mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x20e10b546c8> but the graph is not plotted? Why is that?
Comment: I have a feeling that because you are doing inline plotting you need to create a new figure, just add the first two lines of the first bit of code to the second.
Comment: You are right. That solved it!
Comment: Let me put it as an answer then, glad I could help.
Answer: As you are plotting inline, you will need to create a new figure (as in the first section):
fig = plt.figure()
ax = plt.axes(projection= '3d')
zdata = np.random.random(500)
xaxis = np.sin(zdata)
yaxis = np.cos(zdata)
ax.scatter3D(xaxis, yaxis, zdata, c=zdata, cmap='Greens')

When inline a plot wont update. Hope this helps!

3D Plot not showing up


Allow IMAP for Roundcube and as external service only for some special users. How to configure?

Question: It's easy to set up a special passdb query in dovecot to restrict IMAP access to certain users, e.g. see this documentation on the dovecot wiki.
But when I use a webmailer like Roundcube and want to allow every other user to use it (and not just the users I allowed to use IMAP per method above) this approach fails.
What would be a working configuration idea?
The webmailer is on the same server as dovecot. Maybe a special crafted SQL-passdb-statement along with a allow_nets extra field to the local address for all webmailer-only users? Or a special option in Roundcube itself?
Answer: You could do some sort of CASE statement in your MySQL query, based on the allow_nets field, something like SELECT password CASE WHEN allow_nets = '127.0.0.1' OR <whatever you're using> THEN allow_imap = 'true' ELSE allow_imap = 'false' END FROM users WHERE userid = '%u' and active='1'
Look into the CASE statement, I'm pretty sure mine won't actually work, but the idea should be solid.
Comment: Thanks for the CASE statement suggestion. While you answered I tested a CLAUSE with the %r variable (I'll answer below). Let me (maybe superfluously) add that 'allow_imap' or imap_allowed have no special meaning for dovecot. In the wiki example they are used within the SQL condition itself (as a value of a column).
Comment: Yeah, like I said, it wasn't functional, and I haven't looked at the DB structure in a while..
Comment: No problem, it's a good suggestion. But it's good to not have to add complexity by extra fields and values for my many mailboxes. My SQL statement (the part you don't see in my answer) is right now too long anyway :)
Answer: I found a way to not go into an extra_fields overhead and use a simple variable, '%r', instead. It resolves to the remote ip, so I can use something like
WHERE active = '1'\
   AND ('%s' = 'pop3' OR (imap_allowed = true OR '%r' = '220.127.116.11'))

The default case pop3 is tested first (via '%s') then

who is always allowed to IMAP? (imap_allowed column in the table)
or who uses the webmailer (remote ip == webmailer ip)


Clarification on Continuous Matrices and reference request

Question: I have not been able to obtain a clear definition of what is currently called a 'continuous matrix' nor 'continuous matrix operators.'
It is unclear if the definition would involve a matrix with continuous elements such as continuous functions, or if somehow the matrix itself is to be considered continuous. In the latter case, I would imagine an example of a continuous matrix to be the Green's Function for a function, where integration of a function by its Green's function would be akin to some sort of continuous matrix multiplication.
So I would like to ask:

What is the current accepted definition for a continuous matrix and a continuous matrix operator?
Is there an existing definition for a continuous matrix, of the type I mention, where Green's Function is an example of such a matrix?
If there is such a definition (2.) then does someone know of a clear reference for the theory? I would appreciate both pure and applied works.
Comment: I've never seen the term used anywhere, and a Google search returns very sporadic results, so I don't think this is even an accepted term in the mathematical community. Where in the world are you getting it from? The closest concepts I've found are the product and factorization of matrices that have components which are functions.
Comment: Assuming that you matrix depends on some parameter t it could also mean that the mapping $t \to A(t)$ is continuous in various operator topologies. For example in the uniform topology this means that for every $\epsilon > 0$ there exists $\delta > 0$ such that $\|A(t_1) - A(t_2)\| < \epsilon$ whenever $|t_1 - t_2| < \delta$.
Comment: I believe it's somtimes used in the sense that the coefficients denpend continuously on a parameter - like in the book I link. Nevertheless, it would be better if @Roberto would provide some context. http://books.google.com/books?id=9FHaRYB8kdsC&pg=PA147&dq=%22continuous+matrix+C%28t%29%22&hl=en&ei=O5kWTtbPLYeq8AP2tukO&sa=X&oi=book_result&ct=result&resnum=1&ved=0CCgQ6AEwAA#v=onepage&q=%22continuous%20matrix%20C%28t%29%22&f=false
Comment: Thank you for your responses. If a definition was not readily available then either the theory doesn't exist or is not widely disseminated, which answers my question.
Answer: The question has been answered.
Comment: ... in the comments.
Answer: The term is frequently used in OpenCV when you want to reshape a matrix cv.Reshape() or perform other operations such as implement K-Means algorithm cv.KMeans2() .. I am also trying to find a clear concise definition of the term 'continuous matrix' but have not been able to find one.


Constant Lag in CDC Pipeline (JDBC Sink Connector)

Question: I am running a CDC Pipeline (data streaming) with source DB as PostgreSQL (Debezium Source Connector) and target DB also PostgreSQL with confluent JDBC Sink Connector (10.6.4) reading data from Kafka. I am experiencing a constant lag around 40 messages. And publishing rate is 5 messages per second.
I also a another JDBC Sink Connector running to a different PostgreSQL DB but lag is around 10 messages.
Even though i tried to modify the following properties still lag didn't reduced:
max.poll.records=5000
max.poll.interval.ms=300000
fetch.min.bytes=100000
fetch.max.wait.ms=500
fetch.min.bytes=100000
consumer.override.auto.commit.interval.ms=100
consumer.override.offset.flush.interval.ms=200
batch.size=4000

How do i reduce the lag, so that pipeline works in real time or near real time?
Answer: The issue is most likely because the JDBC sink connector does not actively perform any batch operations when the connector receives a collection of SinkRecord to be processed.
This is an enhancement that is actively being worked on and we plan to introduce batch support in Debezium 2.5.0.Final, due out in December.
If you want to track the progress of this work, please see DBZ-6317
Comment: Does Confluent JDBC Sink (Version 10.6.4)  Connector also doesn't support batch operation?
I am using Confluent JDBC Sink Connector and at Source PG Debezium Sink Connector is being used.
Comment: It should, but you'd need to check the documentation to be sure.


What is the difference between a JOIN and a RELATIONSHIP in hook_views_data_alter()

Question: What is the difference between these two as implemented on hook_views_data_alter()? Why choose one over the other?
I did notice that in setting up a relationship between mytable1 and users tables, the Views UI gave me the option to add the mytable1.uid field under the relationship section, that way allows me to add users fields into the query.
What am I supposed to notice on the views-UI when I implement a join on a table? My implementation is as follows:
mymodule_views_data_alter(&$data){

    $data['mytable1']['table']['join']['users'] = array(
        'left_field' => 'uid',
        'field' => 'uid',
    );

}

I did this without a relationship setting, so I can observe the exclusive effect of each(join vs relationship)
Answer: From my experience, a join is always done when the query is executed. This means that you can utilise the fields on the joined tables without adding a relationship in the view. When a join is used, I don't think the views information tied to that table is pulled in. For example, you won't be able to add relationships tied to that table.
A relationship is a choice that the user can make on the view. They can choose to add the relationship (from the section on the right side of the view). When a relationship is added, the views information tied to that entity is also pulled in. For example, you will be able to add relationships linked to that table.


Simple percentage calculation

Question: This is an easy question, but since I grew dumb in the years, I ask for your help! :)
A = 50%
B = 75%
C = 100%
D = 125%
E = 150%
How can I calculate the value of any of these letters? I'm making a dopesheet and the more I think the more confused I am.
Can have only 1 number. For example:
D is "x". Calculate A,B,C,E.
Etc.
Thanks in advance!
Answer: You would want to obtain value of 1% namely if D is x then we need to divide x by 125,then we can enlarge it as many times as we like be it 50 for 50% or 3 for 3%,that way you can calculate it

Simple percentage calculation


An Ordered Ring does not have zerodivisors

Question: In one of our quizzes one of the questions goes like this:

Show that an ordered ring $R$ does not have zero divisors.

Ordering property satisfies:
i) Closure: for all $a,b\in P$ , $a+b\in P$ , $ab\in P $.
ii) Trichotomy: for each $a\in R$, exactly one of the following hold,$$a\in P , a=0 , -a\in P$$
Zero divisor states that "If $a,b$ are two nonzero elements of $R$ such that $ab=0$ then $a$ and $b$ are divisor of zero."
I tried to prove this and it goes like this:
let $a,b\in R$
then, by closure property, $ab\in P$ and by trichotomy, one and only one of the following hold:$$ab\in P , ab=0 , -(ab)\in P$$
taking $ab=0$, it implies that $a=0$ or $b=0$ , and if this is the case then it is done since $a$ or $b$ must not equal to $0$ by the definition of zero divisor. Therefore ordered ring $R$ has no 0 divisor.
But what I want to ask is that, "what if $ab\neq0$".
Comment: This is not so much a ring question as one about basic proof technique. Given $a\in R$, how would you prove using the definition that $a$ cannot be a zero divisor?
Comment: Trichotomy should be "exactly one of the following...," not "only one of the following... ."
Comment: The "Taking $ab=0$, it implies that $a=0$ or $b=0$" is very wrong; that statement is only true if $R$ has no zero divsors, which is what you are trying to prove.
Answer: $R$ has no zero divisors iff $a,b \ne 0 \implies ab\ne 0$. Let's prove that then.
Take $a,b \in R$ with $a,b \ne 0$. Then:

If $a,b \in P$, then $ab \in P$ and so $ab\ne 0$ because $0 \notin P$.
If $a \in P$ and $b \notin P$, then $-b \in P$ and $-ab=a(-b) \in P$ and so $ab\ne 0$ because $0 \notin -P$.
If $a \notin P$ and $b \in P$, then $-a \in P$ and $-ab=(-a)b \in P$ and so $ab\ne 0$ because $0 \notin -P$.
If $a,b \notin P$, then $-a,-b \in P$ and $ab=(-a)(-b) \in P$ and so $ab\ne 0$ because $0 \notin P$.


react re-render component but not the whole page issue

Question: I am trying to re-render one component on my webpage in react and I am having troubles. When I click the back button, I want to go to the section which is alphabetically previous to the current one - I break down the sections of my component into letters. So my handleBack function should re-render the component. This is my code below:
function handleBack() {
    const currentId = window.location.href.split('/').pop();

    const backId = String.fromCharCode(currentId.charCodeAt() - 1);

    return(

       <Route>

         <Redirect from={'/form/${currentId}'} to={'/form/${backId}'} />

       </Route>);

}

It knows that currentID is B and backID is A for example, but it isn't re-rendering the component and showing page A. Why is this happening? How do I fix this? I thought route and redirect would work but it doesn't do anything.
Comment: Can you share complete component code?
Answer: First
Change this to....
function handleBack() {
    const currentId = window.location.href.split('/').pop();

    const backId = String.fromCharCode(currentId.charCodeAt() - 1);

    return(

       <Route>

         <Redirect from={'/form/${currentId}'} to={'/form/${backId}'} />

       </Route>);

}

To...
function handleBack() {
    const currentId = this.props.match.params.id; // Use the route params instead of using window.location

    const backId = String.fromCharCode(currentId.charCodeAt() - 1);

    this.props.history.push('/form/${backId}');

}

Comment: this doesn't work as it's a function and i am not using any props.. this gives me an error as it can't read props of undefined :(
Comment: You can force refresh to see the issue with the code
`this.forceUpdate() `
You can place this inside a `constructor()`  or `componentDidMount()`


Update após digitar sem refresh

Question: Tenho uma lista de nomes que vem do banco de dados e preciso atualizar estes nomes quando necessário. Trago todos já dentro do formulário e atualizo com um Javascript.
Com um registro funciona perfeitamente. O problema é quando trago mais de um nome do banco, daí ele só funciona no primeiro formulário.
<?php
$consulta = mysql_query("
SELECT * FROM categoria limit 2");
while ($dados = mysql_fetch_array($consulta)) {
?>
<form method="POST" action="" id="ajax_form">

            <input type="text" id="id_categoria" name="id" class="form-control" value="<?echo$dados['id_categoria']?>" readonly>
            <input type="text" id="nome" name="nome" class="form-control" maxlength="100" placeholder="Seguimento" value="<?echo$dados['nome']?>" required autofocus>
            <button class="btn btn-primary" type="submit">Atualiza</button>

</form>
<?}?>

JS

Comment: Cade o código que atualiza, ou seja a página seguimento_lista_sql_update.php ?
Answer: Tente dessa forma mais simplificada, fiz umas atualizações no formulário para o botão ter um id (o mesmo da categoria) e o campo do texto ter um id também (s+id_categoria), mudei o submit para button e adicionei uma classe atualiza a ele, removi também o campo id_categoria pois não era necessário, caso deseja exibir, basta adaptar no modelo:
Formulário com as alterações:
<form method="POST">

            <input type="text" class="form-control" id="s<?=@$dados['id_categoria']?>" maxlength="100" placeholder="Seguimento" value="<?=@$dados['nome']?>" required autofocus>
            <button id="<?=@$dados['id_categoria']?>" class="btn btn-primary atualiza" type="button">Atualiza</button>

</form>

JQuery:

Espero que ajude, abraços
Comment: funcionou perfeitamente!Aproveitando existe alguma função que eu possa colocar junto com o botao.text para ele mudar a classe em quanto a atualização está sendo feita?
Comment: Existem 3 funções, pesquise mais sobre: `.removeClass()` , `.addClass()` e `.toggleClass()`
Comment: Obrigado! @Mastria

Update após digitar sem refresh


Solving recurrence equation with floor and ceil functions

Question: I have a recurrence equation that would be very easy to solve (without ceil and floor functions) but I can't solve them exactly including floor and ceil.
\begin{align}
k (1) &= 0\\
k(n) &= n-1 + k\left(\left\lceil\frac{n}{2}\right\rceil\right) + k\left(\left\lfloor\frac{n}{2}\right\rfloor\right) \qquad n \in \mathbb{N}_+
\end{align}
How can I solve such an equation?
Comment: you can deduce it to :
$$\left\{\begin{matrix}
k(1)=0 & \\
k(n)=n-1+k(q)+k(q) &n=2q \\
k(n)=n-1+k(q+1)+k(q) & n=2q+1
\end{matrix}\right. \\\left\{\begin{matrix}
k(1)=0 & \\
k(n)=2q-1+2k(q) &n=2q \\
k(n)=2q+k(q+1)+k(q) & n=2q+1
\end{matrix}\right.$$
Comment: Do you need an exact closed for solution or just a bound on the solution?
Comment: Have you tried splitting into cases where $n$ is even and odd?
Comment: I'm trying to get an exact closed formula for that equation.
Answer: SKETCH: It's often useful to gather some numerical data:
$$\begin{array}{rcc}
n:&1&2&3&4&5&6&7&8&9&10&11&12&13&14&15&16&17&18\\
k(n):&0&1&3&5&8&11&14&17&21&25&29&33&37&41&45&49&54&59\\
k(n)-k(n-1):&&1&2&2&3&3&3&3&4&4&4&4&4&4&4&4&5&5
\end{array}$$
Notice that the gaps in the bottom line are a single $1$, two $2$s, four $3$s, and eight $4$s. This suggests that if $2^{m-1}<n\le 2^m$, then $k(n)-k(n-1)=m$. Assuming this to be the case, we must have
$$k(2^m)=\sum_{\ell=1}^m\ell2^{\ell-1}=(m-1)2^m+1\;.$$
This can now be proved by induction on $m$, since $k(2n)=2n-1+2k(n)$. Now let $n=2^m+r$, where $0\le r<2^m$. Then the obvious conjecture is that
$$k(n)=k(2^m)+(m+1)r=(m-1)2^m+1+(m+1)r\;,$$
which again can be verified by induction, though the argument is a bit messier.
Note that $m=\lfloor\lg n\rfloor$, and $r=n-2^m$, so $m$ and $r$ are both readily obtained from $n$.


Issue with "import java.io.RandomAccessFile;"

Question: This is my homework assignment...
"You are the owner of a hardware store and need to keep an inventory that can tell you what different tools you have, how many of each you have on hand, and the cost of each one. Write a program that creates a random-access file "hardware.dat". Your program should allow you to input the data for each tool and write your data to the file it created. Use the following information to start your file: ..." Then it gives a list of the info.
These are what I have for my assignment.. (classes below) the second (Hardware class) I have no issues with it, but I just want to make sure that it's right.
But I'm having issues with RandomAccessFile in the first link. I have no clue if I'm doing it right. It keeps saying "RandomAccessFile is already defined in this compilation" whenever I hover over "import java.io.RandomAccessFile;" what does that mean?? (I can't paste the links without code being included with it)
What am I doing wrong?
RandomAccessFile class:
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Scanner;

public class RandomAccessFile  {
    public static void main(String[] args)
    {
        RandomAccessFile file;
        Scanner sc = new Scanner(System.in);

        int toolId;
        String toolName;
        int quantity;
        double cost;

        System.out.println("Please Input Tool ID: ");
        toolId = sc.nextInt();

        System.out.println("Please Input Tool Name: ");
        sc.nextLine();
        toolName = sc.nextLine();

        System.out.println("Please Input the Quantity: ");
        quantity = sc.nextInt();

        System.out.println("Please Input the Price: ");
        cost = sc.nextDouble();

            try
            {
                file = new RandomAccessFile(new File("hardware.dat"), "rw");
                long FileSize = file.length();
                file.seek(FileSize);

                file.writeInt(toolId);

                file.writeUTF(toolName);
                for(int i = 0; i < 24- toolName.length(); i++)
                {
                    file.writeByte(24);
                }

                file.writeInt(quantity);

                file.writeDouble(cost);

                System.out.println("Item added to inventory");
                file.close();
            }

            catch (FileNotFoundException e)
            {
                System.err.println("File not found. Check Project Folder and if you have read and write permissions to it");
            }

            catch (IOException e)
            {
                e.getStackTrace();
            }
    }
     }

Hardware Class:
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.FileNotFoundException;

public class Hardware
{

    private static final int RECORD = 24;

    public static void main(String[] args)
    {
        RandomAccessFile file;
        int toolId = 0;
        String toolName = null;
        int quantity = 0;
        double cost = 0.00;

        try
        {
            file = new RandomAccessFile(new File("hardware.dat"), "rw");

            long FileSize = file.length();
            file.seek(0);
            long NUMRecords = FileSize / RECORD;
            for (int j = 0; j < NUMRecords; j++)
            {

                toolId = file.readInt();

                toolName = file.readUTF();
                for (int i = 0; i < 24- toolName.length(); i++)
                {
                    file.readByte();
                }

                quantity = file.readInt();

                cost = file.readDouble();

                System.out.println("Tool ID: "  + toolId + "  Tool Name: " + toolName + "  Quantity: " + quantity + "  Cost:  $" + cost);

            }

            file.close();
        }

        catch (FileNotFoundException e)
        {
            System.err.println("File not found. Check Project Folder and if you have read and write permissions to it");
        }

        catch (IOException e)
        {
            e.getStackTrace();
        }

    }
}

Answer: I figured it out. It was something dumb/silly. My class name was "RandomAccessFile" (to help me keep things organized for class) and once I changed that then the code ran fine...
Answer: I can't access your links but apparently you have named your class as RandomAccessFile ? If so try to change its name, because at the same time you import another class named java.io.RandomAccessFile, hence the error.


How can I define in Visual Studio a new constant?

Question: I need to define a new constant in Visual Studio.
I explain: I have a custom Compile Configuration (sorry I'm not sure the name is exact, I have a localized version of VS), and I need to define another constant besides the TRACE and DEBUG ones.
How can I do it?
Answer: You can do it in two ways:

in the top of one of your code files, write the line:
#define MYCONSTANT

then elsewhere within the same file you can refer to it with code like
<code>#ifdef MYCONSTANT
    ... some code...
#endif
</code>

right click on a project file, select Properties. In the Build tab, you have a checkbox for each of the two constants you mentioned - above that is a textbox, enter your new constant there. You don't assign it a value, just the fact that it is declared is all you need.
Comment: Sorry for the dumb question, I found it.
I was expecting "Custom defined constants" or something like that instead of the label of THAT textbox


text-align: center; not working for Inputfields Bootstrap

Question: I've got the following code that will allow the user to type the text from center. But when I edit the textbox with some text, the cursor moves to the right end for every character pressed. I'm using bootstrap 2.x, how do I fix it?
<input type="text" class="input-xxlarge" style="text-align: center;">

JSFiddle Link
Comment: Please provide some screenshots describing your issue or any additional information. From your explanation, that sounds as the correct behaviour.
Comment: please provide your code.
Comment: i guess its working fine https://jsfiddle.net/DTcHh/17604/.. in particular which browser its not working?
Comment: The js fiddle by G.L.P is using Bootstrap 3, should be 2.x. Here is a working example using Bootstrap 2 https://jsfiddle.net/mrght049/
Comment: The code provided works with bootstrap 2.x as is. You must add something else that changes the behavior/rules.
Answer: You can remove the inline style and use text-center class instead :
<input type="text" class="input-xxlarge text-center" >


How do I select multiple values with one checkbox?

Question: With Facets module/search API, I have a checkbox filter where I need to merge some value.
Example:
vocabulary  = color

term = light red

term = dark red

term = light blue

term = dark blue

In this case i have 4 checkbox.
My checkbox should look like this
vocabulary  = color

term = red

term = blue

And When i tick Red it list all content tagged with dark red and light red
And When i tick blue it list all content tagged with  dark blue and light blue
thus the parent term will not be a used value in the filtered content, but only the child value will filter the content.
Question : Is it possible to do that with taxonomy hierachy option in the facets?
Comment: Are red and blue actual terms in your vocabulary, where light red and dark red are children of a parent term, red?
Answer: I've resolved this with by activating 'index Hierarchy" in the Search API processor configuration page with the proper taxonomy selected. in the taxonomy i've created new parent term and putted the childs in it, then in the facets those parent are displayed - in a checkbox in my case - and when selecting those parent it filter the content with the value of all the childs.
Note that I've excludes the display of the childs in the checkbox, in the facets properties.


New Apple Map Transition

Question: How can i do the new appleMaps transition in iOS 6, which allows you to take the map view and lift it to see and set the settings menu.
I would like to put this transition in my apps in xCode, does somebody know how to do that stuff?
Thank You
Answer: The new API for using maps in iOS6 is named "MapKit", here are the specifications :
http://developer.apple.com/library/ios/#documentation/userexperience/conceptual/LocationAwarenessPG/MapKit/MapKit.html
Hope it helps you :)

New Apple Map Transition


How many permutation matrixes for a $4 \times 4$ matrix?

Question: How many permutation matrixes for a $4\times 4$ matrix ? Given an $n \times n$ matrix what is the general way to find the number of permutation matrixes ?
Comment: Do you know the definition of permutation matrices?
Comment: Of course I do. I wanted to know how to derive them ?
Answer: The answer is $n!$. See more information in the Wikipedia article on permutataion matrix.

You might also want to read this (if you haven't):
https://math.stackexchange.com/help/how-to-ask


Rails 5.1.5 upgrade causes - uninitialized constant Mime::JSON

Question: Whenever a controller renders json I get,
uninitialized constant Mime::JSON
I have not modified any code related to this.
Ex, the code for this controller method that throws the error:
def names
    @families = Family.pluck(:name)
    render json: @families
  end
This was working fine before the rails 5 upgrade.
Comment: I think the issue is using the responders gem.  I had to use the normal respond_to do |format|, syntx in order for it to render correctly.
Answer: In my case, it was jbuilder causing this error.
Upgrading jbuilder to latest (2.7.0 at time of writing) solved this. The old jbuilder references JSON wrong and causes responder to fail.
Answer: I was obtaining the error after upgrade from rails 5.0.1 to 5.1.0 and in my case the gem 'web-console','~> 2.0' was causing the error, I solved it updating it to gem 'web-console','>= 3.3.0'.


I want to start compose music but I don't know where to start

Question: I play the Double Bass and I've always wanted to compose music for an orchestra. I know that I need to learn more theory, but I don't know where to learn it. I was thinking about learning it in a book, is that a good starting point? Also is it beneficial to learn the piano to compose and understand chords?
Answer: Learning the piano would be a good place to start. It will get you  more familiar with the treble clef and how multiple voices interact as well as harmony. (This should also give you great benefits on the bass, too.)
A second important skill is musical handwriting. Get fast at making the dots and stems on staff paper. Write down all your little melodic ideas in a notebook which you can refer to when you're writing something and stuck for ideas.
Imitate your heros. Take a piece that you like and try to copy all the tricks and ideas that it uses but built upon a different melody (your melody).
Comment: You're welcome. Lots of info to be learned from other Q&As on here. Especially check out [theory tag](https://music.stackexchange.com/questions/tagged/theory).
Comment: @LeoMeyer also look into software like MuseScore for writing your music. If you have a tablet there are apps which can help you write down and play back your ideas while away from your PC.
Comment: Ok I sure will!
Comment: @B.M. Yeah I have found flat.io, which is convenient because I can use it on my phone and computer.


collect all array items from each object

Question: I have 2 entities:
class A {
    ...
}
class B {
    IEnumerable bs;
}

I have array of A's and I need to get all the B's in one IEnumerable. I can do:
IEnumerable as=....;

IEnumerable<IEnumerable> bss=as.Select(x=>x.bs);

IEnumerable all=null;
foreach (IEnumerable bs is bss) {
    if (all==null) { all=bs; }
    else { all=all.Contact(bs); }
}

I want to know if there is shorter way to do this.
Thanks
Comment: Your code doesn't compile because you can't call a variale `as` (it's a reserved keyword) and your `A` class doesn't appear to have a field called `bs` (since you have it on `B`.) Please try to provide *working* samples with your questions.
Comment: @dlev: This is JUST an example to explain my question and not code that should compile. If you get the point - it is enough. Don't get much into details if you understand the question.
Comment: @Naor if your code has errors like dlev mentions it will confuse people who are trying to answer your question. I recommend editing your question to provide a better example and give better names as all the b, bs, bss stuff can be hard on the eyes to follow.
Comment: @Naor I understand that it's just a sample, and the choice of variable (while illegal) doesn't matter *much*. But providing code that compiles, with types and fields used consistently helps get you better answers, and *really* helps others who have a similar problem and stumble across this question.
Answer: You can Use SelectMany that will concatenate all the IEnumerables together
var all = as.SelectMany(a => a.bs);

Answer: Use the SelectMany method to flatten a single level of nesting:
all = as.SelectMany(a => a.bs);

Answer: Use SelectMany:
foreach (var b in allAs.SelectMany(a => a.Bs))
{
    // Do work here
}

Answer: Are you wanting SelectMany to flatten the B's?
IEnumerable allBs = as.SelectMany(a => a.bs);

or using LINQ expressions:
IEnumerable allBs = from a in as
                       from b in a.bs
                       select b;


R feature extraction for text

Question: My question is about text mining, and text processing.
I would like to build a dataframe from my text.
My data is:
text <- c("#*TeX: The Program,
#@Donald E. Knuth,
#t1986,
#c,
#index68,
""
#*Foundations of Databases.,
#@Serge Abiteboul,Richard Hull,Victor Vianu,
#t1995,
#c,
#index69,
#%1118192,
#%189,
#%1088975,
#%971271,
#%832272,
#!From the Book: This book will teach you how to write specifications of computer systems, using the language TLA+.")

My expected output is :
expected <- data.frame(title=c("#*TeX: The Program", "#*Foundations of Databases."), authors=c("#@Donald E. Knuth", "#@Serge Abiteboul,Richard Hull,Victor Vianu"), year=c("#t1986", "#t1995"), revue=c("#c", "#c"), id_paper=c("#index68", "#index69"),
                       id_ref=c(NA,"#%1118192, #%189, #%1088975, #%971271, #%832272"), abstract=c(NA, "#!From the Book: This book will teach you how to write specifications of computer systems, using the language TLA+."))

My code is:
coln <- c("title", "authors", "year", "revue","id_paper", "id_ref", "abstract")
      title_index <- grep("^#[*]", text)
      authors_index <- grep("#@", text)
      year_index <- grep("#t", text)
      revue_index <- grep("#c", text)
      id_paper_index <- grep("#index", text)
      id_refindex <- grep("#%", text)
      abstract_index <- grep("#!", text)
      df <- matrix(NA, nrow=length(title_index), ncol=length(coln))
      colnames(df) <- coln
      stoc_index <- grep("#cSTOC", text)
      sigir_index <- grep("#cSIGIR", text)}

  ########## titre
  {der_pos <- length(title_index)
    tit_position  <- c(title_index , der_pos)
    for(i in 1:length(title_position)){
      if(i != length(title_position)){
        df[i, "title"] <- text[title_position[i]]
      }
    }
  }

  ########## author
{der_pos <- length(authors_index)
    authors_position  <- c(authors_index )
    for(i in 1:length(auteur_position)){
      if(i != length(auteur_position)){
        df[i, "auteur"] <- text[auteur_position[i]]
      }
    }
  }

  ########## year
{der_pos <- length(year_index)
    year_position  <- c(year_index , der_pos)
    for(i in 1:length(year_position)){
      if(i != length(year_position)){
        df[i, "année"] <- text[year_position[i]]
      }
    }
  }

  ##########??? revue
  {der_pos <- length(revue_index)
    revue_position  <- c(revue_index )
    for(i in 1:length(revue_position)){
      if(i != length(revue_position)){
        df[i, "revue"] <- text[revue_position[i]]
      }
    }
  }

  ########## id_paper
  {der_pos <- length(id_paper_index)
    id_paper_position  <- c(id_paper_index , dern_pos)
    for(i in 1:length(id_paper_position)){
      if(i != length(id_paper_position)){
        df[i, "id_paper"] <- text[id_paper_position[i]]
      }
    }
  }

  ########## id_ref
  {der_pos <- length(id_ref_index)
    id_ref_position  <- c(id_ref_index , der_pos)
    for(i in 1:length(id_ref_position)){
      if(i != length(id_ref_position)){
        df[i, "id_ref"] <- text[id_ref_position[i]]
      }
    }
  }
  ########## abstract
  {der_pos <- length(abstract_index)
    abstract_position  <- c(abstract_index , der_pos)
    for(i in 1:length(abstract_position)){
      if(i != length(abstract_position)){
        df[i, "abstract"] <- text[abstract_position[i]]
      }
    }
  }

So I would like to extract the reference in a single line
Thank you in advance if you have solution for concatenate many citation in one column separated by coma for one article.
Thank you :)
Comment: What have you tried so far?
Comment: I have tried to extract with grep, by can't concatenate id_ref in only row.
Comment: See my comment to below answer...
Answer: Here a solution based on the answer of @AkselA. I could not deal with this only in comments, therefore, an additional answer (I know I could have formatted it more nicely...)
#split into individual docs
text.s = strsplit(text, "\n(?=#\\*)", perl = T)[[1]]

# function to extract information from individual docs
extract_info = function(x, patterns = list(title="^*#\\*",
                                           autors="^*#@",
                                           year="^*#t",
                                           revue="^*#c",
                                           id_paper="^*#index",
                                           id_ref="^*#%",
                                           abstract="^*#!")) {
  lapply(patterns, function(p) {
    extract = grep(p, x, value = T)
    # here you check the length of the potential output
    # and modify the type according to your needs
    if (length(extract) > 1) {
     extract = list(extract)
    } else if (length(extract) == 0) {
     extract = NA
    }
    return(extract)
    })
}

# apply the function to the data
# and rbind it into a data.frame
do.call(rbind,
        lapply(text.s, function(x) {
  x = strsplit(x, "\\n")[[1]]
  extract_info(x)
})
)

# title                         autors                                        year     revue id_paper   id_ref
# [1,] "#*TeX: The Program"          "#@Donald E. Knuth"                           "#t1986" "#c"  "#index68" NA
# [2,] "#*Foundations of Databases." "#@Serge Abiteboul,Richard Hull,Victor Vianu" "#t1995" "#c"  "#index69" List,1
# abstract
# [1,] NA
# [2,] "#!From the Book: This book will teach you how to write specifications of computer systems, using th" [truncated]

Comment: Thank you very much, your answer is correct. But I could only give one solution. Thank you, you are a genius.
Answer: New and improved
text.n <- strsplit(text, "\n(?=#\\*)", perl=TRUE)[[1]]; text.n

text.s <- lapply(text.n, function(x) strsplit(x, "\n")[[1]])

patterns <- list(title="^#\\*",
                autors="^#@",
                  year="^#t",
                 revue="^#c",
              id_paper="^#index",
                id_ref="^#%",
              abstract="^#!")

tex.l <- lapply(text.s, function(x)
  lapply(patterns, function(y)
    paste(sub(y, "", grep(y, x, value=TRUE)), collapse=",")
  )
)

tex.m <- matrix(unlist(tex.l), ncol=length(tex.l[[1]]), byrow=TRUE)
tex.df <- as.data.frame(tex.m, stringsAsFactors=FALSE)
colnames(tex.df) <- names(patterns)

str(tex.df)

# 'data.frame': 2 obs. of  7 variables:
# $ title   : chr "TeX: The Program" "Foundations of Databases."
# $ autors  : chr "Donald E. Knuth" "Serge Abiteboul,Richard Hull,Victor Vianu"
# $ year    : chr "1986" "1995"
# $ revue   : chr "" ""
# $ id_paper: chr "68" "69"
# $ id_ref  : chr "" "1118192,189,1088975,971271,832272"
# $ abstract: chr "" "From the Book: This book will teach you how to write
#                     specifications of computer systems, using the language TLA+."

Comment: @ManuelBickel: No trouble, just had to pause and look at it anew. Thanks for the regex pattern, what I had was a bit less than optimal.
Comment: You could use `list()` or `paste0(..., collapse = ", ")` to concatenate multiple elements and store them as a single entry.
Comment: The size of the data frame will be that of the title. Since each article necessarily has a title.
Comment: @ManuelBickel: But then we'd just end up with a vector.
Comment: @cincinnatus: `id_ref` will clash with that.
Comment: Please check my anwer, which hopefully makes clear what I meant with above comment (sorry for making it an additional answer, too many lines for a comment).
Comment: Oh, sorry had not checked your update before posting. Thanks for incorporating my comment.

R feature extraction for text


Open the last closed tab in Android Studio

Question: I'm new to Android Studio, and wanted to know if there are any shortcut / option to re-open the last closed tab.
Answer: There is no shortcut assigned, but you can easily assign a new one:
Go to IDE settings | Keymap | Main menu | Window | Editor Tabs | Reopen Closed Tab (type reopen into the filter field to find it faster), right click on that item and select Add Keyboard Shortcut
Update: As stated in another answer, you can also use Ctrl + E to see a list of all recently viewed files. Additionally, you can use Ctrl + Shift + E to see a list of all recently edited files, which is handy when working on multiple files.
Comment: @ThomasDavidBaker Whenever some UI works in unexpected ways, it's a bug, because doing thing as expected by a user is the main principle of UI. Feel free to file it to Jetbrains. Probably if everybody were filing tickets. there would be a day when software worked as expected.
Comment: Almost all `Alt + Letter` shortcuts are still available ;)
Comment: Any idea why this doesn't work when no files are open?
Comment: Thanks for the tip. Most of the shortcut combinations are already taken :P, I had to conform with ctrl-shift-p.
Answer: For Windows -> ctrl+e
For macOS -> cmd+e
It will show a popup window for the files you visited previously.
Answer: The shortcut is cmd[ (CtrlAlt← on Windows). It correspond to Navigate > Back.
It will bring your cursor where it was previously, re-opening the tab if needed, and you can do it many times.
Comment: doesn't work when tab was closed without first being in focus....
Answer: You may don't have to google this thing.
There are some shortcut given in Android Studio Screen :) :)


Borda chanfrada transparenet apenas com css

Question: Existe uma forma simples de fazer uma borda chanfrada apenas com CSS, mas transparente. Sem precisar de um svg, png, etc?

Veja o que já fiz até agora: https://jsfiddle.net/Cafardo/zn5oysqy/5/

.home_fundo{
   width: 300px;
   height: auto;
   background: url(http://www.simi.org.br/files/Janeiro%20-%202017/11096.jpg);
}
.home_banner_caixa {
  width: 200px;
  max-width: 400px;
  height: auto;
  position: relative;
  background-color: #c77316;
  padding: 20px;
  font-size: 12px;
  color: #ffffff;
}

.home_banner_caixa_chanfro {
  width: 70px;
  height: 70px;
  position: absolute;
  top: -10px;
  right: -10px;
  -ms-transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  -moz-transform: rotate(45deg);
  transform: rotate(45deg);
}

.home_banner_caixa_chanfro1 {
  width: 70px;
  height: 35px;
  display: block;
  background-color: #ffffff;
}

.home_banner_caixa_chanfro2 {
  width: 70px;
  height: 35px;
  display: block;
  background-color: #c77316;
}

      Lorem ipsum

 dolor sit amet, consectetur adipiscing elit. Duis vitae augue ut mi fermentum sodales. Sed euismod est mollis sem malesuada, vitae placerat est congue

Reparem que o canto banco deveria ser transparente, pensei que talvez exista algum tipo de mascara em jquery para deixar a div branca do chanfrado transparente, ou algo do tipo...  conseguem me ajudar?
Comment: Possível duplicata de [Elementos com cantos cortados com Css](https://pt.stackoverflow.com/questions/52938/elementos-com-cantos-cortados-com-css)
Comment: Obrigado, o post me ajudou bastante. O problema é que precisaria ser transparente a bordinha chanfrada, e não com uma cor....
Comment: Vc também pode fazer usando pseudo elemento. Vou responder na outra pergunta com essa opção caso tenha interesse. []´s
Comment: De uma olhada na propriedade `clip-path` em [MDN clip-path CSS Property](https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path). *Observe a tabela de compatibilidade de navegadores.
Comment: Obrigado! Mas funciona em poucos navegadores....
Comment: Não vai ficar bonito, mas vou fazer um exemplo pra vc.
Answer: Para Imagens
No caso de precisar cortar o canto de uma imagem com CSS, ou chanfrar uma imagem com CSS você pode consultar aqui: Fazer efeitos nas bordas em CSS, como chanfro

Para core sólidas
Existem alguma opções diferentes, vou abordar 3 delas.
Opção 1
Opção mais atual com com linear-gradiente. A técnica é fazer um linear-gradiente em 45deg, onde a última porção referente a 10% do gradiente é transparente. Assim teremos uma cor sólida de 0% até 90% e de 90% a 100% a cor transparente.

body {
    background-image: linear-gradient(to left, blue, green);
}
.container {
    width: 200px;
    height: 100px;
    background-image: linear-gradient(45deg, #f00 0%, #f00 90%, rgba(0,0,0,0) 90%, rgba(0,0,0,0) 100%);
}

Opção 2
Fiz essa opção usando pseudo elementos ::before e ::after mais transform: skewX(45deg); assim o canto da div fica "transparente" diferente das outras opções da resposta marcada como Duplicada...

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
body {
    background-image: url(http://placecage.com/420/320);
    background-size: cover;
    display: flex;
    position: relative;
}
.container {
    background-color: tomato;
    position: relative;
    margin: auto;
    width: 200px;
    height: 100px;
}
.container::after {
    content: "";
    top: -20px;
    left: -10px;
    height: 20px;
    width: 100%;
    background-color: tomato;
    position: absolute;
    transform: skewX(45deg);
}
.container::before {
    content: "";
    bottom: 0px;
    left: -20px;
    height: calc(100% + 20px);
    width: 20px;
    background-color: tomato;
    position: absolute;
}

Meu texto aqui! Meu texto aqui! Meu texto aqui!

Edit
Opção 100% Crossbrowser: (o código é mais feio, mas funciona em todos os browsers)

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
body {
    background-image: url(http://placecage.com/460/320);
    background-size: cover;
    display: flex;
    position: relative;
}
.container {
    background-color: limegreen;
    position: relative;
    margin: auto;
    width: 200px;
    height: 100px;
    padding: 0 10px 10px;
    box-sizing: border-box;
}
.barra {
    width: 180px;
    height: 20px;
    position: absolute;
    left: 0;
    top: -20px;
    background-color: limegreen;
}
.box {
    box-sizing: border-box;
    width: 20px;
    height: 20px;
    position: absolute;
    right: 0;
    top: -20px;
    border-left: 10px solid limegreen;
    border-bottom: 10px solid limegreen;
    border-top: 10px solid transparent;
    border-right: 10px solid transparent;
}

    Meu texto aqui! Meu texto aqui! Meu texto aqui!

Dica: Nessa técnica usei bordas com cores transparentes e position:absolut com top negativo
Comment: Ótima resposta @hugocsl, +1!
Comment: @AndréFilipe valeu jovem! Ela é criativa, mas não funciona para imagem... pois é uma composição de pseudo elementos etc... aqui deixei uma alternativa para usar com imagens https://pt.stackoverflow.com/questions/355578/fazer-efeitos-nas-bordas-em-css-como-chanfro/355584#355584
Comment: Perfeito! O segundo exemplo fucnionou muito bem. Tive que fazer algumas mudanças no layout.. pois o texto começa a ser escrito no meio do chanfrado na versão original, mas tudo bem. obrigado!
Comment: De uma olhada nessa resposta no StackOverflow gringo: https://stackoverflow.com/questions/49138218/border-bevelled-transparent-only-with-css
Comment: Caio o CSS é lindo né! Com linear-gradiente foi algo que não me passou pela cabeça! Muito interessante também!
Comment: Hmmmmmmm, bacana. vou dar uma olhada meu amigo!


java Get the list or name of all attributes in a XML element

Question: i have an xml element
   <base baseAtt1="aaa" baseAtt2="tt">
        <innerElement att1="one" att2="two" att3="bazinga"/>
   </base>

and i would like to get the list of attributes.
for both the base element and the inner element.
i dont know the name of the innerElement
 it can have many different names.
 NodeList baseElmntLst_gold  = goldAnalysis.getElementsByTagName("base");
 Element baseElmnt_gold = (Element) baseElmntLst_gold.item(0);

the goal is to get a kind of dictionary as output,
for example for the xml above the output will be a dictionary with those valuse.
baseAtt1 = "aaa"
baseAtt2 = "tt"
att1 = "one"
att2 = "two"
att3 = "bazinga"

i am using jre 1.5
Answer: Here is plain DOM based solution (however there is nothing wrong to combine XPath with DOM in Java):
NodeList baseElmntLst_gold  = goldAnalysis.getElementsByTagName("base");
Element baseElmnt_gold = (Element) baseElmntLst_gold.item(0);

NamedNodeMap baseElmnt_gold_attr = baseElmnt_gold.getAttributes();
for (int i = 0; i < baseElmnt_gold_attr.getLength(); ++i)
{
    Node attr = baseElmnt_gold_attr.item(i);
    System.out.println(attr.getNodeName() + " = \"" + attr.getNodeValue() + "\"");
}

NodeList innerElmntLst_gold = baseElmnt_gold.getChildNodes();
Element innerElement_gold = null;
for (int i = 0; i < innerElmntLst_gold.getLength(); ++i)
{
    if (innerElmntLst_gold.item(i) instanceof Element)
    {
        innerElement_gold = (Element) innerElmntLst_gold.item(i);
        break; // just get first child
    }
}

NamedNodeMap innerElmnt_gold_attr = innerElement_gold.getAttributes();
for (int i = 0; i < innerElmnt_gold_attr.getLength(); ++i)
{
    Node attr = innerElmnt_gold_attr.item(i);
    System.out.println(attr.getNodeName() + " = \"" + attr.getNodeValue() + "\"");
}

Result:
baseAtt1 = "aaa"
baseAtt2 = "tt"
att1 = "one"
att2 = "two"
att3 = "bazinga"

Comment: why just get first child in second loop, i always gare first row data and unable to get second and third continue?
Answer: You can use this XPath to retrieve all attributes of 1st element node:
base/element[1]/@*

To get all attributes of all nodes in your XML yo can use this expression:
//@*

Comment: @yossi, XPath is cross-platform technology. Java supports XPath, but I don't know syntax and Java's classes to evaluate this expression.
Comment: @yossi, May be this link is helpful: http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html
Answer: If you use XPath you will have less code, but for a dom base solution I have a suggestion here:
public void printElementsAndAttributes() throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    org.w3c.dom.Document doc = db.parse(new File("test.xml"));
    NodeList base = doc.getElementsByTagName("base");
    Node basenode = base.item(0);
    System.out.println(basenode.getNodeName() + getAttributesAsString(basenode.getAttributes()));
    NodeList children = basenode.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node item = children.item(i);
        if (item.getNodeType() == Node.ELEMENT_NODE) {
            System.out.println(item.getNodeName() + getAttributesAsString(item.getAttributes()));

        }
    }

}

private String getAttributesAsString(NamedNodeMap attributes) {
    StringBuilder sb = new StringBuilder("\n");
    for (int j = 0; j < attributes.getLength(); j++) {
        sb.append("\t- ").append(attributes.item(j).getNodeName()).append(": ").append(attributes.item(j).getNodeValue()).append("\n");
    }
    return sb.toString();

}

Answer: Use this method..
 public static void listAllAttributes(Element element) {

             System.out.println("List attributes for node: " + element.getNodeName());

             // get a map containing the attributes of this node
                 NamedNodeMap attributes = element.getAttributes();

             // get the number of nodes in this map

             int numAttrs = attributes.getLength();

             for (int i = 0; i < numAttrs; i++) {
            Attr attr = (Attr) attributes.item(i);
            String attrName = attr.getNodeName();

 String attrValue = attr.getNodeValue();
  System.out.println("Found attribute: " + attrName + " with value: " + attrValue);

             }
 }

call this method by using following call in the main method
  NodeList entries = doc.getElementsByTagName("NameOfTheNode");
                int num = entries.getLength();
                 for (int i=0; i<num; i++) {
                                                  Element node = (Element) entries.item(i);
                                                  listAllAttributes(node);

                          }

Answer: NodeList bList = eElement.getElementsByTagName("base");
Node node1 = bList.item(0);

if (node1.getNodeType() == node1.ELEMENT_NODE) {
                     Element ele = (Element) node1;
                     System.out.print("Attribute : ");
                     System.out.println(ele.getAttributes());
                  }

Should work.
Very nice explanation is given at https://www.tutorialspoint.com/java_xml/java_xml_quick_guide.htm You can refer that for more clarity.


How to provide the ability to upload media to the server?

Question: I want to provide the ability to upload PDFs/mp3s etc. to the server.
What is the best way of achieving this?
I've seen the media plugin but it seems that replaces the upload field rather creating a stand-alone media area? Or maybe it does?
Answer: I think Media is a great module unless if your client will upload and use the same PDFs/MP3 once a time.
But if your client plan to use at severals places the same Media, so Media module is for you.
Also, give a look at Scald, seems to be a promise module.


Clarifications about a weakly convergent seaqence

Question: I came across a situation in a paper page 36   where I need some clarifications. I have a weakly convergent sequence $(a_n)$ in the space $L^2(0,T;L^2(\Omega))$, which converges weakly to $a$. The paper proves that $(b_n)$ is a bounded sequence in the same space, then concludes that:
$$ \int_0^T \langle a_n(t)-a,b_n(t) \rangle_{L^2(\Omega)}  \mathrm dt  \longrightarrow 0 $$
I'm trying to understand the reasoning behind this result. Could someone please explain why this integral tends to zero as $n$ approaches infinity?
Answer: There is no reason behind this, as the claim as written in your question is wrong. (To see that this is not true, take $a_n=b_n$ weakly but not strongly converging to zero.)
In addition, nothing in the paper suggests that the authors are using some unmentioned compactness. In my opinion, the proof is wrong and cannot be corrected without adding assumptions on $N_j$. One remedy would be to require $N_j \in \mathcal L(Y,Y)$ (instead of $N_j \in \mathcal L(V,Y)$). At least the proof could be salvaged, as then $Ny_k \to N \bar y$ strongly in $L^2(0,T;Y)$ by Aubin-Lions lemma. But then the examples in Section 8 fail to satisfy this requirement.
Comment: Yes if $ N_j \in \mathcal L(Y,Y)$  the problem will be immediatly solved using compactness arguments.
Comment: I find a related quetion https://math.stackexchange.com/questions/3788402/weak-convergence-of-product-of-sequences-that-are-weakly-convergent-in-h1-and , and I am curious if the response provided there can potentially serve as a justification for the proof mentioned in the referenced paper?
Comment: I do not think so unless we assume $N_j = Id$.