IEM, 3.5 and 6.35 jacks - Only get left ear when plugged fully in

Question: I am using a vocal and guitar processor in one. The headphone out is not loud enough so I am using a small amplifier (for 4 sets of headphones).
Problem is, I only get a left ear unless I remove the 3.5mm jack slightly, and then I get stereo.
This is the set-up order:

FX............................Processor: 3.5mm stereo out
Cable 1....................3.5mm to 3.5mm cable
Jack.........................6.35mm to 3.5mm
Headphone Amp......6.35mm stereo in
Headphone Amp......6.35mm stereo out
Jack..........................6.35mm to 3.5mm
Cable 2.....................3.5mm extension lead (male A -> female B)
Headphones.............3.5mm

What surprises me, is that I get stereo when I slightly remove the 3.5mm (cable 1) from the jack into the amp AND... I also get stereo when I do the same with my 3.5mm headphone jack going into the extension (cable 2).
If I plug Cable 2 directly into the FX there are no problems (but not loud enough). I also get ground buzz sometimes but I doubt this is related.
I then went and got another small amp, with a 3.5mm headphone socket, but this time with a TRS and XLR input. No problems, but sadly not loud enough. So I chained this up to the original (new one, then old one) and the same problem stands, but with distortion (which I can live with when I need volume)
My guess is I need a 6.35mm to 6.35mm stereo between the two amps because of a miss-match in the converting jacks but why does removing my headphones right at the end of the chain still give me stereo?
I need to understand the issue as the last thing I want is a dodgy monitor for performing
Answer: There are already some good answers, but I just had a couple things to add. In general it's best to minimize the length of cable and number of adapters you use in your signal chain (I think you called the adapters "jacks"). This reduces the number of possible failure points. For example, do you really need the headphone extension cable? And getting the right cables as you suggested will mean you won't need adapters at all. This can potentially improve your sound quality and it will definitely remove extra sources of possible failure.
I agree with the recommendations to check your adapters and cables and make sure they are all stereo on both ends. Obviously if you've got a mono cable or adapter somewhere in your chain, you are going to lose half of your signal.
Also, when you remove the cable halfway and it still works, my guess would be that you are hearing a mono signal, but it's going to both the left and right headphones so it seems like it's working. If the jack isn't fully inserted you probably aren't getting true stereo.
The best way to fix these problems is check each cable and adapter by itself and isolate which ones might either be broken or just mono. Confirm your headphones are working in stereo with some other device, then confirm the FX is outputting stereo with the headphones, then once you know those two are working properly you can use them to test each part of the chain one cable or adapter at a time. That's usually the best way to troubleshoot anything in your signal chain by removing the variables.
Answer: Take a close look at both Cable 1 and the adapter (jack) connecting Cable 1 to the amp.  Are you sure that these are both stereo devices?
A stereo plug will have three metal sections (tip, ring, and sleeve).  A mono plug will only have two (tip and sleeve).
If you are hearing only one side, and then get both sides when you pull it part way out, that is a sign that something in your chain is mono and not stereo.  The reason this can happen is that when a stereo plug is inserted into a mono jack, normally you will only hear one side, because the tip of the stereo plug is connected to the tip of the mono jack, and the ring of the stereo plug is not connected to anything.  When you pull the plug part way out, the tip of the mono jack touches both the tip and ring of the stereo plug.  You hear both sides, but it is actually still mono sound, because both sides are playing the one mono channel.
If you are sure that everything is a stereo device all the way through your chain, then you have a faulty device.  Use the process of elimination to find it by removing the elements, one at a time, until the problem goes away.
Answer: A mono jack in a stereo socket or a stereo jack in a mono socket will shorten out the right channel.
Maybe your adapters are not what you think they are for.
Answer: My instinct is to blames those adapters (or 'jacks' as you call them, but I've always used 'jack' to refer to the the input assembly on the device or the lead assembly on the cable). Adapters, being conceptually so simple, are easy to botch in production. It's just some bent lengths of wire that fit (or don't!) into little slots in the molded plastic. From your description, my guess is that both adapters have similar problems. If it has a screw and can be disassembled, it may be very easy to repair them; or it may be impossible if it's some kind of solid-molded construction.
If you can disassemble it, you'll see the two spring leads that connect to the tip of the cable (left channel) and that little space between the two tiny plastic rings just past the indentation (right channel). Since it's the right channel that cuts out, I recommend you examine this second lead closely; since you can connect with it by slight removing the cable, I'd suspect that this spring is too long, possibly from having slipped from its correct place in the plastic housing. It could also be corrosion at any of these contact-points (clean with alcohol if you see any corrosion).
Your proposal to use 1/4"-connecting cables and remove the need for adapters also seems like a good strategy.
Comment: It was an adapter causing the issue. Ordered some more as they are not expensive. And replaced the need for 2 of them in the link mentioned above with a 1/4" stereo cable.


Proper way to handle toast notifications in Ionic app

Question: I have an Ionic 2 app that has toast notifications in various places.
A good example of this is where the user updates their profile on the app and I run some validation checks.  If the user fails some validation I might call the following:
      let toast = this.toastCtrl.create({
        message: 'Sorry, your password must be at least 6 characters long.  Your account was not updated.',
        duration: 3000,
        position: 'top'
      });
      toast.present();

No problems there.  It just displays for 3 seconds then disappears.
The problem comes when multiple are shown at once.  For example, the user may type a 6 character password, but it doesn't validate for another reason, so another toast notification is raised:
    let toast = this.toastCtrl.create({
      message: 'Sorry, your passwords do not match.  Your account was not updated.',
      duration: 3000,
      position: 'top'
    });
    toast.present();

This causes 2 toasts to overlap and one will permanently remain.  The two overlapping isn't an issue, but the fact one remains indefinitely is a huge issue.
I imagine this is because I'm effectively overwriting the toast variable every time.
What is the best way to approach this?  I don't want to have toast1, toast2, etc, as that won't fix the problem because the user might launch the same toast notification twice (<6 character password, submit twice).
Comment: Just lots of `let toast = this.toastCtrl.create({ ... }); toast.present();`.  I've only tested on the lab (`ionic serve --lab`), but assume it's the same on device.
Comment: How do you create your toast? I created multiple toast at a same time and all work as expect.
Comment: Please check [this answer](https://stackoverflow.com/questions/45074161/prevent-duplicate-toast-messages-in-ionic2/45074283#45074283). By using the same property for all the toast, you could show only one toast each time (since it doesn't make sense to overlap toasts if they're validation messages).
Comment: @sebaferreras: Do you know how to reproduce this problem? I tried many ways but can not face it. LOL
Answer: I would suggest handling all Toast interactions in a service. And inject it in whatever component/page/service you need it in. In the service you keep a reference to a single Toast and call dismiss() on it before presenting it.
This solution will keep you from having more than one Toast presented at a time.
ToastService:
import { Injectable } from '@angular/core';
import { ToastController, Toast } from 'ionic-angular';

@Injectable()
export class ToastService{
    toast: Toast = null;

    constructor(private toastCtrl: ToastController){ }

    presentToast(text:string):void{
        let toastData = {
            message: text,
            duration: 3000,
            position: 'top'
        }

        this.showToast(toastData);
    }

    presentClosableToast(text:string):void{
        let toastData = {
            message: text,
            showCloseButton: true,
            closeButtonText: 'X',
            position: 'top'
        };

        this.showToast(toastData);
    }

    private showToast(data:any):void{
        this.toast ? this.toast.dismiss() : false;
        this.toast = this.toastCtrl.create(data);
        this.toast.present();
    }
}

Comment: I must say that I'm not sure if this is a good approach, since providers are not mean to be used to interact to the end user (or the UI) directly. A better way to do this would be to create a `BaseComponent` with that code, and extend your page with it.  Or if you use toasts only in a single page, add this code to that page instead.
Comment: I agree @sebaferreras. Is there a difference between extending a `class` and a `component` in this case? I made an edit yesterday (see edit history) where I extend a `class`. I used a `class` since only functionality and no template is needed.
Comment: The main difference would be that _components_ also have metadata (decorators), and even tough metadata it's not important in this example, it may cause some errors when building for production (it only happens in some version of Ionic) , so you can add an _empty decorator_ to avoid that. Please take a look at [this SO answer](https://stackoverflow.com/questions/43029212/typescript-and-multiple-classes/43030491#43030491) where I create a `BaseComponent` to handle showing/creating toasts :)
Answer: you can do it like this.
when you need to show a toast . call as a function .
inside the function. you have a timer for 3 seconds.
then if the toast function is recall again . you need to clear the timer then
reset it again. like this code.
//delacare timer
_timer:any = null;

showToast(){
    let toast:any;
    //check if timer is running ,if its clear out and dismiss existing toast
    if (this._timer) {
         toast.dismiss()
         clearTimeout(this._timer)
    };

    this._timer = setTimeout(() => {
       toast = this.toastCtrl.create({
        message: 'Sorry, your passwords do not match.  Your account was not updated.',
       position: 'top'
    });
    toast.present();
    },3000)

}

UPDATE
or you can also put a string argument like this . to avoid many toast code.
showToast(string_message){
        let toast:any;
        //check if timer is running it its . clear out
        if (this._timer) {
             toast.dismiss()
             clearTimeout(this._timer)
        };

        this._timer = setTimeout(() => {
           toast = this.toastCtrl.create({
            message: string_message,
           position: 'top'
        });
        toast.present();
        },3000)

    }


Hw can I get last inserted id in cakephp 3.x?

Question: I am trying to get last inserted id in cake php 3.
if($this->request->is('post')){
<code>       $this->loadModel('MyPlaylists');

                    $playlistData = [];
                    $playlistData["user_id"] = $_POST['user_id'];
                    $playlistData["play_list_name"] =  $_POST['play_list_name'];
                    $playlistData["section"] = $_POST['section'];
                    $playlistData["created"] = date('Y-m-d H:i:s', strtotime('now'));
                    $playlistData["status"] = 'active';
                    $playlist_en = $this->MyPlaylists->newEntity();
                    $this->MyPlaylists->patchEntity($playlist_en, $playlistData);
                    $this->MyPlaylists->save($playlist_en);
                    $id=$this->MyPlaylists->id;
                }
</code>
I have also tried:
<code>$id=$this->MyPlaylists->lastInsertedId;
</code>
But it is giving error as below screenshot:
Comment: yes, it is not due to Auto-Tables
Comment: Offtopic: never fiddle with superglobals directly in CakePHP, instead use the abstratcted wrappers to access the data, in this case via the request objects `data()` or `getData()` method: https://book.cakephp.org/3.0/en/controllers/request-response.html#request-body-data
Comment: can you give example?
Answer: Your code needs some fine tuning.
<code>$playlist_en    =    $this->MyPlaylists->newEntity();
$playlist_en    =    $this->MyPlaylists->patchEntity($playlist_en, $playlistData);
$isValid        =    $this->MyPlaylists->save($playlist_en);
if ($isValid) {
    $id    =    $playlist_en->id;
    debug($id); // Check your last insert id
} else {
    pr($playlist_en->errors()); // Check errors
}
</code>
Answer: Make a query selecting the first element of the query ordered in DESC. way
<code>$newPlaylist = $this->Playlists->find('all',['order' => ['Playlists.id' => 'DESC']])->select(['id']);
</code>


Length of locally free resolution complex

Question: Let $X$ be a projective scheme and let $C^{\bullet} = \left\{\dots\rightarrow C^i\rightarrow C^{i+1}\rightarrow\dots\right\}$ be a perfect complex in $D^b(X)$. As $X$ carries an ample family of line bundles it has the resolution property, i.e. every perfect complex is strictly perfect. So suppose $C^{\bullet}$ is quasi-isomorphic to a bounded complex $E^{\bullet}$ consisting of locally free sheaves.
If we know the projective dimensions of each of the $C^i$, is it possible to make a statement about the (minimal) length of the locally free resolution $E^{\bullet}$?
For example, if $C^{\bullet} = \left\{C^0\rightarrow C^1\right\}$, $\mathrm{pd}(C^0)=1$ and $\mathrm{pd}(C^1)=2$ I would assume that we can find a 3-term complex $E^{\bullet}$ of locally free sheaves with $E^{\bullet}\simeq C^{\bullet}$ by correctly combining the locally free resolutions of $C^1$ and $C^0$, but I am not sure if this really works.
Answer: Yes, you can do this - take the total complex of the following double complex after chopping off the $C^\bullet$ row at the bottom:
$$\require{AMScd}
\begin{CD}
E^{0,\bullet} @>>> E^{1,\bullet}\\
@VVV @VVV \\
C^0 @>>> C^1
\end{CD}$$
where we define the map $E^{0,\bullet}\to E^{1,\bullet}$ by applying the  lifting property of projective modules for the map $E^{0,0}\to C^1$ to the surjection $E^{1,0}\to C^1$ to get a map $E^{0,1}\to E^{1,1}$ and then inductively define the rest of the maps using the same sort of argument.


How to load hive orc partitioned to Hbase table

Question: I'm completely beginning into hbase data store, we are currently migrating hive external file system with orc file format. Past 2 years data needs to move to hbase tables, i seen few of bulkload approach hcatalog and pig using but not orc file format. Can you please help me out or give me some suggestion on this issue. Here i mentioned hive table schema structure also;
CREATE EXTERNAL TABLE countTbl (
 client_id bigint,
 count1 bigint,
 inserted_at bigint,
count2 bigint,
 date_time bigint,
id_dic STRUCT<id1:array<STRING>,id2:array<BIGINT>>,
 partition_date string
)
partitioned by (primaryid string)
stored as orc
LOCATION 'hdfs://user/hadoop/countTbl';

Answer: hbase support only simple datatype, your hive table field id_dic should be simplified to store into hfile
you can use hive table project to hbase or bulkload into hbase


Handle invalid characters from filename in unix

Question: I need to do some linux command operations on files having "!" like characters in filename. But whenever I am trying to execute the commands, I am getting below error.
[root@ATD-6000 ~]# cat a!aapoorv.txt
-bash: !aapoorv.txt: event not found

I am executing these commands in python using paramiko module. I can't use raw string r'filestringname', as I am reading string name from db itself.
How to escape/handle these king of characters using python/bash.
Comment: @AhsanulHaque: It doesn't .
Comment: `open("a!aapoorv.txt")` should work just fine
Answer: try this:
cat a\!aapoorv.txt

or this
cat 'a!aapoorv.txt'

Note that while cat a\!aapoorv.txt works in all shells that implement that csh-style history expansion, cat 'a!aapoorv.txt' doesn't work in csh/tcsh.

for more information, you can see man bash about the QUOTING.
Here is some of that document:

Quoting  is  used to remove the special meaning of certain characters or words to the shell.
Quoting can be used to disable spe‐cial treatment for special characters, to prevent reserved words from being recognized as such, and to prevent  parameter  expan‐sion.

And here is the output:
[kevin@Arch test]$ ls
a!aapoorv.txt
[kevin@Arch test]$ cat a\!aapoorv.txt
Hello, This is a test
[kevin@Arch test]$ cat 'a!aapoorv.txt'
Hello, This is a test

On Python, you don't need to escape the special character, here is a test:
>>> with open('a!aapoorv.txt') as f:
...     f.read()
...
...
'Hello, This is a test\n'
>>> with open(r'a!aapoorv.txt') as f:
...     f.read()
...
...
'Hello, This is a test\n'
>>>

Comment: The last one (with double quotes) is not going to work (you'd still need to escape the `!` with a backslash). Another option is to disable history expansion with `set +H`.
Comment: do all of them work? i have tested the 3rd one for creating a file and it doesn't work.
Comment: Yes they can all work, let me edit my answer and add some more info and output.
Comment: @gniourf_gniourf I've tried it again, I think you're right. Thanks :)
Comment: @StephaneChazelas I've just add them to my answer. Thanks :)
Answer: use singlequotes ' ':
$ cat 'a!aapoorv.txt'
cat: a!aapoorv.txt: No such file or directory

Answer: For Bash, you need to use the escaping methods (single quotes or backslash) described by the other answers.
In Python, you shouldn't need to use raw strings or any other type of escaping to open a file with special chars.
For example, this works fine:
my_f_contents = open("a!aapoorv.txt").read()


If $\langle X,<\rangle$ is a total order which is c.c.c. in the order topology then it has a dense subset of cardinality $\leq\omega_1$

Question: I have been trying to solve a few questions in Kunen's book (Set Theory An Introduction To Independence Proofs) and I got stuck with the following question :

Let $\langle X,<\rangle$ be a total ordering which is $c.c.c$ in the order topology.
Show that $X$ has a dense subset of cardinality $\le \omega_1$

I would really appreciate any help with this question
Thanks
Comment: Note the asterisk, indicating more than average work or difficulty.
Comment: Actually I have no relevant idea or direction to share, I did try few things (based on the Suslin line section) but all of my work was useless .. I just need some help .. I will edit my post if I will get some progress.
Answer: For any topological space $X$ the cellularity $c(X)$ is the least infinite cardinal $k$ such that any open cellular (discrete) family in $X$ has cardinal $k$ or less. (An open cellular family is a family of pair-wise disjoint open sets). And the density $d(X)$ is the least infinite cardinal $k'$ such that $X$ has a dense subset of cardinal $k'$ or less. (It has been said in jest that "There are no finite cardinals in point-set topology".).
It is an  easy exercise that $c(X)\le d(X).$
Let $(X,<,T)$ be a linear space. That is, $<$ is a linear (total) order on $X,$ and $T$ is the topology induced by $<.$
We prove that $d(X)\le c(X)^+,$ (...$k^+$ is the least infinite cardinal greater than the infinite cardinal $k$...), and conclude that $d(X)=c(X)$ or $d(X)=c(X)^+.$ So if $(X,<,T)$ is a Suslin line then $\omega=c(X)<d(X)\le c(X)^+=\omega_1,$ so $d(X)=\omega_1.$
Lemma. For $\emptyset\ne V\in T$ there is a unique open cellular family $V^*\subset T$ such that (i) $\cup V^*=V,$  and (ii) each $ U\in V^*$ is a non-empty $<$-convex open set. Proof: For $x,y \in V$ let $x\sim y$ iff the open interval between $x$ and  $y$ is a subset of $V.$ Let $V^*$ be the set of $\sim$-equivalence classes. I will leave it to the reader to confirm that $\sim$ is an equivalence relation on $V,$ and that the $\sim$-equivalence classes are open and $<$-convex, and that $V^*$ is unique.
By def'n of $c(X),$ if $\emptyset\ne V\in T$ then $|V^*|\le c(X). $
Now let $c(X)=k$ and assume $d(X)>k$ (because if $d(X)=c(X)$ then we're done).
We show that $d(X)=k^+.$ We construct a collection $F=\{F_a:a\in k^+\}$ of open cellular families in $X ,$ none of them containing $\emptyset,$ and construct a Choice Function  $D:\cup F\to X$ such that $\{D(f):f\in \cup F\}$ is dense in $X.$
Step 1. Pesky isolated points. Let $X^i=\{x\in X: \{x\} \in T\}.$ Since $(X^i)^*=\{\{x\}:x\in X^i\}$ we have $|X^i|=|(X^i)^*|\le c(X)<d(X).$ Let $F_0=(X^i)^*$ and let $D(\{x\})=x$ for $x\in X^i.$
Step 2. Since $(X^i)^*$ is an open cellular family we have $|X^i|=|(X^i)^*|\le c(X)<d(X)$ so $X\ne \overline {X^i}.$
Let $F_1=(X\setminus \overline {X^i})^*.$
Step 3. Inductive construct (i). For $0\ne a\in k^+:$ Assume $F_a$ is a non-empty family of pair-wise disjoint non-empty open convex sets. That is, $\emptyset \ne F_a=(\cup F_a)^*. $ And that each $f\in F_a$ is disjoint from $X^i.$  For $f\in F_a$ let $D(f)\in f\setminus \{\min f, \max f\}$ regardless of whether $\min f$ or $\max f$ exist. Now for brevity let $f^-=\{x\in f:x<D(f)\}$ and $f^+=\{x\in f: x>D(f)\}$.
And define $F_{a+1}=\cup \{\{f^-,f^+\}: f\in F_a\}.$
Step 4. Inductive construct (ii). For $0\ne a=\cup a \in k^+:$ Let $f\in F_a$ iff $f$ is the non-empty interior of $\cap \{H(b):0\ne b\in a\}$ for some $H:a\setminus \{0\}\to \cup_{0\ne b\in a}F_b$ such that (1) $H(b)\in F_b$ and (2) if $0\ne b\in c \in a$ then $H(b)\supset H(c).$
At this point I will leave it to you to see if you can finish.
You must show that $F_a$ is not empty in Step 4, using the fact rhat $\{D(g):g \in \cup_{b\in a}F_b\} $ is not dense in $X$ because its cardinal is at most $c(X)$, and $c(X)<d(X)$.
Then to see that Step 4 cannot apply when $a=k^+$: Suppose instead that dom $(H)=k^+\setminus \{0\}.$ With $H(b)^-$ and $H(b)^+$ defined as $f^-$ and $f^+$ are defined in (3), let $\phi(b)=H(b)^+$ if $H(b+1)=H(b)^-$ and let $\phi(b)=H(b)^-$ if $H(b+1)=H(b)^+.$ Then $\{\phi (b):0\ne b\in k^+\}$ is an open cellular family of cardinal $k^+>c(X),$ which is absurd. We use this now  to show that no non-empty convex open set can be disjoint from the image of the Choice Function $D$.
Remarks. In Step 3, when $0\ne a\in k^+$ and $f\in F_a$ then the only members of $F_{a+1}$ that are $not$ disjoint from $f$ are $f^-$ and $f^+$.......For $f,g \in \cup F=\cup_{a\in k^+}F_a$ let $f<_W g \iff f\supsetneqq g. $ Then $(\cup F, <_W)$ is a set-theoretic $k^+$-Suslin tree.
Comment: Arthur Jensen showed that if $V=L$ then there exists an $\omega_1$-Suslin tree and hence a Suslin line. By methods of iterated forcing, it is consistent with ZFC that there is no Suslin tree and hence no Suslin line.
Comment: Jensen's first name is Ronald.
Comment: @AndreasBlass .Right. There's an Arthur J. somewhere in my memory too but I dk where.


Using addClass in jQuery UI Menu

Question: I'm using jQuery UI Menu for navigation purpose. I want that when one item is clicked it's background color should change (to show active state) and when user clicks on other item then the new item's color should change and the previous one's color should revert back to original.
I used addClass for that but somehow it's not working, let me know where I'm doing wrong.
Fiddle link
HTML:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

CSS:
.selected{
    color:red;
}

jQuery
  $(function() {
    $( "#menu" ).menu();
  });
  $(function () {
  $(".nav a").click(function () {
    $(this).parent().addClass('selected'). //

      siblings().removeClass('selected');
  });
  });

Comment: You must use `background-color` instead of `color`.
Comment: Yes, got it, stupid mistake.
Answer: Apply style on the anchor instead of li. since anchor's inherited red color gets overridden by .ui-widget-content a
.selected a {
    color:red;
}

Demo
With background color:-
Demo
Comment: Oops, just had to use `background-color` instead of `color`.
Comment: If I do ".selected a {color:inherited;}" then it will take priority over ".ui-widget-content a" right ??
Comment: @PSL yes that ".selected {color:red;}" is already there.. thanks for confirming. :)
Comment: @ChankeyPathak suit yourself. This has both the options working.. :)
Comment: @SarveshKumarSingh not really, it is `inherit`. But then you will have to have both the style rules like http://jsfiddle.net/BNWBX/.
Answer: $(this).parent().siblings().removeClass('selected');
$(this).parent().addClass('selected');

.selected{
    color:red;
}

.selected a {
    color:inherit;
}

Answer: Please have a look at http://jsfiddle.net/PaHXs/8/
May i know is this your requirement or not.
I did change in
.selected{
    background-color:red;
}

Using addClass in jQuery UI Menu


Including missing words when applying Naive Bayes in document classification

Question: When applying a naive Bayes classifier to document classification, the classifier (at least in the applications I've seen) always iterates only over the words actually present in the document.
That is, when computing (say)
$P(SPAM|d) \propto P(d|SPAM) * P(SPAM) = [P(w_1 | SPAM)  \cdots P(w_n | SPAM)] P(SPAM)$
the $w_i$ only include words actually present in the document $d$. So $P(w_1|SPAM)$ is always $P(w_1 \text{ present}|SPAM)$, and never $P(w_1 \text{ not present} | SPAM).$
Why is this? I can't think of any a priori reason why including the missing features would hurt the classifier's performance.
Answer: A primary concern is efficiency. If you include all missing words, you have to incorporate every word in the whole corpus.
Beside, adding this words may improve the performance in rare cases, put I predict that in general it will decrease performance on unseen data.
In general, including a missing word will improve the performance if it has not been used in the text on purpose or because the spammer will never consider it.
Three examples

Let's say the word eudaimonia has appeared in the corpus several times because the mail inbox does belong to a man who lives in a barrel. No mail containing this word was spam and this a word a spammer will certainly not consider to use to make you open the mail.
A word which may have not used on purpose is viagra, just because everyone knows that emails which such words are already filtered using blacklists.
The majority of the missing words are, however, a word the spammer may be using anytime (just because it is belonging to the base vocabulary), even it does not appear in the training data set (if it appears, it should be rendered useless by the algorithm just because it is a common word).

So, in summary, you may improve the performance in the validation set, but will hurt the future performance on unseen data due to the mass of common words. You may overcome this problem by throwing a ton of data on the classifer, but at this point it is just getting impractical.


Line bundle corresponding to the Segre embedding

Question: I am trying to understand the theorem that characterizes morphisms to projective space as equivalent to the data of a line bundle together with global sections generating it.
I tried to find the corresponding line bundle associated with the Serge embedding, say from $\mathbb{P}^{1} \times \mathbb{P}^{1}$ to $\mathbb{P}^3$. But working directly with the definitions Hartshorne gives looks impractical. I don't know how to compute explicitly the global sections of the pullback of the twisting sheaf on $\mathbb{P}^3$. Is there any technique to compute the pullback of a line bundle, or more generally of any quasi coherent module in practice?
Answer: The global sections of the twisting sheaf on $\mathbb{P}^3$ are just the coordinate functions on $\mathbb{P}^3$.  The ambiguity in isomorphism of a fiber of the line bundle with $\mathbb{C}$ is what makes it a projective coordinate rather than an affine coordinate.  So, if you know your embedding in terms of coordinates, you know the line bundle, or at least you know what its sections look like.
The Segre embedding is given by taking a point $([x_0,x_1],[y_0,y_1])$ to $[x_0y_0,x_0y_1,x_1y_0,x_1y_1]$.  Therefore, the $x_0y_0$ is the restriction of a global section of the twisting sheaf to $\mathbb{P}^1 \times \mathbb{P}^1$ under the serge embedding, which, in terms of line bundles is a global section of $\mathcal{O}_{\mathbb{P}^1}(1) \otimes \mathcal{O}_{\mathbb{P}^1}(1)$  ( technically, the pullback of $\mathcal{O}_{\mathbb{P}^1}(1)$ under the two projections.  )
Also, technically I've only described this in terms of global sections, but the whole description is natural over any open, so shows an isomorphism of sheaves (and therefore line bundles).  I tried to describe it as one would think about it rather than all the fine details.  Hope this helps.


Allow users to publish content to their profiles

Question: I want my users to be able to upload content to their own profiles. then when people view their profile they see a list of links which lead to what the user has uploaded.
Is this possible?
Answer: You can create a block view (Optional  with a filter to show the type of content you want to show) Add the Content title fields and any other field you want to add.
Then You have to set a Contextual Filter of the type Content Author.
Select the "provide default" option and from the type dropdown select user id from url.
Place this block in the user profile page.


Julia/Dates : convert a timespan from "days" to "year" or "Float64"

Question: I would like to convert a timespan from "days" to "year" or "Float64"
let be at timespan t:
t = Date("2000-02-04") - Date("1996-06-04")

However each following lines give me an error
t/365
Float64(t)
parse(Float64,t)
convert(Dates.Year, t)

Answer: You can get the value stored in t and divide it by 365
julia> Dates.value(t)/365
3.671232876712329

Note however that this assumes that each year is 365 days which is not true. For some scenarios a more elegant solution would be to count the years assuming that the date starts at some point, have a look at the example below:
julia> d0 = Date("2000-01-01")
2000-01-01

julia> d1 = d0 + t
2003-09-02

julia> year(d1)-year(d0), month(d1)-month(d0), day(d1) - day(d0)
(3, 8, 1)


Fingerstyle guitar - thumb fretting

Question: When piece requires fretting 5 independent notes, some chords are really hard to fret. The common situation is when you need to reach octave from bass note on G string and have still three fingers free.
Example: 10x97810
It sometimes causes pain when I try to twist thumb too much. I know everything takes time, but with correct technique it should be accessible. What approaches could help here?
One thing I noticed is that fretting thumb first and pulling string a bit towards edge makes this chord a bit easier. I'm not sure if this should be part of my technique.
Comment: I found this impossible to play anyway. 10 is bottom (fat) string, x is 5th (A) ? It's unusual to use a thumb to fret notes higher than the rest of those in a chord. Or am I missing something ? (Like a strange shaped hand).
Answer: Here are a couple of fingerings for that chord that don't require using your L.H. thumb.  The first uses a first finger barre at fret 10; the second uses an open B. It would be easiest if you could get a voicing with the open D as the bass note, but I'm not sure this is possible - if I find one I'll post it…!

NB: The first shape is "movable", as it doesn't have any open strings, so would be useful whenever you need this particular Major-2nd-inversion voicing (shape), whatever the key.

Fingerstyle guitar - thumb fretting


Dynamic loading of sprites from JSON file does not work

Question:
The Unity project I am building is targeting iOS, Android and Windows X64.
Problem
In one of my scenes, I use a JSON file to load some sprites located in the Resources folder dynamically during runtime. The problem I currently have is this: When I run the game in the Unity Editor, it behaves as expected (the sprites are dynamically loaded and displayed in the scene). But when I run it on any of the three platforms (on real hardware) the sprites are not loaded/displayed in the scene. Static sprites are loaded though.
Setup
The scene is kind of a level selection screen. For every level, a sprite is displayed. The sprite and the number of sprites displayed is based on a JSON file that is read when the scene starts. Here is a screenshot to give you a better impression:

In one of the game objects's Startcallback I run the code to read the JSON data:
var sceneSelectionInfoList = JsonHelper.GetSceneSelectionInfoForLanguage(GameLanguage.German);

The JSONHelper class so far (uses JSON.NET for Unity asset from the Asset Store):
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public static class JsonHelper
{
    private const string SceneDataIndexFilename = "Assets/Resources/SceneData/SceneDataIndex.json";

    // Start is called before the first frame update
    public static List<SceneSelectionInfo> GetSceneSelectionInfoForLanguage(GameLanguage language)
    {
        var sceneSelectionInfoList = new List<SceneSelectionInfo>();

        // Open scene selection index
        var sceneDataIndexEntries = GetSceneDataIndexEntries(SceneDataIndexFilename);

        foreach (var sceneDataIndexEntry in sceneDataIndexEntries)
        {
            Logger.LogInfo(sceneDataIndexEntry.Filename);
            using (var streamReader = new StreamReader(sceneDataIndexEntry.Filename))
            {
                var jsonData = streamReader.ReadToEnd();
                var jObject = JObject.Parse(jsonData);
                var id = jObject.SelectToken("id").ToString();
                var basePath = jObject.SelectToken("basePath").ToString();
                var sceneSelectionImage = basePath + jObject.SelectToken("dragAndDrop.sceneSelectionImage");
                string title = null;

                switch (language)
                {
                    case GameLanguage.English:
                        title = jObject.SelectToken("titleEN").ToString();
                        break;
                    case GameLanguage.French:
                        title = jObject.SelectToken("titleFR").ToString();
                        break;
                    case GameLanguage.SwissGerman:
                        title = jObject.SelectToken("titleSG").ToString();
                        break;
                    case GameLanguage.Spanish:
                        title = jObject.SelectToken("titleES").ToString();
                        break;
                    case GameLanguage.German:
                        title = jObject.SelectToken("titleDE").ToString();
                        break;
                    case GameLanguage.Italian:
                        title = jObject.SelectToken("titleIT").ToString();
                        break;
                }

                var sceneSelectionInfo = new SceneSelectionInfo();
                sceneSelectionInfo.SceneId = id;
                sceneSelectionInfo.SceneSelectionImage = sceneSelectionImage;
                sceneSelectionInfo.Title = title;
                sceneSelectionInfoList.Add(sceneSelectionInfo);
            }
        }

        return sceneSelectionInfoList;
    }

    private static List<SceneDataIndexEntry> GetSceneDataIndexEntries(string sceneDataIndexFilename)
    {
        using (var reader = new StreamReader(sceneDataIndexFilename))
        {
            var jsonData = reader.ReadToEnd();
            Logger.LogInfo(jsonData);
            return JsonConvert.DeserializeObject<List<SceneDataIndexEntry>>(jsonData);
        }
    }
}

Just for completeness: The SceneSelectionInfo class is just a data container (DTO) holding some values to pass around:
public class SceneSelectionInfo
{
    public string SceneId;
    public string SceneSelectionImage;
    public string Title;
}

Here are the paths to the JSON files and sprites, relative to the Unity project folder:
Sprite Path:
Assets/Resources/SceneData/AfternoonAtTheBeach/DragAndDrop/SceneSelection.png
JSON File Path:
Assets/Resources/SceneData/AfternoonAtTheBeach/SceneData.json
Here is the snipped from the JSON file (basePath and sceneSelectionImage together build up the path to the sprite to be loaded):
{
  "id": "AfternoonAtTheBeach",
  "basePath": "SceneData/AfternoonAtTheBeach/",
  "titleEN": "Afternoon at the beach",
  "titleFR": "Après-midi sur la plage",
  "titleSG": "Namitag am Strand",
  "titleES": "Tarde en la playa",
  "titleDE": "Nachmittag am Strand",
  "titleIT": "Pomeriggio in spiaggia",
  "dragAndDrop": {
    "sceneSelectionImage": "DragAndDrop/SceneSelection",
    "levels": [
      {
        "backgroundImage": "DragAndDrop/Graphics/Level1/Background",
        "items": [
          {
            "image": "DragAndDrop/Graphics/Level1/Ball",
            "dropPosX": -623,

The code to load the sprites (after having read the path from JSON file):
  var sprite = Resources.Load<Sprite>(sceneSelectionInfo.SceneSelectionImage);
  swiperItem.GetComponent<SpriteRenderer>().sprite = sprite;

What I have checked so far

I refer to sprites by using relative paths, starting from the Assets/Resources directory, no file extensions (see sprite path example above).
I have disabled Library Caching in Unity Cloud Build to avoid issues with old build artifacts (so every time I build, I do a proper, clean build)
I can locally build all three platforms (Unity reports it as "Build successful")
I am using LoadSceneMode.Single (default)
I am using the same Unity version locally and in Unity Cloud Build: 2018.3.0f2

Thanks for any hints!
Comment: This is a complex problem so here's some stuff you can update your question with: What are the full paths to your JSON file as well as your sprite (in relation to the unity project)?  What's your code for loading the JSON look like? Do you have any complex async operations or coroutines running during the scene transition? How about any statics that could end up in a bad state?  Anything scene A depends on during initialization (`Awake()` and `Start()` methods)? Are you using `LoadSceneMode.Single` or `LoadSceneMode.Additive`? Have you tried switching to `SceneManager.LoadSceneAsync()`?
Comment: @Foggzie Thanks for your feedback. I have added more details to the question. I hope this makes it more clear. Regarding coroutines: Yes, I have some (but none of them run async). See example code.
Comment: Have you considered that / is not always the path delimiter and should be the one appropriate?
Comment: @BugFinder Hm, no I didn't. Are there any known problems with forward slashes? Thx.
Comment: Windows uses backslashes - you can always pick up the relevant one with Path.PathSeparator
Answer: The two major issues here are 1) the way your JSON file is being loaded and 2) the way your manager object destroys itself.

For the JSON file:
You're using StreamReader which is a C# tool for reading from a file system. This isn't exactly how Unity's "Resources" system works. Since it exists under the "Assets" directory, your Editor can find it just fine; that's where it exists in the file system it's running under. When you make a device build, anything under a "Resources" directory is packaged into the build and must be accessed via the Resources API.
You have two options here:  You can replace your usage of StreamReader with a Resources.Load<TextAsset> call and make sure you use "SceneData/SceneDataIndex" (note: no file extension) instead of the version with "Assets/Resources".  You're other option is to place the JSON asset in a folded named "Assets/StreamingAssets" and then use Application.streamingAssetsPath to load it with StreamReader.  The streaming assets path with allow it to be loaded with regular C# file loading conventions as it'll be placed at a readable file system path.
Some notes: Resources API calls MUST use forward slashes (/) no matter the platform.  When using file system-based loaders like StreamReader, you should use Path.Combine or Path.PathSeparator to ensure you have the correct slashes.

Now for the second load of Scene A.  It's difficult to be certain what your issue is here without knowing the exact layout of your game object hierarchy but my assumption is that your GameManager script is sitting on an important GameObject and you're destroying it with:
else if (Instance != this)
{
    Destroy(gameObject);
}

This will destroy the game object, all scripts on it, and all of it's children and all scripts on them.  If you change that to Destroy(this), it'll only remove the script from the object and leave your game object hierarchy intact.
Comment: Thank you very much for your detailed response. In fact, your tip regarding JSON and Resources.Load solved my problem with the missing sprites. So that is good. Awesome! I am currently investigating the second issue. Keep you posted.
Comment: Is it ok for you, if I move the sexond problem (scene A) not loaded into a separate SO question? After that, you then just  move your answer part over to the new one. Finally, I can mark your answer here as correct.
Comment: Ok, I have split the questions apart. Here's the link to the other SO question. Just move your part of the post over there. Also added some more details to the problem description. https://stackoverflow.com/questions/54775006/scene-not-properly-loaded-when-switching-back-and-forth  Thanks alot!


How do I factor "Higher order" polynomials?

Question: I missed a day of math class and didn't have time today to go over this with my teacher.
In math we covered factoring and solving higher order polynomials yesterday, but I wasn't there.
I've figured out difference and sum of cubes, which are pretty easy. I've also figured out difference of squares such as $4x^4-16$, but I'm having trouble with some other polynomiAls.
Take for example, $x^4-9x^2+14$. I recognize that the first part is difference of squares, so I can get $(2x^2-3x)(2x^2+3x)+14$, but then what do I do with the 14?
For another example, take $6x^4+24x^2-72$. I can take out the common factor of $6$, and get $x^4+4x^2-12$, but then what do I do from here? I see a sum of squares, but can that be factored? Is that the next reasonable step or do I do something different?
On the same page is also $m^4-8m^2+7$, and I'm not even sure where to start in this one. There's no common factor, so I can't do that, and it's not sum or difference of squares or cubes, so what do I do?
Comment: Let $u=m^2$ and use quadratic formula or factor if you can (hint: you can).
Comment: @ZacharySelk I'm not quite sure what you mean, care to expand a little bit?
Comment: Can you factor $u^2-8u+7$ ?
Comment: The general method is to find roots through guess and check (plug into the function, check it comes out to zero) then use polynomial division to pull the linear factor out of the polynomial, and get a new smaller polynomial to factor. Of course, as you've shown above, there is better methods for some polynomials.
Comment: @ZacharySelk oh, thanks, that particular equation is meant to be facotring, not solving, but I'm sure that will come in handy at some time
Comment: @Kaynex helps to mention the rational roots theorem, or else your idea of factoring is hopeless.
Comment: @Kaynex we have't learned polynomial division yet, so I doubt that's the method my teacher is wanting us to use.
Comment: I know it's about factoring. I'm telling you how to factor it. Can you factor $u^2-8u+7$? If you can, just let $u=m^2$.
Comment: @Travis Usually, the general goal is to complete the square.
Comment: @ZacharySelk, yeah, I realized that a couple seconds after replying, just didn't think first.
Comment: @SimplyBeautifulArt, The specific questions I have are from the section of the homework asking me to factor them.
Comment: Completing the square will let you find roots, which allows you to factor.
Answer: If all the terms have even powers, you have a polynomial of half the degree in the square of the variable.  $5x^4+24x^2-72=6((x^2)^2+4(x^2)-12)$, which is a quadratic that you should know how to factor.  It might be easier to see if you define $y=x^2$ and write the polynomial as $6(y^2+4y-12)$.  Once you have factored that, plug the $x^2$s back in and you will have two quadratic factors that you can factor.
Generally and here it is not useful to factor part of an expression.  In your first example, you can write it as $(x^2+3x)(x^2-3x)+14$ (you have extra factors of $2$) but you are right that you don't know what to do with the $14$.  You could complete the square to get $x^4-9x^2+14=(x^2-\frac 92)^2-\frac {25}4$ and then use the difference of squares.
Answer: In general, multiplication is easy, but undoing it (factoring) is hard, both for numbers and for polynomials.
In the particular case of the polynomials you're looking at, where all the exponents are even, you can make the substitution $u = x^2$.   So $x^4 - 9x^2 + 14$ becomes $u^2 - 9u + 14$.  You can factor this as $(u-2)(u-7)$, either by "inspection" (that is, looking at it until you recognize the answer) or by using the quadratic formula to find that this has solutions $u = (9 \pm \sqrt{25})/2 = (9 \pm 5)/2 = 2, 7$.  Then you can remember that $u = x^2$ to get $x^4 - 9x^2 + 14 = (x^2-2)(x^2-7)$.  This same idea will work for the other polynomials you're looking at.
Noticing that you have a sum or difference of squares or cubes, when you're just looking at part of the polynomial, is a red herring in this case.  Say you have the number 9900.  You notice that it's $100^2-10^2$ and so you can factor it as $(100-10)(100+10) = 90 \times 110$.  Does this tell you anything about the factorization of 9901?  (No.). Polynomials work the same way.


How to create alter script from two mysqldump files

Question: I'm trying to figure out how to implement migration between two databases. My plan is

Create mysqldump --no-data of source DB
Create mysqldump --no-data of target DB
Create alterscript based on 2 created mysqldump files
Run alter script on target DB to migrate new changes

However I haven't found a way to compare 2 mysqldumps and create alter script from that. Is there any tools for that?
-kari
Answer: Looks like this tool does what I need. http://search.cpan.org/dist/MySQL-Diff/bin/mysqldiff
I can compare Databases and mysqldumps and it creates alter script from differences.
Example:
<code>mysqldump -uroot --no-data db1 > db1.sql
mysqldump -uroot --no-data db2 > db2.sql
mysqldiff --user=root db1.sql db2.sql
</code>
Comment: is there any other implementation of this tool.. Like in Java or in Go ?


MySQL return true/false if col value != specified value

Question: How can I write a MySQL query that returns true/false (1/0 actually)  based upon the value of a column.
In my instance I want to return  "hasDate" for a date time col, let's call it myDateTime
if myDateTime has a value of 000-00-00 00:00:00  I want to return hasDate of 0 (false)
If myDateTime has any other value I want to return hasDate of 1 (true)
Thanks for your assistance.
Comment: NULL is a bit of a special case since it's equal to nothing (including NULL), so you need to check for NULL using `IF(myDateTime IS NULL,0,1)`, otherwise the same as usual.
Comment: Just to point out the obvious, but "does not exist" is what NULL is for.
Comment: Worded differently than Joachim, this is a case where `myDateTime` should be nullable. It's less work and more reasonable to query and determine if a column is NULL instead of a specific (bogus) zero-ought value.
Comment: OK, so the best bet would be to change to having a null value instead of the bogus 0000-00-00 00:00:00 value and then to check if Null.  Would the resulting query then be something like:  SELECT col1, col2, col3, IF(myDateTime = NULL,0,1)  WHERE id = 1234 FROM myTable
Answer: Use a IF statement
SELECT IF(myDateTime = '0000-00-00 00:00:00',0,1) AS hasDate FROM myTable

But the best idea would be to change your data structure to avoid doing that.
Comment: If the table has 10000 rows, this will return 10000 times '0', right?
Comment: Thanks, this should work until I can get the data structure changed.  Unfortunately I don't have the power to do that right now.
Comment: I still don't know how you can test for `0000-00-00 00:00:00` considering MySQL's accepted range is `1000-01-01 00:00:00` through `9999-12-31 23:59:59` (per the [docs](http://dev.mysql.com/doc/refman/5.0/en/datetime.html))
Comment: @BradChristie Per the same doc: *The sole exception to this rule is the special "zero" value '0000-00-00'*. `0000-00-00` means `0` for a `DATETIME` field.
Comment: @MathieuImbert: Illegal values are converted to that format. Try inserting the value; you should see `Cannot convert value '0000-00-00 00:00:00' from column 2 to TIMESTAMP` or something similar.
Comment: @BradChristie I tried it, it works: `INSERT INTO pictures (update) VALUES ('0000-00-00 00:00:00')`. It will also default to `0000-00-00 00:00:00` if the field is left uninitialized.


Is there other answer of $\lim\limits _{n\rightarrow \infty }\left( ( an+b)^{n}/( an+c)^{n}\right)$?

Question: Here is my thinking:
$ $$\displaystyle  \begin{array}{{>{\displaystyle}l}}
\ \ \ \ \ \ \lim\limits _{n\rightarrow \infty }\frac{( an+b)^{n}}{( an+c)^{n}} \ \ \ a\neq 0\\
=\ \lim\limits _{n\rightarrow \infty }\frac{e^{n\ln( an+b)}}{e^{n\ln( an+c)}} \ \ \ \ \ \ \ \ \ \ \ \ \ \ \\
=\ \lim\limits _{n\rightarrow \infty } e^{n\ln( an+b) -n\ln( an+c)} \ \\
=\ \lim\limits _{n\rightarrow \infty } e^{n[ \ln( an+b) -\ln( an+c)]}\\
=\lim\limits _{n\rightarrow \infty } e^{n\ln\left(\frac{an+b}{an+c}\right)} \ \ \ \ \ \ \ \ \ \ \ \ \\
=\ \lim\limits _{n\rightarrow \infty } e^{n\ln\left(\frac{1+\frac{b}{an}}{1+\frac{c}{an}}\right)} \ \ \ \ \ \ \ \ \\
=\lim\limits _{n\rightarrow \infty } e^{n\ln1} \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \\
= 1
\end{array}$

But there are two standard solutions of the limit, one is based on $b=c$, the other is based on $b≠c$.
I don't know why to consider these situations. Whatever relationship between $b$ and $c$, seems to fit in my solution?
Please let me know where is wrong. Thanks for help
Comment: $n \ln a_n$ need not tend to $0$ when $a_n \to 1$. This is an indeterminate form $(0)(\infty)$.
Comment: Please note that the case where $b=c$ is quite easy to solve!
Answer: In your derivation this final step
$$\ldots=\ \lim\limits _{n\rightarrow \infty } e^{n\ln\left(\frac{1+\frac{b}{an}}{1+\frac{c}{an}}\right)}
=\lim\limits _{n\rightarrow \infty } e^{n\ln1} \ldots$$
is uncorrect because you are taking the limit only for a single factor for the expression which is an indeterminate form.
To proceed, for $b\neq c$, as an alternative we have
$$\frac{( an+b)^{n}}{( an+c)^{n}}=\left(\frac{ an+b}{ an+c}\right)^n=\left(\frac{ an+c+b-c}{ an+c}\right)^n=$$
$$=\left(1+\frac{ b-c}{ an+c}\right)^n=\left[\left(1+\frac{ b-c}{ an+c}\right)^{an+c}\right]^{\frac n {an+c}}\to \left(e^{b-c}\right)^\frac1a=e^{\tfrac{b-c}{a}}$$
For the case $b=c$ we simply have
$$\frac{( an+b)^{n}}{( an+c)^{n}}=\frac{( an+b)^{n}}{( an+b)^{n}}=1$$
Refer also to the related

Analyzing limits problem Calculus (tell me where I'm wrong).
Answer: Recall that $\lim_{n\rightarrow\infty}\big(1+\tfrac{x}{n}\big)^n=e^x$ for any $x\in\mathbb{R}$ (in fact this also works if $x$ is replaced by a complex sequence $z_n$ that converges to $z\in\mathbb{C}$). In any event,
$$\frac{(na+b)^n}{(na+c)^n}=\frac{(1+\tfrac{b/a}{n})^n}{(1+\tfrac{c/a}{n})^n}\xrightarrow{n\rightarrow\infty}e^{b/a}e^{-c/a}=e^{\tfrac{b-c}{a}}$$

Commment: The classical limit $\lim_{n\rightarrow\infty}\big(1+\tfrac{x}{n}\big)^n=e^x$ can be established without resorting to L'Hospital theorem and without the introduction of logarithms. There are several discussions about this in MSE, here is example
Answer: Hint: To find $\ \lim\limits _{n\rightarrow \infty } e^{n\ln\left(\frac{1+\frac{b}{an}}{1+\frac{c}{an}}\right)} \ \ \ \ \ \ \ \ \\$ use the fact that $\ln (1+x) \sim x$ as $x \to 0$.


Declaring a JNDI variable in JBoss 4.0.5

Question: I want to declare a new JNDI variable in the JBoss 4.0.5 server. Can someone please explain how this can be done?
waiting for your replies.
Thanks.
Answer: Found these two links that can help...
create a file called filename-service.xml under $CATALINA_BASE$/deploy directory with contents as indicated in these links
http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.2/doc/Server_Configuration_Guide/Additional_Naming_MBeans-JNDI_Binding_Manager.html
check a jboss jira, JBPAPP-2809 for correction in xmlns:jndi
Answer: Have a look here and specifically here. You need to add an entry in the ejb-jar.xml file of your application.
Comment: Hi, could you please let me know where is this context.xml is placed?

because, in the link you gave, it is specified that the context.xml present in $CATALINA_BASE/conf/context.xml but, I' not able to find this file in my Jboss. (it's inside default\deploy\jbossweb-tomcat55.sar folder)
Answer: I am facing this probelm too today. Looks like to add a simple jndi entry on the app server, in JBoss one will have to create a new file  $CATALINA_BASE/conf/context.xml and invoke a MBean to add the variable and its value.
In server like websphere you can pass new values in jndi.properties, which jboss 5.0.0 upwards does not like.
Very Bad that there is absolutely NO DOCUMENTATION in jboss/docs that indicate anything on this topic.


What is the error "error: type mismatch;" in scala?

Question: import java.time.LocalDate
object Main extends App{
    val scores: Seq[Score] = Seq(score1, score2, score3, score4)
    println(getDate(scores)(LocalDate.of(2020, 1, 30))("Alice"))
    def getDate(scoreSeq: Seq[Score]): Map[LocalDate, Map[String, Int]] = scores.groupMap(score => score.date)(score=>Map(score.name -> (score.english+score.math+score.science)))
}

I would like to implement a function that maps the examination date to a map of student names and the total scores of the three subjects on that date, and if there are multiple scores for the same student on the same date, the function returns the one with the highest total score. However, here is the function
found :scala.collection.immutable.Map[java.time.LocalDate,Seq[scala.collection.immutable.Map[String,Int]]]]
"required: Map[java.time.LocalDate,Map[String,Int]]".
How can I resolve this?
Comment: Its like when asked to provide a `Car`, you actually provided a `Cup`. And the compiler is telling you that it wanted a `Car` and not this `Cup`.
Comment: How can I improve it?
Answer: The error means what it says: The type of the variable and the type of the value being assigned to the variable don't match. It even tells you what the two types are!
The actual problem is that groupMap isn't returning the type you think it should. The values in the resulting Map are a Seq of Maps rather than a single Map with all the results.
You can use groupMapReduce to convert the List to a single Map by concatenation the Maps using ++:
scores
  .groupMapReduce(_.date)
    (score=>Map(score.name -> (score.english+score.math+score.science)))
    (_ ++ _)


How does KillSignal interact with TimeoutStopSec in systemd?

Question: Can someone let me know the following about systemd service shutdown sequence

If I have specified KillSignal=SIGTERM then how does this interact
this TimeoutStopSec ? Does this mean that during shutdown of
service, first SIGTERM will be sent and if the service is still
running after TimeoutStopSec SIGKILL will be sent (if SendSIGKILL is
set to yes)? I am asking about the case where nothing is specified in
ExecStop.
Does TimeoutStopSec take into account ExecStop and all ExecPostStop?
Answer: This has been answered in systemd email thread. Posting the answer below

Can someone let me know the following about systemd service shutdown
    sequence
1.

If I have specified KillSignal=SIGTERM then how does this interact this
TimeoutStopSec ? Does this mean that during shutdown of service, first
SIGTERM will be sent and if the service is still running after
TimeoutStopSec SIGKILL will be sent (if SendSIGKILL is set to yes? I am
asking about the case where nothing is specified in ExecStop.

Yes, that's correct

2.

Does TimeoutStopSec take into account ExecStop and all ExecPostStop?

TimeoutStopSec is for every command. If ExecStopPost command fails (or
  times out) subsequent commands are not executed, but if each command
  requires almost TimeoutStopSec time, total execution time will be
  close  to ExecStopPost commands multiplied by TimeoutStopSec.
Answer: From that systemd man

This option serves two purposes. First, it configures the time to wait
for each ExecStop= command. If any of them times out, subsequent
ExecStop= commands are skipped and the service will be terminated by
SIGTERM. If no ExecStop= commands are specified, the service gets the
SIGTERM immediately. This default behavior can be changed by the
TimeoutStopFailureMode= option. Second, it configures the time to wait
for the service itself to stop. If it doesn't terminate in the
specified time, it will be forcibly terminated by SIGKILL (see
KillMode= in systemd.kill(5)). Takes a unit-less value in seconds, or
a time span value such as "5min 20s". Pass "infinity" to disable the
timeout logic. Defaults to DefaultTimeoutStopSec= from the manager
configuration file (see systemd-system.conf(5)).
If a service of Type=notify sends "EXTEND_TIMEOUT_USEC=…", this may
cause the stop time to be extended beyond TimeoutStopSec=. The first
receipt of this message must occur before TimeoutStopSec= is exceeded,
and once the stop time has extended beyond TimeoutStopSec=, the
service manager will allow the service to continue to stop, provided
the service repeats "EXTEND_TIMEOUT_USEC=…" within the interval
specified, or terminates itself (see sd_notify(3)).


Windows 2008 file server: How to find unused permissions?

Question: Following some security breach in my office and stealing data from the company, my manager gave me the task of finding all the folders on the file server which users have read access to and they didn't use that permission in the last 3 months.
Is that possible without a third party software?
Comment: I found some software called Varonis Data Advantage that gives you this feature but it costs about 80k$ per year.
Comment: how many servers?
Comment: 4 file servers, about 30 TB of data
Answer: You could setup auditing for the paths which should give you information (as logged events) who read folder content/when etc. which then you would somehow need to process (scripts would be a minimum) and then you would need to give it 3 months to actually build up the information.
If your company is actually putting this on the top of the priority list then I would suggest:

Create a 'file/folder permission request' procedure and make sure you can maintain the information over months and years
Give your users a week or two to put in formal requests to read/write certain folders
Go through your file system/shares and strip out all permissions
Add those for which you got formal requests

Seems draconic but if relaxed/unmaintained permissions have been at least a part of the reason why data theft in your company happened then I think it is something worth considering (highly depends on the size of your company).
Comment: There are about 400 employees in the company but we work with very sensitive information, so stuff like that should never happen.
Comment: Well then that's quite a bit, especially if sensitive information is involved. I think you do need to get tougher on file permissions in general.


Ports for Hive on AWS EMR

Question: I created 1 node EMR (master only) with Hive.
After opening inbound port 22 I can SSH to EMR and type hive and can open and run SQL queries.
How to curl hive from inside of EMR - locally? (which URL / port should use?)
How to access Hive from outside of EMR? (which URL / port should use?)
Comment: Hive runs of 10000 by default
Comment: Yes, but I need it on 443.
Answer: It should be on port 443 as rest api for hive needs to be ssl encrypted.
Please check details over here
In terms of url you need to check your AWS config, and usually you call the EMR API as per details in here and from there you call the hive commands.
Comment: It is not on 443 by default. It is on 10000.
Comment: 10000 is for the https:// based hive via ambari or any other visual interface. i dont think the api has the same port

Ports for Hive on AWS EMR


How to exclude nodes with a taxonomy term from XML Sitemap?

Question: We can exclude content type, or individual node from XML Sitemap. But, is there anyway to exclude nodes with specific taxonomy term? For example excluding nodes with longlivethetroll tag.
Answer: You can use hook_xmlsitemap_element_alter() to check if the node has a particular taxonomy term & exclude it.
function MYMODULE_xmlsitemap_element_alter(&$element, $link, $sitemap) {
  // Check if link is a node link
  if ($link['type'] == 'node') {
    $node = node_load($link['id']);

    // Code to check if $node has taxonomy term goes here
    if ($node has taxonomy term) {
      $element['disabled'] = TRUE; // This removes the node link from sitemap
    }
  }
}


Confidence in cross validation

Question: A paper I'm reading reports classification accuracy, calculated using 5-fold cross validation. Each accuracy number is reported together with 95% confidence given inside the parenthesis. For instance: 69.92 (0.545).
I understand accuracy is averaged over 5 tests data sets, but what is 95% confidence and how it is calculated?
Answer: First of all, I'd like to emphasize that it's really up to the paper should really to say what was calculated, and to spell out which approximations were used.
I'm afraid there's likely too much ambiguity to really find out without asking the authors.

I can think of two possibilities that you may be able to check out:

This may be a binomial confidence interval. As only one number is given, possibly using the Gaussian approximation.
The standard deviation of an observed fraction of cases $p$ (e.g. accuracy) is $$\sigma_\hat p = \sqrt{\frac{p (1 -p)}{n}}$$ p being the true fraction (or probability).
Assuming that the 95 % c.i. used the normal approximation, so the reported $0.545 \% = 1.96 \sigma$, we can plug in the observed accuracy  $\hat p = 0.6992 \%$ for the true accuracy $p$ and solve for n:
$$n = \frac{p (1 -p)}{(ci/2)^2} = \frac{0.6992 (1 - 0.6992)}{(0.00545/1.96)^2} \approx 27200$$
(And at that sample size and $p$, the Normal approximation is safe to make. This calculation implicitly assumed the models are stable, so that variance due to model instability between the $k$ surrogate models is negligible.)
If this lines up with the sample size in the paper, we probably found what they did.
OTOH, if often see papers giving the standard deviation observed over the $k$ folds as observed uncertainty - this is a useful number, but of course in no way a 95 % confidence interval. And as it is not easy to calculate even the standard error of the mean here since we have possibly several relevant variance terms (the test sample size which I used above, model instability, and depending on the task at hand further sources of variance) at the very least the paper would need to explain what is included in this and what assumptions were taken.
Comment: The value in parentheses could be s.d. based on average over 5 folds.  I don't know why so many reports just don't pad the confusion matrix during any test fold they are in, and then just obtain one accuracy equal to $\sum_i c_{ii} / \sum_i \sum_j c_{ij}$? Probably because they didn't develop the code, and have no option but to determine the average and s.d.
Comment: yes, it would have to be based on the variance of a binomial proportion, $p$, which is indeed $\sqrt{pq/n}$
Comment: @NXGLogic: the important question is: is it? And, with that precision due to the large sample size and an accuracy of 70 %, I'd like to see something that model instability is negligible compared to those 0.5 % ci width.
Comment: @NXGLogic: neither do I know *why* this happens - but judging from the amount of questions around that topic I see here on CV.sx I know that there is a whole lot of confusion.

Confidence in cross validation


Copy to clipboard with no Flash - Firefox, Chrome, Safari, Opera

Question:
Possible Duplicate:
Copy to clipboard without Flash

I want to copy some text from an element by a given id to clipboard. I want to be flashless solution, no Flash at all. It can be in jQuery or JavaScript.
The solution for IE is simple (clipboardData), but for FF, Chrome and others - it doesn't work.
Help.
Comment: jQuery is *not* Javascript -- it's a client-side Javascript framework
Answer: There is no javascript method to do this - its prevented by browser security ... Flash is the best alternative ...
Explanation of security policy on Firefox -> http://kb.mozillazine.org/Granting_JavaScript_access_to_the_clipboard
Comment: this is garbage... how does chrome say "this is a security problem so we won't implement it, but we will bundle flash with our browser which allows it to happen anyways"
Comment: This is false. The Clipboard API is a work in progress standard, being currently implemented by Firefox with the other browsers pending - http://dev.w3.org/2006/webapi/clipops/clipops.html#widl-ClipboardEvent-clipboardData
Comment: Clipboard API now works in Chrome and Firefox (but not Safari AFAIK) - example here: http://codepen.io/nottrobin/pen/meObWe


Probabilities of medical risks

Question: Recently, I read a UK Supreme Court judgment Montgomery (2015), a judicial decision advocating patient's dignity and safety.
The Court held that no matter how small the percentage of a certain risk of harm/damage relating to certain clinical procedure (e.g. the risk of brachial plexus injury in case of shoulder dystocia involving diabetic mothers (delivering the baby vaginally), is just about 0.2%), if (1) the risk could, if materialised, cause serious harm to the patient, and (2) a reasonable patient, if properly warned, would attach significance to it, a healthcare provider is duty bound to disclose that risk to the patient. That risk, in legal definition, is material, even though statistically speaking, negligible (too small in terms of number/percentage).
I like this judicial decision very much as it really respect patients' dignity and care about patients' safety. After all, common sense! We used to see healthcare providers, as part of medicine culture, ordinary relying upon statistical figures to explain for their failure to disclose material risks of harm to patients, claiming that the relevant risk was just negligible (in figure), not worth mentioning. As a result, denying patients rights to make informed decisions very important to their own health, at times, resulting in some serious and sad consequences.
Now I know how the judges approach this question of healthcare providers' clinical decision making.
I want to know, on the other hand, how statisticians and mathematicians would approach the same question: statistical figures naturally lead many healthcare providers to feel confident in choosing their favorite "gold standard" clinical procedures, most if not all invasive and have the potential however small to cause serious harm (especially when the relevant published incident rate was small). Are healthcare providers correct in applying statistical figures that way in their everyday clinical decisions on individual patients?
I heard about Bayesian and Frequentist approach but I don't know if they are relevant to the question I asked cos' I'm just a sport medicine student without any training in statistics.
I would be most grateful if someone may enlighten me in this regard. Thanks in advance!
Comment: I don't understand from your question what it is you are seeking. I can say that estimates of adverse outcomes from medical procedures are from limited data sources, often highly selected (published in journals), and frequently out of date. Nonetheless we must have them since they are necessary to inform patients who are starting clinical trials.
Answer: It basically says that patients should be told about all meaningful risks of a procedure, even if these risks are very small in statistical terms.
Now, from a stats perspective, there are two main approaches - Frequentist and Bayesian. Frequentists look at the long-term frequency of an event, so a doctor might use this to say the risk is very low based on lots of data. However, Bayesians would start with this general knowledge but then update it with specifics about the patient, like their age or health condition.
While both methods might lead to the same decision about a procedure, the key thing from the court ruling is to make sure all meaningful risks are shared with the patient. That's where technology could help! Think about a medical app that gives up-to-date, personalized risk assessments. It could help doctors explain risks and help patients make informed decisions.
Answer: I doubt a reasonable statistician would argue with such interpretation. This is a kind of problem you look at from decision theoretic perspective. First thing you need to do is to assign some numeric values to possible gains and harms (say monetary values). Next, you would estimate the expected "harms" of such procedure, i.e. multiply the harms by their probabilities and sum everything. Reasonable decision maker would consider such medical procedure if the amount of expected harms of such procedure is not greater then the amount of expected gains. What follows, this means that "large" harm that happens even with a small probability can have a noticeable impact on the overall expected outcome.

Probabilities of medical risks


Sun X4170 squealing after disk eject. How do I fix this?

Question: I just ejected one of the "hot swappable" hard drives from a Sun X4170 running RAID 10 and it is making quite a loud noise. It's like a system beep that's one long continuous note.
I'm wondering what is causing this and how I fix it. Preferably fast as it is driving me mad (it's in the office for setup and testing).
We are running ESXi
Answer: The HDD had not reconnected properly when being reinserted into the server. Removing and reinserting the drive correctly stopped the noise and the RAID resynced.
Answer: This is typically a "hardware failed" warning, and is supposed to alert DC techs that something needs replacing.  You typically tell the machine to quiet down via IPMI (or whatever the Sun equivalent is) or an OS-specific tool that talks to the hardware.  If you provide your OS details, it's likely someone will be able to give you the exact invocation you need (I'm not real up to speed on Sun hardware).
Comment: It's running ESXi


Overwrite Taxonomy Term page display settings with custom URL's

Question: I would like to define the display settings of my Taxonomy term page. As I understand, this is possible by configuring the Taxonomy view provided by the Taxonomy module.
However, I use custom URL's and by so, my taxonomy pages doesn't have the URL taxonomy/term but something like products/tents.
Is there a way to customize these pages with the provide view?
Comment: `taxonomy/term` is the _router_ path, `products/tents` is the _alias_. The path for your view should be the router path, i.e. `taxonomy/term/%`. No square brackets though, those are for tokens :)
Comment: So if I understand you correctly, if you insert `taxonomy/term` in the path of your view, you should be able to style the term page of your taxonomy items? But if I enter a contextual filter, the results turn out to be empty... Am I doing something wrong here?
Comment: @Clive, the view only returns some results whenever I enter a number as contextual filter. If I enter a term like "tents", I don't get any results? It has been a while since I touch Drupal... :)
Comment: Ah ok, if memory serves you need to edit your contextual filter, specify validation criteria, and validate against the taxonomy term name rather than the id. Does that make sense?
Comment: More or less... I think I've got it working now but there seems to be another problem going on right now. Care for a chat? Or do I just create another question?
Comment: I'd ask another question to be honest, you'll get more eyes on it that way
Comment: Hoppa! Please convert your comment to an answer so I can accept it :)
Answer: You can set the patterns used for Taxonomy URL aliases.
http://drupal.org/node/120631
Sounds like you want to use: [term:vocabulary]/[term:name]
If you have it enabled, you should be able to see the patterns here:
www.yoursite.com/admin/config/search/path/patterns
Comment: That's what I figured, but when I enter `[term:vocabulary]/[term:name]/%` in my path on the Views UI, nothing happens...
Answer: First thing, For customize path you can use Pathauto module where you can provide customize path according to your requirements for Node, Taxonomy terms pages etc. Go to this path for customize paths : admin/config/search/path/patterns
Second thing, for customize Taxonomy Term pages you have to enable Page Manager which is available in Ctools module and then go to the admin/structure/pages and then enable the default Taxonomy term template. After enabling, click on edit. It will open a panel page. Then add the view that you want to show on this panel page.


equallogic as direct network drive

Question: at work we have an equallogic which currently does nothing. I know how to create volumes and configure the equallogic.
But I am wondering if it is possible to use it as a direct network drive via iSCSI with. The main problem I see is the filesystem. I would need to use a locking filesystem. Does anyone have a good idea which software to use?
Comment: "Network drive" sounds like you're after a network share, but "direct" and "iSCSI" sound more like you're after block-level access. Go in the direction of ewwhite's answer if a network share is what you're after. If you're looking for block level access, what operating systems will your hosts have? And what application is it for? (Database, Virtualization, Etc)
Comment: What do you intend to connect the storage to?
Comment: a network. Which then would allow multiple clients to acces it via iSCSI
Comment: And that's not possible already? What are your clients?
Answer: I think you're asking for a way to turn your Dell Equallogic storage into shared network storage; e.g. converting SAN to NAS.
The Equallogic SAN is block-only, so your easiest solution is to configure a server to interface with the Equallogic device over iSCSI. Use that server to present the block storage to the rest of your network as a network filesystem.
You don't mention the operating systems in use, but with a Windows server, you could easily provide Samba/CIFS to your clients. If a Linux machine, export NFS or Samba/CIFS shares.

equallogic as direct network drive


Python threading problem for "self.running=Bool"

Question: I want to create camera program for stereo vision. Therefore i think the program for left and right cameras.  Because i want to seperataly work for my cameras. Otherwise program slowdowns and cameras gives low fps. Anyway...
When i tried True state; program start truly but when i pressed stop button program stops there is no problem but not start again when i press start button.
Or i tried None state; program starts there is no problem after  when i press start button  cam window appear   but not stops when i press stop button this time.
from threading import Thread
import time
import cv2
import keyboard

class Left_Frame(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.running = False # True or False or None i tried...

    def run(self):
        cap = cv2.VideoCapture(0)
        while self.running:
            success, img = cap.read()
            cv2.imshow("qwe", img)
            tecla = cv2.waitKey(1) & 0xFf

    def stop(self):
        self.running = False

    def ss(self):
        self.running=True

left=Left_Frame()

if not left.is_alive():
    left.start()

while True:
    if keyboard.is_pressed('f'):
        left.stop()
        time.sleep(1)

    if keyboard.is_pressed('s'):
        left.ss()
        time.sleep(1)

Comment: If you press the `s`key, you shouldn't set the state of your thread to running, you should start it (as far as it's not running already). The start method should set the state to running.
Comment: So, can you explain what must I do?
Comment: Look at your code. It states: `if keyboard.is_pressed('s'): left.ss()`. And the `ss()` function does nothing else than setting `self.running = True`. Instead you should first check if the thread is still running. If so, ignore the pressed key. If it's not running, call `left.start()` again (this can all be done in the function `ss()`). The `run()`method should set `running` to True when it's entered.
Answer: Here is the solution.
from threading import Thread
import time
import urllib.request
import cv2
import keyboard

class left_Frame(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.running = True

    def run(self):
        cap = cv2.VideoCapture("http://192.168.137.109/stream")
        state=True
        while self.running:
            # print(state)

            if state==True:
                success, img = cap.read()
                cv2.imshow("left", img)
                tecla = cv2.waitKey(1) & 0xFf

            if keyboard.is_pressed('f'):
                state = False
                cap.release()
                cv2.destroyAllWindows()

            if keyboard.is_pressed('s'):
                if not state==True:
                    cap = cv2.VideoCapture("http://192.168.137.109/stream")
                    state = True

left=left_Frame()
left.start()


LINQ to SQL not getting correct data

Question: Using Studio 2008, C#, SQL Server 2005, Winforms. I've looked all over this site and can't find a situation that is the same...
I have data1 window filled from a LINQ to SQL connection. I click a button to open data2 window and edit data in there.
When I close data2 window, I need to refresh the data in data1 window.
So I call the SQL Server with a query through LINQ. I'm not getting back the new data I just saved from data2 window. I'm getting the old data back that was already there.
Any ideas why? I verified that the data was saved in the SQL database and it is there.
Now if I close data1 window and reopen it, the correct data is there. But why when I requery the database right after closing data2 window is the data in data1 window not updating?
Code:
IEnumerable<tblConstructionRevision> newRev1 = (from y in DDBML.tblConstructionRevisions orderby y.RevDate descending, y.RevNo descending where y.DrawID == drawID select y);

It doesn't matter if I get back FirstOrDefault or the list. I can't return it to a List<> because I need the entire dataset.
Comment: Thanks to all for the answers. It was a cache issue. Didn't know that existed but now I do.
Answer: It's cached, check this - http://blogs.msdn.com/b/dinesh.kulkarni/archive/2008/07/01/linq-to-sql-tips-9-understanding-datacontext-s-internal-caching.aspx
Comment: Excellent. Thank you. That was a good reading and helped me figure out the problem...it was caching it and now I know how to fix that.
Answer: You need to use Refresh method of your data context to invalidate the cache.
Answer: Its sounds like you're keep DDBML around with your form.  I think as long as the context is open it will cache the tracked entities.  You should use the datacontext then dispose if it, and open a new one when you need to.  See this for more about the caching: http://blogs.msdn.com/b/dinesh.kulkarni/archive/2008/07/01/linq-to-sql-tips-9-understanding-datacontext-s-internal-caching.aspx
Answer: If you want only the current data, use MergeOption.NoTracking. This means that they are not stored in the graphs that track updates and deletions of entities in the same context. If the data you are reading is already updated in another context, window, or application, this method ensures that the data you read will be up-to-date. It should be noted that disabling object tracking will also prevent you from submitting updates to the database. So after reading, you should put the MergeOption value into the original.
System.Data.Objects.MergeOption mergeOption = DDBML.tblConstructionRevisions.MergeOption;
DDBML.tblConstructionRevisions.MergeOption = System.Data.Objects.MergeOption.NoTracking;

var newRev1 = (from y in DDBML.tblConstructionRevisions
     orderby y.RevDate descending, y.RevNo descending
     where y.DrawID == drawID select y);

DDBML.tblConstructionRevisions.MergeOption = mergeOption;

Or you can use ExecuteStoreQuery() method, and specify NoTracking in the parameters. The same effect can be achieved.
var newRev1=db.ExecuteStoreQuery<tblConstructionRevisions>(
   "SELECT * FROM tblConstructionRevisions y WHERE y.DrawID = @ID
          order by y.RevDate desc, y.RevNo desc",
   "tblConstructionRevision",
   System.Data.Objects.MergeOption.NoTracking,
   new SqlParameter("@ID", drawID));

In Entity Framework 4.1, you can use the new AsNoTracking() method:
var newRev1 = (from y in DDBML.tblConstructionRevisions.AsNoTracking()
     orderby y.RevDate descending, y.RevNo descending
     where y.DrawID == drawID select y);

or
var newRev1 = (from y in DDBML.tblConstructionRevisions
     orderby y.RevDate descending, y.RevNo descending
     where y.DrawID == drawID select y).AsNoTracking();

What NoTracking Does
Entity Framework exposes a number of  performance tuning options to help you optimise the performance of your applications. One of these tuning options is .AsNoTracking(). This optimisation allows you to tell Entity Framework not to track the results of a query. This means that Entity Framework performs no additional processing or storage of the entities which are returned by the query. However it also means that you cant update these entities without reattaching them to the tracking graph.

LINQ to SQL not getting correct data


How can I listen to changes of multiple providers from a future builder?

Question: I want to display a BarChart where I use as source information two different providers.
My initial approach was to use a future builder where I show a loading icon while the data is being fetched, and then manipulate that data to suite my needs in the graph.
So I used a future builder from the widget where I display my graph and initialized it with a Future that will get the context from another reusable file.
my_wdiget.dart
...
class _MyWidgetState extends State<MyWidget> {
  late Future<List<MyObject>> myFutureVariable;

 Future<List<MyObject>> _getMyObjects() async {
    return getMyObjects(context);
  }

  @override
  void initState() {
    super.initState();
    myFutureVariable= _getMyObjects();
  }

...

FutureBuilder<List<MyObject>>(
                future: myFutureVariable,
                builder: (BuildContext context,
                    AsyncSnapshot<List<MyObject>> snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.waiting:
                      return Center(child: CircularProgressIndicator())),

                      );
                    default:
                      if (snapshot.hasError) {
                        return Center(
                                    child: Text('Error: ${snapshot.error}'))),

                        );
                      } else if (snapshot.data == null) {
                        return Center(
                                    child:
                                        Text('You don\'t have any item yet.'))),
                        );
                      } else {
                        return BarChart(
                            _getChartData(snapshot.data!),
                          ),
                        );
                      }
                  }
                },
              ),

