java.lang.RuntimeException: Parcel: unable to marshal value

Question: Tenho esse erro quando clico em um item do RecyclerView e passo um objeto pela Intent, já implementei Serializable e não funcionou
<code> @Override
    public void onBindViewHolder(final ProcedimentoViewHolder viewHolder, final int position) {
        //Populando o Procedimento com o item na posição selecionada
        final Procedimento procedimento = mFilter.getProcedimentoFilter().get(position);
        //Setando as informações do adapterLayout na lista
        //holder é a o valor que o metodo onCreateViewHolder retorna, no caso a view com a referencia dos componentes
        viewHolder.titulo.setText(procedimento.getTitulo());
        viewHolder.itemView.setTag(procedimento);
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, Procedimento> mapProcedimento = new HashMap<String, Procedimento>();
                mapProcedimento.put("Procedimento", procedimento);
                Intent intent = new Intent(context, ProcedimentoActivity.class);
                intent.putExtra("mapProcedimento", mapProcedimento);
                context.startActivity(intent);
            }
        });
    }

05-19 14:57:24.058 2994-2994/com.basedeconhecimento E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.basedeconhecimento, PID: 2994
                                                                                java.lang.RuntimeException: Parcel: unable to marshal value com.basedeconhecimento.Modelo.Procedimento@35c8dce
                                                                                at android.os.Parcel.writeValue(Parcel.java:1477)
                                                                                at android.os.Parcel.writeMapInternal(Parcel.java:698)
                                                                                at android.os.Parcel.writeMap(Parcel.java:682)
                                                                                at android.os.Parcel.writeValue(Parcel.java:1389)
                                                                                at android.os.Parcel.writeArrayMapInternal(Parcel.java:724)
                                                                                at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1408)
                                                                                at android.os.Bundle.writeToParcel(Bundle.java:1157)
                                                                                at android.os.Parcel.writeBundle(Parcel.java:764)
                                                                                at android.content.Intent.writeToParcel(Intent.java:8687)
                                                                                at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3082)
                                                                                at android.app.Instrumentation.execStartActivity(Instrumentation.java:1518)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4225)
                                                                                at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4183)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
                                                                                at android.app.Activity.startActivity(Activity.java:4522)
                                                                                at android.app.Activity.startActivity(Activity.java:4490)
                                                                                at com.stefanini.basedeconhecimento.Adapter.ProcedimentoAdapter$1.onClick(ProcedimentoAdapter.java:71)
                                                                                at android.view.View.performClick(View.java:5637)
                                                                                at android.view.View$PerformClick.run(View.java:22429)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>
Quem puder ajudar , muito obrigado
Comment: Michael, pq precisa passar um mapa para a outra Activity, tem alguma razão específica? Minha sugestão é passar o objeto direto no Extras. Além disso, a classe `Procedimento` implementa Parcelable ou Serializable?
Answer: Todos os objetos da classe Collections implementam o Serializable. Então, provavelmente o erro está na implementação da interface serializable da classe Procedimento.


Why would using PrincipalSearcher be faster than FindByIdentity()?

Question: I had this code:
var context = new PrincipalContext( ContextType.Machine );
var user = UserPrincipal.FindByIdentity( context, username );

and it took about 2-3 seconds to run. I was recommended to rewrite it using PrincipalSearcher class:
var context = new PrincipalContext( ContextType.Machine );
var user = new UserPrincipal(context);
user.SamAccountName = username;
var searcher = new PrincipalSearcher(user);
user = searcher.FindOne() as UserPrincipal;

and it runs in less than one second - notably faster. The person why advised the rewrite is as clueless as me why it runs faster.
Why does it make any performance difference?
Comment: http://stackoverflow.com/a/14673947/932282
Answer: The only plausible reason I can think of is that .FindByIdentity has to check multiple attributes for a match, since you're not specifying exactly which attribute you're looking for.
You can do that by specifying the attribute you're looking for (using this method overload) - try this for a comparison:
var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);

How fast is this?
Comment: Interesting, code using three-pararemeters `FindByIdentity()` works a bit slower than the original `FindByIdentity()`.
Comment: Maybe algorithm implementation differences?


Proving that $m(\{f^{-1}(S) : S \in A\}) = \{f^{-1}(S) : S \in m(A)\}$ (monotone classes)

Question:
Let $X,Y$ be sets, $A \subseteq \mathcal{P}(Y)$ and $f: X \to Y$. Then $$m(\{f^{-1}(S) : S \in A\}) = \{f^{-1}(S) : S \in
 m(A)\}$$ Where $m(A)$ denotes the monotone class generated by $A$.

For proving the inclusion $\subseteq$ it is enough to show that $$\{f^{-1}(S) : S \in
 m(A)\}$$ is a monotone class. Hence we take an increaing sequence $(f^{-1}(S_n))_{n \in \mathbb{N}}$ where $S_n \in m(A)$ an look at its union. I mean trivially $$\bigcup_{n \in \mathbb{N}}f^{-1}(S_n) = f^{-1}\left( \bigcup_{n \in \mathbb{N}}S_n\right)$$ So if we could show $\bigcup_{n \in \mathbb{N}}S_n \in m(A)$ we are done. For this $(S_n)_{n \in \mathbb{N}}$ must be increasing, which is not per se the case, isn't it? I asked the one which wrote this exercise and he replied that it is the same as for $\sigma(A)$ ($\sigma$-algebra generated by $A$) no further assumptions on the nature of $f$ have to be made. But I mean, $\sigma$-algebras are a richer structure than monotone classes, hence it could be that we have to assert more in this case. My assumption would be that $f$ has to be surjective. So my question is: Is this assumption necessary or is it right that it is like in the case of $\sigma$-algebras? Does the proof work nevertheless and I do not see it?
Answer: The fact that the sets $f^{-1}(S_n)$ are increasing implies that the sets $f( f^{-1}(S_n))=S_n \cap f(X)$ are also increasing. As you already remarked, if $f$ were surjective this would imply that the sequence $(S_n)_{n \in \mathbb{N}}$ is increasing and the result would follow.
I believe the following is a counterexample to your claim when $f$ is not surjective.
Counterexample:
Let $f: (0,1) \to \mathbb{R}$ be the inclusion. Thus, if $S \subset \mathbb{R}$ is a set then $f^{-1}(S)$ is simply $S\cap (0,1)$. Define the following collection of subsets of $\mathbb{R}$:
$$
A = \{ (q\, , \,q+1) : q \in \mathbb{Q} \} \cup \{\mathbb{R}\}
$$
So $A$ is the collection of intervals of length $1$ with rational endpoints. This is a monotone class since there are no nested sets except the trivial $(q,q+1) \subset \mathbb{R}$. Thus we have $m(A)=A$.
The idea of the construction is that, even though the sets in $A$ are not nested, we can arrange for their intersection with $(0,1)$ (i.e. their preimage under $f$ ) to be nested.
Take an irrational number $a \in (0,1)$. Take a decreasing sequence $\{ q_n \}$ of rational numbers $q_n \in (0,1)$ which converges to $a$. Define $S_n =(q_n, q_n+1) \in A$. Then $f^{-1}(S_n) = (q_n,1)$ is an increasing sequence of sets since $\{q_n\}$ is decreasing. Since $q_n \to a$, we have $\bigcup_{n} (q_n , 1) = (a,1)$.
However, there is no set $S \in A$ such that $f^{-1}(S) = (a,1)$ since $a$ is irrational! Thus $\{ f^{-1}(S) : S\in m(A) \}$ is not a monotone class.


Solve $2\tan (x)\cos (x)=\tan (x)$, algebraically where $0 \leq x < 2\pi$

Question: please help me correct if anything is wrong.. or even if i'am right

Solve $\quad 2\tan x\cos x=\tan x,$ algebraically where $0≤x<2π$

$$2\tan(x) \cos (x) - \tan (x) = 0$$
$$\tan (x)(2\cos (x) - 1) = 0$$
$$\text{So, either}\;\;\tan (x) = 0 \Longrightarrow x \in \{0, π,  2π\} $$
$$\text{Or}\;\;2\cos(x)-1 = 0, \cos (x) = 1/2 \implies x \in \{-π/3, π/3\}$$
$$\text{Solutions}\;\;: x \in \{0, \pi/3, -\pi/3, \pi, 2\pi\}$$

2) Solve $2\sin^2(x)-\sin(x)-1=0$ where $0≤x<2π$

