How to color a row based on cell value in pure css?

Question: I am using a a framework which generated very layered css.
I just want to simply give a whole row (or each cell) a background color based on a string cell value (of one column). I don't want to use javascript but pure css.
Below is the html css snippet, where a whole row should get a background color based on  . The title value has different values, whereby Geen Voorraad should add a background color red. Anyone an solution?

          Naam

          <input type="text" class="form-control">

          Code

          <input type="text" class="form-control">

          Prijs

          <input type="text" class="form-control">

          Voorraadstatus

          <select class="form-control">
            <option value=""></option>
            <option value="mxui_widget_SearchInput_11_Inactief">Gearchiveerd</option>
            <option value="mxui_widget_SearchInput_11_ActiefVoldoendeVoorraad">Voldoende Voorraad</option>
            <option value="mxui_widget_SearchInput_11_ActiefBeperkteVoorraad">Beperkte Voorraad</option>
            <option value="mxui_widget_SearchInput_11_ActiefGeenVoorraad">Geen Voorraad</option>
            <option value="mxui_widget_SearchInput_11_Verlopen">Verlopen</option>
          </select>

      <button type="button" class="btn mx-button btn-default mx-name-search mx-grid-search-button" id="mxui_widget_Button_12" widgetid="mxui_widget_Button_12"> Zoeken </button>
      <button type="button" class="btn mx-button btn-default mx-name-reset mx-grid-reset-button" id="mxui_widget_Button_13" widgetid="mxui_widget_Button_13"> Wissen </button>

      <button type="button" class="btn mx-button mx-name-newButton2 btn-success" id="mxui_widget_ControlBarButton_10" data-mendix-id="0_17" title="" widgetid="mxui_widget_ControlBarButton_10" data-roving-tabindex="" tabindex="0"> Product toevoegen </button>
      <button type="button" class="btn mx-button mx-name-actionButton3 btn-primary" id="mxui_widget_ControlBarButton_11" data-mendix-id="0_18" title="" widgetid="mxui_widget_ControlBarButton_11" data-roving-tabindex="" tabindex="-1"> Product bewerken </button>
      <button type="button" class="btn mx-button mx-name-actionButton4 btn-danger" id="mxui_widget_ControlBarButton_12" data-mendix-id="0_19" title="" widgetid="mxui_widget_ControlBarButton_12" data-roving-tabindex="" tabindex="-1"> Product verwijderen </button>
      <button type="button" class="btn mx-button mx-name-actionButton5 btn-inverse" id="mxui_widget_ControlBarButton_13" data-mendix-id="0_20" title="" widgetid="mxui_widget_ControlBarButton_13" data-roving-tabindex="" tabindex="-1"> Product archiveren </button>
      <button type="button" class="btn mx-button mx-name-exportToExcelButton2 btn-default" id="mxui_widget_ControlBarButton_14" data-mendix-id="0_21" title="" widgetid="mxui_widget_ControlBarButton_14" data-roving-tabindex="" tabindex="-1"> Naar Excel exporteren </button>

      <button type="button" class="btn mx-button mx-name-paging-first" id="mxui_widget_Button_14" aria-label="Ga naar de eerste pagina" widgetid="mxui_widget_Button_14" data-roving-tabindex="" tabindex="-1" disabled="disabled"> </button>
      <button type="button" class="btn mx-button mx-name-paging-previous" id="mxui_widget_Button_15" aria-label="Ga naar de vorige pagina" widgetid="mxui_widget_Button_15" data-roving-tabindex="" tabindex="-1" disabled="disabled"> </button>

1 tot 2 van 2
 Huidige weergave 1 tot 2 van 2
      <button type="button" class="btn mx-button mx-name-paging-next" id="mxui_widget_Button_16" aria-label="Ga naar de volgende pagina" widgetid="mxui_widget_Button_16" data-roving-tabindex="" tabindex="-1" disabled="disabled"> </button>
      <button type="button" class="btn mx-button mx-name-paging-last" id="mxui_widget_Button_17" aria-label="Ga naar de laatste pagina" widgetid="mxui_widget_Button_17" data-roving-tabindex="" tabindex="-1" disabled="disabled"> </button>

      <colgroup dojoattachpoint="colGroupNode">
        <col style="width: 20%;">
        <col style="width: 20%;">
        <col style="width: 20%;">
        <col style="width: 20%;">
        <col style="width: 20%;">
      </colgroup>

▲

Naam

Code

Prijs

Voorraad

▼

Voorraadstatus

2

2

0,00

0

rrew

rere

1321,00

1

