text:
Q: JSF with Primefaces Menu duplicate Id error? I have a JSF template and several template cliets. When I add a dynamic primefaces menubar, there is an error with the message of there is a duplicate id error. I manually checked and there are no duplicates in the ids I have given. When I remove the p:menubar, the error resolves.
SEVERE: JSF1007: Duplicate component ID j_id2 found in view.
SEVERE: +id: j_id1
 type: javax.faces.component.UIViewRoot@197b245
  +id: javax_faces_location_HEAD
   type: com.sun.faces.component.ComponentResourceContainer@15e344b
    +id: j_idt6
     type: javax.faces.component.UIOutput@5f7a1
    +id: j_id2  <===============
     type: javax.faces.component.UIOutput@1bb6941
    +id: j_id3
     type: javax.faces.component.UIOutput@fb2b4a
    +id: j_id4
     type: javax.faces.component.UIOutput@1d72379
    +id: j_id5
     type: javax.faces.component.UIOutput@159ef51
    +id: j_id6
     type: javax.faces.component.UIOutput@16eaf88
  +id: j_idt2
   type: <?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  +id: j_idt3
   type: <html xmlns="http://www.w3.org/1999/xhtml">
    <!--Author : Dr. M H B Ariyaratne, MO(Health Information), buddhika.ari@gmail.com-->

  +id: j_idt4
   type: javax.faces.component.UIOutput@13e40a4
    +id: j_idt5
     type:
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    +id: j_idt7
     type:
        <title>#{labels.topic}</title>

  +id: j_idt8
   type: javax.faces.component.UIOutput@1c46b0a
    +id: j_idt9
     type: org.primefaces.component.growl.Growl@4f6181
    +id: pStaff
     type: org.primefaces.component.panel.Panel@18a95c1
      +id: pgM
       type: javax.faces.component.html.HtmlPanelGrid@16de90f
        +id: j_idt10
         type: javax.faces.component.html.HtmlPanelGroup@e004a0
          +id: j_idt11
           type: javax.faces.component.html.HtmlForm@14fde45
            +id: j_idt12
             type: javax.faces.component.html.HtmlPanelGroup@8985b5
              +id: j_idt13
               type: org.primefaces.component.menubar.Menubar@a967cb
                +id: j_id2  <===============
                 type: org.primefaces.component.menuitem.MenuItem@1afb24a
                +id: j_id3
                 type: org.primefaces.component.submenu.Submenu@1e22365
                  +id: j_id4
                   type: org.primefaces.component.menuitem.MenuItem@181ddad
                  +id: j_id5
                   type: org.primefaces.component.menuitem.MenuItem@100bceb
                  +id: j_id6
                   type: org.primefaces.component.menuitem.MenuItem@173016f
                  +id: j_id7
                   type: org.primefaces.component.menuitem.MenuItem@16332a4
                  +id: j_id8
                   type: org.primefaces.component.menuitem.MenuItem@191e61d
                  +id: j_id9
                   type: org.primefaces.component.menuitem.MenuItem@19aa7db
                  +id: j_id10
                   type: org.primefaces.component.menuitem.MenuItem@82593c
                  +id: j_id11
                   type: org.primefaces.component.menuitem.MenuItem@1b07eb6
                +id: j_id12
                 type: org.primefaces.component.submenu.Submenu@4ee9d9
                  +id: j_id13
                   type: org.primefaces.component.menuitem.MenuItem@dae23d
                  +id: j_id14
                   type: org.primefaces.component.menuitem.MenuItem@3b2eed
                  +id: j_id15
                   type: org.primefaces.component.menuitem.MenuItem@185f8e9
                  +id: j_id16
                   type: org.primefaces.component.menuitem.MenuItem@98a265
                  +id: j_id17
                   type: org.primefaces.component.menuitem.MenuItem@cdbf40
                  +id: j_id18
                   type: org.primefaces.component.menuitem.MenuItem@1c71499
                  +id: j_id19
                   type: org.primefaces.component.menuitem.MenuItem@119832a
                  +id: j_id20
                   type: org.primefaces.component.menuitem.MenuItem@1f25dd7
                  +id: j_id21
                   type: org.primefaces.component.menuitem.MenuItem@eed568
                +id: j_id22
                 type: org.primefaces.component.submenu.Submenu@1fcb0c2
                  +id: j_id23
                   type: org.primefaces.component.menuitem.MenuItem@b8c8f7
                  +id: j_id24
                   type: org.primefaces.component.menuitem.MenuItem@19205d7
                +id: j_id25
                 type: org.primefaces.component.submenu.Submenu@1bd84ce
                  +id: j_id26
                   type: org.primefaces.component.menuitem.MenuItem@15a29b2
                  +id: j_id27
                   type: org.primefaces.component.menuitem.MenuItem@6766d6
        +id: j_idt14
         type: javax.faces.component.html.HtmlPanelGroup@1dd6bd9
          +id: j_idt15
           type: javax.faces.component.html.HtmlPanelGroup@1d3934a
            +id: form
             type: javax.faces.component.html.HtmlForm@16ae971
              +id: growl
               type: org.primefaces.component.growl.Growl@40dee
              +id: j_idt16
               type: javax.faces.component.html.HtmlCommandButton@2eb374
              +id: j_idt17
               type: org.primefaces.component.panel.Panel@78bf2
                +id: j_idt18
                 type: org.primefaces.component.panelgrid.PanelGrid@174cb3e
                  +id: j_idt19
                   type: org.primefaces.component.panelgrid.PanelGrid@cb6dd6
                    +id: pDetails
                     type: org.primefaces.component.panel.Panel@19819bb
                      +id: tvPs
                       type: org.primefaces.component.tabview.TabView@c15e73
                        +id: tabNewOpd
                         type: org.primefaces.component.tabview.Tab@11ff44f
                          +id: j_idt20
                           type:
                                                New Opd Pt

                          +id: j_idt21
                           type: org.primefaces.component.calendar.Calendar@e08ff0
                        +id: tabSearchOpd
                         type: org.primefaces.component.tabview.Tab@109e252
                          +id: j_idt22
                           type:
                                                Search Opd Pt

                        +id: tabBht
                         type: org.primefaces.component.tabview.Tab@1e995d3
                          +id: j_idt23
                           type:
                                                BHT

                        +id: tabCompany
                         type: org.primefaces.component.tabview.Tab@6b6109
                          +id: j_idt24
                           type:
                                                New Company

                      +id: j_idt25
                       type: javax.faces.component.html.HtmlPanelGrid@1afce81
                        +id: j_idt26
                         type: javax.faces.component.html.HtmlOutputText@11e9df9
                        +id: acPt
                         type: org.primefaces.component.autocomplete.AutoComplete@1154808
                        +id: txtPtName
                         type: javax.faces.component.html.HtmlOutputText@2c2dc7
                        +id: j_idt27
                         type: javax.faces.component.html.HtmlOutputText@71a488
                        +id: txtPtAdd
                         type: javax.faces.component.html.HtmlInputText@e8e006
                        +id: j_idt28
                         type: javax.faces.component.html.HtmlOutputText@cbb18f
                        +id: txtPtPhone
                         type: javax.faces.component.html.HtmlInputText@f651da
                    +id: j_idt29
                     type: org.primefaces.component.panel.Panel@177fa2d
                      +id: j_idt30
                       type: javax.faces.component.html.HtmlSelectOneListbox@1c9a536
                        +id: j_idt31
                         type: javax.faces.component.UISelectItems@17d8e95
                      +id: j_idt32
                       type: javax.faces.component.html.HtmlCommandButton@1bde17
                    +id: j_idt33
                     type: org.primefaces.component.panel.Panel@191e94c
                      +id: j_idt34
                       type: javax.faces.component.html.HtmlDataTable@6ba042
                        +id: j_idt35
                         type: javax.faces.component.UIColumn@1e685b0
                          +id: j_idt36
                           type: #{b.item.name}
                        +id: j_idt37
                         type: javax.faces.component.UIColumn@15314f2
                          +id: j_idt38
                           type: #{b.item.total}
                    +id: j_idt39
                     type: javax.faces.component.html.HtmlOutputText@1845b1f
                    +id: txtTotal
                     type: javax.faces.component.html.HtmlOutputText@7a5621
                  +id: j_idt40
                   type: org.primefaces.component.panel.Panel@1aca028
                    +id: j_idt41
                     type: org.primefaces.component.commandbutton.CommandButton@46dc65
                      +id: j_idt42
                       type:

The Template
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui">
    <!--Author : Dr. M H B Ariyaratne, MO(Health Information), buddhika.ari@gmail.com-->
    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <h:outputStylesheet library="css" name="maincss.css" />
        <title>#{labels.topic}</title>
    </h:head>
    <h:body >
        <p:growl id="publicGrowl" autoUpdate="true"/>
        <p:panel id="pStaff" header="#{labels.topic}" >
            <h:panelGrid id="pgM" columns="1" >
                <h:panelGroup >
                    <h:form>
                        <h:panelGroup >
                            <p:menubar model="#{menuController.model}" ></p:menubar>
                        </h:panelGroup>
                    </h:form>
                </h:panelGroup>
                <h:panelGroup rendered ="#{sessionController.logged}" >
                    <ui:insert name="content"   >
                        Use Menu to Navigate
                    </ui:insert>
                </h:panelGroup>
                <h:panelGroup rendered ="#{!sessionController.logged}" >
                    <ui:insert name="login"   >
                        <p:panel header="Please login" id="loginbox">
                            <h:panelGrid columns="2" >
                                <h:panelGroup >
                                    <h:graphicImage  library="image" name="lock.png" />
                                </h:panelGroup>
                                <h:panelGroup >
                                    <h:form id="formLogin">
                                        <h:panelGrid columns="2">
                                            <h:outputLabel value="Username" ></h:outputLabel>
                                            <h:inputText autocomplete="off"  value="#{sessionController.userName}" ></h:inputText>
                                            <h:outputLabel value="Password" ></h:outputLabel>
                                            <h:inputSecret value="#{sessionController.passord }" ></h:inputSecret>
                                            <h:outputLabel value="Password" ></h:outputLabel>
                                            <h:commandButton value="Login" action="#{sessionController.loginAction()}" ></h:commandButton>
                                        </h:panelGrid>
                                    </h:form>
                                </h:panelGroup>
                            </h:panelGrid>
                        </p:panel>
                    </ui:insert>
                </h:panelGroup>
                <h:panelGroup >
                    <h:form>
                        <h:outputLabel  value="You are logged as #{sessionController.loggedUser.webUserPerson.name} (#{sessionController.loggedUser.role.name})."  rendered ="#{sessionController.logged}" ></h:outputLabel><h:commandLink value="Logout" action="#{sessionController.logout}"  rendered ="#{sessionController.logged}" ></h:commandLink>
                        <h:outputLabel  value="Please login to continue."  rendered ="#{!sessionController.logged}" ></h:outputLabel>
                    </h:form>
                    Copyright © 2013 | All Rights Reserved
                </h:panelGroup>
            </h:panelGrid>
        </p:panel>
    </h:body>
</html>