$$2\sin^2(x)-\sin(x)-1=0$$
$$\iff(2\sin(x)+1)(\sin(x)-1) = 0$$
Thus, either $\;2\sin(x) +1 = 0 \iff \sin x = -1/2 \implies x = -π/6, x = 7π/6$
or $\;\sin(x)-1 = 0 \iff \sin x = 1 \implies  x = π/2$
$$\text{Solutions}\;\;x\in \{-π/6,  π/2, 7π/6\}$$
Comment: note if someone could help me clean the solution aswell :) mine look a little rough
Comment: Use `$ $` to enclose your equations. Use \sin, \cos, \tan \pi etc. This will greatly improve your question.
Comment: does my answer seem correct? if someone could help me
Comment: You were asked to find the solutions in the interval $0\le x\lt 2\pi$. A number of times, you give negative solutions. These do not satisfy the required condition. So for example you need to replace $-\pi/3$ in the first answer by $5\pi/3$. Similar corrections are needed elsewhere.
Comment: It would be better if you know how to use $\LaTeX$.  This way, we are able to read the equations clearly!
Comment: if $AB = 0$ then $A=0$ _or_ $B=0$, not "ALSO" as you have written. What you should do in a case like this is first explicitly consider one case "suppose $\tan(x)=0$, then...", which will give you some solutions, and then consider the other case, "now suppose $2cos(x)-1=0$..., which will give additional solutions.
Answer: Almost!
You might want to give your first answer as inclusive of both possible sets of solutions - the solutions being those satisfying $\tan x = 0$ and/or satisfying $\cos x = 1/2$ - rather than as two answers.
Oops, just noted that you include $x = 2\pi$ as a solution to $\;\tan x = 0$, and it seems as though your domain for $x$ is written as $0\leq x \lt 2\pi$. If that's the correct domain for $x$, then omit $x = 2\pi$ as a solution to $(1)$.
And so you'll also need to omit $x = -\pi/3$, and instead include $x = 5 \pi/3$ as solutions to $\cos x = 1/2, $ in $(1)$. Same angle position, different representation, but this representation within the interval $0 \leq x\lt 2\pi$.
Finally, in the last problem, you list one solution as $x = - \pi/6$. Again this needs to be in your interval $0 \leq x \lt 2\pi$. So instead of $-\pi/6$, represent that angle as $2\pi - \pi/6 = 11\pi/6$.
Comment: can you show me a solution to this :) with the answers clear at the end?
Comment: $1)$ $x\in \{0, \pi/3, \pi, 5\pi/3\}$, $(2)$ $x\in \{\pi/2, 7\pi/6, 11\pi/6\}$
Comment: Your solutions to the equations are correct: $\tan x = 0, \cos x = 1/2$ for $(1)$ and for $(2)$L $\sin x = -1/2$ and $\sin x = 1$. You just needed to have your $x$ values being angles within the interval $0 \leq x \lt 2\pi$.
Comment: Does that help, now?
Comment: yes :D could you possibly show each step though? I want something to compare
Comment: You completed all the steps needed: you solved the equations just fine. All that had to be "fine-tuned" is representing the angles you found by their representations within the interval $0 \leq x \lt 2\pi$. I would just be rewriting what you wrote. Also, you might want to think about accepting some of the answers to your questions (you can only accept one answer per question, though.) At the very least, for the answers that are helpful, you should upvote them: there's no limit on how many answers you can upvote.
Comment: I did "clean up" your post, in terms of formatting, to make your ideas and work flow nicely. Include the updated solution sets for $(1)$ and $(2)$ that I've posted above in the comment, and you've got a nicely solved problem.
Comment: @amWhy I think he means a different way of solving this problems - if that's the case for the first problem you could notice that if $\tan x = 0$ this is true ($0=0$) or then do the following: $$2 \tan x \cos x = \tan x \iff 2 \cos x = 1 \iff \cos x = 1/2$$


Creating a sidenav with a fixed search bar at the top (AngularMaterial2)

Question: Several times in the past have I had an app where I have a sidenav with a lot of navigation option, where amount exceeds the height of the sidenav.
To help with the UX part, I want to include a textbox at the top of the sidenav, which will be fixed at the top and won't move even if the navbar is scrolled down.
I've only succeeded putting the textbox inside of the sidenav, but not making it fixed at the top.
I've tried approaching it using CSS, with either position: fixed or position: absolute, and many thing I've since forgotten, but none have worked. I've managed positioning it at the place I want, but the background had disappeared, and it's not taking place inside the actual sidenav, as the navigation links appear behind the textbox.
I haven't seen a similar approach in other sites, so I haven't had a place to take example from.
The basics are as shown at https://material.angular.io/, except that there should be a textbox on top, to help filter links in the navbar.
Comment: Try this https://medium.com/@MikkelDamm/sticky-header-in-angular2-90364eba81d9
Answer: I can't be sure what you really want... but I think that this is a great place to try and use a technique I recently ran across. You can use transform: translate(x,x) to create a new context for fixed positioning. Usually fixed would respect the body as it's boundery - but using translate on an element seems to create it's own child scope for fixed positioning.
.parent {
  transform: translate(0,0);
}

.parent .form {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}

.parent .sidebar-module-list {
  padding-top: {{formHeight}};
}

Here is an example CodePen


How to hide or delete the zero in my bash script?

Question: This is my script:
echo -n "number 1 :";
read bil1
echo -n "number 2 :";
read bil2
multiple=$(echo $bil1*$bil2 |bc -l |sed -e 's/^\./0./' -e 's/^-\./-0./');
echo " Your result : $bil1 * $bil2 = $multiple ";

If I input 9.5 for $bil1 and 300 for $bil2, the result is 2850.0.
I want the result:
Your result : 9.5 * 300 = 2850

How do I hide or delete the zero at the end of the result? I.e. show only 2850 ?
Answer: Add the following part to your sed command (at the end):
-e 's/\.0*$//'

(Delete a dot followed by arbitrarily many zeroes at the end by nothing.)
By the way, you better replace echo $bil1*$bil2 by echo "$bil1*$bil2", otherwise you may get strange effects depending on the contents of the current directory.
Comment: @Vash2593 Which script are you looking at?
Comment: @Vash2593 No, the `$bil1*$bil2` in the fifth line is currently not quoted.
Answer: Assign the normal, floating-point output of bc to the variable, then trim it using parameter expansion:
multiple=$(echo "$bil1*$bil2" | bc -l)
# Not POSIX, unfortunately
shopt -s extglob
multiple=${multiple%.+(0)}
echo " Your result : $bil1 * $bil2 = $multiple "

A POSIX solution is to let printf do the work
multiple=$(echo "$bil1*$bil2" | bc -l)
printf " Your result : %1.1f * %d = %1.0f\n" $bil1 $bil2 $multiple

Answer: use bash's builtin printf to control the output
$ bil1=9.5; bil2=300; printf "%.0f\n" $(bc -l <<< "$bil1 * $bil2")
2850

Comment: If one wants to round to the next integer, that's probably the best solution; if one only wants to delete redundant _zeroes_ (but not other digits) after the period, it does not work.


What are m-placed relation symbols and function symbols?

