Updating SilverLight lists when Bound in-memory collection gets a new member

Question: I'm trying to pupulate one of three listboxes from a (fourth) source list box.  The source has a list of school Subjects which are classified as elementary, middle or high school subjects.  The source listbox is a list of checkboxes.  The user clicks on the checkbox and one of the other three are intended to get a copy of the Subject object from the source list.  I've got the thing wired up and successfully hit a CheckBox_Changed method.  I can successfully locate the Subject instance from the source list and add it to the target list's Source array.
What I can't do is show the update on the Silverlight control that the target array is bound to.
Any ideas?
Thanks
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
  var cb = (CheckBox)sender;
  var children = ((Grid)cb.Parent).Children;
  // cb has a sibling TextBlock item that has the index of the item in
  //   the list of subjects
  var ch2 = children[1] as TextBlock;
  var subjectIndexStr = ch2.Text;
  var myWorkingSubject = workingSubjectList[int.Parse(subjectIndexStr)];

  switch (myWorkingSubject.SubjectLevelId)
  {
// updates to the elementarySubjects, middleSubjects and highSubjects
//    don't get reflected in the lists that use them as a resource.
    case (int)SubjectLevels.Elementary:
      elementarySubjects.Add(myWorkingSubject);
      break;
    case (int)SubjectLevels.Middle:
      middleSubjects.Add(myWorkingSubject);
      break;
    case (int)SubjectLevels.High:
      highSubjects.Add(myWorkingSubject);
      break;
    default: break;

  }
}

// this is how the target classes are declared.
public class SubjectsElementary : ObservableCollection<WorkingSubject>
{
}
public class SubjectsMiddle : ObservableCollection<WorkingSubject>
{
}
public class SubjectsHigh : ObservableCollection<WorkingSubject>
{
}

Here are snippets from the .xaml file
<TutorRouterSvc:WorkingSubjectList x:Key="subjects" />
<TutorRouterSvc:SubjectsElementary x:Key="elementarySubjects" />
<TutorRouterSvc:SubjectsMiddle x:Key="middleSubjects" />
<TutorRouterSvc:SubjectsHigh x:Key="highSubjects" />

  <ListBox x:Name="subjectList" ItemsSource="{Binding Mode=OneWay, Source={StaticResource subjects}}">

  <ListBox.Resources>

  </ListBox.Resources>
        <ListBox.ItemTemplate>
            <StaticResource ResourceKey="DataSubjectsTemplate1"/>
        </ListBox.ItemTemplate>
    </ListBox>

<Grid Grid.Column="1">
  <Grid.RowDefinitions>
    <RowDefinition Height="*"/>
    <RowDefinition Height="*"/>
    <RowDefinition Height="*"/>
  </Grid.RowDefinitions>

  <ListBox Margin="0,0,8,0" x:Name="elementarySubjectList"
            ItemsSource="{Binding Mode=OneWay, Source={StaticResource elementarySubjects}}"
            Background="#FFE75151" Grid.Row="0">
    <ListBox.ItemTemplate>
      <StaticResource ResourceKey="DataSubjectsTemplate1"/>
    </ListBox.ItemTemplate>
  </ListBox>
  <ListBox Margin="0,0,8,0" x:Name="middleSubjectList"
            ItemsSource="{Binding Mode=OneWay, Source={StaticResource middleSubjects}}"
            Background="#FFE75151" Grid.Row="1">
    <ListBox.ItemTemplate>
      <StaticResource ResourceKey="DataSubjectsTemplate1"/>
    </ListBox.ItemTemplate>
  </ListBox>
  <ListBox Margin="0,0,8,0" x:Name="highSubjectList"
            ItemsSource="{Binding Mode=OneWay, Source={StaticResource highSubjects}}"
            Background="#FFE75151" Grid.Row="1">
    <ListBox.ItemTemplate>
      <StaticResource ResourceKey="DataSubjectsTemplate1"/>
    </ListBox.ItemTemplate>
  </ListBox>
</Grid>

Answer: I'm not quite sure, but this may be fixable by doing the changes inside a Dispatch.BeginInvoke().
You could refactor the switch statement to a new method called UpdateListBox, then call it:
Dispatcher.BeginInvoke(() => UpdateListBox(myWorkingSubject.SubjectLevelId))

Comment: Thanks for the response.  I can't say I understand what the Dispatcher.BeginInvoke() does except initiate a deligate on a queue.  I was thinking that simply adding a new element to the bound data collection would be enough.  What would UpdateListBox() do to update the ListBox?
Answer: Maybe this is happening because the XAML is Newing up a new instance of your objects, which it's databinding to.
Try adding this to the cosntructor on your Page.xaml.cs (or where ever the control is located);
_subjects = Resources["subjects"] as WorkingSubjectsList;
_elementarySubjects = Resources["elementarySubjects"] as SubjectsElementary;

etc...
Maybe that will help. I've implemented the same concept by binding listboxes to Observable collections on several occassions and haven't experienced what you're encountering.
I do have a couple of suggestions:
have you tried this on your check changed event?
workingsubject _item = workingSubjectList[subjectsList.selectedindex];
switch (_item.SubjectLevel) //I'm assuming this property as you have the ID and it looks to be an enumeration
        {
            case Elementary:
                elementarySubjects.Add(_item):
                break;
            case Middle:
                middleSubjects.Add(_item):
                break;
            case High:
                highSubjects.Add(_item):
                break;
                case default:
                        throw new Exception("Unrecognized Subject Level");
        }

hth.


select item in NavigationView with Espresso