Comment: You can do it with CSS, but it would involve lots of hard coding. For instance, you can use data attributes and CSS attribute selector for styling as per the value in the data attribute. But looking at your table, it seems there are many rows and this is not a good solution for large tables. The best solution would be to use JavaScript as it would keep the code clean and minimal. Example: https://css-tricks.com/almanac/selectors/a/attribute/
Comment: What you want is not possible with CSS. You cannot go up in the hierarchy
Comment: Does this answer your question? [Is there a CSS parent selector?](https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector)
Comment: @jsduniya There is no need for a "jsfiddle" for a question about CSS. Stack Snippets work fine.
Comment: No, i have no idea how to write the full css path to apply the selector..you an idea?
Answer: Is not possible in pure CSS to select an element depending on its content.
But in the code you posted you have applied a different class on each row, so -if you could do it dinamically- this would do the trick.
Otherwise you'll need a pair of line of javascript...
[update]
I've found a (pretty tricky) way to do it; starting from your html code I've added a pseudo element to be used as background for the entire row; this require the TRs to have relative position (thus they must have display property set to a different value than "table-row", in this case I've chosen "flex").
Here's the css code:
.voorraad tr,
.voorraad tr div
{
  position: relative;
  overflow: hidden;
}

.voorraad tr div
{
  z-index:1;
}

.voorraad tr,
.mx-name-head-row
{
  display:flex;
  justify-content:center;
  align-items:center;
}

.voorraad td,
.mx-name-head-row th
{
  flex:1;
  text-align:center;
}

td[title="Geen Voorraad"]:before
{
  content: "";
  display:block;
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background-color:orange;
}

This is not what you would call "clean code", but it do the work.
Answer: If you can move td with title to the beginning of the line, then you can do so.

td[title="Geen Voorraad"], td[title="Geen Voorraad"] ~ td {
  background-color: red;
}

2

2

0,00

0

rrew

rere

1321,00

1


Main class can't inherit method from my second class

Question: I have my main class which looks like this:
#include "stdafx.h"
using namespace std;

class MemoryAddressing : Memory {
    int _tmain(int argc, _TCHAR* argv[])
    {
        Memory mem;
        int hp = Memory.ReadOffset(0x000000);
    }
}

and then I have my second class:
#include <windows.h>
#include <iostream>

using namespace std;

static class Memory {
public : static int ReadOffset(DWORD offset) {
    DWORD address = 0x000000;
    DWORD pid;
    HWND hwnd;
    int value = 0;

    hwnd = FindWindow(NULL, L"");

    if(!hwnd) {
        cout << "error 01: Client not found, exiting...\n";
        Sleep(2000);
    }else {
        GetWindowThreadProcessId(hwnd, &pid);
        HANDLE handle = OpenProcess(PROCESS_VM_READ, 0, pid);
        if(!handle) {
            cout << "error 02: no permissions to read process";
        }
        else {
            ReadProcessMemory(handle, (void*) offset, &value,     sizeof(value), 0);
        }
    }
}
};

It is obvious that I'm trying to inherit the ReadOffset method from my Memory class in my MemoryAddressing class. I have no idea how to, it seems like the classes are unable to communicate.
I already know Java and C# but I think C++ is very different.
Comment: Is this code really C++ ?
Comment: I heard about people having `Memory` classes, but I never thought it was true...
Comment: use public inheritance. ie: `class MemoryAddressing : public Memory`
Comment: And why create a mem local variable?
Comment: What output are you expecting? What output are you getting? (Copy and paste please).
Answer: There is no such concept as static class
And the default inheritence for a class is private. Private inheritence means that the relationship is hidden from users of the class. It is rare to use it but is a bit like aggregation and means "is implemented in terms of" on an Object Orientated level, rather than "is a type of".
And it's not advised to call a method _tmain, but what are you trying to do? override main?
(Or you're trying to copy Java where classes have static main methods to make them runnable as entry points).
Answer: In C++ static class doesn't work. Also your inheritance syntax is off:
class MemoryAddressing : Memory {

should be
class MemoryAddressing : public Memory {

In C++ classes require an access modifier after the : in inheritance. If none is provided, it defaults to private. Here is an excerpt from the C++ tutorial's chapter on inheritance:
In order to derive a class from another, we use a colon (:) in the declaration of the
derived class using the following format:

class derived_class_name: public base_class_name
{ /*...*/ };

Where derived_class_name is the name of the derived class and base_class_name is the
name of the class on which it is based. The public access specifier may be replaced by
any one of the other access specifiers protected and private. This access specifier
describes the minimum access level for the members that are inherited from the base
class.

So without a modifier only private members are inherited. However, since private members cannot be accessed from derived classes, so in essence class A : private B essentially causes no inheritance to happen.
Comment: it says error: not a struct or class when inheriting with class MemoryAddressing : public Memory
Comment: @user1924410 probably because `static class` doesn't make sense to the compiler, and in C++ if the declaration of something is screwed up even a little bit it won't recognize it.


Finding the derivative of $e^{x}$ with by taking the limit of e and the derivative in the same limit; done before?

Question: I am a curious Calculus student with an interesting question.
The derivative of $e^{x}$ = $e^{x}$, however taking the derivative using limits, and not sums or some other method, is difficult.
Perhaps would taking the limit of e, which is $\lim_{n \to \infty} {(1+{1\over n})^n}$ and the $\lim_{h \to 0}  {(e^{x+h} - e^{x})\over h}$, which is the derivative formula.
Now, these limits have different terms, n and h respectively, which go to 0 and infinity. In order to get similar terms, an equivalency of the limits could be set up.
$\lim_{h \to 0} {1\over h} = \infty$, and $\lim_{n \to \infty} n = \infty$
$\lim_{h \to 0} {1\over h}$ = $\lim_{n \to \infty} n$ and vice versa for $1\over n$ to $h$.
Rearranging the equation now gives:
$\lim_{n \to \infty} n({(1+{1\over n})^{n(x+{1\over n})} - (1+{1 \over n})^{nx}})$ or $\lim_{n \to \infty} n({(1+{1\over n})^{nx + 1} - (1+{1 \over n})^{nx}})$
Factoring out $(1+{1 \over n})^{nx}$ gives:
$\lim_{n \to \infty} n((1 + {1\over n})^{nx})((1 + {1 \over n})^1 - 1)$ or $\lim_{n \to \infty} n((1 + {1\over n})^{nx})(1 + {1 \over n} - 1)$
Removing the 1's gives $\lim_{n \to \infty} n((1 + {1\over n})^{nx})({1 \over n})$
Distributing out the n gives:
$\lim_{n \to \infty} (1 + {1\over n})^{nx}$ = $e^x$
This method works for $e^{ax}$ as well, where a is equal to some constant coefficient.
For example: $d\over{dx}$ $e^{3x}$ = $3e^{3x}$.
I will apply the previous method to $e^{3x}$.
Setting up the limit:
$\lim_{n \to \infty} {n}({(1+{1\over n})^{3n(x+{1\over n})} - (1+{1 \over n})^{3nx}})$ or $\lim_{n \to \infty} {n}({(1+{1\over n})^{3nx + 3} - (1+{1 \over n})^{3nx}})$
Factoring out $(1+{1 \over n})^{3nx}$ gives:
$\lim_{n \to \infty} {n}((1+{1\over n})^{3nx})((1+{1\over n})^3 - 1)$
Multiplying out the $(1+{1 \over n})^3$ gives:
$\lim_{n \to \infty} {n}((1+{1\over n})^{3nx})(1+ {3 \over n} + {3 \over n^2} + {1 \over n^3}- 1)$
Subtracting the 1's gives:
$\lim_{n \to \infty} {n}((1+{1\over n})^{3nx})({3 \over n} + {3 \over n^2} + {1 \over n^3})$
Distributing the n gives:
$\lim_{n \to \infty} ((1+{1\over n})^{3nx})(3 + {3 \over n} + {1 \over n^2})$
As n approaches $\infty$, $3 \over n$ and $1 \over n^2$ approach $0$.
With that in mind, and removing the diminishing numbers, gives us:
$\lim_{n \to \infty} 3(1+{1\over n})^{3nx}$ = $3e^{3x}$.
It seems that using this method, the only significant term in the expanded binomial is the second term. Using binomial theorem, the second term of an expanded binomial is $\binom{a}{1} \over n$ which multiplied by the $n$ just becomes $\binom{a}{1}$.
The second term of any combination is just the ${a}$ in $\binom{a}{k}$ where $k$ is some number $0 \le k\le a$.
Thus, for all possible values $a$ in $d \over {dx}$ $e^{ax}$, this method will yield the correct derivative, $a e^{ax}$.
My question is, since this "works", is it even following the rules of mathematics? Nowhere else have I seen this method, I just tried it out one day and saw that it worked. Can limits be exchanged like that?
If all these answers are yes, then has someone does this before, who, and when?
I feel like this insight isn't something new, and it'll probably look elementary, but my math teachers haven't seen this method before, so who knows?
Thanks for looking and responding!
--Additional application for $e^{0x}$--
$\lim_{n \to \infty} n({(1+{1\over n})^{n(0+{1\over n})} - (1+{1 \over n})^{0}})$
which equals:
$\lim_{n \to \infty} n(1 + {1 \over n} - 1)$ = $1$, which is equal to $e^{0x}$ = $e^0$.
Comment: What is the question?
Comment: Has this method of finding the derivative of $e^x$ been proven or done before? I haven't seen it anywhere.
Answer: This argument is shaky from the very beginning, since it's far from clear why
$$
\lim_{h\to 0} \frac{1}{h} \left(
\left( \lim_{n \to \infty} \left( 1 + \frac{1}{n} \right) \right)^{x+h}
- \left( \lim_{n \to \infty}\left( 1 + \frac{1}{n} \right) \right)^{x}
\right)
$$
would equal
$$
\lim_{n \to \infty} \frac{1}{1/n} \left(
\left( 1 + \frac{1}{n} \right)^{x+\frac{1}{n}}
- \left( 1 + \frac{1}{n} \right)^{x}
\right)
.
$$
To begin with, when you take $h = 1/n$ with $n\to\infty$, you're only considering the one-sided limit $h \to 0^+$, but that's not the serious problem. The real issue is replacing the double limits, where $n \to \infty$ first and then $h \to 0$, with just a single limit.
An example, to show why this need not work:
$$
\lim_{h \to 0} \left( \lim_{n \to \infty} \frac{1}{hn} \right)
= \lim_{h \to 0} 0
= 0
,
$$
but
$$
\lim_{n \to \infty} \frac{1}{\frac{1}{n} \, n}
= \lim_{n \to \infty} 1
= 1
.
$$


Stop sccm task sequence deployment

Question: I have deployed a 15 Mb application through SCCM to 10000 machines and its killing the network.
Who can i stop the deployment of this task sequence. I have deleted the task sequence but the network throughput high.
Answer: It may unfortunately be too late. Once the clients have picked up the advertisement they're going to attempt to pull it from the distribution point.
Assuming you've stopped advertising the package to your clients by removing them from the collection or removing the advertisement itself, you could prevent an individual machine from thinking it needs the update and thus stop it from downloading it by running the Application Deployment Evaluation Cycle from Configuration Manager on the workstation. Obviously that's not particularly practical across 10,000 machines.
If you want to be drastic, you could probably find and delete the package from any distribution point(s) which would theoretically stop network traffic, but your clients may get quite angry about it - I'm not sure how the Configuration Manager client handles a package disappearing mid-download.
Comment: You could drop the NIC or vNIC on the distribution point servers. That would mitigate your bandwidth issue, and let you buy time. This would be a drastic step and I would weigh the pros/cons of business impact here.

Stop sccm task sequence deployment


Migrate plugin migration_lookup : dynamic migration id

Question: "node_a_migration" is the migration ID of nodes of type "node_a"
"node_b_migration" is the migration ID of nodes of type "node_b"
I'd like to use either "node_a_migration" or "node_b_migration" as a migration_lookup depending on other field value.
The source (not a drupal site, entities of content A and content B can have the same id, because stored in different tables) :
[
  ['entity_type' => 'content_a', 'entity_id' => 123],
  ['entity_type' => 'content_b', 'entity_id' => 123],
]

The migration config :
process:
  pseudo_field_migration_id:
    plugin: static_map
    map:
      content_a: node_a_migration
      content_b: node_b_migration
    source: entity_type
  field_entity_reference:
    plugin: migration_lookup
    migration: '@pseudo_field_migration_id'
    source: entity_id

There is no error when running the migration, but the field_entity_reference is not populated.
It works if I manually replace '@pseudo_field_type_id' by node_a_migration
Any idea how to make it work ?
Thank you!
Comment: This is not possible in YML, the `migration` parameter is a config value and expects a static string. Only the `source` parameter can fetch dynamic values from the source row. You have to create your own process plugin to do something like this.
Comment: Ok thank you i'll try to create my own process plugin and post my solution
Answer: As @Hudri suggested, I've created my own process plugin (extending MigrationLookup plugin):
my_module/src/Plugin/migrate/process/CustomMigrationLookup.php

namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate\Plugin\migrate\process\MigrationLookup;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

/**
 * @MigrateProcessPlugin(
 *   id = "custom_migration_lookup"
 * )
 */
class CustomMigrationLookup extends MigrationLookup {

  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    // We set the migration id based on the field configured in "migration_id_source"
    $this->configuration['migration'] = $row->getDestinationProperty($this->configuration['migration_id_source']);
    // We continue with the standard migration_lookup process
    return parent::transform($value, $migrate_executable, $row, $destination_property);
  }

}

The migration config :
process:
  pseudo_field_migration_id:
    plugin: static_map
    map:
      content_a: node_a_migration
      content_b: node_b_migration
    source: entity_type
  field_entity_reference:
    plugin: custom_migration_lookup
    migration_id_source: 'pseudo_field_migration_id'
    source: entity_id


Javascript em vários html's

Question: Eu estou aprendendo e utilizar o JavaScript e gostaria de saber se é possível utilizar scripts de um arquivo .js em vários outros .html, com funções e tudo mais. Se for possivel, é só chamar o arquivo .js no .html pela tag

Javascript em vários html's


How many monotonic functions on sets of naturals are there?

Question: A function $f\colon P(\mathbb{N}) \to P(\mathbb{N})$ is monotonic iff
$x \subseteq y \implies f(x) \subseteq f(y)$.
What is the cardinality of the set $F$ of all such functions?

What I have tried:
I know the cardinality is either $2^\mathbb{N}$ or
$(2^{\mathbb{N}})^{2^\mathbb{N}} =
2^{\mathbb{N}\cdot 2^\mathbb{N}} = 2^{2^\mathbb{N}}$. I know that if I asked the question about natural numbers and not sets of them, the answer would be the (analogue of the) greater possibility, and if I asked about real numbers, the answer would be the (analogue of the) lesser possibility. (So as far as I know, there is a kind of "precedent" for both.)
I tried proving it is $2^{\mathbb{N}}$ by finding a bijection between
$P(\mathbb{N})$ and $F$, but I couldn't come up with anything.
I tried proving it is $2^{2^\mathbb{N}}$ in two ways. I tried finding a bijection between $P(\mathbb{N}) \to P(\mathbb{N})$ and $F$. For functions on naturals, this is easy, (and has been asked before): $$g(f) = n \mapsto \begin{cases}
f(0) & n = 0\\
f(n) + f(n-1) & \text{else}
\end{cases}$$
I tried to generalize this trick by defining $g'(f)$ similarly, in terms of sets containing one fewer element. However, such a definition would not be well-founded, because the set of sets of natural numbers is not well-ordered (take the family $\{ n \mid n > c \}$ for some $c$).
I also tried a diagonalization proof by contradiction: assume there is a bijection $$g\colon P(\mathbb{N}) \to F\,,$$ then
$$x \mapsto P(\mathbb{N}) \setminus g(x)(x)$$
or something similar fails to be a monotonic function not in $g$'s image, because it fails to be (necessarily) monotonic, and I don't think this can be fixed.
Comment: What have you tried?
Comment: Can you come up with a minimal and maximal cardinality, to start?
Comment: Yes, I'll update my question with that, and what I tried so far
Answer: Let $$M=\{\,S\subseteq P(\Bbb N)\mid A\subseteq B\subseteq\Bbb N, A\in S\to B\in S\,\}$$
(the set of all upward-closed subsets of $P(\Bbb N)$).
For $f\in F$ and $n\in \Bbb N$, the set $h_f(n):=\{\,A\subseteq\Bbb N\mid n\in f(A)\}$ is an element of $M$. As This gives us a map $h\colon F\to M^{\Bbb N}$, $f\mapsto (n\mapsto h_f(n))$. From $f(X)=\{\,n\in \Bbb N\mid X\in h_f(n)\,\}$ we see that $h$ is injective, but by the same we readily verify that $h$ is onto. So $|F|=|M|^{\aleph_0}$.
Remains to find $|M|$. Clearly, $|M|\le 2^{2^{\aleph_0}}$.
As $\Bbb N\times\Bbb N\approx \Bbb N$, we may as well consider the set of upward-closed subsets of $\Bbb N\times \Bbb N$ instead.
For an arbitrary sequence of non-empty subsets $A_n\subseteq\Bbb N$, we obtain the upward-closed set $X:=\{\,S\in\Bbb N\times\Bbb N\mid\exists n\colon \{n\}\times A_n\subseteq S\,\}$. This map $P(\Bbb N)^{\Bbb N}\to M$ is injective because ee can reconstruct $A_n=\bigcap\{\,A\subset\Bbb N\mid \{n\}\times A\in X\,\}$. It follows that $|M|=2^{2^{\aleph_0}}$.


What's the name for chord progression that always jumps 4 scale degrees?

Question: A very common chord progression in jazz is one where the next root note is at an interval of 4th (perfect or diminished, as the scale suggests) relatively to current root note:

Am7 Dm7 G7 CΔ FΔ Bø Em7 Am7 ... (continue as much as desired)

Does it have a name?
Comment: @Tim the terminology is mathematically acceptable (though still silly) for _scale degrees_, but it's objectively wrong for intervals. 4+5=8, WTH?
Comment: BTW, because of the stupid fact that interval terminology fails to use [the correct way of numbering things](https://en.wikipedia.org/wiki/Zero-based_numbering), _jumping by fourths_ actually means it _always jumps **3** scale degrees_, not 4.
Comment: Now that I know the answer, I found [this related question](https://music.stackexchange.com/q/1136/3032)
Comment: @leftaroundabout - unlike a stopwatch or a ruler, which start from zero, we have to call the first note *note one*, but, point taken. Bit late to change now...
Comment: @Tim It's the distinction between inclusive and exclusive counting.
Answer: It's called a cycle of fourths (or fifths) depending on direction.
Comment: careful there, there is an augmented 4th in there F Maj 7 -> Bm7b5 -> this is not the circle of fourth / fifth.
Comment: The diminished fifth (or augmented fourth) in the progression distinguishes tonality (in the broad sense) from atonality. Having a single diminished fifth (or augmented fourth) causes each note to have a unique environment (neighbors and skips away.)
Comment: Exactly right. Especially important is that this progression mimics the dominant--tonic progression of a descending fifth.
Comment: It seems that the "cycle of fourths" (progression) is mostly the same but not identical to the "circle of fourths" (the thing with the 12 notes) - they overlap for 6 notes/chords, but then part ways. Slightly confusing.
Comment: @gurneyalex It is indeed a cycle of fourths or fifths, as ttw says. If it is felt necessary to distinguish it from a cycle in which all the fifths are perfect, we may more precisely call it a diatonic cycle of fourths or fifths.
Answer: This is called a circle progression, named for the circle of fifths (or fourths, if you like). The circle progression in C Major uses the chords diatonic to C Major, so the roots don't match exactly with the circle of fifths.
The example in the question is a circle progression in A Minor, but in jazz it would be much more common to use an E7 instead of an E-7 as the penultimate chord, since this provides a stronger push to the tonic. The circle progression would in that case no longer be diatonic, though. This circle progression might make more sense as:
<code>I IV vii° iii vi ii V I
</code>
or, in C Major:

    CΔ FΔ B∅ E-7 A-7 D-7 G7 CΔ

since this progression contains a ii - V leading back to the I at the end. It is worth pointing out that the last 5 chords in this sequence are a version of the infamous Rhythm changes played so frequently in jazz: iii7 - vi7 - ii7 - V7 - I7.
Comment: A much simpler, but not diatonic, thus not within a proper answer, would be 'Sweet Georgia Brown'.
Answer: The jazzers call it "back-cycling", because you are going around the circle of fifths ... in reverse.  See, for example: http://www.jazzguitar.be/blog/practicing-back-cycling/
The ii - V  -  I progression is one of the cornerstones of jazz harmony as well.
Answer: The series of chords you posted...

Am7 Dm7 G7 CΔ FΔ Bø Em7 Am7

is a type of sequence known as "descending fifths." This particular sequence is tonal because it honors the diatonic scale. The opposite would be real, which can leave the scale:

Am7 Dm7 Gm7 Cm7 Fm7 Bbm7

For an example of a real descending fifths sequence, try listening to Barber's Adagio for Strings, which runs around the circle of fifths using major 7 chords (with tritone suspensions).
There is also "ascending fifths" which is the opposite, and has a very different effect. An example of this can be found in Mozart's string quarter in G major K. 387, first movement.
Answer: I just call it a progression of fourths. Upwards is assumed.


Node unexpected identifier 'of ' in for loop

Question: I am running an fork of a node based chat server using web sockets,
And after some server issues I pulled the project from github, and was greeted with a node error: ( even though the code was working before )
<code>var server = new ws.Server({host: config.host, port: config.port})
console.log("Started server on " + config.host + ":" + config.port)

server.on('connection', function(socket) {
    socket.on('close', function() {
        try {
            if (socket.channel) {
                for (var client of server.clients) {
                    if (client.nick == socket.nick) {
                        client.connectionCounter--;
                    }
                }
</code>
Node quits giving an un expected identifier error pointing to the 'of ' in the for loop. Help would be appreciated.
Toasty
Comment: What version of node.js are you using?
Answer: for..of is a part of new ES2015 standard and not supported well yet, therefore you need to run node with --harmony flag


How to add application keys in WPF?

Question: I am very new to WPF and I am from the xamarin.foms. I am trying for the login functionality for the WPF application. Here, when the user login the application I need to save the user details in the application kyes like in xamarin.forms.
Application.Current.Properties["UserEmailId"] = userDetails.UserName;

so that, for next login no need to take values from user. How to do this in WPF?
Answer: You can do this with User Settings:
Properties.Settings.Default.UserName = userDetails.UserName;
Properties.Settings.Default.Save();

Comment: Thank you soo much @pinki, I did not set the username setting's scope, this is the reason for getting null. You saved my day :-)
Comment: Thanks, @pinki, I have created new settings file as UsersSettings and added that file to properties folder. When  I run the application the second time, the values are null.
Comment: On initial login: Properties.UserSettings.Default.UserName =userDetails.UserName;
               Properties.UserSettings.Default.Save();
Second time login: Properties.UserSettings.Default.UserName is giving null instead of previously saved value.
Comment: Did you set your username setting's scope as user?

How to add application keys in WPF?


What is the percentage?

Question: From all the population interviewed 36% respondents had a car at home, 19% had a motorcycle and 4% had both.
I need to find the percentage of respondents having a vehicle either motorcycle or car or both.
Could you please give some hints how to solve this problem ?
Thank you
Answer: Look up the inclusion-exclusion principle:
$$P(A\cup B) = P(A) + P(B) - P(A\cap B)$$
Comment: P(A or B) = 0.36+0.19-0.04=0.51(51%) Right ?
Comment: Yep. That's right.
Comment: I had a thought about that and it does not make sence, I need to get percentage for A or B or both. O got only for a or B
Comment: @KostasSt7 Carefully read the linked wikipedia article. The problem is that $P(A)$ also includes those $4\%$ for wich $A$ and $B$ hold at the same time. You want $P(A\cup B) = P(A\setminus B) + P(B\setminus A) + P(A\cap B)$ where $A\setminus B$ denotes set difference ($A$ but not $B$).
Comment: Got it. Thank you very much :)
Comment: @KostasSt7 After you ask a question here, if you get an acceptable answer, you should "accept" the answer by clicking the check mark ✓ next to it. This scores points for you and for the person who answered your question. You can find out more about accepting answers here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/)

What is the percentage?


Return a list type from Product class

Question: I have a Product class in this file: Libraries\Nop.Core\Domain\Catalog\Product.cs
public partial class Product : BaseEntity
{
    public int ProductTypeId { get; set; }
    // 30 more fields, etc.

I have a method in a Controller here: Admin\Controllers\ProductController.cs
public ActionResult ExportExcelAll()
{
    // need to implement this:
    var products = new List<Product>();
    products = ???????

    byte[] bytes = null;
    using (var stream = new MemoryStream())
    {
        _exportManager.ExportProductsToXlsx(stream, products);
        bytes = stream.ToArray();
    }

    return File(bytes, "text/xls", "products.xlsx");
    // PRODUCES AN EXCEL FILE
}

Using that Product class, I want write this query:
select Sku Price from product

But ... the results of the query MUST be returned in a List<Product> type:
var products = new List<Product>();

Can this be done by writing a method in the Product class or something?
Comment: Add `.ToList()` to the end of your query. In other words, `(from p in products select new { Sku = p.SKU, Price = p.Price }).ToList();`
Comment: thanks, but how do I write the query? I'm new to MVC and LINQ.
Comment: We have to know where the data is stored before we can define where it's going to come from ...e.g. if you're using a `Linq.dbml` you'd update the given query with the location of the data e.g., `var db = new LinqDataContext();` and add "db." to `(from p in **db.**products select new { Sku = p.SKU, Price = p.Price }).ToList();`
Answer: If you're using MVC and Entity Framework and letting Visual Studio do all the scaffolding for you, you will have the following at the top of your controller:
public class MyController : Controller
{
    private MyDataContext db = new MyDataContext();

Then to query in your action:
var listOfProducts = (from p in db.Products
                     where p.Property == "condition"
                     select p).ToList();

If you are new to Linq I suggest downloading LinqPad and running through the tutorials supplied. Additionally it is an invaluable tool when playing around with code!

Return a list type from Product class


Primitive element theorem - why any finite and separable extension is simple

Question: I have it in my lectures notes that the claim:
Let $K/F$ be a finite and separable extension then $K$ is a simple extension of $F$ follows immediately from the theorom : Let $K/F$ be a finite extension, then it is simple iff $K/F$ have a finite number of subfiels.
My question is why ? I know that the extension is finite and separable hence $K=F(a_1,...a_n)$ where $a_i$ are all separable, but why there are only finite number of subfields between $F$ and $K$ ?
Comment: Whether this is circular or disallowed depends on how you've developed the theory, but one way is to take the normal closure, which will be a finite Galois extension, and use the Galois correspondence. (A finite group has but finitely many subgroups.)
Answer: Hint: Consider the Galois closure of $K$.


Probability of failure in a finite population

Question: I regularly inspect finite populations for failures (we make custom products in batches of ~500-800).  Currently, we inspect every product for failure, which is quite a bit of work.  I want to reduce the number of samples we inspect by stating a desired error rate, and determining the number of samples needed to inspect to be confident we are hitting the error rate.
I'm aware that the the rule of 3 would apply if there are no failures, but I'd like a more precise solution in situations where the sampling does have a failure.
This seems like it would be best modeled as a hypergeometric distribution, but I'm struggling to frame the question properly in these terms.  I like examples, so say I have a population of 500, and I want to be 99% confident that there are 5 or fewer failures in the population.
How do I frame this type of question using the hypergeometric distribution?
My current attempt is this (in terms of the Wiki variables):
$N=500$; $K=495$; $n=100$; $P(X)=0.01$
With a sample of 50 and 3 failures, the probability of a 10% failure rate is (for some reason, I'm getting a [Math Processing Error] when using LaTex, so I'll post my progress in R commands)
qhyper(p=0.01, m=495, n=5, k=100)
Which gives $k=97$.  Interpreting this, I should take away that from a 100 sample set in a population of 500, I can be 99% confident that if I find 3 or fewer failures in my sample, the error rate is no worse than 1% (or 5 in 500)?
I admittedly don't have a great intuition for this type of distribution, but my gut is giving me pause at the thought of sampling 100 specimens, finding 3 failures, and declaring with 99% confidence that there are only up to 2 more in the remaining 400.
Comment: Rule of 3 is actually not the best choice: https://stats.stackexchange.com/questions/134380/how-to-tell-the-probability-of-failure-if-there-were-no-failures/190573#190573
Comment: Thank you for the update, @Tim.  I'll certainly use a different approach when there are no failures.  I'm still interested, though, in a solution when failures do exist.
Answer: Suppose you sample $n$ members from a population of $N$ (without replacement) and $k$ of them are failures.  The definition of confidence tells us to ask this question:

If there are $K$ failures in the population, what is the chance we observe $k$ or fewer failures in the sample?

Without going into the combinatorial details, let's just call this number $p(k,K;n,N)$.  It can be used to establish upper confidence limits on $K$ through a form of logical inversion.  Let $N$ and $n$ both be known and $\alpha$ be a specified probability.  If $K^\prime$ is so large that $p(k,K^\prime;n,N) \lt \alpha$, then it is unlikely we would have observed $k$ or fewer failures in the first place.  This gives us confidence that the true number of failures, $K$, is strictly less than $K^\prime$.
Pushing this reasoning to its natural limit, we therefore seek the smallest value $K^\prime$ for which $p(k, K^\prime; n, N) \lt \alpha$.  We will use $K^\prime - 1$ for the $1-\alpha$ upper confidence limit on $K$.  Equivalently we could maximize the value $K^{\prime\prime}$ for which $p(k, K^{\prime\prime}; n, N) \ge \alpha$:
$$\operatorname{UCL}_\alpha(k) = \max\{K\,|\, p(k, K; n, N) \ge \alpha\}.\tag{1}$$

Now for the details.  The chance of observing exactly $k$ failures is the chance that (a) our $n$-element sample contains those $k$ failures and (b) the remaining $N-n$ members of the population contain the remaining $K-k$ failures.  This describes $\binom{K}{k} \binom{N-K}{n-k}$ subsets out of $\binom{N}{n}$ equally likely subsets.  Summing these for all values from $k=0$ to $k$ equal to the actual number of observed failures gives
$$p(k,K;n,N) = \frac{1}{\binom{N}{n}}\sum_{j=0}^k \binom{K}{j} \binom{N-K}{n-j}.$$
This is the Hypergeometric distribution.
In R, for instance, the parameters to supply to the Hypergeometric functions are $N-K$ (called m on the manual page), $K$, (n), and $n$ (k).  The phyper function implements $p$ and the qhyper function implements its inverse.
Take, for example, a case of a population with $N=8$ elements from which a sample of size $n=4$ is drawn and $k=1$ failure is observed.  Then
$$p(3, K, 4, 8) = \frac{1}{\binom{8}{4}}\sum_{j=0}^1 \binom{K}{j}\binom{8-K}{4-j} = \frac{1}{70}\left(\binom{8-K}{4} + K\binom{8-K}{3}\right).$$
The possible values of $K$ range from a minimum of $k=1$ (the one failure observed) to $k = k + (N-n) = 5$ (occurring when every non-observed member of the population is a failure).  Plugging these values into the preceding equation gives the sequence
$$(70, 55, 35, 17, 5)/70 \approx (100, 79, 50, 24, 7)/100.$$
R will compute them in one stroke as
phyper(1, 1:5, 8-(1:5), 4)

We read these numbers like this:

There is $100\%$ confidence the population has at least $K=1$ failure.  (We have seen it.)
There is $79\%$ confidence the population has at least $K=2$ failures.  In other words, we attach high confidence to the existence of at least one more failure in the $N-n=4$ members not observed.
There is $50\%$ confidence the population has at least $K=3$ failures.  This may seem counter-intuitive: since we have seen half the population and observed $k=1$ failure, shouldn't we assign exactly $1/2=50\%$ confidence to seeing one more failure in the other half of the population?  This is where confidence differs from probability.  The correct approach asks this question: when there are $K=3$ failures in the population (of size $N=8$) and we sample half of it, what is the chance we will see just zero or one failures?  By symmetry--the unsampled members themselves constitute a random sample of $N-n=4$, too--this is the chance that the remaining unsampled members will consist of just zero or one failures.  Thus observing zero or one failures out of three in the population is an event that will occur half the time.  Consequently, actually observing one failure is perfectly consistent with the presence of three failures total.
There is $24\%$ confidence the population has at least $K=4$ failures and $7\%$ confidence it has at least $K=5$ failures.  These numbers are starting to get close to typical values of $\alpha$.  For instance, with $\alpha=0.10$ the $90\%$ upper confidence limit for $K$ would be $K=4$.  But with $\alpha=0.05$ the upper $95\%$ UCL for $K$ is $K=5$.  When we observe one failure out of four, in a sample from a population of eight, there is an appreciable risk that all the unsampled members are failures!  This is because when five of eight members are failures, there's still a considerable chance--more than $7\%$--that our sample just happens to include all three successes.

Note that qhyper in R does not compute confidence limits.  You need to search, just as we did in this example.  A brute-force search (but relatively efficient for R) tests all the values, as in
which(phyper(1, 1:5, 8-(1:5), 4) >= .10)

This command returns the indexes 1 2 3 4, showing that the first four elements of the vector 1:5 (representing the possible values of $K$) are consistent with our observations at the $\alpha=0.10$ level.  The largest of those, $4$, corresponds to $K=4$ as we found through inspection.

In the example of the question, a sample of size $n=100$ is taken from a population of $N=500$ and $k=3$ failures are observed.  What is a $90\%$ upper confidence limit for the total number of failures $K$?  The R search is
`max(which(phyper(3, 1:100, 500-(1:100), 100) >= .10))`

(The correspondence between this and the mathematical formula for the UCL in $(1)$ is evident.)
It returns a UCL of $30$.  Let's double-check by computing the probabilities $p(3,30;100,500)$ and $p(3,31;100,500)$.  The first should exceed $10\%$ and the second should drop just below it:
> phyper(3, 30, 500-30, 100)
[1] 0.1151626
> phyper(3, 31, 500-31, 100)
[1] 0.09959309

That's exactly what happens.  We conclude, with at least $90\%$ confidence, that there exist up to (but no more than) $K-k=30-3=27$ additional failures among the $N-n=500-100=400$ unsampled members of the population.
Comment: As always, thank you for the time and such a detailed response, @whuber.  This is precisely what I needed.  My "ah ha" moment was during your second bullet point when the population was split in half.
Comment: @nebcb: The confidence isn't the probability that all members of the population are faulty. If there are 4 (5, 6, 7, or 8) failures in the population of 8, what is the chance we observe 4 or fewer failures in the sample of 4? The answer is 100% in every case, and an upper confidence limit at the 100% (or any lower) level is 8. It'd be a weird procedure that, given an entirely faulty sample, ruled out an entirely faulty population at any confidence level. Not a bug but a feature.
Comment: I've been playing with the result above, but it seems to break down when you have a really high failure rate. Take the example of a population of 8 and you sample 4. If all of those 4 fail, then the equation above tells you will 100% probability that all member of the population are faulty. This seems like a "bug".


Programmatically display user names according to the user profile type

Question: This is a Drupal 7 site. I have a profile2 module installed with several profile types for different users. The user name should be displayed according to the profile type:

For personal users - the user name should be build from the first and last name fields.
For business users, the user name should be taken from the business name field.

How do I display user names programmatically?
Answer: I've put the following code on a module:
<code><?
// Find the type of the current user
function mymodule_get_usertype(&$user) {
  $usertype = 'other';
  if (is_array($user->roles) &&
      in_array('authenticated user', array_values($user->roles))) {
    $usertype = 'individual';
  }
  elseif (is_array($user->roles) &&
          in_array('non authenticated user', array_values($user->roles))) {
    $usertype = 'individual';
  }
  elseif (is_array($user->roles) &&
          in_array('business', array_values($user->roles))) {
    $usertype = 'business';
  }
  return $usertype;
}

// Implements hook_username_alter,
// to display the user name according to the profile type
function mymodule_username_alter(&$name, $account) {

  $profile_type = mymodule_get_usertype($account);
  if (!empty($profile_type)) :
    $profiledata = profile2_by_uid_load($account->uid, $profile_type);
  endif;

  if ($profiledata) :

    switch ($profile_type) {
      case 'individual':
        $firstname = field_get_items('profile2', $profiledata, 'field_first_name');
        $firstname = $firstname[0]['safe_value'];
        $lastname = field_get_items('profile2', $profiledata, 'field_last_name');
        $lastname = $lastname[0]['safe_value'];
        $name = "$firstname $lastname" ;
        break;

      case 'business':
        $bizname = field_get_items('profile2', $profiledata, 'field_biz_name');
        $bizname = $bizname[0]['safe_value'];
        $name = $bizname;
        break;

      default:
        // For admin users, no change
    }
  endif;
}
?>
</code>
The result is that the new name is displayed whenever a user name is displayed (e.g. on the menus, on the user page, or on the user listing pages)
Comment: The method chosen is correct but I would recommend checking the for empty results from field_get_items() instead of assuming there is always going to be a value. The $user parameter doesn't need to be a reference in mymodule_get_usertype(). I would use elseif for the role checking to reduce unnecessary code running. - It is also good to keep with the drupal coding standards when providing help to try to promote good practice. https://drupal.org/coding-standards
Comment: Thanks for the code review. Question is if I can directly get the values without using the "$firstname[0]['safe_value'];" syntax.
Comment: Nope there is no way around that.


Ler arquivo txt e fazer validações em javascript

Question: Tenho um arquivo em txt que contem mais de mil linhas, cada linha existe uma númeração que precisa ser validada por um script em javascript que tenho pronto.
Gostaria que algum script em php ou javascript mesmo lesse o arquivo em txt, pegasse linha por linha e fosse validando com o outro script de validação que tenho, e quando validasse, caso a linha seja reprovado na validação, que a mesma seja excluida ou pelo menos marcada com algum caractere especial, mas prefiro que seja removida mesmo.
Obs: Tenho servidores Linux que aguentariam o processamento, caso a solução exija muito da maquina.
Verificação simples que seria utilizada:
var numero = "55555555555"; // Aqui no caso seria puxado o arquivo em txt
if(numero.match(/55555555555/))
{ document.write("OK"); } else{
document.write("Nao Passou");}

Existe alguma forma de fazer isso?
Comment: Esse JavaScript estará rodando no navegador ou no Node?
Comment: No navegador ...
Comment: Que tipo de validação é essa? Tem como colocá-la junto a pergunta?
Comment: São validações simples, mas várias, mas um exemplo seria assim:
Comment: Coloque na pergunta, por favor. Se são validações simples, recomendo que as implemente em PHP e faça tudo por essa linguagem. Utilize o JS somente se a implementação dessa validação em PHP for inviável.
Comment: Mas não existe alguma forma de fazer do jeito que expliquei?
Comment: Em PHP, sim. É bem fácil, mas preciso que você esclareça na pergunta que tipo de validações são essas.
Comment: Poderia me dar um exemplo de como fazer isso no PHP se eu fosse utilizar apenas uma verificação simples caso em alguma linha do arquivo txt fosse encontrado uma sequencia númerica, exemplo 55555555555? Pq o resto eu conseguiria mudar tudo pra php, só precisaria de um exemplo.
Comment: Vc quer criar o novo arquivo txt na máquina ou no servidor?
Comment: O que for mais viavel, pois o resultado disso seria apenas pra mim, não iria colocar pra usuarios rodarem via navegador, apenas eu mesmo rodaria isso.
Answer: Como comentei, com JavaScript rodando no navegador não será possível - de forma simples, pois o JavaScript não possui acesso aos arquivos. Você comentou que são validações simples, estão será mais viável implementá-las em PHP e executar tudo com essa linguagem.
Para abrir e ler o conteúdo de um arquivo, você pode utilizar a função file:
<?php

$file = file("arquivo.txt");

if ($file !== false)
{
    foreach($file as $index => $line)
    {
        // Validação da linha...
    }
}

Com base nos seus comentários, a validação citada seria se o valor da linha casa com o padrão /55555555555/, definido por uma expressão regular. Considerando que quando o conteúdo da linha não casar com esse padrão a linha deverá ser excluída, pode-se fazer:
<?php

$file = file("arquivo.txt");

if ($file !== false)
{
    foreach($file as $index => $line)
    {
        if (!preg_match("/55555555555/", trim($line), $matches))
        {
            unset($file[$index]);
        }
    }
}

Assim, o array $file, após terminar o laço de repetição, possuirá apenas os valores que passaram pela validação. Para escrever novamente no arquivo, basta utilizar a função file_put_contents em conjunto com a implode:
file_put_contents("arquivo.txt", implode("", $file));

Documentação

Função file;
Função preg_match;
Função trim;
Função unset;
Função implode;
Comment: Exatamente isso, resolveu meu problema. Obrigado.
Comment: É possível pelo JavaScript via Ajax.
Comment: @DvD apenas se um servidor estiver servidor o arquivo via HTTP, mas mesmo assim não conseguiria salvar novamente o arquivo. Para salvar, teria que ter um *script* rodando no lado do servidor para isso também. Mais prático fazer tudo no PHP mesmo.
Answer: Usando JavaScript com Ajax
O script abaixo irá percorrer linha por linha do arquivo .txt excluindo as linhas que não possuírem a string desejada e atualizando o arquivo em tempo real:

Arquivo filtrar.php:
<?php
$conteudo = $_GET['cont'];
$arquivo = $_GET['arquivo'];
if(isset($conteudo) && isset($arquivo)){
    $fp = fopen($arquivo,"r");
    $texto = fread($fp,filesize($arquivo));
    fclose($fp);

    $fp = fopen($arquivo,"w");
    $nconteudo = str_replace($conteudo, '', $texto);
    $nconteudo = str_replace(str_replace("\n", '', $conteudo), '', $nconteudo);
    fwrite($fp,rtrim($nconteudo));
    fclose($fp);
}else{
?>

<input type="button" value="Iniciar" id="inicio" />

<?php
}
?>

Necessário que os arquivos estejam no mesmo diretório e que o mesmo possua autorização para leitura e escrita.
Comment: Como comentei, uma solução com complexidade bem desnecessária, pois necessitará de um servidor web servindo o arquivo de texto e necessitará de um *script* PHP no servidor para gravar os novos dados. É válido postar a resposta a título de curiosidade, mas ao meu ver, seria um péssimo jeito de resolver o problema. A única situação que eu vejo isso sendo plausível é quando a validação já estivesse implementada em JS e tivesse uma complexidade tão grande que inviabilizaria sua implementação em PHP - o que é extremamente raro acontecer.
Comment: @AndersonCarlosWoss Sua resposta não necessita de servidor pra rodar?
Comment: Não, apenas o PHP (interpretador) instalado.
Comment: @AndersonCarlosWoss Blz. Não considero "_bem desnecessária_" a solução que propus, é apenas uma forma bem diferente da sua.


How to import your own HEADER (.h) file inside a C project

Question: I am using Xcode (mac) and I want to import my own header file inside of a C project. How do I do this?
Comment: Open that file and choose `Project -> Add Current File to Project`.
Comment: Add Current File To Project is disabled
Answer: With your project open, go to the Project menu, choose Add to Project..., browse to the header file you want to add, on the next dialog click the copy into destination group's folder (assuming the file is NOT within your project's path), then click the Add button. The file will now appear within your project.
Answer: Does <code>#include <C:\MyPath\MyHeader.h></code> not work?
Where "C:\MyPath..." is your OS's way to specify the path.
Comment: Example fail (read again and tell me OP's OS). Also, relative paths are basically standard - for good reasons. Furthermore, if that's supposed to be a preprocessor directive (I don't know Xcode, might be some weird format it uses), strip those brackets and put a `#` in front of it.
Comment: Yes, he's using Mac, but the idea is the same, to write the header filepath within the include statement.
Comment: I used #include
and it works thank u
Comment: I'm glad I could help! Strange though, that the accepted answer actually being accepted has been downvoted previously to being accepted! =P Hehehe...
Comment: @downvoters: Please, explain yourself as I don't understand being downvoted when my answer helped to solve the OP's problem. Isn't it what the OP did after all (please see his comment)!?
Comment: @Will, Perhaps using valid syntax in your example would help? Specifically, using both angles and double-quotes around the file name is incorrect. Use one or the other. And know the difference.
Comment: @RBerteig: I have perhaps made this mistake, but didn't this answer guide to the solution? I knew it was something such as what I have proposed to the OP. I haven't coded in C since about 15 years, so a bit of tolerence sometimes is to be considered. But after all, I have provided a valid solution to the OP. I think we hold to much for the details and syntax stuff than the concepts sometimes. One may have a good solution, but doesn't the EXACT syntax and he's being downvoted! Wonderful! I just don't agree with this EXACTITUDE sickness.
Comment: @RBerteig: No offense meant when I wrote the last comment. I hope one can get my point here. But most importantly, I helped the OP. Secondly, I have reminded something about the C syntax because of you, which I appreciate. Thanks for letting me know. :-) At least I know what was wrong. =)
Comment: @Will, None taken. I'm not one of the downvotes, but I thought I'd hint at what was a likely source of them. Helping the OP is indeed the point, but SO is also trying to be a reliable source. That (IMHO) means that examples should be correct in incidental details as well as helpful. We don't want to create a fresh problem while answering a question for someone new who gets here directly from Google, for instance.
Comment: @RBerteig: I guess that SO also wants we help each other. Under that point of view, I would gratefully appreciate one commenting that the syntax is incorrect, though the main idea is good, and mention what I have been doing wrong. This way, I will be pleased to have to correct my answer to show the right syntax or whatever. Anyway, I get your point, and I'm sure you got mine too. Thanks for having let me know about the syntax information. =)


How to extract the ids from the 99th percentile of results for each day

Question: I have a data set in Kusto and I would like to gather the ids from each day where their latency is greater than the 99th percentile for that day.
e.g I have a table like this:

id
latency
time

a
23.4
1/2/2022

c
1.4
1/2/2022

b
25.6
1/3/2022

d
2.3
1/3/2022

and I want the result table to just be

time
id

1/2/2022
a

1/3/2022
b

where a and b come from the 99th percentile of latency times for those days
What I would like to work:
let 99p= T
| summarize percentiles(latency, 99) by bin(time, 1d);
T
| where startofday(time) == 99p.time
| where latency > 99p.latency
| project time, id

Thanks for any insight, pretty new to kusto
Comment: What is the desired result in case you have multiple ids per day?
Comment: @DavidדודוMarkovitz to list all the ids above the percentile for that day
Answer: // This is not a part of the solution, only generation of a sample data set
let T = materialize (range id from 1 to 1000 step 1 | extend ['time'] = ago(rand()*10d), latency = round(rand()*100,2));
// The solution starts here
T | extend day = bin(['time'], 1d) | as T2
| summarize percentiles(latency, 99) by day
| join kind=inner T2 on day
| where latency >= percentile_latency_99
| summarize make_list(id) by day

day
list_id

2022-03-20T00:00:00Z
[298]

2022-03-21T00:00:00Z
[642]

2022-03-22T00:00:00Z
[200,504]

2022-03-23T00:00:00Z
[726,885]

2022-03-24T00:00:00Z
[590,975]

2022-03-25T00:00:00Z
[107]

2022-03-26T00:00:00Z
[836]

2022-03-27T00:00:00Z
[68]

2022-03-28T00:00:00Z
[527,859]

2022-03-29T00:00:00Z
[172,874]

2022-03-30T00:00:00Z
[274]

Fiddle


BASH - How to retrieve a single line from the file?

Question: How to retrieve a single line from the file?
file.txt
"aaaaaaa"
"bbbbbbb"
"ccccccc"
"ddddddd"

I need to retrieve the line 3 ("ccccccc")
Thank you.
Comment: How would the script/command select that line? Will you provide `3` as an argument to the script, or will you specify it otherwise? What have you tried yourself?
Comment: I need to save it in a variable or used echo
Answer: sed is your friend. sed -n 3p prints the third line (-n: no automatic print, 3p: print when line number is 3). You can also have much more complex patterns, for example sed -n 3,10p to print lines 3 to 10.
If the file is very big, you may consider to not cycle through the whole file, but quit after the print. sed -n '3{p;q}'
Answer: If you know you need line 3, one approach is to use head to get the first three lines, and tail to get only the last of these:
varname="$(head -n 3 file.txt | tail -n 1)"

Another approach, using only Bash builtins, is to call read three times:
{ read ; read ; IFS= read -r varname } < file.txt

Answer: Since, as usual, all the other answers involve trivial and usual stuff (pipe through grep then awk then sed then cut or you-name-it), here's a very unusual and (sadly) not very well-known one (so, I hereby claim that I have the most original answer):
mapfile -s2 -n3 -t < input.txt
echo "$MAPFILE"

I would say this is fairly efficient (mapfile is quite efficient and it's a bash builtin).
Done!
Answer: Here's a way to do it with awk:
awk 'FNR==3 {print; exit}' file.txt

Explanation:

awk '...' : Invoke awk, a tool for manipulating files line-by-line. Instructions enclosed by single quotes are executed by awk.
FNR==3 {print; exit}: FNR stands for "File Number Records"; just think of it as "number of lines read so far for this file". Here we are saying, if we are on the 3rd line of the file, print the entire line and then exit awk immediately so we don't waste time reading the rest of a large file.
file.txt: specify the input file as an argument to awk to save a cat.
Answer: There are many possibilities: Try so:
sed '3!d' test

Here is a very fast version:
sed "1d; 2d; 3q"

Answer: Are other tools than bash allowed?  On systems that include bash, you'll usually find sed and awk or other basic tools:
$ line="$(sed -ne 3p input.txt)"
$ echo "$line"

or
$ read line < <(awk 'NR==3' input.txt)
$ echo "$line"

or if you want to optimize this by quitting after the 3rd line is read:
$ read line < <(awk 'NR==3{print;nextfile}' input.txt)
$ echo "$line"

or how about even simpler tools (though less optimized):
$ line="`head -n 3 input.txt | tail -n 1`"
$ echo "$line"

Of course, if you really want to do this all within bash, you can still make it a one-liner, without using any external tools.
$ for (( i=3 ; i-- ; )); do read line; done < input.txt
$ echo "$line"

There are many ways to achieve the same thing.  Pick one that makes sense for your task.  Next time, perhaps explain your overall needs a bit better, so we can give you answers more applicable to your situation.
Comment: Note: `nextfile` requires GNU awk
Comment: Actually, nextfile also works in FreeBSD's awk, which I suspect means it's also portable to OSX.  But a good point in general; if `nextfile` isn't available, it may be possible to simply `exit` with similar effect.
Comment: I think `exit` is the more straightforward command to use here, regardless of awk version.
Comment: You're right, it is.  I guess I'm just in the habit of using `nextfile`.  Anyway, I like the last (bash-only) solution the best.  :)
Answer: Fast bash version;
while (( ${i:-1} <= 3 )); do
  (( $i == 3 )) && read -r line; (( i++ ))
done < file.txt

Output
echo "$line" # Third line
"ccccccc"

Explanation

while (( ${i:-1} <= 3 )) - Count until $i equals 3 then exit loop.
(( $i == 3 )) - If $i is equal to 3 execute read line.
read -r line - Read the file line into variable $line.
(( i++ )) - Increment $i by 1 at each loop.
done < file.txt - Pipe file into while loop.


How do I use a QR code result from ZXing as a string?

Question: I got ZXing working using an intent, but I am really confused as how to use the output and save it as a string.
Here is the intent:
public void scan(View view) {

    try {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes

        startActivityForResult(intent, 0);
    }
    catch (Exception e) {

        Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
        Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri);
        startActivity(marketIntent);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 0) {

        if (resultCode == RESULT_OK) {
            String contents = data.getStringExtra("SCAN_RESULT");
        }
        if(resultCode == RESULT_CANCELED){
            //handle cancel
        }
    }
}

And trying to use it as a string:
<TextView
    android:id="@+id/result"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/"title_activity_on_activity_result"
    android:layout_marginTop="45dp"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/button"
    android:layout_alignEnd="@+id/button" />

And finally the strings:
<string name="app_name">TEST123</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="button_scan">Scan</string>
<string name="title_activity_activity_result">ActivityResult</string>
<string name="title_activity_on_activity_result">onActivityResult</string>

Exception:
EXCEPTION: main
java.lang.RuntimeException: Unable to resume activity
{com.JunkerDev.testfaggot/com.JunkerDev.testfaggot.MainActivity}:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0,
result=-1, data=Intent { act=com.google.zxing.client.android.SCAN flg=0x80000 (has
extras) }} to activity
{com.JunkerDev.testfaggot/com.JunkerDev.testfaggot.MainActivity}:
java.lang.NullPointerException

How can I fix this problem?
Answer: The text in the QR code is in the local variable contents. This has to be set as the text of your TextView with id result; In code, not in XML.
To do so, you should declare a member in your Activity:
TextView mResult;

In onCreate(), after setContentView(), bind it to the TextView:
mResult = (TextView) findViewById(R.id.result);

And finally in onActivityResult():
if (resultCode == RESULT_OK) {
    String contents = data.getStringExtra("SCAN_RESULT");
    mResult.setText(contents);
}

Comment: Thanks a lot for the help, especially when you go into detail, but i still have a problem, now when i have scanned the qr code and it tries to go back (to hopefully showcase it in the textView) it crashes.
Comment: Can you paste the stack trace of the exception? You can find it in the LogCat window in red text
Comment: Kind of confused where to find the "trace of the exception" and google didn't have any immediate answer. Is that just logcat because for me that's filled up with like millions of messages every second.
Comment: In the LogCat select in the small menu "Error", so you see only the red text, and filter out the rest. The stack trace is a trace of what your app was doing when an exception was risen and it crashed
Comment: think i found it: Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=com.google.zxing.client.android.SCAN flg=0x80000 (has extras) }} to activity {com.JunkerDev.testfaggot/com.JunkerDev.testfaggot.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3495)
            at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2905)
Comment: Yes, that's it. Now edit your original post and the complete message in it. Comments have size restrictions.
Comment: Just added it to the original post
Comment: Man i could really use some help, should be posted correctly
Comment: Good, but I guessed there was more text. The problem is a NullPointerException, it means some variable/reference was null when you tried to call a method on it. In the complete message there is the line number referencing where your code crashed. You can even double click on it to jump exactly there. Please post the rest of the message
Comment: it looks like it's this line of code: mResult.setText(contents); causing the nullpointecxeption
Comment: Are you still up for helping me or should i post a new thread?
Comment: Do not post a new thread. Did you add the line `mResult = (TextView) findViewById(R.id.result);` in `onCreate()` after `setContentView(...)`? Has your TextView got the line `android:id="@+id/result"`?


static variables, what is their life span?

Question: I am using static variables in my app, lots of them. My question is, when I exit the app will they be still in memory..? If yes, how can I correct this. Thanks in advance.
Comment: What do you mean by "signout"? Terminate the program/process/JVM?
Comment: can you give more examples ? or i dont believe this question will live long
Comment: Low-quality questions always seem to attract low-quality answers... and this one is no exception. Voting to close.
Comment: @Jean-François Corbett I think there are lots of good quality answers to this low quality question.
Comment: @Thilo I think he is talking about Android apps... Please specify that, Raghav.
Comment: It is an android application.
Comment: I think I've confused everyone..I think I'm not able to clear myself
Comment: yes specifically android, but I thought the concept would be same for static variables.
Comment: @Raghev: yes, answer quality is good, but quite scattershot. No one really knows what the question is. Voting to close.
Comment: I'm just asking will the static variables be in memory when the app exits. Is it confusing?
Comment: @Raghav can you specify more the word app? Is it nromal java palication, that you start with java command starting new JVM for it?
Answer: Static variable gets loaded when class is loaded by ClassLoader, and would be removed when it is Unloaded
Answer: For the Next Readers of this question-

As Everybody said in the answer that static variables are class
  variables. They remain in the memory until the class is not unload from JVM.

In Android you have seen that when we close any application then it does not close completely,
It remains in the recent application stack, That you can see by long press the home button(On Most Devices).
 Android itself kicked out those recent apps when the other app needs memory

In Android, static variable unload when-
 -You force stop your app.
 -Application crashes.
 -You clear your app data.
 -Switch off your Device.
 -Android kicked out recent app

Answer: The static variable will live as long as the class is loaded in the JVM. When there are no more instances of the class being ran in the JVM the class will be unloaded and the static variable will be eligable for garbage collection.
Comment: The class will not be unloaded, even when there are no instances left. It is only unloaded when the whole classloader goes away.
Answer: In addition to the other answers, also note that if those static "variables" are actually "static final" primitive constants, then they don't really exist as separate entities at all, but their value gets compiled right into all the classes that use them (not just the one that defines them).
Answer: Static variables are associated with a class and they will live as long as the class is in the memory(which ceases to exist once your application terminates).
Comment: or once the class gets unloaded (which very rarely happens).
Answer: Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object.Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
When instance is not use, garbage collector will be destroy it. it means that your instance will erased from memory.
Answer:
I am using static variables in my app, lots of them.

Static variables are immune to automatic memory management and you should set them to null in the onDestroy method (Android). They belong to a class for sure and it works exactly as pointed out by @Jigar Joshi.
Comment: There is no mention of `Android` here.
Comment: sry man, my fault but also its same in classic java, you must set them to null.
Answer: if it is C/C++, and if you didnt collect the garbages, you should use a memory management program. İf it is java, close any "javaw" programs from memory and close jvm
Comment: even in C/C++, when the process terminates (if this is what this question is about), the OS releases all memory.
Answer: static variable's are called class variable and in way of scope they loaded when the class is loaded and unloaded when class is unloaded. for example a class variable like
private int classinVar;

is automatically initialized by its default value when class loaded, and same concept is with signout when you get signout then that class would go out of context with its static field.


Finding $f'(x)$ - possible answer but need help

Question: Question: If $f(x) = \cfrac{x}{x + \cfrac{x}{x + \cfrac{x}{x + \vdots}}}$, find $f'(x)$.
Possible Answer:

After searching all over the place I've given up and resorted to posting this, I know this is a very simple problem for most of you on here but I was wondering if you could check my answer- found this question somewhere on this website yet they didn't post the answer.
Thanks
George
Comment: Please do [not use pictures for critical portions](//math.meta.stackexchange.com/a/20529/290189)
of your post. Pictures may not be legible, cannot be searched and are not view-able to some,
such as those who use screen readers.
Answer: Since we have that
\begin{align}
f(x) = \frac{x}{x+f(x)}
\end{align}
then it follows
\begin{align}
f'(x) = \frac{x+f(x)-x-xf'(x)}{(x+f(x))^2} \ \ \implies f'(x)\left(1+\frac{x}{(x+f(x))^2} \right) = \frac{f(x)}{(x+f(x))^2}.
\end{align}
Hence it follows
\begin{align}
f'(x)=\frac{f(x)}{(x+f(x))^2+x}.
\end{align}
Edit: Observe that
\begin{align}
f'(x) =&\ \frac{f(x)}{x^2+2xf(x)+f(x)^2+x} = \frac{f(x)}{x^2+xf(x)+2x} = \frac{f(x)+x-x}{x^2+xf(x)+2x}\\
 =&\ \frac{1-\frac{x}{x+f(x)}}{x\frac{x+f(x)}{x+f(x)}+2\frac{x}{x+f(x)}} = \frac{1-f(x)}{x+2f(x)}.
\end{align}
Comment: What did I do wrong if this is correct? Thanks for answering
Comment: I don't think you did anything work.
Comment: Is this incorrect https://i.stack.imgur.com/ZtILS.jpg
Comment: Since both answers agree, then I believe you are correct.
Comment: Thank you, amazing explanation/proof, thanks a lot! :)
Answer: I have a somewhat different answer.  Starting from $$\begin{align}
f(x) = \frac{x}{x+f(x)}
\end{align}$$
we have $$xf(x)+f^2(x)=x\\
xf'(x)+f(x)+2f(x)f'(x)=1\implies\\
f'(x)=\frac{1-f(x)}{x+2f(x)}$$
If this solution and Jacky Chong's are both correct (and his certainly looks good to me) we ought to be able to equate them and solve for $f(x).$
EDIT As pointed out in KingW3's answer, instead of equating the derivatives, it's easier to just just solve $$f^2(x)+xf(x)-x=0$$ for $f(x)$ in terms of $x$.  This gives $$f(x)=\frac{-x\pm\sqrt{x^2+4x}}{2}$$  From the well-known continued fraction for the golden section, we know that $$f(1)=\frac{-1+\sqrt 5}{2},$$ so we must pick the plus sign, and $$\boxed{f(x)=\frac{-x+\sqrt{x^2+4x}}{2}}$$
Comment: The OP posted their work, and this was their answer...
Comment: That is what I got as shown in the links I provided, thanks for the response!
Comment: @GeorgeCooper I couldn't read the link you provided.
Comment: Oh thanks for telling me :)
Comment: @saulspatz question:https://drive.google.com/open?id=1e9cPQYzPuIKB5J7myOwF37CY1VUnj9hh.                                        answer: https://drive.google.com/open?id=16sIvBwzhbeyDZX9iycNcMzoe3hu_IAva
Answer: From $xf(x) +f^2(x)=x$ putting $t=f(x)$ we get a quadratic in $t$ and $t_{1,2}=\frac{-x\pm\sqrt{x^2-4x}}2$. Since you have two different functions you get two different derivatives depending on what $f(x)$ you choose. In this particular case $f(x)$ is not uniquely defined so finding it's derivative is impossible.
Comment: I don't think so.  The continued fraction has a unique value.  You've introduced an extraneous solution.  Besides, I don't get the same solutions as you do.  I have $$\frac{-x\pm\sqrt{x^2+4x}}{2}$$
Comment: @saulspatz Yeah I've made a typo on the minus sign, anyway how do you explain that I've introduced an extraneous solution?
Comment: Maybe "introduced" is the wrong term.  I just meant that all we know is that $f$ satisfies this equation; we don't know that it's the only function that satisfies the equation.  Therefore, we know that $f$ occurs among the solutions to the quadratic, but  we have to use other information to decide which it is.  I did this in an edit to my solution; please look there to see why we must pick the + sign.

Finding $f’(x)$ - possible answer but need help


Activity Object.hashCode() is the same on different instances

Question: Predictably same Object.hashCode() of totally different instances
If I understand correctly, then the Object.hashCode() of each new instance of the object should be new and almost always different from the previous ones, with the exception of a collision.
But I found an interesting pattern.
If I use Android Studio, create an Activity and call the hashcode in the onCreate, onStart, onResume, onPause, onStop, onRestart, onDestroy methods and run the application in the emulator, then I get the same hashcode in the logs under the following conditions:

Every Run of Activity in Android Studio, even if I close the emulator and Studio and go back in, and even if I restart the computer (Windows 10), but if I cold boot the emulator, the hashcode changes.
In the emulator itself, of course, the hashcode does not change while the Activity goes through the onStart, onResume, onPause, onStop, onRestart cycle.
If I close the application with the Back button and run it again in the emulator, the Hashcode changes.
If I kill the application by swiping it out from the recent apps screen and start it again - the hashcode becomes the same as when it was first launched.
Answer: The only requirement for the hashcode method is that if two objects are equal then they must have the same hashcode. There is no warranty that two objects that differ should have different hashcodes. If a class doesn't override the hashcode method then the behavior is implementation dependent. A typical behavior is to return the internal object reference. If the activity is the first to run in your emulator then is not that strange if it would always get the same object reference (which could be a simple counter). Of course if you close and rerun the app in the same emulator session you will get a new object reference and so a new hash. Swiping kills the vm process, so a new vm is started and the object reference counter is reset.
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()


WPF Validation Control Template overlapping

Question: I've got a user control with a control template to show validation errors, validation template:
<ControlTemplate x:Key="TextBoxPropertyValidationTemplate">
        <StackPanel>
            <Border BorderBrush="Red" BorderThickness="1">
                <AdornedElementPlaceholder x:Name="MyAdorner" />
            </Border>

            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Image Grid.Column="0" MaxHeight="16" MaxWidth="16"
                       Source="{Binding Source={StaticResource ValidationIcon}, Converter={StaticResource UriConverter}}"
                       Margin="1" RenderOptions.BitmapScalingMode="HighQuality"
                       VerticalAlignment="Center" HorizontalAlignment="Center" />
                <TextBlock VerticalAlignment="Center" HorizontalAlignment="Left"
                           Text="{Binding ElementName=MyAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
                           TextWrapping="Wrap" Grid.Column="1" FontSize="10" Foreground="Red" />
            </Grid>

        </StackPanel>
    </ControlTemplate>

And I can't seem to get around a rather irritating problem which looks like this:

I've been trying to play around with margins on the user control and on the template also some Height=Auto etc but all these don't really help. Any ideas anyone?
If that helps the main user control (which nests the ones with validation) is in a TabItem with a AdornerDecorator.
Any help appreciated.
Comment: What do you want this to look like?  I see the overlap, but it's not clear to me how you expect this to behave.
Answer: I'd say this is because your error message is on the AdornerLayer, which doesn't participate in the same layout as your control. MSDN says "rendering of an adorner is independent from rendering of the UIElement that the adorner is bound to." and that is why the message is just put on top of everything.
You could put the error text into the original template, hide it based on Validation.HasError and include it in the layout process that way.
But changing the layout of the control might not be the best way to go if a validation error occurs. You might consider providing additional information in a ToolTip.
Comment: Good answer, fair enough... I don't want my layout to jump around so it looks like tooltip it is. Thanks
Answer: Alternately, instead of using ControlTemplate, you could put the error message TextBlock beside the TextBox, and set its Text property binding the TextBox's ErrorContent.
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <TextBox x:Name="txtName" Grid.Row="0">
        <TextBox.Text>
            <Binding Path="Name" NotifyOnValidationError="True" ValidatesOnExceptions="True" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <common:RequiredFieldValidationRule/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
    <TextBlock Grid.Row="1" Text="{Binding ElementName=txtName,Path=(Validation.Errors)[0].ErrorContent}"
               Visibility="{Binding ElementName=txtName,Path=Validation.HasError,Converter=...}" />
</Grid>


Time Delay in Union Operator in SQL Server

Question: I am having statement.
SELECT *
FROM   DemoTable
WHERE i = 7
UNION
SELECT *
FROM   DemoTable
WHERE i = 6

What i need i need to put time delay between the union statement i need to check something related to snapshot isolation.
Can i put time delay between the union
Such as
SELECT *
FROM   DemoTable
WHERE i = 7

Will Run First and after 10 seconds
SELECT *
FROM   DemoTable
WHERE i = 6

But i need both in one statement i.e with union only.
Comment: Run two separate queries.
Answer: You cannot put a delay in the middle of the union.  A select/union is part of the SQL DML.  Delay is a programming construct and is not related to data manipulation in any way.
Also, isolation and concurrency would not be impacted by separates reads on the same table.  Reads generally use a shared lock.  You'll need to start a transaction that modifies the data in some way for there to be any impact to concurrency.  You'd be better off using multiple query windows or connections with explicit transactions.
You can use WAITFOR inside of a stored procedure, but never with a union.
CREATE PROCEDURE dbo.testproc
AS
BEGIN
SELECT CURRENT_TIMESTAMP;
WAITFOR DELAY '00:00:02'
SELECT CURRENT_TIMESTAMP;
END
go
EXEC dbo.testproc

Answer: try insert WAITFOR DELAY '00:02';


Closing a nested text file, and also cutting lines from nested text file

Question: for h3 in soup.find_all('a'):

    print((str(h3.text)),file=open("demo.txt", "a"))

Up above is my line of code for scraping a website. I am using beautiful soup and selenium to scrape the website. The first line it says for all "a" tags soup find all. Then print the text of those a tags and print it in the file demo.txt.
For some reason I have to put "a" ,append, for the whole text to be printed out. With "w" it only prints one line. I am looking for a way to close the demo.txt file so that it does constantly keep appending to the same file.
It would also be helpful in learning how to cut certain lines from the text file. Ie the text file will probably be 750-1000 lines so a command to cut (2-5, 94-100) would be very helpful.
Thanks in advance
Answer: Will print one line because every time when he found what u say to search will open that file and will write it. Computer do not know the word "delete" when we talk about words on files =]] So for him, no mater what is on this file (and if that file will not exist will create it) will start from beginning and will write it again. for that reason a is working for you.
try:
    with open(file="demo.txt", mode="w", encoding="utf-8") as file:

        for h3 in soup.find_all('a'):
            file.write(str(h3.text))
finally:
    file.close()

And for that deleting lines I thing u do not want some information's on it, so check what do u not want and make another if statement inside.
...
        for h3 in soup.find_all('a'):
            if stringA in h3.text or stringB in h3.text:
                pass
            else:
                file.write(str(h3.text))
...


Suppose $R$ is a commutative ring and $RR= R$(ideal multiplication). Then, $R$ has an identity.

Question: I am currently reading Hungerford. I am trying to prove theorem 2.19 i.e. every maximal ideal is prime provided that $R$ is unital and commutative. Hungerford states that if you prove $RR = R$, then $R$ is unital which I don't understand. Sorry if this is a stupid question.
Comment: This isn't true. It is possible to have $RR = R$ w/o being unital. What Hungerford is  saying is that $RR=R$ (plus commutative) is sufficient to have that max ideals are prime. A specific case of that is when $R$ is unital.
Comment: One of our users discusses this in detail [here](https://math.stackexchange.com/a/95714/29335).
Answer: This isn't true. What Hungerford is saying that if $R$ is commutative and $RR = R$ then $R$ has the property that maximal ideals are prime. He then remarks that unital rings are the most particular/common example of rings with property that $RR=R$.
In any case, here is a counterexample. Consider $\oplus_{i = 1}^{\infty} \mathbb{Z}_2$ ($\oplus$ means finite support). Note that we have that $x^2 = x$ for all $x$ and so $R^2 = R$ here.
Answer: I think you've misread what Hungerford says.
Here is Theorem III.2.19:

Theorem. If $R$ is a commutative ring such that $R^2=R$ (in particular if $R$ has an identity), then every maximal ideal $M$ in $R$ is prime. [emphasis added]

Hungerford is not saying that if a commutative ring $R$ satisfies $R^2=R$ then $R$ has an identity. It is saying instead that one particular instance in which the condition $R^2=R$ will be satisfied is when $R$ has an identity.
You may have missed the "if" after "in particular". Had the statement read "in particular $R$ has an identity", then this should be understood as saying that the condition $R^2=R$ implies, among other things, that $R$ has an identity; this seems to be what you interpreted. But the "if" means that instead the statement should be understood to mean that "one case, among others, in which this occurs is when $R$ has an identity."
In fact, as noted, the condition $R^2=R$ is more general than having an identity: there are rings without identity that satisfy the condition but do not have an identity. Another example to the one given is the ring of continuous functions $f\colon \mathbb{R}\to\mathbb{R}$ with compact support. For every $f\in R$ there exists $g\in R$ such that $fg=gf=f$, but there is not element $e$ of $R$ with the property that for all $h\in R$ we have $eh=he=h$.


Azure Data Explorer: Failed to download blob

Question: Ok so I'm following this Data Explorer tutorial (but adapting it to my own dataset):
https://learn.microsoft.com/en-us/azure/data-explorer/ingest-sample-data
I'm running this code:
<code>.ingest into table SalesData h'https://XXXX.blob.core.windows.net/sales/SalesDataSata.csv' with (ignoreFirstRecord=true)
</code>
But get the error:
<code>Failed to download blob: The remote server returned an error: (404) Not Found.
</code>
I have copied and pasted the BLOB URL from the Portal exactly as is, and all resources belong to the same resource group.
Comment: Ok I see you've edited your question. Note that, for your own blob, if it's a *private* blob, you won't be able to download it without first creating a Shared Access Signature (or policy). Or you can mark the blob as public (but then it's possible that others can find your content).
Comment: OK thanks that helped
Answer: With thanks to David Makogon for pointing me towards the right answer.
To make the BLOB accessible you need to generate a SAS URL for the blob file.
Do this by selecting the BLOB file in the Azure Portal then click on the ...
Select Generate SAS then ok.
Comment: The other thing you can do is make the blob publicly accessible. Obviously you should only do this with data that is public or you don't care about.


Reduction to LP

Question: What will be the primal and dual of the following problem/
Given an undirected graph $G = (V,E)$, we want to assign non-negative weights to all the edges of $G$, denoted $\{ x_e \mid e\in E \}$ , such that the sum of all the weights is as large as possible,
subject to the constraint: for each vertex $v\in V$, the sum of the weights of the edges
incident to $v$ is at most $1$. If we restricted the weights to be non-negative integers, can you
think what the primal and dual mean?
Answer: Objective Function: maximise the sum of all weights of the graph $$\max \sum_{e \in E} x_e$$
Constraint: For all $v \in V$, sum of weights of edges incident to v is at most 1. $$\sum_{w \in V} x_{vw} \leq 1 \quad \forall v \in V$$
If you restrict the weights to simply be non-negative integers, that basically means $x_e = 0$ or $x_e = 1$ for all $e \in E$ due to the constraint. For this type of problem, I suggest looking up the concept of 'matchings' in a graph for a general idea of what the formulation solves.
For the dual, I suggest figuring out the formulation with actual examples. Hopefully that'll help you figure out what the dual solves for.

Reduction to LP


Spring Websockets: How to validate message and receive clients?

Question: I have Spring WebSockets configured and working. Clients subscribe to a specific topic (e.g. <code>/topic/contract/contract_id</code>) and whenever there's a message for that contract/topic, they receive it.
The issue is that certain types of messages being sent to this topic are sensitive and should only be received by some clients, but not others. So I need to analyze a message that's being sent when it's being sent, the clients that are subscribed to receive it, and let it through for some clients but not for others. Is there a way to do this in Spring WebSockets?
Answer: It sounds like you are using Pub/Sub pattern. I am no expert on Spring Web Sockets, but it sounds like a dilemma on a higher abstraction and not on the level of data transmission.
There are two things you can do:

Either disallow specific clients to subscribe to the channel at the first place, but it sounds like some messages are sent through, some are not. Hence I'd recommend the second option:
Maintain public (group like) and private channels.

In the first case just intercept the end point or service that is being called during subscription, and throw a Security exception or communicate somehow disallowed join.
In the second case, have a unique strong id for the channel name, that is known only to those who concerned, and they can listen to private messages.
I had experience with the second case and it worked perfectly, although we had no critical information as it was part of a game, so only one player can receive that message and not the group.


How to generate all-projects-in-one Gradle project?

Question: I have a gradle monolithic project with too many dependencies.
I'd like to explode it into many sub-projects and publish all sub-projects (build + sources + javadoc) + an extra project being the merge of all sub-projects.
This extra project should be like a virtual artifact with all my projects in a single jar like it is today because I don't want a too big change for my users.
The jar must not include dependencies (it is not an uber-jar) but the resulted pom.xml must contain the dependencies of all sub-projects (the generated pom.xml of the maven artifact must contain all dependencies).
The virtual artifact will include the merge of javadoc and sources too in order to respect Maven Central conventions.
Current state:

Project Main, generate

pom.xml
main.jar
main-sources.jar
main-javadoc.jar

Expected state:

Subproject A, generate

A-pom.xml
A.jar
A-sources.jar
A-javadoc.jar

Subproject B, generate

B-pom.xml
B.jar
B-sources.jar
B-javadoc.jar

virtal-Project Main, generate

pom.xml=A-pom.xml+B-pom.xml
main.jar=A.jar+B.jar
main-sources.jar=A-sources.jar+B-sources.jar
main-javadoc.jar=A-javadoc.jar+B-javadoc.jar

How can I manage it?
Comment: Maybe you be a bit more specific as to what you are asking? From what I get, you pretty much just do what you describe :) You may find the chapter on [multi-project builds](https://docs.gradle.org/current/userguide/multi_project_builds.html) in the user guide useful if you haven't read it already.
Comment: @BjørnVester Thank you for your interest. Creating sub-projects is not a problem but I don't want a too big change for my users.
So I'd like to keep a virtual artifact with all my projects in a single jar like today (including the merge of javadoc and sources artifacts). The jar must not include dependencies but the resulted pom.xml must contains the dependencies of all sub-projects.
I hope my ask is clearer now.
Comment: Yes, it is much more clear now. I initially thought you wanted to publish and use sub-projects while having binary inter-dependencies in Maven and source dependencies in the build. I don't have an answer for merging subprojects in a way to produce the same result as the monolithic approach though.
Comment: Where this requirement is being defined: "The virtual artifact will include the merge of javadoc and sources too in order to respect Maven Central conventions." ??
Answer: We have been in exactly the same situation for some time now. We want to publish a single artifact for our clients to depend on, although internally the product is developed through a few separate component projects. I got it done eventually (with compromises), and here is what I learned:

Merging jars is not as straightforward as it looks like because there could be things like resource files within a jar that are not
always namespace-ed. It is possible that two of your jars have a
resource file with the same name, in which case you will have to
merge the content of those files.

Javadoc is very hard to merge without accessing the original source
files because it has summary pages (index pages).

So my advice would be:

Think twice, maybe what you really want is NOT a single jar, but a single dependency for your clients? These are different. You can easily have a pom only artifact. Depending on this pom only artifact will simply translates transitively into depending on individual artifacts of your component sub projects. To your client, practically, nothing is changed. Spring Boot takes this approach. To do it, you can create an empty java-library project, make all your component projects its api dependency. You don't even need any source code in this project.

If you really want to merge into a single jar, you can try building a fat jar with customization. The customization is not to pull in 3rd party dependencies.

We use the Gradle Shadow plugin for merging jars. Its original purpose was to build a fat jar, which will include all the transitive dependencies. But it also has a special "shadow" configuration, to which you can add dependencies if you want the dependencies to be exported into POM rather than bundled. So what you need to do:

Define a non-transitive configuration (say bundler) to which you will add your sub-project as dependencies. This is going to be the target configuration for the Gradle Shadow plugin.
Define a transitive configuration (bundlerTransitive) that extends from your non-transitive one. This will be manually resolved in order to find the 3rd party dependencies
in your build.gradle, register an afterEvaluate closure, where you find the level two dependencies of the resolved transitive configuration, add them to the shadow configuration. The reason for level-two is that level one dependencies will be your sub-project artifacts.
After all the above, the artifact produced by shadowJar task is the one to be uploaded to maven. You will need to configure the shadowJar task to remove the classifier (which is shadow by default)

Here is a complete example (build.gradle) of bundling vertx-web and all its dependencies within the io.vertx group:
plugins {
    id 'java'
    id 'maven-publish'
    id 'com.github.johnrengelman.shadow' version '5.2.0'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

configurations {
    bundler {
        transitive = false
    }

    bundlerTansitive {
        extendsFrom bundler
        transitive = true
    }
}

dependencies {
    bundler "io.vertx:vertx-web:4.0.0"
    bundler "io.vertx:vertx-web-common:4.0.0"
    bundler "io.vertx:vertx-core:4.0.0"
    bundler "io.vertx:vertx-auth-common:4.0.0"
    bundler "io.vertx:vertx-bridge-common:4.0.0"
}

shadowJar {
    configurations = [project.configurations.bundler]
    classifier ''
}

publishing {
    publications {
        shadow(MavenPublication) { publication ->
            project.shadow.component(publication)
        }
    }
}

project.afterEvaluate {
    // this is needed because your sub-projects might have inter-dependencies
    def isBundled = { ResolvedDependency dep ->
        return configurations.bundler.dependencies.any {
            dep.moduleGroup == it.group && dep.moduleName == it.name
        }
    }

    logger.lifecycle '\nBundled artifacts and their 1st level dependencies:'

    // level one dependencies
    configurations.bundlerTansitive.resolvedConfiguration.firstLevelModuleDependencies.forEach {
        logger.lifecycle "+--- ${it.getName()}"

        // level two dependencies
        it.children.findAll({ ResolvedDependency dep -> !isBundled(dep) })
                .forEach { ResolvedDependency dep ->
                    logger.lifecycle "|    +--- ${dep.name}"
                    project.dependencies.add('shadow', [group: dep.moduleGroup, name: dep.moduleName, version: dep.moduleVersion])
                }
    }

    logger.lifecycle '\nExported Dependencies:'

    configurations.shadow.getResolvedConfiguration().getFirstLevelModuleDependencies().forEach {
        project.logger.lifecycle "+--- ${it.getName()}"
    }
}

For javadoc if you don't care about the index (compromise, as I said), then it is just a jar task with a copy spec:
configurations {
   javadoc {
        transitive = false
    }
}

dependencies {
    javadoc 'com.my:component-a:1.1.0:javadoc'
    javadoc 'com.my:component-b:1.1.0:javadoc'
    javadoc 'com.my:component-c:1.1.0:javadoc'
    javadoc 'com.my:component-d:1.1.0:javadoc'
}

task javadocFatJar(type: Jar) {
    archiveClassifier.set('javadoc')
    from {
        configurations.javadoc.collect { it.isDirectory() ? it : zipTree(it) }
    }
    with jar
}

Comment: Thank you for your complete answer. Do you have any examples for the Shadow plugin? I'm not sure to understand how to exclude 3rd party dependencies from the generated jar.
Comment: I've modified my answer to include a mini example. Depending on your other needs you might want to do a bit more in the afterEvaluate block, e.g. if you dependencies are specified with dynamic versions, you might want to resolve the bundler configuration first to lock the version etc.
Comment: However, you should firstly consider not bundling the jars if possible, which is pretty much always the right choice I think. Getting the bundling to work feels technically an achievement, but it has implications for the overall SLDC process especially when you are building a library.
Comment: I agree, I will try the BOM-like solution first :)
Answer: This cannot be done with maven-publish directly, but one can add individual java-library modules and package each of them with sources and docs. With Gradle this would be a simple jar task, but when the artifacts are publicly available ...such transitive dependencies should better be provided by a meta package; nothing but Maven (Local/Central) dependencies, instead of embedded JARS. In this case, this would be just another module (which obviously would only build after having published the others).
And concerning the concept, that it would require any "merged" JavaDocs ...
https://central.sonatype.org/pages/requirements.html#supply-javadoc-and-sources
While they're referenced (Maven Central) in *.pom, Gradle will be able to find them.
Just use repository mavenLocal() instead of mavenCentral() for testing purposes.