Question: In This Model Theory book, Weiss refers to "m-placed function symbols" and "m-placed relation symbols". Are these just supposed to be functions of $m$ objects and relations between $m$ objects? I'm having some trouble digesting this. I think I am having more trouble understanding the m-placed relations, though.
Answer: They're symbols that are intended to denote such functions and relations; they're not functions or relations themselves.
Comment: Oh I see. For some reason, I was under the impression that $R(x_1 \cdots x_n)$ was something like an equivalence class, under some binary relation $\sim$, such that for all $x_i$ and $x_j$, $x_i \sim x_j$. I understand now, though, thank you!
Comment: Right, thanks. I'm just having a bit of trouble understanding multi-valued relations, though... it's essentially a way to show that $m$ objects are related under some operation?
Comment: If $\underline{\text{R}}$ is, say, a 3-place relation symbol, then you can write formulas of the form $\underline{\text{R}}(x,y,z)$ (where $x,$ $y,$ and $z$ are variables, constant symbols, or other terms), and you can use those as subformulas of sentences or other formulas.  None of these formulas mean anything specific until you have a model with (among other things) an actual 3-place relation $R$ that you will be using as the interpretation of the symbol $\underline{\text{R}}.$  In fact, the meaning of these formulas will be different in different models.
Comment: I didn't have room to include this in my previous comment, but a 3-place relation $R$ in a model with universe $A$ is just a subset of $A \times A \times A,$  where we say that $R(x,y,z)$ is true iff $\langle x,y,z\rangle$ belongs to that subset.
Comment: Oh, that actually makes a lot of sense. Thanks a lot!
Answer: Just think of a relation as a collection of ordered $m$-tuples.  Items $a1$, $a2$, ..., $am$ are related under the $m$-place relation R iff the tuple ($a1$, $a2$, ..., $am$) is in R.  [they don't have to be related 'under some operation' to be related]
For example, there is the 3-place relation which I will call $Pyth()$ : the numeric triplet ($a$,$b$,$c$) is in $Pyth()$ iff $a+b=c$.  When considering $Pyth()$ as a relation, we don't need to involve the '+' or '=' if we don't want to, we can just think about the triplets '(3,4,5)', '(5,12,13)', etc., by themselves (as a collection).  Model Theory takes that perspective.
Comment: Great explanation, thanks.
Answer: In Set Theory an $n$-ary relation on a set $S$ is some (any) subset of $S^n.$ And an $n$-ary function on $S$ is a function from $S^n$ into $S.$ In Model Theory an $n$-ary relation and $n$-ary function symbols  are arbitrary objects that are "interpreted" by a model $\mathbb M=(M,...)$ as  $n$-ary relations  and $n$-ary functions on $M.$ The "..." in $\mathbb M=(M,...)$ is a "list" of the interpretations by $\mathbb  M$ of all the relation symbols and function symbols of the language
Comment: I took courses in set theory , and model theory under  William Weiss at U. of Toronto. He had a difficulty which he said was embarrassing for a mathematician : An allergy to chalk.  He had a large wheeled greaseboard.
Comment: @user21820   I think whiteboard is indeed the more accurate term for what he used
Comment: ^ oh my, haha...
Comment: What about using whiteboards instead?


In which database table does the number views of a node get stored?

Question: I'm using Drupal 7. After enabling the Statistics module (part of Drupal core), I see, under each node, how many times it has been read (e.g. "4 reads").
I wonder where this number of views of a node (e.g. "4 reads") gets stored in some table in the Drupal database.
Answer: As well as statistics there is the aptly titled Node View Count module
https://www.drupal.org/project/nodeviewcount
It has a few advantages over the native stats module in the way it counts and also has views integration so you can get some nice tables up and going quickly.
Answer: Statistics does store some information in accesslog as Shai said, but the view counts themselves are in the table node_counter.
Here's a query I wrote to get the top 100 nodes with titles by views.
<code>select node_counter.totalcount, node.title, node.nid from node_counter, node where node.nid=node_counter.nid order by totalcount desc limit 100;
</code>
Answer: The Statistics module stores data in the accesslog table.


Inscribed Quadrilateral: Collinear Points

Question: $ABCD$ is an inscribed quadrilateral with $O$ being the circumcenter. The $\perp$ raised on $AB$ at $A$ cuts $CD$ at $F$ and the $\perp$ raised on $AD$ at $A$ cuts $BC$ at $E$. Show that $E, O, F$ are collinear.
Answer: Let the second point of intersection of $AE$ with the circumcircle be called $P$ and the second point of intersection of $AF$ with the circumcircle be called $Q$ (the first being $A$ for both lines). Then $O \in BQ$ because $\angle \, BAQ = 90^{\circ}$ implies that $BQ$ must be a diameter. Analogously, $O \in DP$ because $\angle \, DAP = 90^{\circ}$ implies that $DP$ must be a diameter. Consequently, $O = BQ \cap DP$.
Apply Pascal's theorem to the non-convex inscribed hexagon $BCDPAQ$. Then the intersection points of the opposite edges of the hexagon, $E = BC \cap AP, \,$ $F = CD \cap AQ$ and $O = BQ \cap DP$ must be collinear.
Comment: is there a different way? haven't done Pascal's... @Futurologist


Prove that the rational numbers are countable - An alternative way

Question: There are many answers for this topic in the stackexchange forum but I would like to validate an alternative way of finding that the rational numbers are countable.
The set of rational numbers is defined as $Q = \lbrace \frac{p}{q}: p,q \in Z \rbrace$. So, each number can be writter as $p = aq + r \implies aq = p -r \implies p \equiv r (mod q)$. So, there is the set of residuals $Z_q$. There is also a set $P$ that contains the numbers corresponds to the classes of the $Z_q$. The countable sum of the $Z_q$ is the set $nZ$. We only need to prove that countable union of countable sets is a countable set.
Comment: When you say "sum", I presume you mean "disjoint union". Yes, but then your argument is that "disjoint union of countably many countable sets is a countable set", which is pretty much what the whole thing about $\mathbb Q$ being countable *is* about. In other words, you would be "back to square one". Plus, you can make those sets much simpler: $\{\text{fractions with denominator }1\}, \{\text{fractions with denominator }2\}, \{\text{fractions with denominator }3\},\ldots$.
Comment: @halrankard2 Indeed. Either we have some way to do counting rationals in finite groups (which is possible, but seems to be unsuccessful here), or we are counting them in (countably) infinite groups (which is ok, but this is the crux of what we want to show in the first place). BTW: The usual divide of rationals into finite groups (based on the sum of the numerator and denominator in the reduced form) is also quite simple: $\{0\}, \{1, -1\}, \{2,\frac12,-\frac12,-2\}, \{3,\frac13,-\frac13,-3\}, \{4,\frac32,\frac23,\frac14,-\frac14,-\frac23,-\frac32,-4\},\ldots$
Comment: Are you taking union of $\{0\}, \{0,1\}, \{0,1,2\}, \{0,1,2,3\}\ldots$ (i.e. sets of residuals)? Obviously, there are repeated elements, so, intuitively, the union is *smaller* than the sum of sizes of all sets contributing to it. (Finite case: $\{0\}$ has $1$ element and $\{0,1\}$ has $2$ elements, but $\{0\}\cup\{0,1\}$ has $2$ elements - not $3$.) Thus, if your goal is to cap the sum of the sizes, you are supposed to bound it from *above* but you are bounding it from *below*, so to speak.
Comment: Very Nice !! I have an another question here ! If we have a sum of $n$ sets of integers $Z$ then is the set $nZ$ countable ? If the set is countable then I could change what I wrote "the union of $Z_q$" and I could write the sum of $Z_q$.
Comment: One could try to argue that showing the disjoint union of countably many finite sets is countable is simpler than showing the disjoint union of countably many countable sets is countable. But it seems to me that the real point is that your assignment of $p/q$ to $p$ (mod $q$) is not one-to-one (as pointed out in the answer below). In fact, this mapping will have infinite fibers. So you actually are left with showing that the union of countably many countable sets is countable. This is the usual proof, and can be done more easily, as Stinking Bishop says.
Comment: @StinkingBishop Good point.
Comment: By the way: the set of rational numbers is _not_ defined as $\Bbb Q = \lbrace \frac{p}{q}: p,q \in Z \rbrace$. By this definition, $1/2$ and $7/14$ would be different rational numbers. It is (usually) defined as the set of _equivalence classes_ of $\lbrace \frac{p}{q}: p,q \in Z \rbrace$, where $p/q\equiv r/s$ if $ps=rq$.
Comment: Questions here are meant to present a "static" picture, not a dynamic one.  It would likely be better if you removed the struck-through text, and edited your question so that it clearly presents your thinking without elisions and deleted text.
Answer: It is $7 \equiv 2 \pmod{5}$ but $\dfrac{7}{5}\not= \dfrac{2}{5}$ so for  $5$ there are more that $|\mathbb{Z}_5|$ rationals with denominator $5$ so I don't think you count all of the rationals.
After discussion: the exact definition of $P$ is that it is $\mathbb{Z}$ and every time there is $P\to \mathbb{Z}_q$ for a different $q\in\mathbb{Z}$. So in order to show that $\mathbb{Q}$ is countable it remains to be shown that countable union of countable sets is countable.
Comment: No. Suppose $P=\mathbb{R}$ and to each $x\in\mathbb{R}$ I correspond $\overline{[x]}$ (where $[x]$ is the integer part of $x$)
Comment: I'm sorry but I can't get your point
Comment: But what does "produce" mean? Do you mean union? Like if $\cup P$ is countable then $P$ is countable?
Comment: Yes this is true ! But... Don't we claim that if the set of residuals is countable then all classes of this set are countable too ?
Comment: What I want to say is that: If we have a set of numbers $P$ that can produce a countable set (set of residuals), then can the set $P$  be considered as countable ?
Comment: Let assume that there is a set of residuals $Z_q$. This set is countable and contains the classes $\bar{0},...,\bar{{q-1}}$. We assume that there is a set $P$ where each number corresponds to a class. For example, $\bar{0} = \bar{q}$. My question is: Can we consider that the set $P$ is also countable ?
Comment: I think that $P \subset Z$ because based on the definition of the set $Q$ above the $p$ and $q$ are integers and also the residual $r$ is integer. Thus, the $P$ can not be the set of $R$
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/113639/discussion-between---and-dimitris-dimitriadis).
Answer: As mentioned above, your particular encoding may not work, but there are other ways to encode rationals as integers.
One example is to map $(p,q)$ to "$\text{length}(p)\, 0\, p\, q$".
Where $\text{length(x)}$ is simply a unary encoding of $p$ -- that is a string of 1's as long as $p$.
Then you might write

$7/3$ as $1\, 0\, 7\, 3$.
Or $100/17$ as $111\, 0\, 100\, 17$.

Since you can always recover the original fraction, the encoding is a bijection, and since it maps into the integers you have shown that the cardinality of the fractions is the same as that of the integers.


Celery+Django -- How to log non-task module

Question: Currently, my Django+Docker-Compose project is able to use Celery to make the main uploading function, insertIntoDatabase, an asynchronous task that properly runs in the background. I run Celery using a Docker container named worker, and I can see its logs in the console just fine. However, the logging that usually worked in insertIntoDatabase now no longer happens.
Uploading begins in views.py:
from .tasks import db_ins_task
...
db_ins_task.delay(datapoints, user, description) # datapoints is a list of dictionaries, user and description are simple strings

And the task is defined as such in tasks.py:
@app.task()
def db_ins_task(datapoints, user, description):
    from utils.db.databaseinserter import insertIntoDatabase
    insertIntoDatabase(datapoints, user, description)