Question: I have this piece of code
 private void setupDrawerLayout() {
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            final int itemId = menuItem.getItemId();

            switch (itemId) {
                case R.id.drawer_my_mixes:
                    replaceFragment(MyMixesFragment.newInstance());
                    drawerLayout.closeDrawers();
                    break;
                   and so on...

I want to make espresso to click R.id.drawer_settings which will basically open a fragment called SettingsFragment. How do I do this? I tried this with no success
private ViewInteraction navigateToSettings(){
    openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
    return onView(withText("Settings")).perform(click());

}

Answer: The correct way would be to use the onData function of Espresso.
onData(allOf(is(instanceOf(NavigationMenuItem.class)), ... )).perform(click());

But NavigationMenuItem isn't accessible since it is a private nested class.
An issue is pending https://code.google.com/p/android/issues/detail?id=187701 to find a solution on it. Go add a star to it ;-)
Comment: In espresso 2 you can use `onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());`. More info look [this answer](http://stackoverflow.com/a/32854962/1332549)
Answer: openActionBarOverflowOrOptionsMenu() does not open NavigationView.
For me the following works:
//Open NavigationView
Matcher<View> isImageButton = withClassName(is(ImageButton.class.getName()));
Matcher<View> isInToolbar = isDescendantOfA(withId(R.id.toolbar));
onView(allOf(isInToolbar, isImageButton)).perform(click());

//Click on item in NavigationView
onView(withText(R.string.logout)).perform(click());

This solution works for me temporarily until a better solution like suggested by user40797 is working...
Answer: How to select an item in the NavigationView.
In your package utils:
public class NavigationViewTestHelper {

    public static Matcher<View> childAtPosition(
            final Matcher<View> parentMatcher, final int position) {

        return new TypeSafeMatcher<View>() {
            @Override
            public void describeTo(Description description) {
                description.appendText("Child at position " + position + " in parent ");
                parentMatcher.describeTo(description);
            }

            @Override
            public boolean matchesSafely(View view) {
                ViewParent parent = view.getParent();
                return parent instanceof ViewGroup && parentMatcher.matches(parent)
                        && view.equals(((ViewGroup) parent).getChildAt(position));
            }
        };
    }
}

In your test after opening your NavigationView.
ViewInteraction navigationMenuItemView = onView(
                allOf(childAtPosition(
                        allOf(withId(R.id.design_navigation_view),
                                childAtPosition(
                                        withId(R.id.*your_navigation_view_id*),
                                        0)),
                        1), // Position of the element in the Navigation view.
                        isDisplayed()));

navigationMenuItemView.perform(click());

Answer: Using MiguelHincapieC response, This is what worked for me:
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());

Hope it helps :).


If $X$ and $Y$ are uncorrelated random variables, then under what condition is $E[X \mid Y] \approx E[X]?$

Question: Suppose $X$ and $Y$ are real random variables that are uncorrelated. Now, uncorrelated does not imply independence, so $E[X \mid Y] \ne E[X]$.
However, can they be said to be approximately equal? If so, under what conditions does that approximation hold? (I realize that the equality is exact when $X,Y$ is a multivariate Gaussian, but I want to know more generally when the equality can be approximated.)
As a bonus, is it possible to do an expansion of $E[X \mid Y]$ that looks like "$E[X] + $higher order terms", so we can see explicitly when those higher order terms can be said to be negligible? Let's assume that $p(X \cap Y)$ is continuous and infinitely differentiable.
Comment: @whuber I see you what you mean. Yes, correlation is shift invariant while expectations are not. Thank you for clarifying what you were getting at.
Comment: Correlation tells you absolutely nothing about expectations.
Comment: @whuber Are you claiming that they are mutually independent? Or that no proven propositions/theorems/lemmas come to mind? Or something else?
Comment: Consider $X=(Y-\mu_Y)^2$ for $Y$ symmetrically distributed with nonzero variance and  finite third moment for one example. $\text{Cov}(X,Y) = 0$ but $E(Y|X)$ could be very different from $E(Y)$. Five of the ten examples here: https://i.stack.imgur.com/Akcli.png show various of the many ways that $E(Y|X)$ may potentially differ  from $E(Y)$ -- in some cases by a lot. Indeed it may well be the case that the two are never close to equal for any $x$
Comment: @Galen Correlation gives zero information about expectations.  Proof: the correlation of $(X,Y)$ and the correlation of $(X+\mu,Y)$ are the same for all constants $\mu.$
Comment: $E[X\mid Y]$ is a _random variable_ that is a function of $Y$ (say $g(Y)$) whereas $E[X]$ is a constant. So, $E[X\mid Y] = g(Y)$ should be a random variable with _very_ small variance so that its value is close to the _mean_ of $g(Y)$. The law of iterated expectations tells us that $$E[g(Y)] = E[E[X\mid Y]] = E[X]$$ and so we know that the mean of $g(Y)$ is indeed $E[X]$.
Answer: One situation where this is interestingly almost true is when $X$ and $Y$ are both projections from the same high-dimensional distribution, ie, $X=a^TZ$, $Y=b^TZ$ for high-dimensional $Z$.  Hall & Li (and earlier work by various people) showed that for 'most' distributions for $Z$ on a high-dimensional sphere and most $a,b$, $E[X|Y]$ is approximately linear in Y and so if they are uncorrelated they are close to independent.
The result makes sense, because $X$ and $Y$ will be approximately bivariate Gaussian by the CLT, but actually pinning down the error bounds takes work.
This question was motivated by the sliced inverse regression method of Duan and Li, where you regress $X$ on $Y$ to learn about $Y|X$
Answer: No, they cannot be said to be approximately equal in general unless they are exactly equal.   To see this, consider:
$$\mathbb{E}[X|Y] - \mathbb{E}[X] = \delta$$
for any $\delta$ that is near the boundary of what you consider to be "approximately equal".  Now, multiply $X$ by $10^9$:
$$\mathbb{E}[10^9X|Y] - \mathbb{E}[10^9X] = 10^9\mathbb{E}[X|Y] - 10^9\mathbb{E}[X] = 10^9\delta$$
and now $\delta$ is no longer in the range of "approximately equal" values.
You should be able to see this also prevents the expansion of $E[X|Y]$ from giving you any useful information in this regard; basically, one way or another, you'd probably need to actually compute the conditional and unconditional expectations and compare them to determine whether the difference is ignorable in your application, or perhaps compute bounds on the difference and use those as a decision tool instead.
Comment: Thanks for the answer. But when I say "under what conditions", I don't *only* mean conditions on the probability distribution that allows the approximation to apply for all values of $X$. I would also accept conditions on the region of $X$ itself, such as "for small $|X|$...". But I'll upvote because this is a good answer to the former specification of "conditions".
Comment: For example, it's true for Gaussian distribution that $E[X \mid Y] = E[X]$ if they are uncorrelated. Intuitively, I feel like if there was some distribution that was *close* to a Gaussian in form (like, a distribution whose expansion is equal to a Gaussian in first order, but diverges for large X,Y) then the equality would be *close* to true, but would fall off quickly as $X$ or $Y$ gets large. Is my intuition right, and if so, could we state something like that formally?
Comment: Hmmm... that's a much more interesting explanation of your question than I had previously understood it to be.   I may wind up deleting my answer, which doesn't address your actual question.  Could you put a statement like that in the question itself, so new readers don't miss it?
Answer:
Now, uncorrelated does not imply independence, so $E[X \mid Y] \ne E[X]$.

I find the conclusion 'so $E[X \mid Y] \ne E[X]$' in this sentence a bit confusing.

If variables are uncorrelated then it does not follow $E[X \mid Y] \ne E[X]$.
In addition independence does neither mean $E[X \mid Y] \ne E[X]$. You can have independence while $E[X \mid Y] = E[X]$

If you have zero correlation then you can still have dependence, and also while $E[X \vert Y] = E[X]$
Example: Let $X \sim N(0,1)$ and $Y = N(0,\sigma^2 = X^2)$

If you have zero correlation then

then this means that you have a slope of zero for a line that fits $E[Y|X]$ as function of $X$ or $E[X|Y]$ as function of $Y$.

But $E[Y|X]$ can have all sorts of deviations from the straight line.

Example: let $X \sim N(0,1)$ and $Z = N(X^2,1)$

However, can they be said to be approximately equal?

In many situations, you have zero correlation, but still dependence due to heterogeneity as in the first example. There can be dependence but still $E[Y|X] = E[Y]$.
But it is difficult to give general conditions for this. The condition for $E[Y|X] = E[Y]$ is that $E[Y|X] = E[Y]$.


assessing which random sample agrees more with a preferred ranking

Question: I am not a mathematician or a statistician. But, I think the question I have is related to statistics. I will start with a made up example.
If I can grade apples into,say four grades from 1 to 4, one being the best and 4 being the worst. Now, I get two random samples of apples from two farms. The first sample has grade-1 40%, grade-2 20%, grade-3 30% and grade-4 10%. The second sample has grade-1 36%, grade-2 36%, grade-3 20% and grade-4 8%. Is there a summary statistic that can say which of the two samples agree best with the preferred ranking? The preference is to have more of the better grades.
I thought about using a weighted sum of proportions. The weight I thought was the inverse of the numerical value of the rank. This metric will have a value of one if all of the sample is grade 1 (the most preferred situation) and goes down towards zero as the sample consists less of the preferred ranks and more of the lesser preferred ranks.
The second metric I thought of is (Spearman) rank correlation between the inverse of the numerical value of the ranks and the percentages of each rank.
I will be grateful if anyone can tell me if a statistic exists that can help me chose between the two samples as having greater agreement with the ranking. If there are no such statistics, your valuable comments on the appropriateness of the two metrics I have considered and their mathematical properties in the context of example will be greatly appreciated.
Now, the real problem is related to comparison of different keyboard layouts in a language. I can arrive at a subjective ranking of various keys. From a corpus, I can find what frequency of character falls on these keys for each of the layouts. I want to be able to tell which of the layouts agree more with my ranking of keys.
Thanks,
Ajith
Answer: Yes, it's just expected value. If you multiply the ranks by the frequencies (%) and sum it, they would be weighted by how popular they are. You would get the average rank, so the lower the better.
For a different perspective, the weighted average is calculated as a dot product between the values and the weights. Dot product is proportional to cosine similarity and is itself a measure of similarity. So it does measure how "correlated" weights and values are.
See also Why is the expected value named so?
Comment: That simple! Thanks for your answer.


Real values of $x$ in $(1+2^x)\cdot (1+8^x)\cdot (1+9^x)^2 = (1+6^x)^4$

Question:
$(1)$ Real values of $x$ in $2^x+3^{-x}+4^{-x}+6^x = 4$
$(2)$ Real values of $x$ in $(1+2^x)\cdot (1+8^x)\cdot (1+9^x)^2 = (1+6^x)^4$

My Try: For First one:: Here $2^x,3^x,4^{-x},6^{-x}>0$
So Using A.M $\geq$ G.M
We get $$2^x+\frac{1}{4^x}\geq 2\sqrt{2^{-x}}$$ and $$6^x+\frac{1}{3^x}\geq 2\sqrt{2^{x}}$$
So $$2^x+3^{-x}+4^{-x}+6^x\geq 2\sqrt{2^{-x}}+2\sqrt{2^{x}}\geq 2\cdot 2$$
and equality hold when $$2^{x}=3^{-x}=4^{-x}=6^x$$ and $$\sqrt{2^{x}}=\sqrt{2^{-x}}$$
So we get $x=0$ is only one solution.
$(2)$ Using Cauchy Schwarz Inequality Using SchrodingersCat Hint
$\left[1+(\sqrt{2^x})^2\right]\cdot \left[1+\left(\sqrt{8^x}\right)^2\right]\geq (1+2^{2x})^2$
But  I did not understand How can I solve it after that .
Help me Thanks.
Answer: HINT: Think about using Cauchy-Schwarz Inequality.
For $(1,2^\frac{x}{2})$ and $(1,3^x)$,
by Cauchy-Schwarz Inequality, we can say
$$(1+2^x)(1+9^x)\geq (1+2^\frac{x}{2}\cdot 3^x)^2$$
For $(1,2^\frac{3x}{2})$ and $(1,3^x)$,
by Cauchy-Schwarz Inequality, we can say
$$(1+8^x)(1+9^x)\geq (1+2^\frac{3x}{2}\cdot 3^x)^2$$
So multiplying the relations, we get $$(1+2^x)(1+8^x)(1+9^x)^2\geq (1+2^\frac{x}{2}\cdot 3^x)^2\cdot (1+2^\frac{3x}{2}\cdot 3^x)^2$$
Now carefully use Cauchy-Schwarz Inequality again on the Right hand side of inequality.
$$(1+2^\frac{x}{2}\cdot 3^x)\cdot (1+2^\frac{3x}{2}\cdot 3^x)\geq (1+6^x)^2$$
$$(1+2^\frac{x}{2}\cdot 3^x)^2\cdot (1+2^\frac{3x}{2}\cdot 3^x)^2\geq (1+6^x)^4$$
Hence, we get that
$$(1+2^x)(1+8^x)(1+9^x)^2\geq (1+6^x)^4$$
The result is for you to make.
Comment: Thanks SchrodingersCat I have used Cauchy-Schwartz Inequality, But how can i solve it after that
Comment: @juantheron I have completed my answer. All the typos have been corrected.


Next 14, Axios Interceptors for Refresh Token using next-auth - New Problem

Question: I'm currently facing an issue while trying to implement an Axios interceptor for handling refresh tokens in a Next.js 14 application using Next-Auth. The problem seems to have surfaced after the latest update of Next.js.
Issue Description:
The issue arises when I attempt to create an interceptor and utilize useSession from Next-Auth to retrieve access and refresh tokens for the interceptor. As useSession is a hook, I understand it can only be used in client-side components, but I'm at a loss for how to implement this functionality effectively.
I was following a tutorial (link of the video), where the implementation is exactly as I described, yet I'm encountering problems.
Screenshots for Reference:
My codeThe error
Specific Questions:
How can I effectively implement an Axios interceptor with Next-Auth in a Next.js 14 application, especially considering the constraints of using hooks like useSession?
Are there any known issues or compatibility problems with Next.js 14 that might be causing this issue?
Any guidance, code snippets, or references to similar implementations would be greatly appreciated. Thank you in advance for your help!
Following the Video Tutorial: I've closely followed the instructions in the referenced video, expecting it to work with Next.js 14 and Next-Auth. This involved setting up the Axios interceptor and using useSession to retrieve the tokens.
Creating the Interceptor: I set up an Axios interceptor within my application, intending to use it for refreshing tokens.
Using useSession: I tried to use the useSession hook to access the current session and retrieve the tokens needed for the interceptor.
Expected Outcome:
I expected that by following these steps, the Axios interceptor would seamlessly integrate with Next-Auth to handle token refresh scenarios. Specifically, I anticipated that the interceptor would:
Detect when an access token is expired.
Use the refresh token to obtain a new access token.
Retry the original request with the new access token.
Actual Outcome:
However, I'm encountering issues likely due to the nature of hooks and their usage outside of React components, or possibly due to some recent changes in Next.js 14. The specific problems I'm facing are:
Difficulty in correctly implementing the useSession hook within the Axios interceptor setup.
Uncertainties about the proper way to access and refresh tokens in this context.
Answer: I had same error.
The problem was that the useAxiosAuth() method was called in neither React Components nor Custom Hook (which cause Invalid Hook Error).
In addition, if you see the tutorial video(14:37~), the tutor calls useAxiosAuth() method in HomePage component.
Thus, the error does not relate to lates version up of next js and there is no problems in your useAxiosAuth.ts.


Implementing a custom SortedMap in Scala

Question: Somehow, I can't seem to correctly implement a SortedMap. Here's a minimal (non-)working example:
class MyMap[A](t: Map[Long, A]) extends SortedMap[Long, A]  {
  protected val internalMap = TreeMap(t.toArray: _*)

  def -(key: Long) = MyMap(internalMap - key)
  def get(key: Long) = internalMap.get(key)
  def rangeImpl(from: Option[Long], until: Option[Long]) = TreeMap(internalMap.rangeImpl(from, until))
  def iterator = internalMap.iterator
  def ordering = internalMap.ordering
}

But, whatever I pass into the MyMap constructor, calling, for example, its size, always returns 0.

Addendum: I just copy-pasted the code to a new project, and it worked 8-\ Anyway, let me change the question in order to make it useful: is this the correct way to extend SortedMap?
Comment: To answer your addendum with a question: Since `TreeMap` implements `SortedMap`, why do you need to wrap it in `MyMap`? Why not just use a `TreeMap` directly?

(Just to confirm: We are talking about `scala.collection.immutable.TreeMap`, right?)
Comment: @Chris: That was a minimal working example :-) In real-life, I want to re-implement my own functions for a different kind of SortedMap.
Comment: And yes, we are talking about `scala.collection.immutable.SortedMap`.
Answer: After adding a couple of missing methods to make it compile, your code worked fine for me:
class MyMap[A](t: Map[Long, A]) extends SortedMap[Long, A]  {
  protected val internalMap = TreeMap(t.toArray: _*)
  def +[B1 >: A](kv: (Long, B1)) = new MyMap(internalMap + kv)
  def -(key: Long) = new MyMap(internalMap - key)
  def get(key: Long) = internalMap.get(key)
  def rangeImpl(from: Option[Long], until: Option[Long]) = internalMap.rangeImpl(from, until)
  def iterator = internalMap.iterator
  def ordering = internalMap.ordering
}