The JSF Template Client
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:body>
        <ui:composition  template="./resources/template/staff_template.xhtml">
            <ui:define name="content">
                <h:panelGroup >
                    <h:form id="form">
                        <p:growl id="growl" showDetail="true" />
                        <h:commandButton value="Create Pt" action="#{patientController.createRandomPatient('Budi')}" />
                        <p:panel header="Lab Bill" >
                            <p:panelGrid columns="2" >
                                <p:panelGrid columns="1" >
                                    <p:panel id="pDetails" header="Patient Details" >
                                        <p:tabView id="tvPs"  >
                                            <p:ajax event="tabChange" listener="#{labBillController.onTabChange}" update=":form:growl"/>
                                            <p:tab id="tabNewOpd" title="New OPD Patient" >
                                                New Opd Pt
                                            </p:tab>
                                            <p:tab id="tabSearchOpd" title="New OPD Patient">
                                                Search Opd Pt
                                            </p:tab>
                                            <p:tab id="tabBht" title="BHT">
                                                BHT
                                            </p:tab>
                                            <p:tab id="tabCompany" title="Company">
                                                New Company
                                            </p:tab>
                                        </p:tabView>
                                        <h:panelGrid columns="2">
                                            <h:outputText value="Name"/>
                                            <p:autoComplete value="#{labBillController.currentPatient}" id="acPt" completeMethod="#{patientController.completePatient}"
                                                            var="p" itemLabel="#{p.person.name}" itemValue="#{p}"  >
                                                <f:ajax event="select" execute="acPt" render="txtPtName txtPtAdd txtPtPhone" />
                                            </p:autoComplete>
                                            <h:outputText id="txtPtName" value="#{labBillController.currentPatient.person.name}"/>
                                            <h:outputText  value="Address"/>
                                            <h:inputText id="txtPtAdd" value="#{labBillController.currentPatient.person.address}"/>
                                            <h:outputText value="Phone"/>
                                            <h:inputText id="txtPtPhone" value="#{labBillController.currentPatient.person.phone}"/>
                                        </h:panelGrid>
                                    </p:panel>
                                    <p:panel header="Investigation Detail" >
                                        <h:selectOneListbox value="#{labBillController.currentBillItem.item}" >
                                            <f:selectItems  value="#{investigationController.items}"  var="myItem" itemValue="#{myItem}" itemLabel="#{myItem.name}"  />
                                        </h:selectOneListbox>
                                        <h:commandButton value="AddItem" action="#{labBillController.addToBill()}" />
                                    </p:panel>
                                    <p:panel header="Request Details" >
                                        <h:dataTable value="#{labBillController.billItems}" var="b">
                                            <h:column >#{b.item.name}</h:column>
                                            <h:column >#{b.item.total}</h:column>
                                        </h:dataTable>
                                    </p:panel>
                                    <h:outputText value="Total"/>
                                    <h:outputText value="#{labBillController.current.total}" id="txtTotal"/>
                                </p:panelGrid>
                                <p:panel header="Bill Details" >
                                    <p:commandButton value="Settle" actionListener="#{labBillController.settleBill}" ajax="false" >
                                        <!--<p:printer target="pDetails"  />-->
                                    </p:commandButton>
                                </p:panel>
                            </p:panelGrid>
                        </p:panel>
                    </h:form>
                </h:panelGroup>
            </ui:define>
        </ui:composition>
    </h:body>
</html>

A: I completely re-write the code and there was no error afterwords. I think that although I couldn't trace any duplicate Ids in previous time, there must have been one. This time also the same error occurred and I found that there is a duplication introduced by myself. If anyone get the same error, I think there is a very high possibility that it is caused by duplicates in manual insertion of duplicate ids.


text:
Q: How to display Java Timer on a separate J Frame Form label? i have a question , i have this timer code in java that when its executed it displays a count down timer on its own JFrame label, what i want to do is to display this timer on another JFrame form label without having to move the code to other classes.
I hope you can help me with this thanks lot guys .
this is the code for the Timer class:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class TimerExample extends JFrame {

   final JLabel label;
   Timer countdownTimer;
   int timeRemaining = 10;

   public TimerExample() {
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setSize(200, 200);
      label = new JLabel(String.valueOf(timeRemaining), JLabel.CENTER);
      getContentPane().add(label);

      countdownTimer = new Timer(1000, new CountdownTimerListener());
      setVisible(true);
      countdownTimer.start();
   }

   class CountdownTimerListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
         if (--timeRemaining > 0) {
            label.setText(String.valueOf(timeRemaining));
         } else {
            label.setText("Time's up!");
            countdownTimer.stop();
         }
      }
   }

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

}

thanks

A: Here it is,
Following is my TestTimer class which accepts a JLabel as input
public class TestTimer {
     private JLabel label;
     Timer countdownTimer;
     int timeRemaining = 10;

     public TestTimer(JLabel passedLabel) {
        countdownTimer = new Timer(1000, new CountdownTimerListener());
        this.label = passedLabel;
        countdownTimer.start();
     }

      class CountdownTimerListener implements ActionListener {
          public void actionPerformed(ActionEvent e) {
             if (--timeRemaining > 0) {
                 label.setText(String.valueOf(timeRemaining));
              } else {
                 label.setText("Time's up!");
                 countdownTimer.stop();
              }
          }
      }
  }

And here is another Main class which is actually extending a JFrame and showing a label in it,
public class TimerJFrame extends JFrame{
    private static final long serialVersionUID = 1L;
    private JLabel label;

    public TimerJFrame() {
     setDefaultCloseOperation(EXIT_ON_CLOSE);
         setSize(200, 200);
         label = new JLabel("10", JLabel.CENTER);
         getContentPane().add(label);
         new TestTimer(label);
         setVisible(true);
    }

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

Second Code passes a created JLabel to first class and first class uses it to show timer.

A: You need to follow following steps,

*

*Modify TimerExample constructor to accept JLabel. And initialize JLabel of TimerExample class with passwd JLabel

*Pass JLabel from other JFrame class.

*Remove main method from this as it will not be required.

Bu first step here, constructor will accept predefined JLabel from other classes and use those to display timer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: R code that will group_by multiple columns and summarize when a data element appears across the column group How can I summarize the counts of a set of specific factors that appear across a group of columns?
I'm working on summarizing a set of specific factors that appear across a group of columns in my data set (specifically, medical procedure codes that can appear across 15 different procedure columns). I'd like to group the columns and then summarize any time one of a set list of codes appears in any of those columns. This can mean that the specified codes aren't mutually exclusive to a single record of data, there will be overlap in a row of appearances by multiple procedure codes that I'm looking for.
I've used the following dummy df to run a quick test. I want to summarize the count of data points "b" and "e" across columns "Y" and "Z". Clearly, my summary won't work how I want it to, but that's as far as I've gotten.
library(dplyr)

Mydata <- data.frame(W = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
                     X = c(20, 30, 45, 54, 65, 78, 97, 102, 123, 156),
                     Y = c("a","b","c","d","e","e","f","f","f","g"),
                     Z = c("c","a","b","b","c","d","e","e","g","h"))

 test_group <- Mydata %>%   summarize_at(c(z, w), n = n())

Expected results would be a table with the following:
Specified_Data  n
             b  3
             e  4

A: Another user posted an answer but looks like they pulled it down. However, it does work, so I figured I'd throw the code in. Works with dplyr.
Mydata %>%
  select(Y, Z) %>%
  gather(var, val) %>%
  filter(val %in% c("b", "e")) %>%
  count(val)

# A tibble: 2 x 2
  val       n
  <chr> <int>
1 b         3
2 e         4

There is a warning message after the console result, but it doesn't seem to have any impact on the code line working. Message as follows:
Warning message:
attributes are not identical across measure variables;
they will be dropped


text:
Q: CREATE TABLE IF NOT EXISTS always creates new table (even if exsists) Pretty much self explanatory but for some reason it always works instead of working once (when table not exists)...
$mysqli = mysqli_connect('localhost','user','pass','databasename');

$create_table =
'CREATE TABLE IF NOT EXISTS student
(
    `1` longtext NOT NULL,
    `2` longtext NOT NULL
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;';

$create_tbl = $mysqli->query($create_table);

if ($create_table) {
    echo "Table has created";
}
else {
        echo "error!!";
}

it always echo Table has created even if table is already exists!!!
Why?

A: you have to check before if table exsit or not, because $create_tbl return 1 every time.
so run SHOW TABLES LIKE 'student' before
$mysqli = mysqli_connect('localhost','root','root','test');

$create_table =
'CREATE TABLE IF NOT EXISTS student
(
    `1` longtext NOT NULL,
    `2` longtext NOT NULL
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;';

if(mysqli_num_rows($mysqli->query("SHOW TABLES LIKE 'student'")) !=1) {
    $create_tbl = $mysqli->query($create_table);
} else {
     echo "error!!";
}

A: I just removed the IF NOT EXISTS and it works like a charm! Thanks @Mark Baker for pointing this out! :)

A: I never worked with the MySQLi API before(always using PDO), but doesn't it return true because the query actually was successful?
I think it only returns false if your connection failed, or an error like that.

A: You're testing if the SQL statement exists, not the result. Nevertheless, you need to strictly test for the successful execution of the statement using === (not just == or testing the variable directly). Remove IF NOT EXISTS from the query and then test like this;
if ($create_tbl === true) {
    echo "Table was created";
}
else {
    echo "Error!!";
}


text:
Q: How can I get current location of user (Latitude and Longitude ) using BEACONS in android (kotlin)? I want to find my current location i.e latitude and longitude using beacons in android application

A: Beacons don't give latitude and longitude.  They give relative location to the beacons themselves via triangulation.  For example let's say you had 3 beacons in a triangle around you.  If the strength of all 3 beacons is the same, you know you're in the exact center.  If one of them is stronger, you know you're closer to that one.  Using some math you can use the signal strengths to figure out your distance and angle from each beacon.  But that has NOTHING to do with latitude and longitude.  If you knew the exact latitude and longitude of the beacons themselves you could combine your relative distance with the location of the beacon (and more math, because for longitude 1 degree of longitude is bigger or smaller depending on your latitude) to get your latitude and longitude, but you generally wouldn't bother-  the beacon usecase is normally for locating within an enclosed area, for example figuring out what seat someone is at on a resort, or what exhibit in a museum.


text:
Q: What does this statement mean in C: "(void)ptr;" It may not be clear from the title. I came across the following code in an embedded STM32 project. I don't understand the line inside the function.
    static void txend1(UARTDriver *uartp) {
        (void)uartp; // what does this do? Is it a statement?
    }

I've tried searching elsewhere online, but most results are casting pointers to void pointers, which I don't think this is. Thanks for the help!

A: this is just a portable way to suppress the warning on this unused uart parameter.
It has no effect, but compilers see that as used, and don't issue any warning.
Very useful when the prototype of the function is imposed / cannot be changed (callback function) but your implementation doesn't need this parameter.
(note that gcc favors the __attribute__((unused)) construct, easier to understand, but not compatible with all compilers)


text:
Q: Bruhat decomposition for G(R), R local ring or R=Z/p^r Is there an invariant, which encodes the failure of the Bruhat decomposition to hold for a reductive group with coefficients in a local ring like the p-adic integers or the ring $\mathbb{Z}/\mathfrak{p}^r$?
Example $G =GL_2$: Fix a Borel subgroup $B$, e.g. the upper diagonal matrixes. The coset space $B \backslash G$ (or $G/B$) are isomorphic to the projective line. However, the Bruhat decomposition $G = BWB$, where $W$ is the Weyl group, does not hold for the group of $R$ points, where $R$ is not a field. Can we describe $B\backslash G/B$ as a variety over $\mathbb{Z}$ here?

A: Bruhat decomposition over $\mathbf Z/p^r\mathbf Z$ is precisely the problem we looked at in this paper. We defined several invariants of double cosets, and classified the pairs $(n,k)$ for which, when $G=GL_n(\mathbf Z/p^k\mathbf Z)$, the cardinality of $B\backslash G/B$ does not depend on $p$. Unfortunately, the general question seems to involve wild classification problems.


text:
Q: Delete Items in an ObservableCollection That are Bound to A GridView I would like to be able to select an item that is bound to my gridview and press the delete button, which would delete the item from the observable collection to which the gridview is bound to.
<ListView Height="166" HorizontalAlignment="Left" Margin="12,290,0,0" Name="listView1" VerticalAlignment="Top" Width="636" ItemsSource="{Binding SearchTerms}" KeyUp="SearchTermsGrid_KeyPressed">
    <ListView.View>
        <GridView x:Name="SearchTermsGrid">
            <GridViewColumn Width="155" Header="Search Term" DisplayMemberBinding="{Binding Name}"/>
            <GridViewColumn Width="90" Header="Status" DisplayMemberBinding="{Binding Status}"/>
            <GridViewColumn Width="60" Header="Count" DisplayMemberBinding="{Binding NumberToDownload}"/>
            <GridViewColumn Width="60" Header="Size" DisplayMemberBinding="{Binding Size}"/>
            <GridViewColumn Width="60" Header="Type" DisplayMemberBinding="{Binding Type}"/>
        </GridView>
    </ListView.View>
</ListView>

ObservableCollection<SearchTerm> _searchTerms = new ObservableCollection<SearchTerm>();
public ObservableCollection<SearchTerm> SearchTerms
{
    get
    {
        return _searchTerms;
    }
}

private void SearchTermsGrid_KeyPressed(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
        //I dunno, this might be a bad approach.
    }
}

A: does this not work:?
this._searchTerms.Remove(this.listView1.SelectedItem);


text:
Q: View variable's value of a running python script in local machine I have this script,
#!/usr/bin/python3
for i in range(1000):
    sleep 10

I executed it, and the PID is 3030, let's say i need to know the value of i, how can i retrieve it?

A: I recommend you to use some logging library because you need to control running state of the process and it's outputs. As example you may use this: https://github.com/Delgan/loguru


text:
Q: print yum repo configuration of a single repo using yum I'm trying to find a portable command line way to get the full configuration of a single yum repo -- without relying necessarily on the name/id of the repo or what file it's in.
I'd like to just have a pretty straight forward command -- but this is what I've cobbled together.
Let's use epel as an example, I've come up with something like: (forgive the ugly prototype)
$ yum repolist -v "$(yum info epel-release |
   perl -ne 'print if s/^From repo\s*:\s//')" |
   perl -ne 'print if s/^Repo-filename\s*:\s//'