So in databaseinserter.py, the following logging no longer works:
logger = logging.getLogger('myapp.databaseinserter')
...
def insertIntoDatabase(datapoints, user, description):
    # do the database insertion work
    ...
    logger.info("This upload took %.3g seconds", elapsed_time)

The info log at the end is supposed to go to a log file that I configured in settings.py. Now that insertIntoDatabase is called from a task rather than directly, info logs of this sort no longer appear in the proper log file. All other logging that existed in my project still works fine. What should I do to make the logging work again?
For further reference, here is part of celery.py in a separate app named taskman:
from __future__ import absolute_import
import os
from django.apps import AppConfig
from celery import Celery, Task

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproj.settings')

from django.conf import settings

app = Celery('myproj')
class CeleryConfig(AppConfig):
    name = 'taskman'
    verbose_name = 'Celery Config'

    def ready(self):
        app.config_from_object('django.conf:settings')
        app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

And here is the pertinent part of the logging settings in settings.py:
LOGGING = {
    ...
    'handlers' = {
    ...
        'dbinsfile': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'maxBytes':LOG_LIMIT,
            'backupCount':10,
            'filename':'logs/insvals.log',
            'formatter':'values',
        },
    ...

    },
    'formatters' = {
    ...
        'values': {
            'format':'>>> [%(asctime)s.%(msecs)03d] %(levelname)s: %(message)s',
            'datefmt':"%Y/%m/%d %H:%M:%S",
        },
    ...
    },
    'loggers' = {
    ...
        'myapp.databaseinserter': {
            'handlers':['dbinsfile'],
            'level':'DEBUG',
            'propagate':False,
        },
    ...
    }
}

EDIT: I think the issue is that Celery seems to be hijacking the root level logger, or something like that. I've already tried CELERYD_HIJACK_ROOT_LOGGER = False but it didn't change anything, unfortunately. I've also tried adding the following to settings.py:
from celery.signals import setup_logging
@setup_logging.connect
def logging_prevent_celery_hijack(loglevel, logfile, format, colorize, **kwargs):
    import logging.config
    logging.config.dictConfig(LOGGING)

following the Celery docs on signals and logging, but this seemed to have no effect either.
Comment: "no longer works" Meaning what? If the code is called from your Django project (e.g. in a view) it works but if called from a task, then it does not work? How is logging configured in your workers?
Comment: "no longer works" meaning that the logging statements I put in `insertIntoDatabase` are no longer happening. I used to call the function directly but now I call the task which calls the function. All logging was configured in `settings.py` in a manner following the Django documentation.
Comment: Right, so how would I take care of that in the Celery app? I have `celery.py` in an app named `taskman` and there I set it to use my Django settings, which is currently working. What do I need to do in addition so that the worker can basically do the same logging that the original function did?
Comment: I find the use of an `AppConfig` instance that calls the configuration functions of Celery to be unusual. I've always had the `app.config_from_object()` and `app.autodiscover_tasks()` in the topmost scope of my `celery.py`. But I cannot put my finger on what would be wrong exactly.
Comment: Did you ever find a solution to this? I have the exact same issue
Answer: From the official document:
from celery.utils.log import get_task_logger

logger = get_task_logger(__name__)

If the logger.xxxx() is called inside a function by a Celery worker, the logger configured by Celery will be used; otherwise, it will be the one configured manually. The behavior is irrelevant to where the function belongs.


Page expired issue with back button and wicket SortableDataProvider and DataTable

Question: I've got an issue with SortableDataProvider and DataTable in wicket.
I've defined my DataTable as such:
IColumn<Column>[] columns = new IColumn[9];

//column values are mapped to the private attributes listed in ColumnImpl.java
columns[0] =  new PropertyColumn<Column>(new Model<String>("#"), "columnPosition", "columnPosition");

columns[1] =  new PropertyColumn<Column>(new Model<String>("Description"), "description");
columns[2] =  new PropertyColumn<Column>(new Model<String>("Type"), "dataType", "dataType");

Adding it to the table:
DataTable<Column> dataTable = new DataTable<Column>("columnsTable", columns, provider, maxRowsPerPage) {
    @Override
    protected Item<Column> newRowItem(String id, int index, IModel<Column> model) {
        return new OddEvenItem<Column>(id, index, model);
    }
};