From the REPL:
scala> t
res5: Map[Long,String] = Map(123 -> abc, 456 -> def)

scala> new MyMap(t)
res6: MyMap[String] = Map(123 -> abc, 456 -> def)

scala> res6.size
res7: Int = 2

Am I missing something?


Como comunicar entre classes?

Question: Estou iniciando no JavaFX e estou com dúvidas.
A classe principal cria um HBox com um botão. Esse botão tem a ação de criar uma TableView no Center da bdPrincipal. Só que estão em classes/packages diferentes.
Qual a melhor maneira de buscar a bdPrincipal pra adicionar a addTabela()?
BorderPane bpPrincipal;
public void start(Stage primaryStage) {
        bpPrincipal = new BorderPane();
        bpPrincipal.setLeft(Menu.addMenu());
        scPrincipal = new Scene(bpPrincipal);
        primaryStage.setScene(scPrincipal);
        primaryStage.centerOnScreen();
        primaryStage.setHeight(Screen.getPrimary().getVisualBounds().getHeight());
        primaryStage.setWidth(Screen.getPrimary().getVisualBounds().getWidth());
        primaryStage.show();
    }

public class Menu {
    public static HBox addMenu() {

        HBox hbox = new HBox();
        hbox.setPadding(new Insets(15, 12, 15, 12));
        hbox.setSpacing(20);
        hbox.setStyle("-fx-background-color: #336699;");

        Button btnListar = new Button("Listar");
        btnListar.setPrefSize(100, 20);
        btnListar.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent evento) {
                  GestorFX.bpPrincipal.setCenter(addTabela());
            }
        });
        hbox.getChildren().addAll(btnListar);

        return hbox;
    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private static TableView addTabela()
    {
        TableColumn colCodigo = new TableColumn();
        colCodigo.setText("Código");
        colCodigo.setMinWidth(150);
        colCodigo.setCellValueFactory(new PropertyValueFactory("clienteCodigo"));

        TableColumn colFantasia = new TableColumn();
        colFantasia.setText("Nome Fantasia");
        colFantasia.setMinWidth(450);
        colFantasia.setCellValueFactory(new PropertyValueFactory("clienteFantasia"));

        TableColumn colRazao = new TableColumn();
        colRazao.setText("Razão Social");
        colRazao.setMinWidth(450);
        colRazao.setCellValueFactory(new PropertyValueFactory("clienteRazao"));

        TableView tabela = new TableView();
        tabela.setItems(Negocio.Cliente.ListaCompleta());
        tabela.getColumns().addAll(colCodigo, colFantasia, colRazao);

        return tabela;
    }
}

Comment: O seu título não corresponde com a sua dúvida. Na verdade você quer saber como fazer as classes se comunicarem, certo? Além disso você também tem dúvida na criação do TableView? Por exemplo, se eles estivessem na mesma classe você saberia resolver o problema?
Comment: Sim, talvez a minha dúvida possa ser desmembrada. Vou alterar o título.
Comment: Ok. Só nao entendi uma coisa, você sabe então criar o TableView?
Comment: Sim, o TableView acredito que saiba, porém, a comunicação das classes é que estou com dificuldades.
Answer: Basicamente você deve importar o pacote da outra classe e criar um objeto dela, sendo assim você conseguirá acessar seus métodos públicos.
Supondo que o seu primeiro código que possui um BorderPane bpPrincipal; esteja no seguinte arquivo:

src\com\pacote\Paineis.java

Adicione o seguinte import dentro da sua classe Menu:
Menu.java
import com.pacote.Paineis;

Já é possível enxergar a classe, agora crie um objeto da classe Paineis, e acesse o método que desejar dessa classe. Exemplo:
Menu.java
Paineis paineis = new Paineis();
BorderPane bdPrincipal = paineis.getBpPrincipal(); //pronto

Agora use bdPrincipal como desejar, por exemplo adicionando-o na tabela.
Não se esquece de criar um método que retorne o BorderPane da sua classe Paineis:
Paineis.java
public BorderPane getBpPrincipal() {
        return bpPrincipal;
}

Como comunicar entre classes?


Comportamento das diferentes formas de comparação em Java

Question: Se por exemplo eu tenho o código abaixo, eu estou comparando a referência dos objetos no caso ex1 e ex2 e não o objeto em si, correto?
Pessoa ex1 = new Pessoa();
Pessoa ex2 = new Pessoa();
if(ex1 == ex2)
{
    System.out.println("Igual");
}
else
{
    System.out.println("não é igual");
}

Aqui sempre é impresso que não é igual, sendo assim creio eu que estou comparando referências correto?

Minha outra dúvida é se isso é igual ao código acima que foi digitado:
Pessoa ex1 = new Pessoa();
Pessoa ex2 = new Pessoa();
if(ex1.equals(ex2))
{
    System.out.println("Igual");
}
else
{
    System.out.println("não é igual");
}

Comment: Perdoe o "anúncio" mas escrevi um post exatamente sobre esse assunto no blog. Ele é um pouco extenso para ser portado na íntegra para cá: http://a.accioly.7rtc.com/2011/05/java-vs-equals.html
Answer: Resposta :
Comparação utlizando : "==" versus "equals"
O que é o Heap?

O Heap é um local reservado e protegido da JVM (Java Virtual Machine) onde ficam alocados todos os objetos instanciados durante a execução de seu programa... cada um destes objetos possui um endereço de memoria onde está armazenado, e o único acesso a ele, é por via de uma referencia (armazenada fora do heap).... Esta referencia, também possui o endereço de memoria, tornando o seu acesso único e exclusivo a este objeto.

Quando você usa o operador "==" para comparar, você está comparando externa ao heap já
    a comparação utilizando "equals" seria o inverso do operador "==" que compara os objetos dentro do heap, ou seja, suas características.

Resumindo:

"==" ----> é usado para comparar dois objetos, verificando se os objetos referenciam ao mesmo lugar na memória.
"equals" ---> esse método é definido na classe Object, a partir do qual todas as classes ou é um descendente direto ou indireto. Por padrão , o método equals () se comporta o mesmo que o operador "==" mas, a classe String substitui(sobrescreve) o método equals () para comparar os caracteres em uma string e não os seus locais na memória.

Observação:

Além isso é ideal quando criamos um novo objeto, do tipo por exemplo, Pessoa(como você criou), sobrescrevermos o método "equals" herdado de Object, para podermos ver se as pessoas são realmente iguais. Um exemplo seria se sua classe Pessoa possuir os atributos idade e nome você pode sobrescrever o método equals assim:

public boolean equals(Pessoa p) {

      boolean igual = false;
      if ((this.nome.equals(p.getNome())) && (this.idade == p.getIdade()))
         igual = true;

      return igual;
   }

Referências de pesquisa:

Link Programmer Interview
Link Stack Overflow English
Link JavaFree
Answer: Quanto à primeira dúvida, você está correto.
Segunda:
Não necessariamente. Em Java o método Equals() sempre procura (ou pelo menos deveria, depende da implementação real) encontrar a comparação mais descritiva. Até pode em alguns casos comparar a referência, quando esta for a forma mais descritiva de comparar objetos. Mas a princípio a comparação de referência é evitada, quando possível.
O melhor exemplo é a comparação de strings. Duas strings idênticas mas em endereços diferentes retornam true quando usa-se Equals mas false quando usa-se == (isso é um pouco mais complicado que isto por causa do interning, mas isto é outro assunto).
Então para o seu caso específico, até seria a mesma coisa. A não ser que a implementação  do Equals especifica da classe Pessoa mude o comportamento padrão.
Por padrão o Java, através da classe Object onde todas as outras classes são derivadas direta ou indiretamente, tem uma implementação do Equals que compara as referências.
Mas seria adequado que esta classe Pessoa sobrepusesse a implementação padrão com outra que fosse mais descritiva. Que pegasse algum(ns) campo(s) chave(s) e os comparasse para determinar se é a mesma identidade ou não. Estes campos precisariam formar uma chave única, ou seja, nenhuma outra instância da classe poderia ser igual a outra.
Existe esta implementação? Só você pode ver isto, nós não estamos vendo. Você tem que ver nesta classe se há esta implementação e como ela está procedendo.
No comentário do Anthony Acciolly acima tem um link para o blog dele com um bom exemplo de implementação usando o CPF como identificador único de identidade da pessoa. É uma boa forma de tornar o Equals da classe Pessoa mais relevante. Note que não tem nada de extraordinariamente errado deixar comparar as referências neste caso. Mas não é o mais intuitivo. O ideal é fazer esta comparação ter uma semântica própria. Veja como ele fez a implementação do Equals para a classe pensando nas diversas situações do objeto:
@Override
public boolean equals(Object obj) {
    // Um objeto é sempre igual a ele mesmo
    if (this == obj) {
        return true;
    }
    // Um objeto nunca deve ser igual a null
    if (obj == null) {
        return false;
    }
    /* Uma pessoa só pode ser igual a outra pessoa.
     * Caso uma pessoa possa ser igual a uma de suas subclasses
     * use !(obj instanceof Pessoa)
     */
    if (getClass() != obj.getClass()) {
        return false;
    }
    // Converte a referencia para uma pessoa
    final Pessoa other = (Pessoa) obj;
    // Duas pessoas só podem ser comparadas se possuem CPF
    if (this.cpf == null || other.cpf == null) {
        return false;
    }
    // Duas pessoas são iguais se possuem o mesmo CPF
    return this.cpf.equals(other.cpf);
}