/etc/yum.repos.d/epel.repo
$

So, using epel-release as a way to identify which repo I care about and then finding the repo file associated with that repo.
How do I grab just the stanza in that repo file that is for epel -- no debug, no source, no other random repos appended to the file. I can imagine some beginning and ending regex magic -- starting with [<Repo-id>] and until I see the next [<Next Repo-id>] -- that's pretty easy. /start regex/../end regex/
Is there a better way?


text:
Q: Как прибавлять прогресс к кастомному Progress Bar Есть вью, откуда я получаю данные, которые выбрал юзер:
var volumeFromMilimetersVC = 0
var progressToMainVC: Float = 0.0

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    volumeFromMilimetersVC = volume.volumeArray[row]
    progressToMainVC = Float(volumeFromMilimetersVC)
}

Значения, которые может выбрать пользователь берутся из массива:
let volumeArray = [20, 50, 100, 150, 200, 250, 300, 330, 350, 400, 450, 500, 600, 700, 800, 900, 1000, 1500, 2000]

Передаю полученную информацию обратно в другой вью в переменную var progress: Float = 0.0:
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc = segue.destination as? MainViewController
    vc?.delegate = self
    vc?.progress = Float(volumeFromMilimetersVC)
}

В MainViewController создал: @IBOutlet weak var progressBar: ProgressBarView!
и написал функцию апдейта прогресса:
func updateProgress() {
    let volumeMax = Int(UserSettings.result)
    print(volumeMax!)
    let progress2 = CGFloat(volumeMax!) / CGFloat(progress)
    print(progress2)
    progressBar.shapeLayer.strokeEnd = progress2
}

Далее отдельным файлом нарисовал кастомный Progress Bar:
class ProgressBarView: UIView {

var bgPath: UIBezierPath!
var shapeLayer: CAShapeLayer!
var progressLayer: CAShapeLayer!
let main = MainViewController()
let milileters = MilimetersScreen()
let milileters2 = MililetersViewController()

    var progress: Float = 0 {
        willSet {
            let max = main.resultValue.text
            let volumeMax = Int(max ?? "0")
            let progress = CGFloat(main.progress) / CGFloat(volumeMax!)
            progressLayer.strokeEnd = progress
            //print(progress)
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        bgPath = UIBezierPath()
        self.simpleShape()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        bgPath = UIBezierPath()
        self.simpleShape()
    }

    func simpleShape() {
        createCirclePath()
        shapeLayer = CAShapeLayer()
        shapeLayer.path = bgPath.cgPath
        shapeLayer.lineWidth = 15
        shapeLayer.fillColor = nil
        shapeLayer.strokeColor = UIColor.lightGray.cgColor

        progressLayer = CAShapeLayer()
        progressLayer.path = bgPath.cgPath
        progressLayer.lineCap = CAShapeLayerLineCap.round
        progressLayer.lineWidth = 15
        progressLayer.fillColor = nil
        progressLayer.strokeColor = UIColor.blue.cgColor
        progressLayer.strokeEnd = 0

        self.layer.addSublayer(shapeLayer)
        self.layer.addSublayer(progressLayer)
    }

    private func createCirclePath() {

        let x = self.frame.width/2
        let y = self.frame.height/2
        let center = CGPoint(x: x, y: y)
        print(x,y,center)
        bgPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 1.5 * CGFloat.pi, clockwise: true)
        bgPath.close()
    }

Progress Bar почему-то не заполнятся.
Вопрос: как сделать так, чтобы progress bar заполнялся при добавлении пользователем различных значений и заполнялся до тех пор, пока не достигнет максимального значения, которое рассчитано для пользователя? Допустим, максимальное значение, рассчитанное для пользователя: 2500. Он добавляет из массива выше значения и они должны суммироваться и отображаться в линии progress bar'а.
UPD. Получилось сделать, чтобы прогресс бар обновлялся, однако после второго добавления он не прибавляется к предыдущему значению, а перезаписывается.
    var progress: Float = 0.0 {
    didSet {
        updateProgress2(with: progress)
    }
}

    @objc func updateProgress() {
    let userResult = Int(UserSettings.result)
    print(userResult!)
    let progress2 = CGFloat(userResult!) / CGFloat(progress)
    print(progress2)
    progressBar.progressLayer.strokeEnd = progress2 / 100
}
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(updateProgress)))

    public func addProgress(_ value: Float) {
    progress += value
}

     func updateProgress2(with value: Float) {
    let newProgress = value
    UserSettings.userProgress = newProgress
    defaults.set(newProgress, forKey: String(UserSettings.userProgress))
    progressBar.progressLayer.strokeEnd = CGFloat(progress / 100)
}

A: Вот минимальный пример такого функционала на основе вашего кода
vc?.updateProgress(with: Float(volumeFromMilimetersVC))

class MainViewController: UIViewController {

    @IBOutlet var progressBarView: ProgressBarView!

    private let maxProgress: Float = 2000

    private var progress: Float = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        progressBarView.maxProgress = maxProgress
    }

    func updateProgress(with value: Float) {
        progress += value
        progressBarView.updateProgress(with: progress)
    }

}

class ProgressBarView: UIView {

    let progressLineWidth: CGFloat = 15

    var maxProgress: Float!

    private var progressLayer = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        createProgressLayer()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        createProgressLayer()
    }

    private func createProgressLayer() {
        layer.borderColor = UIColor.red.cgColor
        layer.borderWidth = 1
        progressLayer.lineCap = CAShapeLayerLineCap.round
        progressLayer.lineWidth = progressLineWidth
        progressLayer.fillColor = nil
        progressLayer.strokeColor = UIColor.blue.cgColor
        progressLayer.strokeEnd = 0
        progressLayer.frame = bounds

        let path = UIBezierPath()
        path.move(to: CGPoint(x: progressLineWidth / 2, y: progressLineWidth / 2))
        path.addLine(to: CGPoint(x: bounds.width - progressLineWidth / 2, y: progressLineWidth / 2))
        progressLayer.path = path.cgPath

        layer.addSublayer(progressLayer)
    }

    func updateProgress(with value: Float) {
        if value > maxProgress {
            progressLayer.strokeEnd = 1.0
            return
        }

        progressLayer.strokeEnd = CGFloat(value / maxProgress)
    }

}


text:
Q: Printing Strings Using Multiple Files I am new to C programming so bear with me here. I have been assigned a project where in which the user is prompted to enter a "part number, quantity, and price" when the user enters "0" the program ends, and the information is saved in a text file. A separate program gets compiled and then prints out what the user entered. Here is what the first program (save_inventory.c) prompts the user with.
This program stores a business inventory.

Please enter item data (part number, quantity, price): *3, 1, 2.4*

Please enter item data (part number, quantity, price): *1, 4, 3.0*

Please enter item data (part number, quantity, price): *0*

Thank you. Inventory stored in file inventory.txt.

And here is what the second program(display_inventory.c) is supposed to ouput:
Below are the items in your inventory:

Part#    Quantity     Item Price

3           1    $     2.40
1           4    $     3.00
2           4    $     1.30

I have the code working so far, the only issue is that when I use my display_inventory.c program, the last line of the input is printed twice. So 2, 4, $ 1.30 appears again. Here is the code for both programs:
save_inventory.c:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int pn, q;
float p;

 FILE *fp = fopen("inventory.txt", "wb");

printf("This program stores a business inventory.\n");

for(;;)
{
    printf("Please enter item data (part number, quantity, price): ");
    scanf("%d, ", &pn);
    if(pn == 0){break ;}
    scanf("%d, %f", &q, &p);

    fwrite(&pn , sizeof(pn) ,1, fp);
    fwrite(&q , sizeof(q),1 , fp);
    fwrite(&p, sizeof(p) , 1,fp);

}
printf("Thank you. Inventory stored in file inventory.txt.\n");
fclose(fp);

return 0;
}