My data provider:
public class ColumnSortableDataProvider extends SortableDataProvider<Column> {
private static final long serialVersionUID = 1L;

private List<Column> list = null;

public ColumnSortableDataProvider(Table table, String sortProperty) {
    this.list = Arrays.asList(table.getColumns().toArray(new Column[0]));
    setSort(sortProperty, true);
}

public ColumnSortableDataProvider(List<Column> list, String sortProperty) {
    this.list = list;
    setSort(sortProperty, true);
}

@Override
public Iterator<? extends Column> iterator(int first, int count) {
    /*
     first - first row of data
     count - minimum number of elements to retrieve
     So this method returns an iterator capable of iterating over {first, first+count} items
    */
    Iterator<Column> iterator = null;

    try {
        if(getSort() != null) {
            Collections.sort(list, new Comparator<Column>() {
                private static final long serialVersionUID = 1L;

                @Override
                public int compare(Column c1, Column c2) {
                    int result=1;
                    PropertyModel<Comparable> model1= new PropertyModel<Comparable>(c1, getSort().getProperty());
                    PropertyModel<Comparable> model2= new PropertyModel<Comparable>(c2, getSort().getProperty());

                    if(model1.getObject() == null && model2.getObject() == null)
                        result = 0;
                    else if(model1.getObject() == null)
                        result = 1;
                    else if(model2.getObject() == null)
                        result = -1;
                    else
                        result = ((Comparable)model1.getObject()).compareTo(model2.getObject());

                    result = getSort().isAscending() ? result : -result;

                    return result;
                }
            });
        }

        if (list.size() > (first+count))
            iterator = list.subList(first, first+count).iterator();
        else
            iterator = list.iterator();
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return iterator;
}

The problem is the following:
- I click a column header to sort by that column.
- I navigate to a different page
- I click Back (or Forward if I do the opposite scenario)
- Page has expired.
It'd be nice to generate the page using PageParameters but I somehow need to intercept the sort event to do so.
Any pointers would be greatly appreciated.  Thanks a ton!!
Comment: The code will lay out more nicely here if you indent all the lines by four spaces or wrap it all in code tags.
Answer: I don't know at a quick glance what might be causing this, but in order to help diagnose, you might want to enable debug logging for org.apache.wicket.Session or possibly more of the wicket code.
The retrieval of a page definitely involves calls to a method
public final Page getPage(final String pageMapName, final String path, final int versionNumber)

in this class, and it has some debug logging.
For help with setting up this logging, have a look at How to initialize log4j properly? or at the docs for log4j.


In a piano score, what is the meaning of a V with a dot in it

Question: In a beginners piano scorebook, under the last cord there is a V with a dot in it. I searched but can't find what it could mean. In case that matters, it's a French book.

There is no other place in the score where I can find this symbol. What should I do with it or how to play this?
Thank you!
Answer: It's called a "staccato duro", and as the other answer correctly wrote, it's a marked staccato, i.e. shorter than the note duration and with force.
For future reference: all musical symbols and their explanations can be found on dolmetsch
Answer: It's a combination of the wedge (marcato) and the dot (staccato). The note is to be played shorter than normal (like a staccato) but forcefully (like with the wedge.) I didn't find a specific name for the symbol.
Answer: It could also be a short fermata. It is a lesser-known mark signifying that a note is to be played longer than the indicated duration, but only slightly longer.
See this page for an explanation.
Comment: Gardner Read's "Music Notation" (1979), p. 108, calls the blue and green versions a modern innovation.  (So it's not found in music before 1945.)  The traditional notation would be to add a *lunga* or a *poco* to the traditional fermata.
Comment: @phoog - usually, but not always.
Comment: If it were any sort of fermata, it would be above the staff, not below the note.
Answer: Called 'martellato', it's to make sure the note(s) is/are played strongly, hammered. Not necessarily staccato as such. Used more often in violin music - a strong downbow from the frog - but also piano and vox.
Comment: @ttw did you mean to comment on my answer rather than Tim's?
Comment: Interesting. I've never seen other than the crescent. I have seen (and used) fermatas over different length notes (quarter, half, whole, tied wholes) to indicate the length of the fermata. The angular one is a right angle which differs from the dotted wedge in having a bigger angle. I probably would have read the green version as a staccato down-bow.


pyinstaller, import error: no module named pywintypes

Question: I want to create exe from a py script using pyinstaller. I wrote the following command in cmd "pyinstaller --onefile --windowed filename.py", but there is an error showed by the cmd. How do I solve this?
Traceback (most recent call last):
  File "c:\python27\lib\runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "c:\python27\lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "C:\Python27\Scripts\pyinstaller.exe\__main__.py", line 5, in <module>
  File "c:\python27\lib\site-packages\PyInstaller\__main__.py", line 21, in <module>
    import PyInstaller.building.build_main
  File "c:\python27\lib\site-packages\PyInstaller\building\build_main.py", line 32, in <module>
    from ..depend import bindepend
  File "c:\python27\lib\site-packages\PyInstaller\depend\bindepend.py", line 38, in <module>
    from ..utils.win32.winmanifest import RT_MANIFEST
  File "c:\python27\lib\site-packages\PyInstaller\utils\win32\winmanifest.py", line 97, in <module>
    from PyInstaller.utils.win32 import winresource
  File "c:\python27\lib\site-packages\PyInstaller\utils\win32\winresource.py", line 20, in <module>
    import pywintypes
ImportError: No module named pywintypes

Edit: I have tried to "pip install pypiwin32, but still got the same ImportError
Comment: As Traceback says, you haven't got module `pywintypes`. You must install this.
Comment: @R.Gadeev  I tried it and it said '  Could not find a version that satisfies the requirement pywintypes (from versions: )
No matching distribution found for pywintypes'.
Answer: You should try to work in a virtualenv if you are on Windows. I recommand Anaconda. You will be able to easily install most of python packages.
Once Anaconda is installed, just run conda install -c conda-forge pyinstaller=3.2.1
 and you should be fine.
Hope this helps.
Comment: thank you for your help! I will use conda to install other library next time.
Answer: In some case you have to manually mention modules that need to be packes through the keyword "--hidden-import
So in your case:
    pyinstaller --onefile --hidden-import=pywintypes --windowed filename.py
Comment: I tried it, but the result still the same.no module named pywintypes.
Comment: Does this error appear when you run the python script on your machine or only when you try to make an executable? In the first case you need to download it: 'pip install pypiwin32' in later case try the points mentioned here under ImportError: https://github.com/pyinstaller/pyinstaller/wiki/How-to-Report-Bugs
Comment: it is only when i tried to make an executable. I've tried to pip install pypiwin32, but it said that it already installed and tried the github, but the same thing still happen.


Extending a $C^{1}([0, 1/2])$ function to be $C^{1}([0, 1])$ while preserving upper and lower bounds

Question: Suppose $f \in C^{1}([0, 1/2])$ such that $1 \leq f(x) \leq 2$ for all $0 \leq x \leq 1/2$ and $f'(0) = 0$. Does there exist a $g \in C^{1}([0, 1])$ such that

$1 \leq g(x) \leq 2$ for all $0 \leq x \leq 1$
$g'(0) = 0$
$f(x) = g(x)$ for all $0 \leq x \leq 1/2$?

From the Tietze extension theorem there is a continuous $g$ such that $f = g$ on $[0, 1/2]$ and $1 \leq g \leq 2$ on $[0, 1]$. But this $g$ may not be differentiable and so this $g$ obeys the first and third conditions but not the second.
One can also define a candidate $g$ by
\begin{align}
g(x) = \begin{cases}
f(x) & \text{ if } x \in [0, 1/2]\\
f(1/2) + f'(1/2)(x - 1/2) & \text{ if } x \in [1/2, 1]
\end{cases}
\end{align}
and this obeys $g \in C^{1}([0, 1])$, $g'(0) = 0$ and $f = g$ on $[0, 1/2]$ but then one doesn't (necessarily) have $1 \leq g \leq 2$ on $[0, 1]$. So this candidate obeys the second and third conditions but not the first.
Finally, one can define $g(x) = f(x/2)$ which obeys the first two conditions but not the third.
Answer:
(Possibly, there are some typos in the QUESTION).

In general, there is no such $g$. Indeed, let
$$ \forall_{x\in\left[0;\frac 12\right]}\quad
      f(x)\ :=\ 1\,+\,4\cdot x^2 $$
Then $\ f'(0)=0,\ $ and
$$ \forall_{x\in\left[0;\frac 12\right]}\quad 1\le f(x)\ \le 2$$
However, $\ f'\left(\frac 12\right) = 4>0 $ hence every $\ C^1$-extension $g$ of $f$ over $\ [0;1]\ $ would have values $\ >\ 2\ $ in a small right neighborhood of $\ \frac 12.$
Answer: Not positive about this but here is my attempt.
Let $f$ be a function satisfying all of the criteria you list and suppose that $f(1/2) = 2$ and $f'(1/2) > 0$. Now if $g$ is a continuous extension of $f$ on $[0,1]$. Then $g(1/2) = 2$ and $g'(1/2) = f'(1/2)>0$. These both follow from the condition that $f$ and $g$ are equal on $[0,1/2]$. Since $g$ is $C^1$, $g'$ is continuous on $[0,1]$ and hence there exists a neighborhood around $1/2$ where $g'$ is positive. This implies that in this neighborhood, $g$ is increasing, but $g$ cannot exceed $g(1/2) = 2$. Therefore the extension you want does not exist in general.


CSS defined in library is not included, but theme works

Question: themes/custom/teleci/teleci.info.yml:
base theme: bartik
core: 8.x
name: Teleci
package: Custom
type: theme
version: "1.1"
libraries:
  - teleci/global-styling

themes/custom/teleci/teleci.libraries.yml:
global-styling:
  version: "1.1"
  css:
    theme:
      css/override.css: {}
      css/style.css: {}

I also have custom template in themes\custom\teleci\templates\block--teleci-branding.html.twig that is loading correctly - that means the theme works. But the CSS files are not included (they are not in the generated HTML).
I tried

php drupal.phar cr all
setting bartik as default and then set my theme back
clear browser cache
open in private window
disable JS/CSS minification in settings
check both yml files in yamllint.com
disable base theme (bartik)

I'm out of ideas and would appreciate any help :(
Update: I created minimal theme (that does not work as well) for you to test. Could you please test it and let me know if it works for you? https://github.com/tomasfejfar/drupal-simple-theme/ (i have it in /themes/custom)
Update 2: the mini-theme works when I fixed a small bug that is not present in my theme. So there is something about my theme that makes it break.
Comment: Did you clear/flush the Drupal cache? If you are using drupal console, its suppose to be `drupal cr all`
Comment: yes, as noted in list of things I tried: ˙λ php drupal.phar cr all

 Rebuilding cache(s), wait a moment please.