Coloquei no GitHub para referência futura.
Veja os detalhes da implementação no blog dele (ele gentilmente cedeu este exemplo).
Eu falo disso em mais detalhes nessa resposta. Ela é sobre o C# e tem algumas diferenças para o Java, mas ali explico melhor essa coisa de identidade. Também falo um pouco de identidade aqui nessa resposta.
Comment: Eu tenho duas pequenas críticas em relação a esse exemplo de `equals`: 1) se uma pessoa não tiver um CPF, ela será considerada *diferente de si própria*... Ajuda no começo do `equals` colocar um "teste rápido" `if( this == obj )`, que não só previne casos como esse como potencialmente melhora a performance global. 2) Ao comparar as classes, esse código está fechando esse objeto à possibilidade de extensão - ninguém poderia por exemplo criar uma subclasse de `Pessoa` que ainda pudesse ser comparada a ela por igualdade. Na minha opinião, seria preferível fazer `if( !(obj instanceof Pessoa) )`.
Comment: @mgibsonbr. Sobre a comparação com a própria referência eu concordo contigo (e de fato, alguns IDES geram o código dessa maneira). Quanto a fechar a possibilidade de extensão, isso foi proposital, você nem sempre quer que um objeto de uma subclasse seja igual ao objeto da própria classe.
Comment: @AnthonyAccioly Eu imaginei que fosse proposital, mas quis chamar a atenção ao fato de qualquer forma. Há prós e contras em se fazer dessa maneira, acho até que valeria uma pergunta separada sobre o assunto... :P
Comment: Só para mencionar algo que esqueci no blog. Tanto [Guava](https://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained#equals) quanto [Apache Commons](https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html) possuem facilitadores para implementar o método `equals`.
Comment: @mgibsonbr, perdão por tumultuar os comentários mas atualizei o exemplo no blog conforme suas sugestões (aproveitei para linkar para cá ;). Se vocês quiserem atualizar o exemplo por aqui fiquem a vontade.
Comment: @mgibsonbr o exemplo não é meu :P Concordo com todos os pontos levantados. É claro que falta um pouco de contexto. Pode ser que se não tiver CPF é uma pessoa inválida, então uma comparação deveria ser falsa sempre. Talvez deveria ser uma exceção se fosse isso, mas sei lá, é só especulação. Talvez a intenção seja que a classe não deva ser estendida.
Comment: Este site não é fantástico? Todos aprendemos um pouco mais.
Comment: @AnthonyAccioly não está tumultuando nada não, pelo contrário, está contribuindo positivamente.
Answer: Por padrão, toda classe que não declare extensão de outra classe, por baixo dos panos, ela extenderá java.lang.Object. Em seu objeto Pessoa, já que você não sobrescreveu o método equals que ele herdou de java.lang.Object, a comparação será feita assim (código fonte do método equals de java.lang.Object):
public boolean equals(Object obj) {
    return (this == obj);
}

Se você quiser mudar o comportamento de equals (o que é perfeitamente normal para obedecer um contrato de uma possível entidade por exemplo), geralmente faríamos (resumidamente):
public boolean equals(Object obj) {
    return this.id == ((Pessoa) obj).id;
}

Aqui você estaria falando que uma Pessoa só é igual a outra SE os id forem iguais.
Answer: "Aqui sempre é impresso que não é igual, sendo assim creio eu que estou comparando referências correto?"
Correto.
"Minha outra dúvida é se isso é igual ao código acima que foi digitado"
Não é igual. Você mesmo pode definir qual é o critério que torna duas pessoas "iguais" e implementar esse critério no método public boolean equals(Object o) da mesma classe que, com o auxílio da anotação @Override, sobrescreverá o método herdado da classe Object. Exemplo: duas pessoas são iguais se o CPF delas são iguais. Existem alguns critérios que devem ser seguidos (contratos), principalmente com o método compareTo da interface Comparable. Aconselho dar uma olhada nesses contratos também, principalmente para seguir os padrões da comunidade e tornar seu código mais robusto.


Laravel Form Request several validation rules of same type

Question: I have a Form Request Validation file, which checks is an input field not empty ('required') and then if it's value exists in the database in table 'table1'.
I want to add a 2nd exist rule to the same input field, and return a message if 2nd exist validation rule is not met:
public function rules()
    {
        return [
            'tour' => 'required|exists:table1,id|//another exists: table2, id//'
        ];
    }

        public function messages()
    {
        return [
            'tour.required' => 'Message 1!',
            'tour.exists:table1,id' => 'Message 2!',
            'tour.//another exists: table2, id//' => 'Message 3!'
        ];
}

Right now only 2nd rule works. Any ideas how-to?:)
thank you all in advance!
Answer: In this situation you can write your custom validation rule. For example, let create a class called CustomValidator (place him in folder like 'App\Services' or another that you want).
CustomValidator.php

namespace App\Services;

class CustomValidator {
    public function myexistsValidate($attribute, $value, $parameters, $validator) {
        for ($i = 0; $i < count($parameters); $i += 2) {
            $count = \DB::table($parameters[$i])->where($parameters[$i + 1], $value)->count();
            if (!$count) {
                return false;
            }
        }

        return true;
    }
}