And here is display_inventory.c:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int pn, q;
float p;

FILE *fp = fopen("inventory.txt", "rb");
printf("Part#\t Quantity\t Item Price");

for(;!feof(fp);)
{

    fread(&pn , sizeof(pn) ,1, fp);
    fread(&q , sizeof(q),1 , fp);
    fread(&p, sizeof(p) , 1,fp);
    printf("\n%5d\t %8d \t $%9.2f\n",pn,q,p);

}

fclose(fp);
return 0;
}

Since I have spent a bit of time trying to figure this one out, I figured I'd ask if anyone has any tips on how to not have the last entry printed out twice.
Thank you!

A: After the first fread() add an
if (feof(fp))
{
    break;
}

What happens is that the first fread will trigger the end of file, so pn won't be changed. Then the second fread triggers end of file again, q also doesn't get changed. Then the 3rd fread yet again triggers eof, and p remains unchanged. printf will show the old values one more time.


text:
Q: Taking the PMF to find the CDF, probability. Question:We toss a fair coin three times. Let X be the number of heads minus the number of tails obtained.
Write the cumulative distribution function of X.
What I already know: I know how to get the pmf from this problem.
$$
\ P(X=x) = \left\{
  \begin{array}{l l}
   \ {3 \choose 0} (1/2)^3 & \quad \text{for $k = -3$}\\
   {3 \choose 1} (1/2)^3 & \quad \text{for $k = -1$}\\
   {3 \choose 2} (1/2)^3 & \quad \text{for $k = 1$}\\
   {3 \choose 3} (1/2)^3 & \quad \text{for $k = 3$}\\
  \end{array} \right.
$$
I'm not sure how my professor got this cdf:
$$
\ P(X \le x) = \left\{
  \begin{array}{l l}
   \ 0 & \quad \text{for $x \lt -3$}\\
   (1/2)^3 & \quad \text{for $-3 \le x \lt -1$}\\
   (1+3) (1/2)^3 & \quad \text{for $-1 \le x \lt 1$}\\
   (1+3+3) (1/2)^3 & \quad \text{for $1 \le x \lt 3$}\\
   (1+3+3+1)(1/2)^3 & \quad \text{for $3 \le x$}\\
  \end{array} \right.
$$

A: The c.d.f. is not $x\mapsto \Pr(X=x)$; it is $x\mapsto\Pr(X\le x)$.  So, for example, its value at $x=2$ is $\Pr(X\le 2) = \Pr(X=-3) + \Pr(X=-1) + \Pr(X=1)$.


text:
Q: I have got the same mistake frm PDO PHP I use PHP PDO to update my data n database, but htis nt work coretly i still recive te same errror:
        Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number.

how cna i fix this?
             Hello I stil received this error but i can not find a mistake i made. when i throw away execute the code do not throw any error, but nothing change in my database.
            I create code that should update a data in database i still receives this error:
    I really want to now what make this error and hot to fixed i check with manual and everything look find, and i do not find any cntaradiction with my database in sql ask.

         <?php
session_start();
include 'polaczenie_baz_danych.php';
$id_faktury = $_POST['id_faktury'];
$id_sprzedawcy = $_POST['id_sprzedawcy'];
$id_nabywcy = $_POST['id_nabywcy'];
if(isset($_POST['submit']))
{
$numer_faktury = $_POST['numer_faktury'];
$typ_faktury = $_POST['typ_faktury'];
$miejsce_wystawienia = $_POST['miejsce_wystawienia'];
$termin_wystawienia = $_POST['termin_wystawienia'];
$termin_sprzedazy= $_POST['termin_sprzedazy'];
$status_faktury = $_POST['status_faktury'];
$sposob_platnosci = $_POST['sposob_platnosci'];
$termin_platnosci = $_POST['termin_platnosci'];
$numer_konta =  $_POST['numer_konta'];
$towar_usluga = $_POST['towar_usluga'];
$jm = $_POST['jm'];
$ilosc = $_POST['ilosc'];
$cena_netto = $_POST['cena_netto'];
$wartosc_netto = $_POST['wartosc_netto'];
$stawka_vat = $_POST['stawka_vat'];
$kwota_vat = $_POST['kwota_vat'];
$wartosc_brutto = $_POST['wartosc_brutto'];

$nazwa_nabywcy = $_POST['nazwa_nabywcy'];
$nip_nabywcy  = $_POST['nip_nabywcy'];
$adres_nabywcy = $_POST['adres_nabywcy'];
$miasto_nabywcy = $_POST['miasto_nabywcy'];
$kod_pocztowy_nabywcy = $_POST['kod_pocztowy_nabywcy'];

$nazwa_sprzedawcy = $_POST['nazwa_sprzedawcy'];
$nip_sprzedawcy  = $_POST['nip_sprzedawcy'];
$adres_sprzedawcy = $_POST['adres_sprzedawcy'];
$miasto_sprzedawcy = $_POST['miasto_sprzedawcy'];
$kod_pocztowy_sprzedawcy = $_POST['kod_pocztowy_sprzedawcy'];

$sql1 = ('UPDATE faktury SET
typ_faktury=:typ_faktury,
termin_wystawienia=:termin_wystawienia,
miejsce_wystawienia=:miejsce_wystawienia,
numer_faktury=:numer_faktury,
termin_sprzedazy=:termin_sprzedazy,
towar_usluga=:towar_usluga,
jm=:jm,
ilosc=:ilosc,
cena_netto=:cena_netto,
wartosc_netto=:wartosc_netto,
stawka_vat=:stawka_vat,
kwota_vat=:kwota_vat,
wartosc_brutto=:wartosc_brutto,
status_faktury=:status_faktury,
termin_platnosci=:termin_platnosci,
sposob_platnosci=:sposob_platnosci,
numer_konta=:numer_konta

WHERE id_faktury=:id_faktury');

$sql2 = ('UPDATE nabywcy SET nazwa_nabywcy=:nazwa_nabywcy,
 nip_nabywcy=:nip_nabywcy,
 adres_nabywcy=:adres_nabywcy,
 miasto_nabywcy=:miasto_nabywcy,
 kod_pocztowy_nabywcy=:kod_pocztowy_nabywcy
WHERE id_nabywcy=:id_nabywcy');

$sql3 =('UPDATE sprzedawcy SET nazwa_sprzedawcy=:nazwa_sprzedawcy, nip_sprzedawcy=:nip_sprzedawcy, adres_sprzedawcy=:adres_sprzedawcy, miasto_sprzedawcy=:miasto_sprzedawcy, kod_pocztowy_sprzedawcy=:kod_pocztowy_sprzedawcy
WHERE id_sprzedawcy=:id_sprzedawcy');

$performsql1 = $db->prepare($sql1);
$performsql1->bindValue(':typ_faktury',$typ_faktury, PDO::PARAM_STR);
$performsql1->bindValue(':termin_wystawienia',$termin_wystawienia, PDO::PARAM_STR);
$performsql1->bindValue(':miejsce_wystawienia',$miejsce_wystawienia, PDO::PARAM_STR);
$performsql1->bindValue(':numer_faktury',$numer_faktury, PDO::PARAM_STR);
$performsql1->bindValue(':termin_sprzedazy',$termin_sprzedazy, PDO::PARAM_STR);
$performsql1->bindValue(':towar_usluga', $towar_usluga, PDO::PARAM_STR);
$performsql1->bindValue(':jm',$jm, PDO::PARAM_STR);
$performsql1->bindValue(':ilosc',$ilosc, PDO::PARAM_INT);
$performsql1->bindValue(':cena_netto',$cena_netto, PDO::PARAM_STR);
$performsql1->bindValue(':wartosc_netto',($wartosc_netto), PDO::PARAM_STR);
$performsql1->bindValue(':stawka_vat',$stawka_vat, PDO::PARAM_STR);
$performsql1->bindValue(':kwota_vat',$kwota_vat, PDO::PARAM_STR);
$performsql1->bindValue(':wartosc_brutto',$wartosc_brutto, PDO::PARAM_STR);
$performsql1->bindValue(':sposob_platnosci',$sposob_platnosci, PDO::PARAM_STR);
$performsql1->bindValue(':status_faktury',$status_faktury, PDO::PARAM_STR);
$performsql1->bindValue(':termin_platnosci',$termin_platnosci, PDO::PARAM_STR);
$performsql1->bindValue(':numer_konta',$numer_konta, PDO::PARAM_STR);
$performsql1->bindValue(':id_faktury',$id_faktury, PDO::PARAM_INT);
$performsql1->execute();
unset($sql1);

$performsql2 = $db->prepare($sql2);
$performsql2->bindValue(':nazwa_nabywcy',$nazwa_nabywcy, PDO::PARAM_STR);
$performsql2->bindValue(':nip_nabywcy',$nip_nabywcy, PDO::PARAM_STR);
$performsql2->bindValue(':adres_nabywcy',$adres_nabywcy, PDO::PARAM_STR);
$performsql2->bindValue(':miasto_nabywcy',$miasto_nabywcy, PDO::PARAM_STR);
$performsql2->bindValue(':kod_pocztowy_nabywcy', $kod_pocztowy_nabywcy, PDO::PARAM_STR);
$performsql1->bindValue(':id_nabywcy',$id_nabywcy, PDO::PARAM_INT);
$performsql2->execute();
unset($sql2);

Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
$performsql3 = $db->prepare($sql3);
$performsql3->bindValue(':nazwa_sprzedawcy',$nazwa_sprzedawcy, PDO::PARAM_STR);
$performsql3->bindValue(':nip_sprzedawcy',$nip_sprzedawcy, PDO::PARAM_STR);
$performsql3->bindValue(':adres_sprzedawcy',$adres_sprzedawcy, PDO::PARAM_STR);
$performsql3->bindValue(':miasto_sprzedawcy',$miasto_sprzedawcy, PDO::PARAM_STR);
$performsql3->bindValue(':kod_pocztowy_sprzedawcy', $kod_pocztowy_sprzedawcy, PDO::PARAM_STR);
$performsql1->bindValue(':id_sprzedawcy',$id_sprzedawcy, PDO::PARAM_NT);
$performsq3->execute();
unset($sql3);
}
?>

A: In $sql1 you have 18 parameters, but in $performsql1 you have only 17 bindings. You have lost 1 value to bind.
Upd.
You have WHERE id_faktury=:id_faktury' - it's 18th parameter. You have lost value ':id_faktury' to bind.


text:
Q: incorrect syntax when trying to create a url variable Importing and API into a URL variable, but when I add the link it says invalid syntax because of the ' ' for the name.
after get my title the first ' in the demo list end the link. How do I get get the syntax correct so that it finishes the entire url.
url ='https://sitename/sites/org/subsite/test/_api/web/lists/GetByTitle('Demo List')/items'

A: If you want to have apostrophes in your string, then you could put your text between quotation marks instead of apostophes. It should look like this:
url ="https://sitename/sites/org/subsite/test/_api/web/lists/GetByTitle('Demo List')/items"

A: You can put a backslash character followed by the quote ( \' ). This is called an escapesequence and Python will remove the backslash, and put just the quote in the string.
url ='https://sitename/sites/org/subsite/test/_api/web/lists/GetByTitle(\'Demo List\')/items'

This way, you can have any number of quotes in your string and omit them by using backslash.


text:
Q: Create Table by Copying Structure of Existing Table I am trying to create a new table by copying an existing table in SQL Server 2008 using Management Studio. The existing table contains no data. I am using the following code but am receiving an error for Incorrect Syntax near AS. I am not sure what is wrong here. I am a SQL newb and any help would be appreciated.  Thanks.
CREATE TABLE Drop_Centers_Detail
    AS (Select * From Centers_Detail)

A: like this, however this will not create indexes and constraints
select * into Drop_Centers_Detail
from Centers_Detail
where 1 = 0

A: In Sql Server Managment Studio, right-click your existing table and select Script Table as > Create to > New Query Editor Window. This will give you a better starting script that you can use as the base for your new schema.

A: 1) I would suggest generating a create script from the table you want to copy, and then run that on your destination database.
2) Write a Insert statement in another SQL Query window to import that data
Insert Into Database1.Table1(Field1, Field2)
Select Field1, Field2 From Database2.Table


text:
Q: Get character widths for a font I need to get the width for characters from a given font (for example Arial). Only the width of the bounding box, without spacing.
HFONT font = CreateFont(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, L"Arial");

Using the created HFONT, is there a way to extract this information?
int MyGetCharWidth(HFONT font, wchar_t wch)
{
    // How to implement this?
}

A: There's GetCharABCWidths, but be aware that it won't tell you about kerning, so it may or may not be useful depending on what you plan to do with the information.
If you want the width of an actual string of text, there are several functions that will measure it for you, like GetTextExtentPoint32.  Those functions will include any kerning corrections.

A: This should do the job:
int MyGetCharWidth(HFONT font, wchar_t wch)
{
  HDC hDC = GetDC(NULL) ;
  HGDIOBJ oldfont = SelectObject(hDC, font) ;

  RECT rect ;
  DrawText(hDC, &wch, 1, &rect, DT_CALCRECT|DT_NOPREFIX) ;

  SelectObject(hDC, oldfont) ;
  return rect.right - rect.left ;
}

BTW this doesn't make sense:
HFONT font = CreateFont(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, L"Arial");

You must specifiy non null values for some of the parameters, for example:
CreateFont(fontsize, 0, 0, 0, FW_NORMAL, 0, 0, 0,
                          DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
                          CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
                          DEFAULT_PITCH, "Arial");


text:
Q: Will my Logitech 9000 Pro webcam (still) work with Ubuntu? It USED to work - maybe around version 8.04 or earlier. Now all the video apps I used to use just tell me that they can't find a video device.
Even with xscreensavers configured to grab video images, it tells me there's no video device at /dev/video0.
Previously I didn't have to DO anything to make it work. Apparently that's changed?
Thanks in advance!
Aaron

A: If you are talking about the Logitech Quickcam Pro 9000 then i can confirm it works perfectly because i have the same one ;)
The following things work perfectly:

*

*Microphone (Although you need to specify in the sound configuration that you want to use the Mic from the Webcam if you have another Mic connected)

*Changing Brightness, Contrast and Focus.

*Taking Pictures (With Cheese for example).

*Video Recording (If you get slow video then just point the Webcam to some BRIGHT light source then slowly point it to the place you want to record or take a picture. The webcam will auto correct itself)

*Very good lighting (Even in Dark places it does a good job, at least for a Webcam)

*You can change resolution in programs like Cheese (It has very high Resolutions but it lags a little on the higher ones.)

In my case to make it work in Ubuntu 11.04 was this:

*

*Install Ubuntu 11.04

*Connect Webcam

*OMG IT WORKS!!

EDIT - Confirmed again i even used the Motion Tracker program motion and it detected my brother sloooooowly entering the room GOTCHA!!

A: Try running gstreamer-properties and make sure the device is selected. After that try using v4l2ucp to test.


text: Q: User Profile Service not setup, but user information from Active Directory Exists I have yet to setup the User Profile Service on my new SP2010 Farm.  Yet when I go to view my user information or other users' information, it contains properties (mobile number, department, etc) that contain data that were populated from Active Directory.  How did this import/synchronization occur witout the User Profile Service Setup yet?


text:
Q: Can't get opt_expand to work from Ruby (using same code that works in curl) I've written a short Ruby script which creates a nice export of ASANA tasks into csv, however it takes a while to run because I have to do a GET for every task within each project.
I found a way of using opt_expand to get all task data at once for each project which make then number a "Get"s a fraction of what it is at the moment.
However the opt_expand code which works in curl does not work in Ruby, it just ignores the expand command.
Any help would be greatly appreciated,
Normal curl code[snippet1]:
curl -u <token>: https://app.asana.com/api/1.0/projects/<project_id>/tasks

Working opt_expand curl code[snippet2]:
curl -u <token>: https://app.asana.com/api/1.0/projects/<project_id>/tasks?opt_expand=.

Normal Ruby code[snippet3]:
uri = URI.parse("https://app.asana.com/api/1.0/projects/<project_id>")

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
...

Broken Ruby code which returns the same as snippet 3 despite using opt_expand
uri = URI.parse"(https://app.asana.com/api/1.0/projects/<project_id>/tasks?opt_expand=.
")

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
...

A: It's a bit hard to answer without seeing the error message (or server return message) you're getting.
However, keep in mind that Net::HTTP is low level, and might be a bit of an overkill to use for such a simple task. Did you consider using other libraries (i.e: rest-client or Faraday) which will be easier for you to work with. For example:
require 'rest_client'

response = RestClient.get "https://app.asana.com/api/1.0/projects/<project_id>"
if response.code == 200
  # process answer
end

A: Like Greg said, you are not passing the params to server. Ruby URI parse doesn't take in params. Try something like this:
params = { :opt_expand => 'your opt here' }
uri = URI.parse("https://app.asana.com/api/1.0/projects/<project_id>/tasks")
http = Net::HTTP.new(uri.host, uri.port)
...
uri_with_params = "#{uri.path}?".concat(params.collect { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.join('&')) if not params.nil?
req = Net::HTTP::Get.new(uri_with_params, header)
req.basic_auth(key, password)
res = http.start { |http| http.request(req) }


text:
Q: about linux IO performance I wrote a program to test IO performance in java useing FileChannel. Write data and call force(false) immediately. My Linux server has 12 ssd hard drives, sda~sdl, and I test writing data to different hard drive, the performance varies widely, and I don't know why?
code:
public static void main(String[] args) throws IOException, InterruptedException {
    RandomAccessFile aFile = new RandomAccessFile(args[0], "rw");
    int count = Integer.parseInt(args[1]);
    int idx = count;
    FileChannel channel = aFile.getChannel();
    long time = 0;
    long bytes = 0;
    while (--idx > 0) {
        String newData = "New String to write to file..." + System.currentTimeMillis();
        String buff = "";
        for (int i = 0 ; i<100; i++) {
            buff += newData;
        }
        bytes += buff.length();
        ByteBuffer buf = ByteBuffer.allocate(buff.length());
        buf.clear();
        buf.put(buff.getBytes());
        buf.flip();
        while(buf.hasRemaining()) {
            channel.write(buf);
        }
        long st = System.nanoTime();
        channel.force(false);
        long et = System.nanoTime();
        System.out.println("force time : " + (et - st));
        time += (et -st);
    }
    System.out.println("wirte " + count + " record, " + bytes + " bytes, force avg time : " + time/count);
}

Result like this:
sda: wirte 1000000 record, 4299995700 bytes, force avg time : 273480 ns
sdb: wirte 100000 record, 429995700 bytes, force avg time : 5868387 ns
The average time vary significantly.
Here is some IO monitor data.
sda:
iostat data image
sdb:
iostat data image

A: You need to start by measure your SSD disks performance using some standard tool like fio.
Then you can test your utility again using numbers from fio output.
Looks like you are writing into the Linux write cache so that can explain your results :)


text:
Q: Is this a valid React HoC use case? I'm introducing myself to React's HoC pattern.
I have a video player component that sometimes needs to have a select to change a parameter in the video src url.
To simplify things, this a reduced version of my HoC:
function withTimeControl(PlayerComponent) {
  return class extends Component {
    state = {
      src: ''
    }

    updatePlayerDelay = (event) => {
      this.setState({
        src: event.target.value
      })
    }

    render() {
      return(
        <div>
          <PlayerComponent
            title={this.props.title}
            src={this.state.src}
          />

          <PlayerTimeComtrol
            label={this.props.label}
            onChangeHandler={this.updatePlayerDelay}
          />
        </div>
      );
    }
  };
}

And to use it, I would do:
const PlayerWithTimeControl = withTimeControl(Player)

// ...

<PlayerWithTimeControl title='Player title' label='Time control label' />

Where PlayerComponent is the component being wrapped. The HoC basically ads a component, PlayerTimeComtrol to change the src of the video player.
Is this valid use case? Are there other more accurate solutions to this? Maybe just use a component wrapper and not a HoC?

A: This is technically an approach that can be used. But HOCs typically deal with data flow addition/interception, as opposed to UI. IMO, they should be used sparingly. This really feels like overengineering, when you can just have PlayerTimeComtrol accept a children prop and wrap it around PlayerComponent
<PlayerTimeComtrol
  label={this.props.label}
  onChangeHandler={this.updatePlayerDelay}
>
  // with whatever component you want here
</PlayerTimeControl>

A: Yes, that's exactly what HoCs are for: adding functionalities to existing components.


text:
Q: Creating an int and a switch for my quiz app for the iphone Right now I have am creating my first quiz app and have been trying to get into objective c. Right now I have my interface set up minus one thing. There are five different categories of questions in my app.The way I have my interface set up I have my buttons set to be hidden or not hidden depending on the int.
For instance I have one category:
- (IBAction)Category1:(id)sender{

    Category1.hidden = YES;
    Category2.hidden = YES;
    Category3.hidden = YES;
    Category4.hidden = YES;
    Category5.hidden = YES;

    Answer1.hidden = NO;
    Answer2.hidden = NO;
    Answer3.hidden = NO;
    Answer4.hidden = NO;

    Wrong1.hidden = YES;
    Wrong2.hidden = YES;
    Wrong3.hidden = YES;
    Wrong4.hidden = YES;

    SelectCategory.hidden = YES

    int Category1Question = rand() % 100;
    switch (Category1Question) {
        case 0:
            Question.text = [NSString stringWithFormat:@"Actual question in the quiz"]
            Right1.hidden = NO;
            Wrong2.hidden = NO;
            Wrong3.hidden = NO;
            Wrong4.hidden = NO;
            Answer1.text = [NSString stringWithFormat:@"Correct answer here"];
            Answer2.text = [NSString stringWithFormat:@"Wrong Answer"];
            Answer3.text = [NSString stringWithFormat:@"Wrong Answer"];
            Answer4.text = [NSString stringWithFormat:@"Wrong Answer"];
            break;
        case 1:
       //(etc. etc.)

        default:
            break;
    }

}

Right now I think I can figure out how to send back to the category selection page, but I would like to send straight to the next random question within the category and maybe even if they answer incorrectly show a label with the right answer. I think I know how to do the incorrect answer part, but having a switch to bring up the next question within the same category. I think that if I created a new int with it set to 0 and everytime they answer a questions it adds 1 to the int and then an if statement saying if the int = the number of questions then return to the category selection page. The problem is I am not sure exactly where I would do this. This app is strictly for my understanding of how coding works, and what I have for the quiz so far has taught me a lot, but I am lost at where to begin.
Any help is appreciated and if I didn't give the appropriate info to help me please let me know.

A: NSMutableArray *questionArray = [[NSMutableArray alloc] init];
for (int i = 1; i < 5; i++) {
    [questionArray addObject:[[NSNumber alloc] initWithInt:i]];
}

for (int i = 0; i < 4; i++) {

int randomIndex = arc4random() % [questionArray count];
int Category1Question = [[questionArray objectAtIndex:randomIndex] intValue]; //cast to int from NSNumber
[questionArray removeObjectAtIndex:randomIndex];
    switch (Category1Question) {
        case 0:
            Question.text = [NSString stringWithFormat:@"Actual question in the quiz"]
            Right1.hidden = NO;
            Wrong2.hidden = NO;
            Wrong3.hidden = NO;
            Wrong4.hidden = NO;
            Answer1.text = [NSString stringWithFormat:@"Correct answer here"];
            Answer2.text = [NSString stringWithFormat:@"Wrong Answer"];
            Answer3.text = [NSString stringWithFormat:@"Wrong Answer"];
            Answer4.text = [NSString stringWithFormat:@"Wrong Answer"];
            break;
        case 1:
       //(etc. etc.)
} //end for

A little bit of explanation...
The first part creates an NSMutableArray that stores the numbers 1 - 4. I am assuming that you only have four questions in each category, so I went with the numbers 1 - 4. The second for loop iterates four times, or the number of questions you have in each category. Once inside the loop, a random number (1 - 4) is chosen from the array and it is then removed. This random number is then switched and this leads to the specific question being asked. In this case the number is called Category1Question. Note that the for loop cycles four times. This means that every time a question is asked, the switch breaks, then the iteration starts at the top again. A new number is chosen from the array, it is removed, then switched. This time a new question is asked. This process will repeat for as many questions there are. This ensures that all questions are asked and you still stay in the same category.
- Hope this helps.


text:
Q: WordPress, wp-content files I will ask something that I don't realy know if is correct.
in my WordPress installation, I have into wp-content two php files (except the index.php). That two files are they autoloaded from WordPress in some how? Or are they stay there safe ?
Ok. That files are wp-cache-config.php and w3-total-cache-config-ifeed.gr.php

A: Ok, you don't need to worry about those files. They are needed for the Cache plugin you have installed and you don't need to tamper with them. They are perfectly safe.


text:
Q: Massive drop in training error after the first epoch I am training an LSTM autoencoder to recreate the input consisting of eight features(floating-point numbers between 0 and 1). Currently, am utilizing a window size of two and am training the model for 50 epochs. However, while training the network I observed that the training error (Mean Square Error) drops significantly after the first epoch. For example, during the first epoch the training error was 17.25. It dropped to 1.8 at the very next and stagnates after the seventh epoch. I was wondering if random initialization of weights might be causing this therefore I retrained one more network and the same phenomenon repeated.
I am not able to deduce the reason for this significant drop in training error after the first epoch and would appreciate any help. I have attached the training error graph and model information for reference.
Model info:
LSTM_AutoencoderModel(
(encoder): Encoder(
(lstm1): LSTM(16, 64)
(lstm2): LSTM(64, 16)
)
(decoder): Decoder(
(lstm1): LSTM(16, 64)
(lin1): Linear(in_features=64, out_features=16, bias=True)
)
)
Training error graph


text:
Q: Airflow : Not receiving an Error message in Email, whenever the DAG/TASK is failed with on_failure_callback Airflow version 1.10.3
Below is the module code that is been called by on_failure_callback
I have used reason = context.get("exception"), But I get an error as None in the email when the job is failed instead of getting an error message
Output in the email:
Reason for Failure: None
alert_email.py
from airflow.utils.email import send_email
from airflow.models import Variable

def failure_alert(context, config=None):
    config = {} if config is None else config
    email          = config.get('email_id')
    task_id        = context.get('task_instance').task_id
    dag_id         = context.get("dag").dag_id
    execution_time = context.get("execution_date")
    reason         = context.get("exception")

    dag_failure_html_body = f"""
    <title>The below DAG has failed!</title>

    DAG Name: {dag_id}

    Task Id: {task_id}

    Execution Time (UTC): {execution_time}

    Reason for Failure: {reason}

    """

    try:
        send_email(
            to=email,
            subject=f"Airflow alert: <DagInstance: {dag_id} - {execution_time} [failed]",
            html_content=dag_failure_html_body,
        )
    except Exception as e:
        logger.error(f'Error in sending email to address {email}: {e}', exc_info=True)

A: The issue with the version Airflow 1.10.3. We will be upgrading into Airflow 1.10.10


text:
Q: How to inject PathVariable id into RequestBody *before* JSR-303 validation is executed? I'm stuck in an apparently simple problem: I want to perform some custom validation based on the object id in a PUT request.
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public ResponseEntity<Void> update(@Valid @RequestBody ClientDTO objDto, @PathVariable Integer id) {
    Client obj = service.fromDTO(objDto);
    service.update(obj);
    return ResponseEntity.noContent().build();
}

I'd like to create a custom validator to output a custom message in case I update some field that can't be the same of another object in my database. Something like this:
public class ClientUpdateValidator implements ConstraintValidator<ClientUpdate, ClientDTO> {

    @Autowired
    private ClientRepository repo;

    @Override
    public void initialize(ClientInsert ann) {
    }

    @Override
    public boolean isValid(ClientDTO objDto, ConstraintValidatorContext context) {

        Client aux = repo.findByName(objDto.getName());
        if (aux != null && !aux.getId().equals(objDto.getId())) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("Already exists")
                    .addPropertyNode("name").addConstraintViolation();
            return false;
        }

        return true;
    }
}

However, the object id comes from @PathVariable, not from @RequestBody. I can't call "objDto.getId()" like I did above.
On the other hand, it doesn't make much sense to obligate to fill up the object id in the request body, because this way the path variable would become meaninless.
How can I solve this problem? Is there a way to inject the id from PathVariable into RequestBody object before bean validation is executed? If not, what would be a viable solution? Thanks.

A: Try to inject httpServletRequest into the custom validator
public class ClientUpdateValidator implements ConstraintValidator<ClientUpdate, ClientDTO> {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ClientRepository repo;

    @Override
    public void initialize(ClientInsert ann) {
    }

    @Override
    public boolean isValid(ClientDTO objDto, ConstraintValidatorContext context) {
        // for example your path to put endpoint is /client/{id}
        Map map = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        String id = map.get("id");
        Client aux = repo.findByName(objDto.getName());
        if (aux != null && !aux.getId().equals(id)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("Already exists")
                    .addPropertyNode("name").addConstraintViolation();
            return false;
        }

        return true;
    }
}


text:
Q: Is there an Excel function that works the same as filter() from Google Sheets? I have a list of names that each have a value (C:C, D:D). I want to generate a new column (A:A) that only shows the names that have the values I want, without any spaces.
In Google Sheets it's trivial:

I'm moving to Excel due to some shortcomings with Sheets that I can't get around, and can't figure out how to duplicate this functionality. The closest I've come is with MATCH/INDEX, but I was never able to get there. All of the research I've done has pointed to needing VB, which is something I'd like to avoid.

A: In Excel, one must put a formula in each cell that one is expecting a result.  So, the short answer is no there is no function in Excel that would exactly match the use of Filter in Sheets.
To do this I like to use INDEX with AGGREGATE:
=IFERROR(INDEX(C:C,AGGREGATE(15,6,ROW($D$1:INDEX(D:D,MATCH("zzz",C:C)))/($D$1:INDEX(D:D,MATCH("zzz",C:C))<>0),ROW(1:1))),"")

Put that in A1 and copy down till you get blanks.  As stated one must put a function in each cell that one expects a return.

A: Just to update this question, =FILTER now works in Office 365 versions of Excel along with some other dynamic formulas. Excel 2019 or earlier doesn't support this function and I don't think there's any plans to add the functionality into these older products.


text:
Q: Why is my Spring @Autowired not work in this Web Service I Create one Web Service Using JAX-WS but I cant inject a Bean using @Autowired
I tried many things with no success.
Anyone have some ideas to help me on this problem?
Thanks so much.
IndicadoresBSTSWebServiceImpl:
package com.santander.portalcio.ws;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.jws.WebService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.santander.portalcio.backend.entities.IncidentType;
import
com.santander.portalcio.backend.services.bsts.indicators.BSIndicatorVO;
import com.santander.
portalcio.backend.services.bsts.indicators.BSTSIndicatorsFilterVO;
import
com.santander.portalcio.backend.services.bsts.indicators.EntityIndicatorVO;
import

com.santander.
portalcio.backend.services.bsts.indicators.FunctionalityIndicatorVO;
import com.santander.
portalcio.backend.services.bsts.indicators.TSIndicatorVO;
import com.santander.
portalcio.ui.managedbean.home.HomeIndicadoresReportService;

@Service
@WebService(endpointInterface =
"com.santander.
portalcio.ws.IndicadoresBSTSWebServiceInterface")
public class IndicadoresBSTSWebServiceImpl extends
SpringBeanAutowiringSupport
implements IndicadoresBSTSWebServiceInterface {

@PostConstruct
public void init() {
    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}

@Autowired
private HomeIndicadoresReportService homeIndicadoresReportService;

private List<EntityIndicatorVO> resultMesAtual;

private BSTSIndicatorsFilterVO filter = new BSTSIndicatorsFilterVO();

private EntityIndicatorVO selectedEntity = new EntityIndicatorVO();
private BSIndicatorVO selectedBS = new BSIndicatorVO();
private TSIndicatorVO selectedTS = new TSIndicatorVO();
private FunctionalityIndicatorVO selectedFunctionality = new
FunctionalityIndicatorVO();

@Override
public ListaWS teste() {
    filter.setStart(new Date("01/01/2016"));
    filter.setEnd(new Date("01/31/2016"));
    IncidentType[] tipo = { IncidentType.BATCH, IncidentType.ONLINE };
    filter.setTypeList(tipo);
    resultMesAtual = new ArrayList<EntityIndicatorVO>();

    homeIndicadoresReportService.buildValuesToGraph(resultMesAtual,
    selectedEntity, selectedBS, selectedTS,
            selectedFunctionality, filter, false);

    return new ListaWS(resultMesAtual);
    }

}

IndicadoresBSTSWebServiceInterface :
package com.santander.portalcio.ws;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.ParameterStyle;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style = Style.RPC, parameterStyle = ParameterStyle.WRAPPED)
public interface IndicadoresBSTSWebServiceInterface {

@WebMethod
ListaWS teste();

}

web.XML :
<listener>
    <listener-class>
        com.sun.xml.ws.transport.http.servlet.WSServletContextListener
    </listener-class>
</listener>
<servlet>
    <servlet-name>indicadoresBSTS</servlet-name>
    <servlet-class>
        com.sun.xml.ws.transport.http.servlet.WSServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>indicadoresBSTS</servlet-name>
    <url-pattern>/indicadoresBSTS</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>30</session-timeout>
</session-config>

HomeIndicadoresReportService :
package com.santander.portalcio.ui.managedbean.home;

import java.io.Serializable;
import java.util.List;

import     com.santander.
portalcio.backend.services.bsts.indicators.BSIndicatorVO;
import com.santander.
portalcio.backend.services.bsts.indicators.BSTSIndicatorsFilterVO;
import com.santander.
portalcio.backend.services.bsts.indicators.EntityIndicatorVO;
import com.santander.
portalcio.backend.services.bsts.indicators.FunctionalityIndicatorVO;
import com.santander.
portalcio.backend.services.bsts.indicators.TSIndicatorVO;

public interface HomeIndicadoresReportService extends Serializable {

public void selectAndBuildEntityBsTsFunc
(List<EntityIndicatorVO> resultAux,     BSTSIndicatorsFilterVO filter);

public void selectcompFuncInc
(List<EntityIndicatorVO> resultAux, EntityIndicatorVO selectedEntity,
        BSIndicatorVO selectedBS,
TSIndicatorVO selectedTS, FunctionalityIndicatorVO selectedFunctionality,
        BSTSIndicatorsFilterVO filter, boolean isIndicatorsBSTS);

public void selectTotaoInc
(List<EntityIndicatorVO> resultAux, EntityIndicatorVO selectedEntity,
        BSIndicatorVO selectedBS,
TSIndicatorVO selectedTS,
FunctionalityIndicatorVO     selectedFunctionality,
BSTSIndicatorsFilterVO filter);

public void buildValuesToGraph
(List<EntityIndicatorVO> resultMes,     EntityIndicatorVO selectedEntity,
        BSIndicatorVO selectedBS,
TSIndicatorVO selectedTS, FunctionalityIndicatorVO selectedFunctionality,
        BSTSIndicatorsFilterVO filter, boolean isIndicatorsBSTS);

}

HomeIndicadoresReportServiceBean:
package com.santander.portalcio.ui.managedbean.home;
@Repository
@Transactional(propagation =
Propagation.REQUIRED, rollbackFor =     Exception.class)
public class HomeIndicadoresReportServiceBean
implements HomeIndicadoresReportService {

private static final long serialVersionUID = 6513587371275348695L;

@PersistenceContext
private EntityManager em;

@Autowired
private UnavailabilityValidationHelper unavailabilityHelper;

@Autowired
private FunctionalityAvailableService functionalityAvailableService;

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

DecimalFormat df = new DecimalFormat("#,###,###");
DecimalFormat dfHour = new DecimalFormat("00");

@Override
public void buildValuesToGraph(List<EntityIndicatorVO>
resultMes, EntityIndicatorVO selectedEntity,
        BSIndicatorVO selectedBS, TSIndicatorVO
selectedTS, FunctionalityIndicatorVO selectedFunctionality,
        BSTSIndicatorsFilterVO filter, boolean isIndicatorsBSTS) {

    selectAndBuildEntityBsTsFunc(resultMes, filter);

    selectcompFuncInc(resultMes, selectedEntity,
selectedBS, selectedTS, selectedFunctionality, filter,
            isIndicatorsBSTS);

A: While you are attempting to autowire HomeIndicadoresReportService, it does not appear that you have configured that as a Spring bean. You can either annotate that HomeIndicadoresReportService class with @Service, create an XML config entry in your application context file, or create a @Bean configuration method for this in your Java configuration class (depending on how you have configured your Spring context).


text:
Q: Find the range of values that $x$ can take if $9 \log_x5 = \log_5x$ I'm stuck on a homework question about logarithms. I can't work out how to do it, and all I've managed to do is turn $9 \log_x5$ into $ \log_x5^9$. Can anyone guide me onto the right path to solve this?

A: Using $\log_ab=\dfrac{\log b}{\log a},$
we have $$(\log x)^2=9(\log 5)^2=(3\log5)^2=[\log(5^3)]^2$$
$$\implies\log x=\pm \log(125)$$
Either $$\log x=\log(125)$$
Or $$\log x=-\log(125)=(\log125^{-1})$$
Now for real positive $c,d;\log c=\log d\iff c=d$

A: $$\log_x 5= \frac{\log_5 5}{\log_5 x} \Rightarrow \log_x 5=\frac{1}{\log_5 x}$$
$$9 \log_x 5= \log_5 x \Rightarrow  \frac{9}{\log_5 x}=\log_5 x \\ \Rightarrow (\log_5 x)^2=9 \Rightarrow \log_5 x= \pm 3 \Rightarrow 5^{\log_5 x}=5^{\pm 3} \Rightarrow x=5^{\pm 3}$$
So:
$$x=125 \text{ or } x=\frac{1}{125}$$

A: If you prefer to use powers rather than logs you can proceed in this way:
Let $L=\log_5 x$ so that $x=5^L$ and $5=x^{\frac 1L}$ so that $\log_x5=\frac 1L$
We then have $9\cdot \frac 1L = L$ so that $9=L^2$ and $L=\pm 3$ so that $x=5^3$ or $x=5^{-3}$

A: We have
$$9\frac{\ln(5)}{\ln(x)}=\frac{\ln(x)}{\ln(5)}$$ if $x>0$ and $x\ne 1$.

A: For me, it is more natural to go through $\cdots$ natural logarithms. So, $$9log_x5 - log_5x=0$$ becomes $$\frac{9 \log (5)}{\log (x)}-\frac{\log (x)}{\log (5)}=0$$ which simplifies to $$9 \log ^2(5)-\log ^2(x)=0$$ that is to say $$\log(x)=\pm 3\log(5)=\pm \log(5^3)=\pm \log(125)$$ and then the answers you already received.
For the more general problem  $$k\log_xa - \log_ax=0$$ the same procedure would lead to $$\log(x)=\pm \sqrt k \log(a)=\pm \log(a^{ \sqrt k })$$ that is to say $$x=a^{\pm \sqrt k }$$


text:
Q: Vim Configuration for expl3 I've started with programming in expl3 and vim doesn't realise that underscores are now part of LaTeX identifiers.
I'd be much obliged if somebody could explain how to best configure vim so it has the "usual" word boundaries, including underscores, and also does syntax highlighting of words properly.
I know it should be possible to find this information in the vim documentation, but I prefer a quick-and-dirty solution.

A: Quick and dirty solution
:syn match texStatement "\\[a-zA-Z_:]\+"

or add @
:syn match texStatement "\\[a-zA-Z_:@]\+"

It isn't enough, but looks much better.
But better
Modify $VIM/syntax/tex.vim, search b:tex_stylish, and modify all expressions about it.


text:
Q: ASIHTTPRequest synchronously I have an iPhone app which uses ASIHTTPRequest to communicate to a REST service on my server. When I'm running on the simulator, it works just fine, but when I get onto the phone itself, I get weird behavior.
The very first time I click the button that initiates the request, I get the results back immediately, and all is fine. From that point on, when I click the button to initiate the connection it takes about 2-3 minutes to connect. It almost seems like the ASIHTTPRequest that I kicked off first (and from which I've already received the correct results) has not completed. Is there some sort of magic I need to use to terminate the original request before starting the next one? I assumed that since the -start method returned, and I have results from the server that the original request was completed and I could start another.
Any ideas?
Thanks
--Steve

A: Steve - What you've described is a common problem that will occur if the requests are attempting to keep a persistent connection. Try this out:
[request setShouldAttemptPersistentConnection:NO];

A: You're not suppose to call the -start method, it belongs to the NSOperation. The ASIHTTPRequest interface is either -startSynchronous or -startAsynchronous.
However, it's highly recommend to use the asynchronous call otherwise, your main thread (ie., UI) will be blocked.
From the ASIHTTPRequest documentation[1]

In general, you should use
  asynchronous requests in preference to
  synchronous requests. When you use
  ASIHTTPRequest synchronously from the
  main thread, your application's user
  interface will lock up and become
  unusable for the duration of the
  request. Synchronous requests are only
  really suitable for software without a
  UI (like a script that runs from the
  terminal), or if you are running the
  request from a separate thread that
  you maintain (perhaps from inside your
  own NSOperation, for example).

[1] http://allseeing-i.com/ASIHTTPRequest/How-to-use


text:
Q: Acessing request attribute in jsp (Spring 3 mvc) iam using a very basic basic basic controller in spring mvc
...
@RequestMapping("/welcome")
    public ModelAndView helloWorld() {

        String message = "Hello World, Spring 3.0!";
        return new ModelAndView("helloteste", "message", message);
    }
...

but when accessing it from a jsp, nothing is shown.
Jsp bellow
<html>
<head>
<title>Spring 3.0 MVC Series: Hello World </title>
</head>
<body>
${message}

</body>
</html>

Result on the screen (the server does not resolve the tag ...)
${message}

However if i get te info directely from the attributes of the request, it works ...
<%
String s = (String ) request.getAttribute("message");
out.print(s);

%>

Why the notation ${...} is not working ???

A: It seems as if the JSP is not resolving the expression language.  This can be a configuration issue if your web.xml file does not specify a version attribute of 2.4 or greater for the <web-app/> tag.  In this case, I would recommend updating your web.xml file to following, provided that your app server is modern enough:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

</web-app>


text:
Q: Git Incorrectly Storing CoreData xcdatamodel Found this issue yesterday when needing to restore a versioned CoreData model from git and it didn't work. XCode only saw it as an XML file and would never allow me to change it to a CoreData Model.
It seems that when storing to Git the xcdatamodel and xcdatamodeld files are being converted to folders with xml files inside called contents.
I posted about the issue in the iOS Community on Twitter and was told that I needed to create a .gitattributes file with the line
*.xcdatamodel binary merge=union

I did that and have tried everything I can think of to get this to store the xcdatamodel correctly and nothing is changing.
I have done:
mv .git/index .git/index.bak
git reset
git status
git add .
git commit
git push

I have tried modifying the CoreData model in XCode so it notices a change and then pushing to git again, and closing XCode and deleting the xcdatamodeld pushing to git and then putting it back and pushing as if it's a new file.
No matter what I've tried I still see the xcdatamodeld as a folder with xcdatamodel folders inside it and inside them, xml contents files.
What am I doing wrong?


text:
Q: Messaging: This browser doesn't support the API's required to use the firebase SDK. (messaging/unsupported-browser) I am getting this error after deploying our website , my domain is domain.com and i can't change it to https or localhost , so how do i get rid of this error.
provider.ts:122 Uncaught FirebaseError: Messaging: This browser doesn't support the API's required to use the firebase SDK. (messaging/unsupported-browser).
    at e.instanceFactory (index.ts:56:25)
    at e.getOrInitializeService (provider.ts:318:33)
    at e.getImmediate (provider.ts:115:21)
    at e._getService (firebaseApp.ts:136:22)
    at e.<computed> [as messaging] (firebaseNamespaceCore.ts:228:29)
    at Object.s [as messaging] (firebaseNamespaceCore.ts:209:32)
    at Module.<anonymous> (firebaseInit.js:18:28)
    at a ((index):1:2329)
    at r ((index):1:2198)
    at Array.t [as push] ((index):1:2061)

A: Firebase Cloud Messaging is only supported on HTTPS web sites. If you can't put your site on HTTPS, you won't be able to use FCM to deliver push notifications.
Also see:

*

*Firebase messaging is not supported in your browser how to solve this?


text:
Q: In R, how can I draw a negative (1:1 ratio) line in graph? Here is a data
x<- c(10,25,35,45,55)
y<- c(30,50,25,17,17)
dataA<- data.frame (x,y)

ggplot(data=dataA, aes(x=x, y=y)) +
  geom_point (col="Black", size=4) +
  scale_x_continuous(breaks= seq(0,70,10), limits = c(0,70)) +
  scale_y_continuous(breaks= seq(0,70,10), limits = c(0,70)) +
  labs(x="x", y="y") +
  theme(axis.line = element_line(size = 0.5, colour = "black")) +
  windows(width=5.5, height=5)

I want to draw a 1:1 ratio line (not a regression). So if I add geom_abline()
ggplot(data=dataA, aes(x=x, y=y)) +
  geom_point (col="Black", size=4) +
  scale_x_continuous(breaks= seq(0,70,10), limits = c(0,70)) +
  scale_y_continuous(breaks= seq(0,70,10), limits = c(0,70)) +
  geom_abline (slope=-1, linetype = "dashed", color="Red") +
  labs(x="x", y="y") +
  theme(axis.line = element_line(size = 0.5, colour = "black")) +
  windows(width=5.5, height=5)

The line is not a full 1:1 ratio. If I add geom_abline (slope=1, linetype = "dashed", color="Red"),
it works well.

How do I draw a negative 1:1 ratio line?
Thanks,

A: The -1 slope line you're drawing will intersect the origin [0,0]. I'm guessing you want to move the line so more of it shows. You can do x = 'x' , y = 'y' + 70 in the plot coordinates. Replace 70 with max(y) for a dynamic plot?


text:
Q: How to Create New Array with Most Recent Timestamps from a Log Array If given an array of indices let indices = [0,1,15,16,22].
And an array of objects
let history = [{
  id: 0
  status: 200,
  time: 123454678
}, {
  id: 1
  status: 404,
  time: 123454678
}, {
  id: 1
  status: 200,
  time: 123454678
}, {
  id: 1
  status: 404,
  time: 143454678
}, {
  id: 2
  status: 200,
  time: 103454678
}, etc.]

How could I create a new array that contains:

*

*The status is 200

*The most recent object at index (by timestamp)

*Only one index per id

I think the pattern is something like the following, but I am not sure how to ensure that only one (most recent by id) object is pushed to dataToUpdate.
let dataToUpdate = [];
history.map((el, i) => {
  if (el.id.includes(indices) && el.status === 200 && some_other_check_for_id) {
    dataToUpdate.push(el);
  }
});

A: You could reduce the array by looking for status and indices. If valid, seach for an inserted object in the result set and either update or push the object to the result set.

var indices = [0, 1, 15, 16, 22],
    values = [{ id: 0, status: 200, time: 123454678 }, { id: 1, status: 404, time: 123454678 }, { id: 1, status: 200, time: 123454678 }, { id: 1, status: 404, time: 143454678 }, { id: 2, status: 200, time: 103454678 }],
    result = values.reduce((r, o) => {
        if (o.status !== 200 || !indices.includes(o.id)) return r;
        var index = r.findIndex(({ id }) => id === o.id);
        if (index !== -1) {
            if (r[index].time < o.time) r[index] = o;
        } else {
            r.push(o);
        }
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can sort the history by timestamp, then filter elements by status and id and remove duplicates after that using another filter:

let indices = [0,1,15,16,22];

let history = [{
  id: 0,
  status: 200,
  time: 123454678
}, {
  id: 1,
  status: 404,
  time: 123454678
}, {
  id: 1,
  status: 200,
  time: 123454678
}, {
  id: 1,
  status: 404,
  time: 143454678
}, {
  id: 2,
  status: 200,
  time: 103454678
}]

const dataToUpdate = history
  .filter(el => el.status === 200 && indices.includes(el.id))
  .sort((a, b) => b.time - a.time)
  .filter((el, i, arr) => i === arr.findIndex((item) => item.id === el.id))

console.log(dataToUpdate)

A: You can firstly filter your array, to have in it only items, that is included in the indices array and their status is 200. Then filtered array convents into the map. That map contains most recent items belong to provided indices. Then it should be converted back to the array.

let indices = [0,1,15,16,22];
let history = [
{
    id: 0,
    status: 200,
    time: 123454678
},
{
    id: 1,
    status: 404,
    time: 123454678
},
{
    id: 1,
    status: 200,
    time: 123454678
},
{
    id: 1,
    status: 200,
    time: 143454679
},
{
    id: 2,
    status: 200,
    time: 103454678
}];

const dataToUpdate = getMostRecentById(indices, history);

function getMostRecentById(ids, logs) {
    const recentsMap = logs.filter(log => {
            return ids.includes(log.id) && log.status === 200;
        })
        .reduce(getMostRecentMap, []);

  return Object.values(recentsMap);
}

function getMostRecentMap(mostRecentMap, currentLog) {
    const isAlreadyMappedByCurrentLogId = Boolean(mostRecentMap[currentLog.id]);

    if (!isAlreadyMappedByCurrentLogId) {
        mostRecentMap[currentLog.id] = { ...currentLog };

        return mostRecentMap;
    }

    const isIdsEqual = mostRecentMap[currentLog.id].id === currentLog.id;
    const isCurrentLogGoneLater = mostRecentMap[currentLog.id].time < currentLog.time;

    if (isIdsEqual && isCurrentLogGoneLater) {
        mostRecentMap[currentLog.id] = { ...currentLog };
    }

    return mostRecentMap;
}

console.log(dataToUpdate);


text:
Q: Materials to complement "Interacting Electrons and Quantum Magnetism" by Assa Auerbach Does anyone know of any material, such as lecture notes from a university, that can complement the sometimes brief chapters of the book "Interacting Electrons and Quantum Magnetism" by Assa Auerbach?
Any suggestions for supplemental material for this book will be helpful.

A: These lecture notes should be helpful for sections I and II:
https://www.physik.tu-dresden.de/~timm/personal/teaching/thmag_w09/lecturenotes.pdf
https://www.st-andrews.ac.uk/~jmjk/keeling/teaching/magnetism-notes.pdf
For section III on path integrals, the Tong Lecture Notes on Statistical Field Theory are great.


text:
Q: "She kissed her son goodbye". Is there another better way? I don't understand the sentence "She kissed her son goodbye". It's not better to say "She kissed her son (in the) goodbye", isn't it?

A: Adding "in the" is decidedly worse, not better.  The original sentence is a perfectly natural, common idiom in English.
An expanded version that might help clarify the meaning for you would be:
She kissed her son as a way of saying goodbye to him


text:
Q: Content is pushed down I would like to let my page look like the following:

However, currently it looks like that:
my website
I tried to change the padding-right / left, but nothing changes within the menu.
<article style="padding-right: 10px; padding-left: 10px;" class="post-6 page type-page status-publish entry" itemscope="" itemtype="http://schema.org/CreativeWork"><header class="entry-header">

Any suggestions what I am doing wrong?
I  appreciate your replies!

A: Apply the following rules:
.entry-content {
  width: 100%;
}

aside {
  float: right;
  width: 75%;
}

A: Well, here you go:
first step:
move entry-content div to facet-container beside facet_selection then change your css from:
.entry-content {
    float: left;
    width: 790px;
}

to:
 .entry-content {
    float: left;
    width: 100%;
}

because your parent div is entry-content and that product div is entry-content too. you should change class name for ex. to entry-content2 now set some style for it:
.entry-content2 {
    float: right;
    width: 795px;
}

then change css from:
#facet_selection {
    width: 22%;
    padding: 1%;
    margin-right: 2%;
}

to:
#facet_selection {
    width: 260px;
    padding: 1%;
    margin-right: 2%;
}

ok, now your turn, you can change width or padding or margin as you want. I see you used many extra padding or margin, you can remove some. I did it on inspect element and it works, can't move all your website to JSFiddle, so follow my instruction.
result:


text:
Q: How to get value of start and end in dataZoom changed event in echarts baidu? How to get value of start and end in dataZoom changed event in echarts baidu?

A: Listen to the dataZoom event dispatched by eCharts after the dataZoom has changed.
myChart.on('dataZoom', function(e) {
    console.log(e);         // All params
    console.log(e.start);   // Start value
    console.log(e.end)      // End value
});

Documentation on dataZoom event

When using eCharts with vue.js library:
Template:
<IECharts @dataZoom="updateZoom"></IECharts>

Code (wrap in methods):
methods: {
    updateZoom(e) {
        // See all available properties of the event
        console.log(e);
    }
}

Documentation on IEcharts


text:
Q: How to remove subarray with a common element in another array in python? ListA = [['abc','15','2021-10-02 08:53:29'],
         ['def','10','2021-10-01 07:52:19'],
         ['abc','15','2021-10-02 09:53:29'],
         ['def','10','2021-10-01 06:52:19'],
         ['gfc','10','2021-10-01 07:52:19']]

ListB = ['abc','def']

Since ListB has 'abc' and 'def', the script should

*

*compare subarrays in array A which have "abc":

*

*find the latest date. eg.'2021-10-02 09:53:29'

*remove subarray which has "abc" but the date is earlier than the latest date

*compare subarrays in array A which have "def"
a) find the latest date. eg. '2021-10-01 07:52:19'
b) remove subarray which has "def" but the date is earlier than the latest date
The final output should be
A = [['def','10','2021-10-01 07:52:19'],
     ['abc','15','2021-10-02 09:53:29'],
     ['gfc','10','2021-10-01 07:52:19']]

How to do this in Python?

A: You could sort the array by key and date, then groupby and take the item with highest date if key is in ListB else, the whole array. Finally flatten using chain:
from itertools import groupby, chain

list(chain(*([list(g)[-1]] if k in ListB else list(g)
             for k,g in groupby(sorted(ListA, key=lambda x: (x[0], x[-1])), lambda x: x[0])
            )
          ))

output:
[['abc', '15', '2021-10-02 09:53:29'],
 ['def', '10', '2021-10-01 07:52:19'],
 ['gfc', '10', '2021-10-01 07:52:19']]

NB. this is not preserving the original order of the lists
keeping order
If order is important, it is possible to save it (here using enumerate) and to reorder after filtering:
from itertools import groupby, chain

[
i[1] for i in
sorted(chain(*([list(g)[-1]] if k in ListB else list(g)
             for k,g in groupby(sorted(enumerate(ListA), key=lambda x: (x[1][0], x[1][-1])), lambda x: x[1][0])
            )
          ))
]

output:
[['def', '10', '2021-10-01 07:52:19'],
 ['abc', '15', '2021-10-02 09:53:29'],
 ['gfc', '10', '2021-10-01 07:52:19']]