 [OK] Done clearing cache(s).˙
Comment: I've never seen it used with `php` but ok.
Comment: any errors in the log or in the browser console?
Comment: Nothing in console, nor error log
Comment: Why the downvotes? Have I done something wrong?
Comment: I +1 u to make up for the those unjustified down votes. Maybe try without using a base theme (for testing purposes).
Comment: +1, I don't see the reason for having been downvoted. Did you check your YAML indentation to be sure it's accurate? It looks fine from here but perhaps double check that.
Comment: Did that first thing after seeing simmilar problems ("check both yml files in yamllint.com" in list) :(
Comment: Tried without base theme - the page is now unstyled. Although there are some imported styles in header:
`
Answer: Finally it seems to have been fixed. I re-created the same template again under a new name. Checked the diff of theme.info.yml and theme.libraries.yml files - only difference is the name. The new template has all the same functionality the previous had and is 1-to-1 copy except for the name. So only thing I can think of is that while playing with the template something has broken and left some residue in the database that prevented the theme from functioning properly ever again.
Thanks everyone who tried to help!


Linguagem C - Ler Ficheiro para gravar em Listas

Question: Imaginem uma escola com várias salas, e cada sala tem varios alunos
Estou com dificuldades em ler ficheiro com o nome da sala, numero de lugares por filas(linhas e colunas)
Tenho a seguinte estrutura!
typedef struct
{
    char nome[50];
    int numero;
}Aluno;

typedef struct nodo{
    Aluno dados;
    struct nodo *anterior;
    struct nodo *seguinte;
}Nodo;

typedef struct{
    char sala[50];
    int linhas, colunas;
    Nodo inicio;
} Lista;

E o seguinte para ler do ficheiro, mas sei que está mal
int LerFicheiro(char *nf)
{
    FILE* w=fopen(nf, "r");
    Lista* li;

    int l,c;
    while (!feof(w))
    {
        fread(&li->nome, sizeof(Lista), 1, w);  // nome da sala
        fread(&li->linhas, sizeof(Lista), 1, w); //  nº linhas
        fread(&li->colunas, sizeof(Lista), 1, w);  // nº colunas

        for (l = 0; l <= li->linhas; l++)
        {
            for (c = 0; c
colunas; c++)
            {
                /*LER NOMES E NUMEROS*/

            }
        }
    }
    fclose(w);

}

Este é o ficheiro para ler!
Tem o nome da sala, na linha seguinte o numero de lugares em linha e em coluna!!! De seguida é tem o numero do aluno e nome do respetivo aluno
Sala de Historia
8 5
1231
Joao Afonso
563
Zé Alves
7634
Rita Pereira
948
Patricia Mendes
39
Rui Santos

Alguém me consegue fazer ou ajudar nisto?
Muito Obrigado!!!!
Answer: fscanf(f, "%d", &Imag->NLINHAS);
Normalmente eu costumo usar o "fscanf" em vez do "fread" para ler o conteúdo do ficheiro.
    fscanf(f,"%s" ,&li->titulo);  // nome da imagem
    fscanf(f,"%d",&li->linhas); //  nº linhas
    fscanf(f,"%d",&li->colunas);  // nº colunas
    fscanf(f,"%d",&li->canais);  // nº canais

As estruturas que colocaste são relativas à sala, mas o código para ler ficheiro é relativo a uma imagem, não te enganaste???
De qualquer modo, tens ainda de definir na estrutura Lista o título e os canais, sendo que queres essas variáveis no ler ficheiro.
typedef struct{
char sala[50];
char titulo[50];
int linhas, colunas,canais;
Nodo inicio;
} Lista;

Comment: Sim, erro meu, ja editei!!
Comment: nesse caso podes usar na mesma o que te mandei anteriormente, mas substituis as variáveis que tinhas, pelas novas (nome, linhas, colunas)
Comment: Mas, como vou fazer com as salas? a minha duvida é mesmo essa, ler sala a sala os lugares com os alunos
Comment: Como é que tens escrito no ficheiro? consegues mandar print de como está o ficheiro? assim é mais fácil para perceber como te hei de ajudar


php implode array elements

Question: How do I turn the following array
$p = array('1' => 'a', '2' => 'b', '3' => 'c');

into the following output? Note that each array element is on a separate line:
1:a
2:b
3:c

Answer: You're looking for the basic for-each construct:
$p = array('1' => 'a', '2' => 'b', '3' => 'c');
foreach($p as $key => $value) {
  echo $key.":".$value."\n";
}

Answer: var $colon_separated = array();
foreach ($a as $key => $value) {
    $colon_separated[] = "$key:$value";
}
$result = implode("\n", $colon_separated);

php implode array elements


Property of homogeneous separable Differential equation

Question: The following is the textbook extract while it shows that if the right side of a equation can be expressed as function of ratio $(y/x)$, then the equation is homogeneous and a homogeneous equation can always be represented in a separable form.

... This means that integral curves have the same slope at all
  points on any given straight line through the origin, although the
  slope changes from one line to another. Therefore the direction field
  and the integral curves are symmetric with respect to the origin.

I did not understand the conclusion of the slope, is it so that all the homogeneous DE integral curves are symmetric about some straight line through origin?
Comment: Your equation (1) doesn't match its description.
Comment: NARQ. $ $ $ $ $ $
Answer: The integral curves have the same slope on the straight lines passing through the origin.
Actually, it is more simple to start with the equations of the form
$$
\frac{dx}{dt}=f(x),
$$
which is called autonomous, because the right hand side does not depend on $t$ explicitly. What special about this equation? Answer: If $x(t)$ is a solution for the initial condition $x(0)=x_0$, then $x(t+C)$ is a solution for the initial condition $x(C)=x_0$. In different words, all the solutions can be obtained from one by translating to the left or right. And yet in another words: if you plot your solution curves of this equation, the slope on the straight lines parallel to the time axis is the same (because they are the same curves, obtained by translation!) I leave you make a picture yourself. Note that sometimes the straight lines $x(t)=\hat{x}$ are solutions, and in this case they separate families of other solutions.
For the homogeneous equations similar facts are valid if you replace straight lines parallel to the time axis by the straight lines passing through the origin. That is, the integral curves of the homogeneous equation are obtained with the expanding and shrinking of one solution. That is, the slope on the integral curves on the straight lines through the origin is the same (see the first paragraph of the Arnol's book Geometric methods...)


Procurve switch SFP only works when not firmly seated

Question: I have a Procurve switch with an SFP transceiver in Port 28. The switch will not bring this port online while the transceiver is securely seated and latched.
However, if I pull the transceiver out slightly so that it's not seated firmly, the module comes online.
Is this normal?
Comment: That sounds like either a faulty switch or a faulty transceiver. What happens if you try that transceiver in a different SFP port?
Comment: +1 for experimenting w/ other slots. Only other thing I could think of is taking some canned air and blowing out the slot, and also (gently) cleaning the connective surface on the tranceiver unit itself.
Answer: Sounds like dirty contacts on either the module or the switch.  Try cleaning them, or using a different module/slot.
Answer: This is definitely not normal and indicative of a bad slot or SFP.  Try another SFP in that slot or your SFP transceiver in a different port to test which (if not both) is faulty.


Best way to tag/identify processes for killing them later?

Question: In my linux startup scripts, when I start a process like (openvpn used for this example, but the question is general to any process);
openvpn --config /etc/myserver.conf

what is the best way to find it and be 100% certain it's the right process and kill it in the stop section? I normally use stuff like:
pid=$(ps -efww | grep -v grep | grep openvpn | grep /etc/myserver.conf | awk '{print $2}')

Sure it works nearly all of the time, but sometimes there are issues with accidentally matching processes with nearly the same name (e.g. myserver.conf-new), so I'm looking for a better approach.

Some processes have a way to store the pid somewhere, that's fine, but generally I'm skeptical of killing processes solely based on a pid sitting in a file somewhere.
Solaris has projects, it's not all roses in my limited experience because you have to set up /etc/projects first, but it does make it easy to tag and later find processes.
Maybe using the environment, like setting an environment variable like (MYID=myserver) and then looking for it with ps e -ef | grep MYID=myserver? Still may suffer the same problem with accidental matching.

I wish there were something easy like:
launch --tag myserver openvpn --config /etc/myserver.conf

and
pgrep --tag myserver

Answer: Thank you @Iain, @KyleSmith, and @M_1 for your answers, and for helping me get started on Server Fault. If I had more rep here I'd +1 you guys. (Edit: now I have rep, +1s all around).
I'm going to answer my own question because I've found something that does what I was looking for: a general solution that avoids imprecise pattern matching with ps, and doesn't use pid files. It's completely subjective that this would be the "best" way because there's obviously a long and successful history in unix of using pid files, however this was something I explicitly said I didn't like for various reasons, and those are: they can be tricky to create properly, different for every piece of software, done differently on every distro, can be stale/overwritten, and inherently don't necessarily represent what's actually going on. I'd rather use some kind of process tagging, ask the kernel and get real answers.
Trimmed down example:
#!/bin/sh
_TAG=d726cc7fa57a308afdc057b228a13f6d
case "$1" in
start)
  _TAG=$_TAG ./self-backgrounding-process
  _TAG=$_TAG ./non-self-backgrounding-process &
  ;;
stop)
  pids=$(grep -l "\b_TAG=$_TAG\b" /proc/*/environ | cut -d/ -f3)
  [ -n "$pids" ] && kill $pids
  ;;
esac

The key points are:

using an md5sum (something very unlikely to be accidentally matched) for the tag
using a different tag in each service's startup script
querying /proc/*/environ to get an accurate list of running/relevant/tagged processes
using grep with \b to match word boundaries to ensure an exact match

I'm not sure I like polluting the environment, but I don't know of any other way (e.g. Solaris projects) to tag a linux process in an arbitrary way that I can ask the kernel for later. At least, /proc/<pid>/environ appears to reflect the environment at startup, and not be affected by any changes the process might make after, which suggests this should be reliable, however, there's the chance this could change unexpectedly. This may or may not work outside Linux, depending on the OS's /proc and grep implementation.
I think I'll give it a try for a while and see how it goes.
Comment: One thing that occurred to me later is this technique doesn't find processes started by hand. Not a big deal maybe, but not good either.
Answer: Don't be afraid of pidfiles, of they're tried and true and typically owned by root!  :)
Most distributions use a standard function or binary to launch daemons and store the resultant PID in a file.  In Debian, for example, you have start-stop-daemon with the --pidfile option.  Other distributions have /etc/rc.d/init.d/functions (or similiar) that are used for starting daemons.  Check some of the more generic startup scripts included with your distribution.
Comment: You're probably right on the point don't be afraid of pidfiles. I'll check out my system startup script libs for some more ideas. Thanks.
Answer: A nice idea would be to use a simple bash wrapper script that writes a lock/pid file of that application (commonly used in webservers or databases) and then use that file to kill exactly this one process if needed.
Comment: I like this idea, but sometimes the programs I call fork themselves into the background, so it's tough to keep track of the right pid.
Answer: For openvpn in particular you can use the --writepid /path/to/file command line option e.g.
/usr/sbin/openvpn --writepid /var/run/openvpn/server.pid  --config /etc/myserver.conf ...

Which will write the PID of the openvpn main process to the named file.
In general you can wrap your program in a small script and use the bash $! builtin variable to write the pid to a file
#!/bin/bash
yourcommand &
echo $! >/path/to/pid.file

Comment: Good point on --writepid for openvppn, I may use that for openvpn in particular. I'll have to find another program to use as an example, but openvpn forks into the background, so if I launch it with & ($! only appears to work when you background something), then you end up with the wrong pid.
Comment: @SteveKehlet: Having something write a PID file is generally the way to do this. Most daemons will write a PID file so you don't need to wrap them you just need to know (or tell) where the PID file is. You only need to write a wrapper for something that doesn't and can't be made to create it's own PID file. Beyond that everything becomes a special case.
Comment: Good point. I may think I have an unusually high number of special cases, but I shouldn't forget that some of them are actually not. Thank you for your answers Iain.


(ssh tunnel?) Access remote server with private IP through a *DIFFERENT* server with public IP

Question: Let's assume the following hosts:

localhost : my laptop
remoteserver : a server with a public IP which runs a SSH server.
private.remoteserver : a server with a private IP which is only accessible from remoteserver.

I don't have sudo access to remoteserver, so I can't make changes with the root user.
The question is: Is it possible to access a port on private.remoteserver from remoteserver, in a single command?
I've played around a bit with ssh tunnels without luck. It would like to create an SSH alias to private.remoteserver as described in this article.
For example, I'd like to run from localhost:
curl http://private.remoteserver:8080/

to connect to port 8080 on private.remoteserver. Is this possible?
Answer: You haven't show us what you've tried so far, but something as simple as this should work:
ssh -L 8080:private.remoteserver:8080 remoteserver

Which would then let you run:
curl http://localhost:8080/

...which due to the port forwarding we just set up would actually connect to port 8080 on private.remoteserver.
If you want to be able to directly access http://private.remoteserver:8080/ from your client, you'll need to (a) set up some sort of proxy and (b) configure curl (or other software) to use the proxy.  You can set up a SOCKS5 proxy with ssh using the -D option:
ssh -D 1080 remoteserver

And then you can:
curl --socks5-hostname http://private.remoteserver:8080/

Most web browsers (Firefox, Chrome) can also be configured to operate with a SOCKS5 proxy.  If you search for "ssh dynamic forwarding" you'll find lots of good documentation, including this article from Ubuntu.
Comment: Thanks, the command ssh -L 18080:private.remoteserver:8080 -f -N user@remoteserver allows to me to curl on port 18080, but do is there a way to avoid to run 1 command like this (or 1 proxy per service) for each port I want to access on private.remoteserver?
Comment: Sure, that's what the dynamic proxy is all about.  Take a look at the docs I linked to in the answer.
Comment: Yes, but I have to specify the proxy in all applications. I'd like to create an alias in /etc/hosts and get all traffic to this host fowarded through ssh tunnel.
Comment: I accept your answer, as it is valid for the question I originely asked. thanks.
Answer: Actually I solved my problem with sshuttle:
sshuttle --dns -HN -r user@remoteserver

No other proxy configuration required, then I can access any ports of the private IP :
curl http://private:8080/


django wsgi correct configuration on vhosts

Question: I want put my working application on apache2 vhosts (Ubuntu), other hosts with php works ok but my problem is with django. I have 500 Internal
/home/py/django/kitty/kitty/wsgi.py
import os
import sys
sys.path.append('/home/s/py/django/kitty')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kitty.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

/etc/apache2/sites-available/wiersze.td.conf
<VirtualHost *:80>
ServerAdmin firstname.lastname@example.com
ServerName  wiersze.td
#DocumentRoot /
WSGIScriptAlias / /home/s/py/django/kitty/kitty/wsgi.py
Alias /adminmedia/  /opt/python2.7/lib/python2.7/site-packages/django/contrib/admin/media/
<Directory "/home/s/py/django/kitty/kitty/">
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
    </Directory>
</VirtualHost>

and in error.log
...
ImportError: Could not import settings 'kitty.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named kitty.settings
...

Answer: In you wsgi.py you are importing kitty.settings those are not on your python path.

Edit your wsgi.py the following way:
path = '/path/to/kitty'
if path not in sys.path:
    sys.path.append(path)

see also:
https://docs.djangoproject.com/en/1.2/howto/deployment/modwsgi/


Mapster Dependency Injection via Autofac

Question: As per Mapster documentation https://github.com/MapsterMapper/Mapster/wiki/Dependency-Injection
I am supposed to do the following:
public void ConfigureServices(IServiceCollection services)
{
    ...
    var config = new TypeAdapterConfig();
    services.AddSingleton(config);
    services.AddScoped<IMapper, ServiceMapper>();
    ...
}

The following is my attempt to add the above configuration in our MVC 4 app using Autofac:
public static void RegisterDependencies()
{
    var builder = new ContainerBuilder();

    ...

    var config = new TypeAdapterConfig();

    //services.AddSingleton(config); <- Not sure what is the equivalent of this line in Autofac?

    //services.AddScoped<IMapper, ServiceMapper>();
    // Not sure if the following is correct? Is AddScoped the same as InstancePerHttpRequest?
    builder.RegisterType<MapsterMapper.ServiceMapper>()
        .As<MapsterMapper.IMapper>()
        .InstancePerHttpRequest();

How to add singleton of config instance?
Not sure if I added IMapper - ServiceMapper configuration properly and if InstancePerHttpRequest is equivalent to AddScoped?
Answer:

How to add singleton of config instance?

In general, you register services as singletons using the fluent method SingleInstance(), e.g.:
builder.RegisterType<MySingleton>().SingleInstance();

Each component with a dependency on MySingleton will get the same instance passed. However, in your case, there is no need to tell Autofac to use a single instance, because you create the instance yourself without the help of Autofac (var config = new TypeAdapterConfig();). Just register this one instance and Autofac won't have any other choice than injecting it wherever its required:
builder.RegisterInstance(config);

Not sure if I added IMapper - ServiceMapper configuration properly ...

Yes, it should work fine this way.

... and if InstancePerHttpRequest is equivalent to AddScoped?

Well, basically yes, but not entirely.
It is not that easy to map functionality from Microsoft.Extensions.DependencyInjection to Autofac. Autofac comes with a concept called lifetime scopes. It allows you to register components that will be unique for the life of a specific scope and won't be used once this scope ends (thus the name lifetime):
builder.RegisterType<MyComponent>().InstancePerLifetimeScope();

You may create lifetime scopes for whatever lifetime concept comes to your mind. In the world of web application frameworks, the most common lifetime concept is the concept of requests, so you could create a new lifetime scope for each request. In fact, the Autofac integrations for the respective frameworks work exactly this way, so you don't have to create the lifetime scopes on your own.
This works fine, as long as there is only a single lifetime concept in your application domain. Once you start to create lifetime scopes inside other lifetime scopes, you cannot define to which lifetime scope a component should be unique. That is why Autofac supports tagging of lifetime scopes. This way you can register a component to be unique only for lifetime scopes with a specific tag:
builder.RegisterType<MyComponent>().InstancePerMatchingLifetimeScope("MyScope");

Now, for each lifetime scope created using the tag "MyScope" a new instance of MyComponent will be used, but other lifetime scopes may share the same instance. As you can read in the Autofac documentation, InstancePerHttpRequest() is just a convenience method for InstancePerMatchingLifetimeScope with a specific unique tag for HTTP requests:

Instance per request builds on top of instance per matching lifetime scope by providing a well-known lifetime scope tag, a registration convenience method, and integration for common application types. Behind the scenes, though, it's still just instance per matching lifetime scope.


Does this Scala Perl/Python architecture make sense

Question: In another question I asked for "the best" language for a certain purpose. Realizing this goal was a bit too much to start, I simplified my idea :) But there were really useful language hints. So I decided on Scala for the desktop-app and consider between Perl and Python on the webserver.
I want to program something like an asynchronous chat (little bit like an email). So you start your program pick your name and add a friend with his unique id. Then you can write him a simple message and when your friends start up his pc, launches the "chat.exe" he receives the mail (internet is required) and is able to answer. No special functions, smiley's or text formatting, just simple for learning purpose.
My concept is: Use Scala for the "chat.exe" (Or is just a "chat.jar" possible?) which communicates via SOCKET with a Perl/Python Framework which handles the requests.
So you type "Hello there" and click on send. This message is transfered via SOCKET to a Perl/Python script which reads the request an put this message in a MySQL database. On the otherside the chat.exe of your friend checks for new messages and if there is one, the Perl/Python script transfer the message. Also via SOCKET.
Do you think this works out? Is SOCKET appropriate and fits in? Or perhaps REST? But I think for REST-Requests you have to use the URI (http://example.com/newmessage/user2/user3/Hi_how_are_you). This looks very unsecure.
Look forward to your comments!
Have a nice day,
Kurt
Comment: Why use three languages and a low-level communication channel?
Comment: You would not need to use the URI for the content of a REST request, for example you could POST `{"sender":"user2","recipient":"user3","message":"Hi how are you"}` to http://example.com/newmessage
Comment: I think you might have more success if you flipped your language choices around: Scala for the server and Python for the desktop app. That being said, you could easily use Scala (or any decent language) for both. But, frankly, your question is rather nebulous and hard to give any sort of authoritative answer.
Comment: "internet is required"?  What does this mean?  Why is it in here?
Comment: @Andrew: thanks i look at this in detail!
@pr1001: Ok, thanks. But I am not sure if I can compile a standalone python programm (py2exe and pyinstaller look very immature)
@Raphel: What would you recommend, I thankful for improvements!
@S.Lott Because otherwise the Desktop app could not receive the message from the server
Answer: If you ask me, I think Scala is most suitable for the server side.  Scala runs on the JVM and Java has a really big ecosystem at the server side.  You have a big variety of application servers for every taste (tomcat, jetty, glassfish, etc.).
Chat is a classical use case for actors.  I think Akka can inspire you in this area.
You can use wonderful Scala web frameworks like Lift.  You can even make a web-based chat. Here is an example of a chat application that uses comet (server push):
http://demo.liftweb.net/chat
About REST: If you feel that it's not secure, then

Use HTTPS to communicate with server
In your example, your intent is to put the message to the server (at least that is how I understood it), so most probably you want to use PUT requests, and in this case the message text would be in the POST request body.
Comment: @Kurt: Yes,  you can use use remote actors: http://doc.akka.io/remote-actors-scala. About hosting... you can use http://code.google.com/appengine/ for free (but if you need more processing power, you should pay) and as far as i know Scala works there. You can also look at AWS: http://aws.amazon.com/ec2/
Comment: I thought on using Scala on the server as well. Unfortunately my webhosting plan only supports Perl/Python/PHP (a lot of P's!) but I should consinder to upgrade. Or do you know good alternatives? So with Actors I can communicate between Client/Server? Because I want a desktop program and not "only" a webpage. Thanks!
Answer:
Use Scala for the "chat.exe" (Or is just a "chat.jar" possible?)

Step 1.  Figure that out.  Actually write some stuff and see what you can build.

which communicates via SOCKET with a Perl/Python Framework which handles the requests.

Not meaningful.  All internet communication is done with sockets.  Leave this sentence out and you don't lose any meaning.

This message is transfered via SOCKET to a Perl/Python script which reads the request an put this message in a MySQL database.

A little useful information.  Sockets, however, go without saying.

On the otherside the chat.exe of your friend checks for new messages and if there is one, the Perl/Python script transfer the message. Also via SOCKET.

Right.  Sockets, again, don't mean much.
On top of sockets there are dozens of protocols.  FTP, Telnet, HTTP, SMTP, etc., etc.
Step 2 is to figure out which protocol you want to use.  REST, by the way is a particular use of HTTP.  You should really, really look very closely at HTTP and REST before dismissing them.

This looks very unsecure

Not clear why you're saying this.  I can only guess that you don't know about HTTP security features.

A lazy programmer might do this.

Install Python, Django, MySQL-Python and Piston.
Define a Django Model, configure the defaults so that model is exposed as a secure RESTful set of services.

That's sort of it for the server side message GET, POST, PUT and DELETE are all provided by Django, Piston and the Django ORM layer.  Authentication can be any of a variety of mechanisms.  I'm a big fan of HTTP Digest authentication.
Answer: To implement something like that you would need to go through a MQ System like perhaps ActiveMQ instead of using plain sockets.
Comment: Thanks, Do you have a good introduction to these MQ (same as message brocker?) systems? Kurt


How can I change the displayed name of a pwa on home screen?

Question: (I'm using Nuxt 3.0.0-rc.13 and @kevinmarrec/nuxt-pwa 0.9.1, but I think my question is generic to any PWA.)
On my Android tablet, I go to the website with my PWA in Chrome and it asks me if I want to install it on my home screen. I touch that and it installs and works properly.
However, the name of the app matches the name in my package.json file, which is lower case and has hyphens instead of spaces. Can I change that name to be more friendly? That is the name that appears in the prompt for the user and also appears under the icon on the user's home screen.
Bonus question:
I'd love to be able set that name programmatically, too. I will eventually have the same app set up in multiple domains with the only difference being the data that is displayed. I'd like to be able to name the app differently for each of those instances.
Comment: `manifest.json`
Comment: @chovy pretty limited lead in the given context since everything happens down there. Here OP is asking on how to perform that for that specific Nuxt abstraction by using a package.
Answer: The name that appears on the home screen is set in the manifest.json file (more).
This file is generated by @kevinmarrec/nuxt-pwa, but I couldn't find any further documentation about the module. But as far as have understood the module defintion (module.ts), it provides a similar configuration interface like @nuxtjs/pwa.
@nuxtjs/pwa and expecially the manifest can be configured via nuxt.config.js. More information here. Use this as a guideline and see what is available in the module.ts file.
Comment: OP is using Nuxt3 here, hence why the usage of `@nuxtjs/pwa` is not possible in that case. Otherwise, as [mentioned here](https://stackoverflow.com/questions/74348548/why-arent-the-fonts-getting-cached-in-my-pwa#comment131259556_74348548), the team is focused on shipping an official baked-in support anyway. A matter of waiting the core team to finish the implementation or not using any Nuxt modules at all I'd say.
Comment: @kissu, you are right. I am not really familiar with nuxtjs. But if I understand the module definition correctly (https://github.com/kevinmarrec/nuxt-pwa-module/blob/main/src/module.ts#L24) it looks like that `@kevinmarrec/nuxt-pwa` uses a very similar configuration interface as `@nuxtjs/pwa`.
Comment: Yep, he tried to backport some part of it. But not everything from the official Nuxt2 module. At the end, the solution is probably quite trivial but I'm no workbox expert.
Answer: In nuxt.config.ts you can set the name like this:
pwa: {
  manifest: {
    name: "Friendly Name",
    short_name: "Home Screen Label",
    },
},


Spark read multiple CSV file with header only in first file

Question: I want to read multiple CSV files from spark but the header is present only in the first file like:
file 1:
id, name
1, A
2, B
3, C

file 2:
4, D
5, E
6, F

PS: I want to use java APIs to do so
Answer: You can use header=true and use inferSchema=true to get the correct data types from the file you have headers. Then get this schema type into to a StructType in Java and use that to import the other csv files without headers. This was tested in spark version 2.3.2
    import org.apache.spark.sql.Dataset;
    import org.apache.spark.sql.Row;
    import org.apache.spark.sql.SparkSession;

    SparkSession spark = SparkSession.builder()
        .appName("SimpleApp")
        .master("local")
        .getOrCreate();

  // Use this to get the headers automatically
    Dataset<Row> csvData = sparkSession.read()
       .format("csv")
       .option("header","true")
       .option("inferSchema","true")
       .load("C:\\MyData\\numData.csv");

    csvData.printSchema();

Answer: Surely you would know the name of the one file that has the header, if not all.
In that case, extending from the existing answer, assuming name of file with the header is h.csv :
val sqlContext = new SQLContext(sc)

val file1DF = sqlContext
  .read
  .format("csv")
  .option("header", "true")
  .load("<path to folder>/h.csv")

val schema = file1.schema

val file2DF = sqlContext
  .read
  .format("csv")
  .schema(schema)
  .load("<path to folder>/{[^h],h[^.]}*.csv")

Now, the regex functionality provided is not too exquisite. But, I don't think the Spark DataFrameReader.load public api provides us any powerful way to exclude specific names.
More links to glob pattern that this API accepts are there @ this answer.
The internal API's from hadoop though seem to allow for a filtering (below image from relevant book section linked in above answer):

For your case you may want to name your file with header with a simplistic name, e.g. h.csv and the regex for second section in above code may have {[^h],h[^.]}*.csv, to include all files that don't start with h or if they start with h then the 2nd character is not ..
Comment: @Sandeep, did this help?
Answer: You'll want to do something like the following
Scala solution:
val sqlContext = new SQLContext(sc)

val file1DF = sqlContext
  .read
  .format("csv")
  .option("header", "true")
  .load("file1.csv")

val schema = file1.schema

val file2DF = sqlContext
  .read
  .format("csv")
  .schema(schema)
  .load("file2.csv")

Java will be similar exception you'll want to use the StructType for the schema.
DataFrame file1DF = sqlContext.read()....;
StructType schema = file1DF.schema();
DataFrame file2DF = sqlContext.read()....schema(schema)....;

Comment: That would surely work but I'm looking for a generic solution that works for all files in a path. Also, I don't know the number of files in the path. So it won't be possible to read file individually.


What non-user directories can sandboxed mac app read/write to?

Question: I have an app which needs to preserve data between times it runs. I had been using NSUserDefaults for this, but I've had a few users point this out to me: this causes different users to end up with different data, which isn't the way the app should work. It needs a single directory that it can read/write from regardless of which user is running it.
So, I need a non-user specific directory that a sandboxed mac app can read and write to.
Thanks!
(Oh, and if this directory is persistent between updates of my app, that'd be helpful, too!)
Quick barely related question: Is there a way to have a user modifiable resource file in a Mac App Store approved app? I don't want it to be modifiable via my app; I just want to make sure that users modifying it won't cause the system to kill the app for not matching a code signature hash or something.
Comment: Valve (makers of Steam) will be launching a competeting app store soon which will be much more flexible... with any luck, Apple will fix their sandbox implementation to allow such a directory in response, but if they don't I can always sell a better version of my app on Steam.
Answer: I don't think that you will be able to read and write in a directory outside of the App Sandbox container without prompting the user to select it using Powerbox and saving a security-scoped bookmark (see App Sandbox Container Directory).  From what I've gathered about App reviews lately, you won't even be able to specify a default in the open dialog if you elect to have the user choose the directory.
As for the second question, as I understand it any verification of code signatures is left to the developer.  So while MAS apps have a <code>_CodeSignature</code> folder containing a plist with all the hashes of the resource, in my experiments changing them had no effect on app launch.