And this is the file where I generate the data:
my_object_utils.dart
Future<List<MyObject>> getMyObjects(BuildContext context) async {
  await Future.delayed(Duration(seconds: 1)); // Simulation delayed query
  var source1= Provider.of<MySource1>(context, listen: false).items;
  var source2 = Provider.of<MySource2>(context, listen: false).otherItems;
  List<MyObject> myObjects= [];
  // Do some stuff to fill the myObjects using source1 and source2
  return myObjects;
}

Problems:

This kind of works but I get the warning use_build_context_synchronously from the lines of the Provider.
I want to listen to changes, but if I set the default listen: true it will crash telling me to change that property.

So my question is, how can I have a FutureBuilder listening to changes of multiple providers?
Update using approach suggested @hydra:
If I have:

  void test() {
    print('a');
    setState(() {});
  }

Consumer2<MySource1, MySource1>(
  builder: (context, sourceOne, sourceTwo, child) {
    myFutureVariable = getMyObjects(sourceOne.items, sourceTwo.otherItems),
    return FutureBuilder<List<MyObject>>(
      future: myFutureVariable,
      builder: (context, snapshot) {
          ...
           else{
             return child: ElevatedButton(
                                child: Text('a'),
                                onPressed: test,
                              );
      }
      }
    ),
  },
),