We created a new rule called myexists. This rule can accept pair of paramaters divided by commas lile this: 'myexists:table1,searchfield1,table2,searchfield2...'`
I wrote very simple example of implementation of this rule, ofc you can add some approach or another validations...
Next you must register your own validation rule in AppServiceProvider in method boot (string that you place as a first parameter will be a name of new rule):

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use \Validator;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Validator::extend('myexists', 'App\Services\CustomValidator@myexistsValidate');
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Next in your FormRequest place code like this:
public function rules()
{
    $rules = [
        'id' => 'myexists:tableName1,field1,tableName2,field2',
    ];
    return $rules;
}

You can add a validation message for this rule, for example in your lang\en\validation.php file 'myexists' => 'Field :attribute must exists in all described tables.'
Comment: :) maybe you can help me with this also: https://stackoverflow.com/questions/44886845/laravel-form-request-array-validation-custom-rules


DefaultListModel.clear errors

Question: I'm trying to display a list of items and, when the user clicks on an item, to clear the list and display another list.
If I run this and click on the first entry on the displayed list, the program dies with a long trail of runtime exceptions.  If I remove the clear() line (commented below), it runs fine. Adding try/catch didn't reveal any information useful to me.  Apologies for the long code, but I couldn't figure out how to shorten and still generate the errors.
What at I doing wrong?
import java.util.*;

import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class ListGui extends JPanel implements ListSelectionListener {

    private static JList list;
    private static DefaultListModel listModel = new DefaultListModel();

    public ListGui() {
        super(new BorderLayout());
        list = new JList(listModel);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.addListSelectionListener(this);
        JScrollPane listScrollPane = new JScrollPane(list);
        add(listScrollPane, BorderLayout.CENTER);
    }

    public static void Populate(List<String> lines) {
        listModel.clear();
        for(String line : lines) {
            listModel.addElement(line);
        }
    }

    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting() == false) {
            List<String> out = new ArrayList<String>();
            out.add("three");
            out.add("four");
            Populate(out);
        }
    }
}

public class TestClear {

    static JComponent newContentPane = new ListGui();

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("toast");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(newContentPane);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        List<String> out = new ArrayList<String>();

        createAndShowGUI();

        out.add("one");
        out.add("two");
        ListGui.Populate(out);
    }
}

Comment: Can you post the exception thrown please?
Comment: When I ran my original code, the exception was "-1"  I'm this running this shortened version from a windows command line which only captures about 100 lines and it's scrolling off the screen.  What's the best way to record?
Comment: Use command redirection to write the console output or error stream to a file: see http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
Answer:
I'm trying to display a list of items and, when the user clicks on an item, to clear the list and display another list.

That doesn't sound like the best design to me. The selection will change whenever you click on an item or when you use the arrow keys to move up or down the list. I'm sure for users that like to use the keyboard you don't want the list to change every time you use an arrow key.
The normal design would be to invoke an Action on the list on a "double click" or when the user users "Enter" from the keboard. This is easily implemente using the List Action concept.
However, if you really do want to update the list on every selection then I would use code like:
list.removeListSelectionListener( this );
populate(...);
list.addListSelectionListener(this);

Comment: Invoking an action on double click or enter is on my to do list.
Answer: The problem is that you are calling Populate() in valueChanged() which triggers valueChanged() and hence the stackoverflow.
The simplest solution is to have a flag to prevent reentry.
 boolean busy = false;
    public void valueChanged(ListSelectionEvent e) {

        if (e.getValueIsAdjusting() == false && !busy) {
            busy = true;
            List<String> out = new ArrayList<String>();
            out.add("three");
            out.add("four");
            Populate(out);
            busy = false;
        }
    }

If your code could be accessed by multiple threads, you should be looking into ReentrantLock
Comment: That makes sense, but why would it only die when I click on the first element and not die when I remove clear?  I'll try the busy flag and report back.
Comment: Yep, that works. I hadn't realized the program changing the list would trigger valueChanged().
Comment: My two cents worth. I don't like the "busy flag" approach because now you have code in three different places in your class. 1) you need to define the variable, 2) you need to reset it in the valueChanged() method and 3) you need to test it in the populate() method.
Comment: I'm more or less indifferent between the two approaches.  Removing and adding back the listener isn't that much less effort than removing and setting a busy flag.  Would adding a listener be a more "expensive" activity than just setting a variable?  It seems closer to an OS operation, which typically takes more resources.
Comment: The comment is about maintenance of the code. Its easier to maintain and understand code when all the logic for a given piece of functionality is contained in one place rather than trying to track it down over 3 different places to find out where/when the boolen variable is set and reset. In general boolean variables should be avoided if possible when the related functionality is contained in multiple different methods.
Comment: It's clearly easier to maintain when everything is in one place, but that doesn't seem to apply here.  The flag is set and reset within a few lines, and could be rewritten to just surround the one line Populate()

DefaultListModel.clear errors


How to Override OG Group Owner Permissions for view/edit group content?

Question: So I have a group content type called student portfolio, which is managed by the student. Then I have a group content node type called endorsement that can be written by professors that are group members.
Question 1: How do I prevent students from editing endorsements? There is no checkbox anywhere in my configuration that says the student role can edit endorsement. Also, on my group permissions, for Members, only "Edit own Endorsement content" is checked, but the student can still edit, which seems like a bug if you ask me.
I'm thinking I'll need some sort of hook_menu_local_tasks_alter() code, but just wanted to verify.
Question 2: How do I prevent the student from even viewing a group content page type? (This is a different project.) On the group page, I think this is just a simple matter of setting the permission on the pane, but I also don't want students to be able to view the stand-alone page.
Answer: Because group owners are considered the equivalent of "Super administrator" (user 1) of their group AND group content, which I happen to totally disagree with, this wound up being solved using hook_node_access() as follows for Question 1:
/**
 * Implements hook_node_access().
 *
 * Runs every time a user tries to edit an endorsement
 */
function icme_admin_node_access($node, $op, $account) {
  if ($node->type == 'endoresment' && $op == 'update') {

    // Does the user explicitly have create/edit endorsement content access?
    // By default, the OG module provides group owners add/edit/delete access
    // to all group content
    $ua_create = user_access('create endoresment content');
    $ua_edit = user_access('edit own endoresment content');
    if (!$ua_create && !$ua_edit) {
      // Show access denied message, and, interestingly enough,
      // also sets the permission for the edit link.
      return NODE_ACCESS_DENY;
    }
  }
}

Question 2 is similar, but just need to change $op == 'update' to $op == 'view'.
I'm curious to see if anyone posts a better solution (other than fixing the OG module).
Answer: As @Webdrips said

'group owners are considered the equivalent of "Super administrator"
  (user 1) of their group AND group content'

However, this behavior may be controlled via an OG setting. Navigate to 'admin/config/group/settings' and UN-check option 'Group manager full permissions'.
On a side note, in my opinion this is a poor literal selection for the setting, as 'group manager' can be confused with the 'administrator member' role that manages the group. I've spent a few hours on a similar bug, and I had to dive into the code before I understood that this setting actually refers to the group author/creator.


"Login to your account" form block not showing on frontpage when "View published content" is disabled for anonymous

Question: I am new to Drupal 8 but not to Drupal ;
In Drupal 8, I enabled the "Login to your account" block in one of my regions :

But on the homepage, the block is not showing in the correct region, instead the login form appears in the "Main content" block (but on 404 pages, for instance, it works fine).
Please note that as it is a private website, I disabled the "View published content" for anonymous users, may it be related ? Maybe it triggers the login form in the main content block, thus deactivating the one in the other region ?
How to set up the login form block in the correct region, on my homepage ? Do I have to render the form in a template hook and then pass it to html.twig ou region.twig ?
Thanks in advance for your answers
For the comment reply :
There is nothing fancy with the theme, this is the generic page template, and the theme is quite empty, derivated from the Stable theme, in which I didn't find any noisy tampering. My gues is that the Core is rendering the form, thus hiding the block.
Comment: Most likely an issue with your templates. (There might be a different page template for the front page/an if statement in your generic page template that is printing these regions on a different position of your markup.) Enable theme debugging, locate the templates in use and check where the banner region is printed. If this wasn't the cause, check if your theme's preprocessing is tampering with the block region blocks.
Answer: Drupal core does not support a good way to have a site that requires the user to log in.
The Require Login contrib module adds this functionality.  It also allows for public sections of the site (e.g. a login landing page, links to how to get help, and the like.
Answer: Digging into the user module, I found out that the function blockAccess inside core/modules/user/src/Plugin/Block/UserLoginBlock.php hides the block on the user.login page. Too bad, I had no homepage defined, so the default page was /user, and so the default route was ... user.login.
I guess I know what to do now: define a proper homepage, which will return a regular "403" that show the block.
Thanks again for your replies.


Cannot run anaconda

Question: I just installed anaconda and I have udpated the PATH variable.
However, I cannot run any conda related commands.
Every time I run a command starting with "conda" I get the following error.
Can anyone help?
I am using macOs High Sierra 10.13.6.
<code>Traceback (most recent call last):
  File "/anaconda3/lib/python3.6/site-packages/conda/common/path.py", line 18, in <module>
from urllib.request import url2pathname
  File "/anaconda3/lib/python3.6/urllib/request.py", line 2585, in <module>
from _scproxy import _get_proxy_settings, _get_proxies
ImportError: dlopen(/anaconda3/lib/python3.6/lib-dynload/_scproxy.cpython-36m-darwin.so, 2): Symbol not found: __cg_jpeg_resync_to_restart
  Referenced from: /System/Library/Frameworks/ImageIO.framework/Versions/A/ImageIO
  Expected in: /anaconda3/lib/libJPEG.dylib
 in /System/Library/Frameworks/ImageIO.framework/Versions/A/ImageIO

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/anaconda3/bin/conda", line 11, in <module>
sys.exit(main())
  File "/anaconda3/lib/python3.6/site-packages/conda/cli/main.py", line 112, in main
from ..exceptions import conda_exception_handler
  File "/anaconda3/lib/python3.6/site-packages/conda/exceptions.py", line 18, in <module>
from .common.io import timeout
  File "/anaconda3/lib/python3.6/site-packages/conda/common/io.py", line 24, in <module>
from .path import expand
  File "/anaconda3/lib/python3.6/site-packages/conda/common/path.py", line 21, in <module>
from urllib import unquote, url2pathname  # NOQA
ImportError: cannot import name 'unquote'
</code>
Comment: It looks like [this](https://github.com/conda/conda/issues/7130)
Comment: @erip in that link the solution is to rename a library, in my case I have to rename "/System/Library/Frameworks/ImageIO.framework/Versions/A/ImageIO" . I am not sure this would be ideal!
Answer: I seem to recall something similar when I first ran Anaconda on my Mac as well. I believe I solved it by doing two things:

Uninstalling Anaconda (Link)
Reinstalling Anaconda (potentially in a different location, say, under your User home)

I think in the process of installation my PATH pointed finally to a different location than the Conda/Python install.
Comment: I cannot run those commands to uninstall. I get the same error!
Comment: Ah! Then you may have to do it the long way: https://nektony.com/how-to/uninstall-anaconda-on-a-mac

Cannot run anaconda


Call a controller method via button in Rails

Question: I want to create a button in views/companies/edit.html.haml for destroy_referrals method, but I can't get the button to work. To call the action on a button I tried to create a new route, but I am still receiving the error The action 'destroy_referrals' could not be found for CompaniesController
I created a destroy_referrals method in Admin::CompaniesController,
def destroy_referrals
    load_company
    @company.destroy_referrals
    flash[:notice] = 'Referrals deleted'
    redirect_to :action => :index
end

it manipulates the company.rb model to find the referrals from users with the same company_id and destroys them,
def destroy_referrals
    Referral.joins(:user).where("users.company_id = ?", self.id).destroy_all
end

Some things I've tried below...
routes.rb
post '/destroy_referrals' => 'admin/companies#destroy_referrals', :as => 'destroy_referrals'

views/companies/edit.html.haml
= button_to 'Destroy Referrals', destroy_referral_path

= button_to 'Destroy Referrals', admin_company_destroy_referral_path(@company)

Comment: Take a moment to read your question. Ask yourself what the words you're using mean, and whether there might be less ambiguous terms that would be more clear. E.g. "To call the action on a button I tried to create a new route". You don't "call" an "action", a "button" is a UI concept and also an HTML tag (neither of which have an explicitly defined "action"). Did you create a new route, or did you just try? How did you anticipate that would change things?
Comment: I can run the method through the console and it executes as expected. I am now trying to extend the functionality to the UI and having a button.
Comment: The error seems to indicate it's not going to the admin/companies controller.  Could you post the rest of your routes file?  Is the request being intercepted by another route?
Comment: @Swards the route needed to be `delete 'companies/:id/destroy_referrals' => 'companies#destroy_referrals', :as => 'destroy_referrals'`
Answer:
HTML links (not "buttons") aren't wired up to call "methods" directly.
The button_to method creates an HTML button, which behaves similarly to a link, but with different visual styles.
Ruby has methods, which are a common programing construct.
HTML links have an href attribute that a browser can follow by making a subsequent HTTP request to.
When a browser sends a request to your Rails application, the application uses your routes to determine how to handle that request.
The conventional way to handle a request in Rails is to route it to a controller action.
A RESTful request to /products/1 might, by convention, route to the show action on the ProductsController.
In Rails, an "action" is created by defining a method on the controller.
RESTful routes reflect the representational state transfer paradigm, involving reading, listing, creating, updating, and deleting records/objects.
To delete (or destroy) a record, RESTful convention would be to send a DELETE request to the Rails application, which would be routed to the relevant controller's destroy action, defined by the destroy method.
You can create an HTML link that results in a browser sending such a request using the link_to helper and specifying method: :delete in the parameters.
You can define a route instructing Rails to handle such a request using the built in "resourceful" routing: e.g. resources :products. Alternately, an explicit route can be defined: delete '/products/:id' => 'products#destroy'.

This all said, the error Rails is giving you is that it can't find the destroy_referrals method in CompaniesController. Defining methods in Admin::CompaniesController won't do anything to resolve this.
Comment: Thanks Corey, not the silver bullet I was hoping for but something for me to step back and reconsider.
Answer:
@Swards the route needed to be delete
  'companies/:id/destroy_referrals' => 'companies#destroy_referrals',
  :as => 'destroy_referrals'

I thought it might be a simple fix.  Do you still need the admin namespace?
Consider this, instead of creating a named route
namespace 'admin' do
  resources :companies do
    delete 'destroy_referrals', :on => :member, :as => 'destroy_referrals'
  end
end

And refer to it as admin_destroy_referrals_company_path
= button_to 'Destroy Referrals', admin_destroy_referrals_company_path(@company), :method => :delete

Comment: `admin_destroy_referrals_company_path` is a url_helper and only returns a URI; in order to send a `DELETE` request (or a mocked `POST` request using the `_method=delete` parameter) you need to specify the `method: :delete` option and have `rails_ujs.js` on the page as well.
Comment: That's right, method delete is needed on the button_to.


how can i solve Reverse for 'Add' with arguments '('',)' not found. 1 pattern(s) tried: ['agregar/(?P[0-9]+)/\\Z'] error?

Question: I'm doing a tutorial from django, and i getting this error when trying to add an href button, i use django 4.0.4 version and python 3.9 version.
Models.py
class Producto(models.Model):
    serie_producto = models.CharField(max_length=30)
    nombre = models.CharField(max_length=30)
    codigo = models.CharField(max_length=15)
    marca = models.CharField(max_length=30)
    precio = models.IntegerField()
    created_date = models.DateTimeField(default=timezone.now)

urls.py
...
urlpatterns = [
    ...
    path('agregar/<int:producto_id>/', agregar_producto, name="Add"),
    ...

]
template catalogo that causes te error. The message error highlights {% url 'Add' producto.id %}
{% for producto in response %}

{{producto.nombre}}

{{producto.marca}}

{{producto.precio}}

                Agregar al carrito

          {% endfor %}

view.py
from tienda.models import Producto
from tienda.carrito import Carrito
def catalogo(request):
    url = "http://127.0.0.1:8000/api/Producto/"
    response = requests.get(url, auth=('admin','duoc'))
    datos = response.json()
    return render(request, 'catalogo.html', {'response' : datos })

def agregar_producto(request, producto_id):
    carrito = Carrito(request)
    producto = Producto.objects.get(id=producto_id)
    carrito.agregar(producto)
    return redirect("Tienda")

The Problem
When i got to the catalogo template i get the before mentioned error, the api works perfectly when i dont use the {% url 'Add' producto.id %}, i think that is something with the id, cant read it maybe??, i dont know if is this. I have no idea how to solve this or what is wrong.
how can i solve this ?
any suggestion or help are welcome.
EDIT:
Complete error message from cmd:
File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\giova\Desktop\Pagina-Web-Django-con-Api\tienda\views.py", line 17, in catalogo
    return render(request, 'catalogo.html', {'response' : datos })
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\shortcuts.py", line 24, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\backends\django.py", line 62, in render
    return self.template.render(context)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 175, in render
    return self._render(context)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 167, in _render
    return self.nodelist.render(context)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 1000, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 1000, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 958, in render_annotated
    return self.render(context)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\defaulttags.py", line 238, in render
    nodelist.append(node.render_annotated(context))
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 958, in render_annotated
    return self.render(context)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\defaulttags.py", line 472, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\base.py", line 88, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 802, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'Add' with arguments '('',)' not found. 1 pattern(s) tried: ['agregar/(?P<producto_id>[0-9]+)/\\Z']

Comment: ready, i just added the complete error message and changed the title for a question, i hope that the question is right
Comment: Please show a [complete](https://meta.stackoverflow.com/questions/359146) error message, by copying and pasting, starting from the line that reads `Traceback (most recent call last):`, and formatting as code. Instead of trying to fit part of the error message into the title, please  use a title that summarizes and clearly asks the question. Finally, please make sure to **ask a question** - "any suggestion or help are welcome" [does not qualify](https://meta.stackoverflow.com/questions/284236).
Answer: ok guys i just fin the error to my problem, i going to post here for other people with the same problem.
In my serializer i dont specified the 'id'
class ProductoSerializer(serializers.HyperlinkedModelSerializer) :
class Meta:
    model = Producto
    fields = ['url', 'nombre', 'codigo', 'precio', 'serie_producto', 'marca']

soo, the solution is:
class ProductoSerializer(serializers.HyperlinkedModelSerializer) :
class Meta:
    model = Producto
    fields = ['id' #here ,'url', 'nombre', 'codigo', 'precio', 'serie_producto', 'marca']

Comment: Alternatively you can do `fields = '__all__'` to render all fields in the serializer.
Answer: django.urls.exceptions.NoReverseMatch: Reverse for 'Add' with arguments '('',)' not found. 1 pattern(s) tried: ['agregar/(?P<producto_id>[0-9]+)/\\Z']

This error tells you that the view with name 'Add' expects an integer argument, but you passed it an empty string ''. To debug this, you can add print(datos) before your render() call. Most likely you will see a list of JSON objects with at least one that has id: "".


Amp Creates Feedback When Using Output

Question: Title essentially sums up the problem. I have a VHT AV-RL-20R combo amp that I am trying to hook up to my computer for recording, but every time I plug in my amp via the output jack on the rear panel, both the internal speaker and my PC's audio monitors start giving some awful feedback and make it impossible to record anything. I thought it may have been the cable I was using at first, as it's one of the cheap-ish Real Tone cables used for the game Rocksmith, but after plugging it in directly to my electric guitar, it produces a very clean sound free of noise, which hopefully means I've managed to isolate the issue. Any advice is greatly appreciated, it's one of the only issues I haven't been able to solve yet.
Answer: The socket on the rear is a speaker output. I'm surprised you haven't blown a circuit yet.
You cannot even plug the headphone output directly into a computer's headphone input, the pins won't match. It's not really designed to do what you're trying to do with it. You'd have to get a cable made up to take one side of the stereo headphone output to the mic input of your computer's headset socket… & even that would really be too powerful for it.
Better to either mic it, or get a proper USB interface that can take line level.
Rather limited spec manual, for those so inclined.
Comment: *"1/4"-to-USB"* is an unusual beast. What is it supposed to do? Whose is it, where's it from, do you have a link?
Comment: It's the Real Tone cable bundled with the Rocksmith series of games, manufactured by Ubisoft (https://store.ubi.com/us/rocksmith-real-tone-cable/57c14e3cca1a643c1e8b4567.html?lang=en_US). It works fine when it's plugged directly into the guitar, but trying to use it through the headphone out on the amp produces no output in my DAW. Would investing in a proper interface and using a line input solve this issue, or would the amp still not connect?
Comment: the DAW/USB issue maybe should be a separate question. Hopefully @Tetsujin has made it clear that the output on the back is potentially dangerous current when plugged into the wrong thing. The headphone output is two-channel "Tip-Ring-Sleeve" and microphone-in is always/usually mono, so 1-channel "Tip-Ring". Tetsujin is saying to look for a "female TRS to 2x male TR splitter" adapter.
Comment: I'm glad you were able to explain that a bit more clearly, thank you. So my understanding of what you said is, it would be more practical of me to buy a proper audio interface and run the headphone output to a line input on the interface? The cable I have currently is a 1/4"-to-USB, if that helps at all. In case it isn't obvious, I'm better at the music side of things lol.
Comment: That *might* work with something like this - https://www.ebay.co.uk/itm/350808582237?hash=item51add2285d:g:Z~QAAOSwpDdVcEyd - stereo plug to two mono sockets. Plug your existing cable to one or other of the sockets - BUT it's going to be too loud for it, so you are really going to have to start at minimum volume & see what it will take before distortion. It might be noisy too.
Comment: I think I may be a bit confused. The cable I have currently only has a 1/4" jack and a USB end. How would I connect it to the cable you listed?
Comment: It goes in either of the two sockets on that adapter. Headphones need both left & right, but I'm assuming the amp itself is just sending dual mono.
Answer: The best way to record guitar using the equipment you have would be connecting the guitar directly to computer using the RealTone cable and an amplifier modeling plugin in the DAW. The RealTone cable is a small audio interface in itself.
If you want to record the tone of your amplifier, you need a microphone.
Recording the speaker output does not work, both because the electrical properties of the speaker output are very different from guitar or line output and because the guitar speaker itself affects the tone by filtering out high frequencies and adding some distortion. There are dummy load boxes that take the speaker output and emulate the speaker, but these are made for recording powerful tube amps at low volumes and you probably don't want to pay for one. If you are happy with the tone from the amp's headphone output, plugging that to a line input may work, but the RealTone cable probably won't work with it.
Comment: This helps clear a lot of things up, I think I might give the mic route a shot because trying to wire it directly has been a pain. Thank you!

Amp Creates Feedback When Using Output


How to correctly reformulate the universal property of the direct sum of abelian groups?

Question: In this post I learned that if $G$ is an abelian group we may state (without diagrams) the universal property of the direct sum of finitely many abelian groups by saying that that map from there is a group isomoprhism between $\prod \mathrm{Hom}(G_i,G)$ and $\mathrm{Hom}(G_1\times\cdots\times G_n,G)$. I would like to know if it is essential to say that the map is a group isomorphism. I was looking at this post and I think that we just need that map between $\prod \mathrm{Hom}(G_i,G)$ and $\mathrm{Hom}(G_1\times\cdots\times G_n,G)$ to be bijective. Why would we also need it to be a group homomorphism? I know it is, but is it truly necessary to say that when writing down the universal property?
Comment: Consider the statement: If $G_1,...,G_n$ and $H$ are abelian groups such that
$$
\prod_{i=1}^n \;\Bigl| \mathrm{Hom}(G_i,G)\Bigr|
=
\Bigl|
\mathrm{Hom}(H,G)
\Bigr|
$$
holds for all abelian groups $G$, then
$$
H\cong \bigoplus_{i=1}^n G_i
$$
Is this your claim?
Answer: It is not necessary. When an object satisfies some universal property, that means that it is an initial or terminal object of some category. But the group structure on $\text{Hom}(G,H)$ is not part of the structure of the category of abelian groups. This additional group structure is the result of all abelian groups being group objects in the category of groups, so the fact that the map you described is an isomorphism is an additional property, and not really part of the definition.
Comment: Thank you, I just wanted to make sure that I get this basic things right.


jquery slide toggle - affects all on the page

Question: I have a view with a list of a content type and using drupal behaviors and jquery toggle, I trying to toggle some content when the user clicks a div. The only problem is that it's affecting all the divs and they're all toggling open, I'd just like the one they clicked to open.
Here is my code:
(function ($) {
 Drupal.behaviors.myToggle = {
  attach: function(context, settings) {
  $('.views-row').find('.views-field-field-mp3').hide();

    $('.mp3-toggle', context).click(function() {
     $('.views-field-field-mp3').slideToggle();
    });
  }
 };
})(jQuery);

I've tried return false and a couple of other things, though none seem to work.
Any help would be much appreciated.
Comment: Should be able to change `$('.views-field-field-mp3').slideToggle();` to `$(this).parents('.views-row').find('.views-field-field-mp3').slideToggle();` if `.mp3-toggle` is within the views row
Comment: Where in your document is `.mp3-toggle` in relation to `.views-field-field-mp3`?
Comment: .mp3-toggle is within a views-row but not the same, so it should be in the same views row?
Comment: Thanks that appears to work now! Submit your comment as the answer and I'll mark as the correct an answer.
Answer: You'll need to make use of the this keyword inside your click function:
 Drupal.behaviors.myToggle = {
   attach: function(context, settings) {
     $('.views-row').find('.views-field-field-mp3').hide();

     $('.mp3-toggle', context).click(function() {
       $(this).parents('.views-row').find('.views-field-field-mp3').slideToggle();
     });
   }
 };


Mongo find() does not work with multer to list all images

Question: I have built a simple CRUD API for multer/gridfs to storage image files. It does work properly in terms of adding, deleting and finding certain image by it's name. However it does not list all the added files with find(). I am new to multer, so maybe I don't know something specific about chunks/files that makes this behave like that.
Here is my API for listing all files:
const Grid = require("gridfs-stream");
...
const conn = mongoose.connection;
conn.once("open", function () {
    gfs = Grid(conn.db, mongoose.mongo);
    gfs.collection("images");
});
...
app.get("/api/v1/files", async (req, res) => {
    try {
        const file = await gfs.files.find();
        const readStream = gfs.createReadStream(file);
        readStream.pipe(res);
    } catch (error) {
        res.send("not found");
    }
});

Here is error log for GET request:
.../WebstormProjects/irrisfileapiv1/node_modules/mongodb/lib/utils.js:113
      throw err;
      ^

MongoError: file with id  not opened for writing
    at Function.create (.../WebstormProjects/irrisfileapiv1/node_modules/mongodb/lib/core/error.js:59:12)

Answer: I don't have much experience with gridfs-stream or multer, but I think we can use some context clues to start figuring out what might be happening here.
The error message is:
MongoError: file with id  not opened for writing

Looking very closely, note there are two spaces here:
id  not

I am guessing this is not a typo. The code generating this message is probably generating a string such as:
"file with id " + fileName " not opened for writing"

So the file name that this function is attempting to use/open is probably incorrectly set to null. In your code we can see:
        const file = await gfs.files.find();
        const readStream = gfs.createReadStream(file);

This looks incorrect to me. The .find() function is going to return a cursor. But as far as I can tell from the readme, the createReadStream function is expecting to receive a filter with an _id or a filename.
Also, the error message specifically references opening the file for writing. But the code snippets you've shared are just about read streams. So the specific line of code that is generating the error message you've reported may be elsewhere.


AHSME 1981 #22 - Number of lines that pass through four distinct points

Question:
How many lines in a three dimensional rectangular coordinate system
  pass through four distinct points of the form $(i, j, k)$ where $i$, $j$, and $k$
  are positive integers not exceeding four?
$\text{(A)} \ 60 \qquad \text{(B)} \ 64 \qquad \text{(C)} \ 72 \qquad \text{(D)} \ 76 \qquad \text{(E)} \ 100$

I am interested in knowing why my solution below is incorrect:
Any line in 3D space is characterized by an initial point and a vector.
Starting with an initial point of form $(x, y, z)$ and a vector of $(\Delta x, \Delta y, \Delta z)$ you can get other points on the line by adding the vector to the initial point. Since we are interested in a line that passes through four points, the fourth point on this line will be $(x + 3\Delta x, y + 3\Delta y, z + 3\Delta z)$
You need each of these points to be between 1 and 4 (inclusive). If the initial and final points are within the boundary then all points inbetween will also be.
Thus if, $$1 \leq x\leq 4$$
and $$1 \leq x + 3\Delta x \leq 4$$ then you have the following choices:
$x = 1$ and $\Delta x = 0, 1$
$x = 2$ and $\Delta x = 0$
$x = 3$ and $\Delta x = 0$
$x = 4$ and $\Delta x = 0$
Resulting in a total of $1\cdot2 + 1\cdot1 + 1\cdot1 + 1\cdot1 = 5$ valid for $x$ and $\Delta x$. The same holds true for the $y$ and $z$ cases, resulting in a total of $5^3$ total choices.
However, because the points need to be distinct a vector of $(0, 0, 0)$ is not allowed, and thus we must subtract all cases where $\Delta x = 0$, which make up $(1\cdot1 + 1\cdot1 + 1\cdot1 + 1\cdot1)^3$ cases.
The total is thus $5^3 - 4^3 = 61$. However, the correct answer is 76. Why did I not get the right answer?
Answer: You're assuming that $\Delta x,\Delta y,\Delta z\ge 0$ but that doesn't cover all of the possibilities. The diagonal that runs from $\langle 1,4,4\rangle$ to $\langle 4,1,1\rangle$, for instance, isn't covered by any of your cases.
Comment: @1110101001: You're welcome!
Comment: That adds the case of $x = 4$, $\Delta x = -1, 0$. Which still does not lead to the right answer, however.
Comment: @1110101001: That's not the only case that it adds. You're missing every diagonal along which at least one coordinate increases while another decreases.
Comment: I don't quite get what you mean. When you add in the cases of $x = 4$ and $\Delta x = -1$ to the others to get a total of 6 cases and then cube it to account for the y and z, are you not including all possibilities? Referring to the table posted by @turkeyhundt I don't see any cases which are not covered by this
Comment: @1110101001: If you're making the calculation that I think you're making, you're now counting some diagonals twice, once from each end.
Comment: Ah yes. I got it now. Doing $6^3$ then subtracting out 0 vectors to get $6^3 - 4^3$ then dividing by two to account for the possibilities of the same line counted by vectors in opposite direction gives wanted answer. Thanks for the help!
Answer: You can think of it in a physical sense instead of math.
For each pair of opposite faces, there are 16 lines that can go through the $4\times4$ cube perpendicularly.  So that's $3\times 16=48$.
And for each pair of diagonally opposite edges, there are 4 lines that will go through 4 lattice points.  So that's $6\times 4 = 24$
Then for each opposite pair of vertices there is one line.  $4\times 1$
Add them up and you get 76 :)
ETA:
Doesn't really address your question, but I think these are all the point vector solutions.
\begin{array}{|c|c|c|} \hline
(x,y,z)& (\Delta x, \Delta y, \Delta z) & \text{count}\\ \hline
(1,y,z) & (1, 0, 0) & 16\\ \hline
(x,1,z) & (0, 1, 0) & 16\\ \hline
(x,y,1) & (0, 0, 1) & 16\\ \hline
(1,1,z) & (1, 1, 0) & 4\\ \hline
(4,1,z) & (-1, 1, 0) & 4\\ \hline
(1,y,1) & (1, 0, 1) & 4\\ \hline
(4,y,1) & (-1, 0, 1) & 4\\ \hline
(x,1,1) & (0, 1, 1) & 4\\ \hline
(x,4,1) & (0, -1, 1) & 4\\ \hline
(1,1,1) & (1, 1, 1) & 1\\ \hline
(1,4,4) & (1, -1, -1) & 1\\ \hline
(4,1,4) & (-1, 1, -1) & 1\\ \hline
(4,4,1) & (-1, -1, 1) & 1\\ \hline
\end{array}
Comment: Ah, my bad.  Misread the question.
Comment: I am interested as to why my solution was incorrect. I already know the answer and how to get it another way.
Comment: It's fine. Still keep your answer up though.
Answer: Just reading your solution, when I got to the part about $x = 4$, then $\Delta x = -1$ is a permissible condition and I stopped right there.
Reading a bit further, we can also immediately see that your enumeration is flawed in a second way, which is that the choices of $(x, \Delta x)$, $(y, \Delta y)$, and $(z, \Delta z)$ are not independent of each other, which is what you are assuming when writing $5^3$.
Comment: wouldn't that case already be accounted for with $x=1$ and $\Delta x = 1$
Comment: No.  For what choices of $(x, y, z)$ and $(\Delta x, \Delta y, \Delta z)$ where none of the $\Delta$ are negative, can you obtain the line passing through $(4,1,1), (3,2,2), (2,3,3), (1,4,4)$?
Comment: Ah yes.  I was definitely missing that.
Comment: Why aren't the choices of (x, dx)... independent of each other? Doesn't the value you choose for (x, dx) have no impact on the others?


How to Rearrange a string and store them in an array?

Question: I need to parse a string and store them in a 2D double array.
My string is
-0.06409677515180673  0.12516724483856012  -0.06188844693840026  0.1542289929525214  -0.06603595481351604  0.07823062287735344  0.10161817634744892  $ -0.33597610014929263

double[][] A =     -0.06409677515180673
                    0.12516724483856012
                   -0.06188844693840026
                    0.1542289929525214
                   -0.06603595481351604
                    0.07823062287735344
                    0.10161817634744892
double [][] B = -0.33597610014929263

both of them should be a column 2D array.
I tried spliting with $ but it is not working.
what i tried
String getpart = "my string";
double[][] A = null;

String[] parts = getpart.split("\\$");
            String part1 = parts[0];
            String part2 = parts[1];
           /*checking for part 1*/
            int i = 0;
            StringTokenizer st= new StringTokenizer(part1," ");
            String getdata = null;
            while (st.hasMoreTokens()) {
                int j=0;
                getdata = st.nextToken();
                A[i][j] = Double.parseDouble(getdata);
                i++;
            }

But showing null pointerexception in A[i][j] = Double.parseDouble(getdata);
Any suggestions?
Comment: why is this a 2 dim array?
Comment: `split` takes a **regex**, try to split with `\\$`.
Comment: Why 2D array? I think 1D is enough.
Comment: yes it is 1 dimension. but for further computation i need them as 2D
Comment: How do you intend to store your doubles in array A?
Comment: Hey NSK, I removed [solved] from the title. We don't do that on Stack Overflow because it creates clutter and confusion. Instead, when you mark an answer as accepted, the question will appear on the main page as answered, so this isn't really needed anyway. Hope this helps clarify.
Answer: For splitting using $ as the delimiter you will have to use the escape character '\' in the regex.
String[] inputs = input.split("\\$");

Once you have splitted using '$', You can then split using space to get each double value
inputs[0].split(" ");

Comment: Nearly correct. The second split gives you again a string[] which then can be parsed to their double values. Somebody who has issues with declaring an array (like the OP in the question), needs every step at least mentioned to understand the solution.
Comment: ys upto 2 nd split i am getting. but how to know about the dimensions. they can very each time
Comment: You need to provide us entire details as why you need a 2 dimensional array. From the usecase provided by you single dimension array should suffice.
Comment: @NSK, trying splitting with white space `\\s+` as i have shown, then you will have an array of double value using which you can get the `dimension`
Answer:
tried spliting with $ but it is not working

in Java, for an instance str of String, str.split(String regex) function splits string around matches of the given regular expression regex, for finding a pattern to be matched with the given pattern. However, Regular expression allows finding pattern by specifying location by matching known as boundary matchers. $ is such a boundary matcher which represents The end of a line. If you however want to bypass it's usage as a boundary matcher, you need to escape it. For example, str.split("\\$")
After splitting you should have an array s[] with strings split on \\$, you will have to split each String of s with \\s+ for splitting with white space :
    String s[] = str.split("\\$");

    String dVal[] = s[0].split("\\s+");
    double A[] =  new double[dVal.length];

    int i = 0;
    for(String data: dVal)
    {
        A[i++] = Double.parseDouble(data);
    }

Reference:

Boundary Matchers
Answer: Try this:
@Test
public void test() throws Exception {
    String stringToSplit = "-0.06409677515180673  0.12516724483856012  -0.06188844693840026  0.1542289929525214  -0.06603595481351604  0.07823062287735344  0.10161817634744892  $ -0.33597610014929263";
    String[] splitArrayPhaseA = stringToSplit.split("\\s*\\$\\s*");

    String[][] stringValues = new String[splitArrayPhaseA.length][];
    double[][] doubleValues = new double[splitArrayPhaseA.length][];
    for (int i = 0; i < splitArrayPhaseA.length; i++) {
        stringValues[i] = splitArrayPhaseA[i].split("\\s+");
        doubleValues[i] = new double[stringValues[i].length];
        for (int j = 0; j < stringValues[i].length; j++) {
            doubleValues[i][j] = Double.parseDouble(stringValues[i][j]);
        }
    }

    double[][] a = new double[1][];
    double[][] b = new double[1][];
    a[0] = doubleValues[0];
    b[0] = doubleValues[1];

    for (double doubleValue : a[0]) {
        System.out.println("First array in 2D array [a] element value: " + doubleValue);
    }
    for (double doubleValue : b[0]) {
        System.out.println("First array in 2D array [b] element value: " + doubleValue);
    }
}

Edit: Updated the code to store result in 2D arrays a and b.
The result of running the code should yield:
First array in 2D array [a] element value: -0.06409677515180673
First array in 2D array [a] element value: 0.12516724483856012
First array in 2D array [a] element value: -0.06188844693840026
First array in 2D array [a] element value: 0.1542289929525214
First array in 2D array [a] element value: -0.06603595481351604
First array in 2D array [a] element value: 0.07823062287735344
First array in 2D array [a] element value: 0.10161817634744892
First array in 2D array [b] element value: -0.33597610014929263

Comment: This will split the string into a 2D double array. Please, if you are going to downvote, post a comment of why you want to do so.
Comment: Oh, and the code is tested and works. I am sure you can read the code and figure out how to put it to use for you.
Comment: Also note that in the first pass I am splitting with \\s*\\$\\s* in order to remove unwanted whitespace elements. The same goes for \\s+ in the second pass.
Comment: I am not the downvoter, but why you need to split `\\s*\\$\\s*` instead of `\\$` in the first place. If there are unnecessary extra space, they will be removed by your second split call `\\s+` automatically.
Comment: I tried to print doubleValues . but showing array indexoutofbound I need the doublevalues array(need my array as 2D double) but in 2 different 2 D array.after # it should go into 2 nd array B
Comment: I need to split initially with \\s*\\$\\s* to remove whitespace. If I don't do this, the second split with \\s+ will generate an empty element if the string to split (the second string generated from the first split) starts with whitespace.
Comment: My comment about downvoting was ment for the downvoter :) I honestly do not know who it was..
Comment: ys u are really right . But my a array should be 2 dimensional itself.a[][] and b[][]
Comment: so according to my input a is of 7 by 1 matrix and b is of 1 by 1 matrix
Comment: The dimension of a is [1][7] and the dimension of b is [1][1]. If you want your data stored differently, then from this point it is a matter of allocating array slots and rearranging the parsed double values into the correct array slots.
Answer: Try this.
This is the working code.
String stringToSplit = "-0.06409677515180673  0.12516724483856012  -0.06188844693840026  0.1542289929525214  -0.06603595481351604  0.07823062287735344  0.10161817634744892  $ -0.33597610014929263";

        String[] splitArrayPhaseA = stringToSplit.split("\\$");
        String part1 = splitArrayPhaseA[0];
        String part2 = splitArrayPhaseA[1];

        /*
         * Part 1
         */
        String[] innersplitpart1 = part1.split("  ");

        String[][] omegastr = new String[innersplitpart1.length][];
        int omegar = 0;
        for (String omegakeyrow : innersplitpart1) {
            omegastr[omegar++] = omegakeyrow.split("  ");
        }

        String[] innersplitpart2 = part2.split("  ");

        String[][] gamastr = new String[innersplitpart2.length][];
        int gamar = 0;
        for (String gamakeyrow : innersplitpart2) {
            gamastr[gamar++] = gamakeyrow.split("  ");
        }
        /*
         * part1 and part2 to double
         */

        double[][] A = new double[omegastr.length][omegastr[0].length];
        double[][] B = new double[gamastr.length][gamastr[0].length];

        for(int vali =0;vali< omegastr.length ;vali ++){
               for(int valj = 0;valj <omegastr[0].length;valj++){
                  A[vali][valj] = Double.parseDouble(omegastr[vali][valj]);
               }

           }
        for(int valgi =0;valgi< gamastr.length ;valgi ++){
               for(int valgj = 0;valgj <gamastr[0].length;valgj++){
                   B[valgi][valgj] = Double.parseDouble(gamastr[valgi][valgj]);
               }

           }
        System.out.println(omegastr.length+":"+omegastr[0].length);
        System.out.println("Part 1");
       for(int vali =0;vali< A.length ;vali ++){
           for(int valj = 0;valj <A[0].length;valj++){
               System.out.print(A[vali][valj]+ "\t");
           }
           System.out.println("");
       }
       System.out.println();
       System.out.println("Part 2");
       for(int vali =0;vali< B.length ;vali ++){
           for(int valj = 0;valj <B[0].length;valj++){
               System.out.print(B[vali][valj]+ "\t");
           }
           System.out.println("");
       }

output
7:1
Part 1
-0.06409677515180673
0.12516724483856012
-0.06188844693840026
0.1542289929525214
-0.06603595481351604
0.07823062287735344
0.10161817634744892

Part 2
-0.33597610014929263


Alterar cor de fundo da 'textarea' quando botão é clicado

Question: Desenvolvi uma aplicação em Javascript, Jquery e HTML.
Gostaria de fazer com que quando o usuário clicar no botão btnalterar, a textarea criada altere a sua cor de background.
Alguem tem uma ideia de como fazer isso?

    <meta charset="UTF-8">

        <title>Página</title>

        <link href src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen"/>

        <link href="design.css" rel="stylesheet" media="screen">

Página Monstra

        <form name="input" method="get">

                    <button type="button" class="button" onclick="add_field(); contador();">ADICIONAR CAIXAS DE TEXTO</button>

        </form>

        <form name="input" method="get">

                    <button type="button" class="btnsave">SALVAR</button>

        </form>

Comment: Tens estilos implementados logo a seguir à abertura da tag `` que deveriam estar no `` logo a seguir ao `bootstrap.css` em vez disso.
Comment: Vendo bem ainda há mais erros do que isso. Tinhas um CSS link mal fechado, estava ``, quando devia estar ``.
Answer: Sei muito pouco de Javascript, mas você pode programar para quando o btnalterar for clicado, ele mudar o style do textarea:

    <meta charset="UTF-8">

        <title>Página</title>

        <link href src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen"/>

        <link href="design.css" rel="stylesheet" media="screen">

Página Monstra

        <form name="input" method="get">

                    <button type="button" class="button" onclick="add_field(); contador();">ADICIONAR CAIXAS DE TEXTO</button>

        </form>

        <form name="input" method="get">

                    <button type="button" class="btnsave">SALVAR</button>

        </form>


Manual Implementation of Sobel Operator in OpenCV

Question: I am trying to apply a sobel operator by iterating through an image and applying a mask to surrounding pixels.
For now, I am trying to apply the vertical portion of the mask, which is:
-1 0 1
-2 0 2
-1 0 1

In my implementaiton, I am iterating through the rows and columns as follows:
for (int i = 1; i < image.rows-1; i++){
            for (int j = 1; j < image.cols-1; j++){
            int pixel1 = image.at<Vec3b>(i-1,j-1)[0] * -1;
            int pixel2 = image.at<Vec3b>(i,j-1)[0] * 0;
            int pixel3 = image.at<Vec3b>(i+1,j-1)[0] * 1;

            int pixel4 = image.at<Vec3b>(i-1,j)[0] * -2;
            int pixel5 = image.at<Vec3b>(i,j)[0] * 0;
            int pixel6 = image.at<Vec3b>(i+1,j)[0] * 2;

            int pixel7 = image.at<Vec3b>(i-1,j+1)[0] * -1;
            int pixel8 = image.at<Vec3b>(i,j+1)[0] * 0;
            int pixel9 = image.at<Vec3b>(i+1,j+1)[0] * 1;

            int sum = pixel1 + pixel2 + pixel3 + pixel4 + pixel5 + pixel6 + pixel7 + pixel8 + pixel9;
            verticalSobel.at<Vec3b>(i,j)[0] = sum;
            verticalSobel.at<Vec3b>(i,j)[1] = sum;
            verticalSobel.at<Vec3b>(i,j)[2] = sum;
        }
    }

Where the pixels are labeled as:
1 2 3
4 5 6
7 8 9

However, the resulting image is far off of what it should look like.
For reference, the resulting image is
Where it should look similar to:

The guide I am using is: https://www.tutorialspoint.com/dip/sobel_operator.htm
I am not sure if I am simply implementing the operator incorrectly, or just iterating through the image incorrectly.
Any help would be greatly appreciated. Thanks!
Answer: You seem to have problems where the sum is negative. Take the absolute value of sum, and clamp it to 255 (or instead of absolute value, clamp it to 0 - depending of what you want to achieve. A "full" sobel operator usually uses 2d distance formula, so a horizonal/vertical only variant should use the absolute value)
Comment: you can use opencv's saturate_cast function to prevent over- and underflows.
Comment: Perfect! Using abs(sum) when setting my pixel value fixed it. I'm just curious as to what you mean by clamping the value. Are you saying if the value is > 255, then set it to 255?
Comment: @ecatalano: yes, as `sum` can be larger than 255


Verificar data inicial e final e inserir um texto entre elas!

Question: Bom dia, tenho um código "pronto" em que o usuário deve cadastrar um evento que posteriormente será mostrado em um calendário, bom a primeira parte já está pronta mais a segunda está me dando problemas, eu gostaria de fazer um verificação da data inicial e final e inserir um texto (Ex: evento!!) nos dias entre essa datas,PS: as datas são adquiridas via banco de dados, todos os dados já estão gravados
exemplo: data inicio 6/6/16 data fim 16/6/16 , o texto deve aparecer em todos os dia do dia 6 ao 16

        <?php
        include 'connect.php';
        $sql = "select Data_inicio, Data_fim from walldata";
        $result = mysqli_query($con, $sql);
        if ($result->num_rows > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                $Data_in = $row['Data_inicio'];
                $Data_fim = $row['Data_fim'];
            }
        }
        if (isset($_POST['datac'])) {
            $datee = explode('-', $_POST['datac']);
            $mes = $datee[1];
            $ano = $datee[0];
            $ultimo_dia = date("t", mktime(0, 0, 0, $mes, '01', $ano));
        } else {
            $mes = date('m');
            $ano = date('o');
        }
        if ($mes == date('m')) {
            $ultimo_dia = date("t", mktime(0, 0, 0, $mes, '01', $ano));
            $dias = $ultimo_dia;
        } elseif ($mes == '') {
            $mes = date('m');
            $ano = date('o');
            $dias = $ultimo_dia;
        } else {
            $dias = $ultimo_dia;
        }

        ?>

        <form method="post" action="date.php">
            <input type="month" name="datac" value="<?php echo $ano ?>-<?php echo $mes ?>" required><input type="submit">

                    Domingo
                Segunda
                Terça
                Quarta
                Quinta
                Sexta
                Sábado

                <?php
                echo "
";
                for ($i = 1; $i <= $dias; $i++) {
                    $diadasemana = date("w", mktime(0, 0, 0, $mes, $i, $ano));
                    $cont = 0;
                    if ($i == 1) {
                        while ($cont < $diadasemana) {
                            echo "	";
                            $cont++;
                        }
                    }
                    echo "";
                    echo $i;
                    echo "	";
                    if ($diadasemana == 6) {
                        echo "
";
                        echo "
";
                    }
                }
                echo "
";
                ?>

        </form>

Se tiverem alguma ideia de como posso fazer isso ;D
Comment: Preciso que seja  mais específico. Onde você quer colocar a palavra ? TIpo, em cada data ?
Comment: Sim nos dias em que o evento acontecer
Comment: exemplo, data inicio 6/6/16 data fim 16/6/16 , o texto deve aparecer em todos os dia do dia 6 ao 16
Answer: Existe o http://fullcalendar.io/, onde faz isso automático.
O código abaixo irá te ajudar.
Faz um range de datas utilizando sua data inicial e sua data final:
function dateRange($first, $last, $format = 'Y-m-d', $step = '+1 day'){
$dates = array();
$current = strtotime($first);
$last = strtotime($last);

while ($current <= $last) {
    $dates[] = date($format, $current);
    $current = strtotime($step, $current);
}
return $dates;

}
Percorre as datas adicionando o evento nos dias:

$eventos[] = array('dataIni' => '2016-01-01', 'dataFim' => '2016-01-10', 'evento' => 'Evento Janeiro');
$eventos[] = array('dataIni' => '2016-01-09', 'dataFim' => '2016-02-5', 'evento' => 'Evento Fevereiro');
$calendar = array();
foreach ($eventos as $evento) {
    $range = dateRange($evento['dataIni'], $evento['dataFim']);
    foreach ($range as $data) {
        $calendar[$data][] = array('evento' => $evento['evento']);
    }
}

Percorre o calendário verificando os dias e adicionando a descrição do evento nos locais.