Every time the button is pressed it will trigger the setState and and the circularProgressIndicator will appear although no changes were made in the consumers.
Answer: to solve both problems you can use Consumer2
the FutureBuilder will rebuild if either of the two provider changed
Consumer2<MySource1, MySource1>(
  builder: (context, sourceOne, sourceTwo, child) {
    return FutureBuilder<List<MyObject>>(
      future: myFutureVariable(sourceOne.items, sourceTwo.otherItems),
      builder: (context, snapshot) {
        // ...
      }
    ),
  },
),

and update your function to:
Future<List<MyObject>> getMyObjects(final items, final otherItems) async {
  // use your items and otherItems here.
  await Future.delayed(Duration(seconds: 1)); // just for testing, right?
  List<MyObject> myObjects= [];
  // Do some stuff to fill the myObjects using source1 and source2
  return myObjects;
}

Comment: Thanks, that I was looking for. But I have a problem with that solution, you wrote `future: myFutureVariable(sourceOne.items, sourceTwo.otherItems),` but that is rebuilt everytime setState is called, causing `setState() called after dispose()` in elements under the futureBuilder`
Comment: I have no idea, can you add a snippet of code of where you use `setState()`
Comment: I have updated my question to add this information.


Problema em CSS

Question: Galera, estou com um problema, eu sei que isso é funcional, porém nunca funcionou comigo.
Segue o código:
HTML

Departamentos

Blusas e Camisas

Manga curta

Manga cumprida

Camisa social

Camisa casual

Calças

Saias

Vestidos

Sapatos

Bolsas e Carteiras

Acessórios

CSS
.menu-departamentos li ul {
    display: none;
}

A minha dúvida deve ser bem simples.

li ul separados por espaço -> Qual o nome que se da para isso?
li,ul separados por vírgula -> Qual o nome que se da para isso?

O meu problema de fato é... consigo fazer alterações em css utilizando li,ul NORMAL, PORÉM, utilizando li ul, que é o que eu de FATO preciso, ele NUNCA altera.
Browser utlizado: Google Chrome
Answer: Seletor separado por espaço é chamado de seletor descendente, significa que ele vai pegar por exemplo todos os ul que é filho de li que é bisneto de .menu-departamentos.
Seletor separado por vírgula é usado pra aplicar o mesmo estilo a dois ou mais seletores(por classe, id e tag), sem a necessidade de repetição de código.

Problema em CSS


Is it possible to combine Firestore streams in Flutter?

Question: In my flutter app, I'm using this Firestore Stream :
  late Stream<QuerySnapshot> requestsClosedOrPending = FirebaseFirestore.instance
      .collection(clients)
      .where('isOpened', isEqualTo: false)
      .where('isPending', isEqualTo: true)
      .snapshots();

So to include the documents in the stream, the document needs to have the field isOpened = false AND isPending = true.
But what I want is to have an OR statement instead : to include the documents in the stream, the document should have the field isOpened = false OR isPending = true. Is it possible ?
Also, I'm using this stream in a StreamBuilder :
  StreamBuilder<QuerySnapshot> requestsStream(Future triggerAnalytics) {
    return StreamBuilder<QuerySnapshot>(
      stream: requestsClosedOrPending,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
              // Rest of the code..//

Maybe I should add the or statement in the StreamBuilder itself ? I'm opened to any suggestion that could combine the streams.
Answer: Firestore nowadays supports having OR conditions in a query, but you got the syntax wrong. Your requirement would translate to something like:
FirebaseFirestore.instance
    .collection(clients)
    .where(
      Filter.or(
        Filter('isOpened', isEqualTo: false),
        Filter('isPending', isEqualTo: true)
      )
    )

Also see the Firestore documentation on using an OR condition in a query.

If you ever find a case where you do need to combine multiple streams, have a look at How do I join data from two Firestore collections in Flutter?


JCalendar Focus Event

Question: I use JCalendar's JDateChooser in a table date column as a tablecelleditor. The problem is that when the column cell clicked JDateChooser appears but if it loses its focus it does not fire focus lost event. How to make it fire focus lost event? And after doing this is there any way to prevent its firing focus lost when JCalendar appeared after clicking the JCalendar Button?
The thing I try to do is if some one specify a date by selecting a date from the calendar stopCellEditing(); Else wait until focus lost event to stop or cancelCellEditing();
Comment: as I know with JCalendar is there included TableEditor/Renderer too
Comment: are you using JCalendar from jar, or from Source Files, if from jar, then download source File (JCalendarCellEditor.java)
Comment: i use jar and found the class. Should i still download the source file?
Comment: check before if you are able to use this class, I think that there any difference betweens plain java file and class
Comment: It is a very simple CellEditor :/

I need something like JDateChooser.addDateSelectionListener(
    public void dateSelected(DateEvent evt){
        ...
    }
);
Comment: And focus event of jDateChooser get work
Comment: @mKorbel is correct, there's a working `TableCellEditor` in the source distribution.
Answer: In the source distribution mentioned by @mKorbel, com.toedter.calendar.demo.DemoTable is an example that uses com.toedter.calendar.JDateChooserCellEditor as a cell editor. The essential steps are these.
JTable table = new JTable(…);
table.setDefaultEditor(Date.class, new JDateChooserCellEditor());

Addendum: Here is an sscce that shows the expected behavior.
import com.toedter.calendar.demo.DemoTable;
import java.awt.EventQueue;
import javax.swing.JFrame;

/** @see http://stackoverflow.com/questions/7643893 */
public class CalendarTable {

    private void display() {
        JFrame f = new JFrame("CalendarTable");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new DemoTable());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new CalendarTable().display();
            }
        });
    }
}

Comment: By the way i found a propertyChanged event when date is changed in JDateChooser. Now i just need make JDateChooser fire focusLost
Comment: I can't reproduce the effect you describe using `JDateChooserCellEditor`; an [sscce](http://sscce.org/) might shed some light.
Comment: it should be a normal behaviour of table cell editor. Table cell editor should cancelCellEditing when focus lost, and stop cell editing when editing finished. So when someone selects a date it should stop the cell editing. This can be done by propertyChanged event. But when cell editor lost focus such as when i change the tab which cell editor's table is contained cell editor dont cancel cell editing
Comment: and jTable1.putClientProperty("terminateEditOnFocusLost", true); fixes it
Answer: I found a propertyChanged event in JDateChooser which is fired when a date selected. And jTable1.putClientProperty("terminateEditOnFocusLost", true); make the table terminate edit on focusLost
Edit : When calendar popup is down if you want to change the year that make table cell lose focus and terminateEditing :(
jDateChooser.addPropertyChangeListener(new PropertyChangeListener() {

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals("date")) {
            stopCellEditing();
        }
    }
});

Edit(Solved) : Instead of using jTable1.putClientProperty("terminateEditOnFocusLost", true); adding ta FocusListener to JTable in TableCellEditor and cancel editing when focus lost give a chance to check if the JDateChooser's popup is visible or not. But before this, JDateChooser should be extended with a popup isVisible method. Because popup variable is protected. And cell editor components should not be focusable else JTable also loses its focus

JCalendar Focus Event


Create Polymer menu like Google IO 2015 website

Question: I am new to polymer.
I want to build menu like Google IO 15 website.
I tried by adding core-toolbar to core-scroll-header-panel.
<core-scroll-header-panel headermargin="128" condenses headerheight="192" id="core_scroll_header_panel">
  <core-toolbar id="core_toolbar" class="tall">
    <core-icon-button icon="arrow-back" id="core_icon_button"></core-icon-button>

      <core-item id="core_item2" icon="home" label="Home" horizontal center layout></core-item>
      <core-item id="core_item" icon="account-box" label="Our Objectives" horizontal center layout></core-item>

Title

    <core-item id="core_item1" icon="settings" label="Business Activities" horizontal center layout></core-item>
  </core-toolbar>

</core-scroll-header-panel>

But that went like below shown image

How can I get that ripple effect or hover effects like in Google IO 2015 website.
Is there any other way to achieve it.
Comment: The menu is the element `paper-tabs`
Answer: Just add paper-tabs to core-scroll-header-panel and it worked.
Below is the code snippet
    <core-scroll-header-panel id="core_scroll_header_panel">
       <core-toolbar id="core_toolbar" class="tall">

         <paper-tabs selected="1" selectedindex="1" horizontal center layout>
          <paper-tab id="paper_tab" flex horizontal layout>Home</paper-tab>
          <paper-tab id="paper_tab1" flex horizontal layout active>Phone</paper-tab>
        <paper-tab id="paper_tab2" flex horizontal layout>Activities</paper-tab>
      </paper-tabs>

  </core-toolbar>

</core-scroll-header-panel>

I got ripple effect too as they are paper elements.


Draw line with increasing lineWidth on iPhone

Question: I'm drawing a line on iOS by stroking a path onto a CALayer. How can I stroke this line with an increasing lineWidth (stroke width), so that the left end of the line is thinner than the right end? (It really has to be a line, not a shape or closed path, since I'm going to be using the strokeEnd property.)
Thank you for your help!
Answer: Use a draw function. It's pretty annoying to get used to at first, but it does its job. If you need anymore help just leave comment
<code>-(void)draw{
     float lineHeight = 5;//change this as you see fit, like set it equal to an incrementing/decrementing variable of your choice...
     glEnable(GL_LINE_SMOOTH);
     glLineWidth(lineHeight); // change this as you see fit
     glColor4ub(255,255,255,255); // change these as you see fit :)
     ccDrawLine(ccp(10,310), ccp(30,310));  // these numbers are probably off, you'll   have to mess with these to get it in the right position :)
        [super draw];
        }
</code>
Comment: Am I correct in thinking this has something to do with cocos2D? I'm using a QuartzCore CALayer/CAShapeLayer, not CCLayer..
Comment: Oh crap sorry, you may need cocos2d for this... sorry I thought it was part of xcode.
Comment: Is there another possible solution, apart from using cocos2D?
Comment: Hrm... you could have the width set to a variable that changes with an NSTimer.