text:
Q: Junit HSQLDB - user lacks privilege or object not found - THIS_.oh-ordnbr I am getting an exception when my column name contains hyphen "-"
    Entity : this is the entity name.
    @Entity
    @Table(name = "RequestHeader")
    public class RequestHeader implements Serializable {
    ....
    ....
    @Column(name = "`oh-ordnbr`")
    private Integer ohOrdnbr;

Schema definition: This is the query for schema creation.
    CREATE MEMORY TABLE PUB.REQUESTHEADER(
           REQUESTID INTEGER,
           IMUSERID INTEGER,
           REQUESTDATE DATE,
           REQUESTTIME INTEGER,
           REQUESTSTATUS VARCHAR(19),
           REQUESTTYPE VARCHAR(22),
           HEADERINSTRUCTIONS VARCHAR(5150),
           DATEFORMAT VARCHAR(20),
           TIMEFORMAT VARCHAR(20),
           LANGUAGEID INTEGER,
           "OH-ORDNBR" INTEGER,
           "OH-TRCNSTAMP" INTEGER,
           ISPICKUPLIST BIT(1),
           CONSTRAINT "RQH-1" PRIMARY KEY(REQUESTID)
     );

The error is below:
Exception Stack: Error message which I have received by running the Junit.
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: THIS_.oh-ordnbr
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.ExpressionColumn.checkColumnsResolved(Unknown Source)
at org.hsqldb.QueryExpression.resolve(Unknown Source)
at org.hsqldb.ParserDQL.compileCursorSpecification(Unknown Source)
at org.hsqldb.ParserCommand.compilePart(Unknown Source)
at org.hsqldb.ParserCommand.compileStatement(Unknown Source)
at org.hsqldb.Session.compileStatement(Unknown Source)
at org.hsqldb.StatementManager.compile(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)

Could some one help me in fixing this?

A: The reason for the object not found error is the fact that the oh-ordnbr column is defined to be case sensitive (this is due to the double quotes you put around it).
You have two possible solutions:

*

*Do not use dashes (hyphens) in your SQL. It is bad practice anyway, use underscores instead.

*Update the JPA annotation as follows:
  @Column(name = "`OH-ORDNBR`")
  private Integer ohOrdnbr;

I strongly recommend using underscores instead of dashes, you never know what weirdness different JPA implementations might have when using the second solution.

A: Check your configuration file has correct provider, I fixed same issue by providing org.hibernate.ejb.HibernatePersistence provider.

A: If HSQL Scripts are run via Java and if any new table query is followed by select/alter/update queries it always throws "user lacks privilege object". In reality the create queries after execution with Java Statements never gets commited into the DB and it is not persisted and we run our select/alter/update and it results in the exception. If we run the queries line by line and commit for each line, we could avoid this error.


text:
Q: Maps Pro working in Jasper Studio but not on IBM WAS Server I installed the TIBCO Jaspersoft Studio Professional - Visual Designer for JasperReports verion 6.0.1 30 Day Trial. I was able to create simple bar and pie chart and after compiling the jrxml into jasper i was also able to deploy them on IBM WAS Server, all of them worked like charm. But when i created chart using Maps Pro i was able to view it correctly in Preview but when i compiled it to jasper and deployed it to IBM WAS server it didn't worked.
In my view following was root cause:
Caused by: java.lang.ClassNotFoundException: com.jaspersoft.jasperreports.fusion.maps.StandardMapComponent from [Module "deployment.siperian-mrm.ear.zds-gui.war:main" from Service Module Loader].

Does in Trial version this doesn't work or i am doing something wrong, or need some classpath settings?
Following is the detail log for the error i am getting in server:

18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  com.siperian.dsapp.domain.common.DomainLevelException: EXCEPTION||An
  unexpected error occurred. 18:17:55,856 INFO  [stdout]
  (AsyncAppender-Dispatcher-Thread-144)       at
  com.siperian.dsapp.mde.domain.report.MDEReportService.generateReport(MDEReportService.java:70)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  com.siperian.dsapp.mde.jsf.server.report.ReportHandler.handleRequest(ReportHandler.java:61)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.springframework.web.context.support.HttpRequestHandlerServlet.service(HttpRequestHandlerServlet.java:63)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:295)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  com.siperian.dsapp.jsf.server.security.AbstractSecurityFilter.doFilter(AbstractSecurityFilter.java:210)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  com.siperian.dsapp.jsf.server.security.StandardSecurityFilter.doFilter(StandardSecurityFilter.java:112)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:236)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:231)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:926)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at java.lang.Thread.run(Thread.java:745) 18:17:55,866 INFO  [stdout]
  (AsyncAppender-Dispatcher-Thread-144) Caused by:
  com.siperian.dsapp.datasource.report.DBReportServiceException:
  net.sf.jasperreports.engine.JRException: Class not found when loading
  object from InputStream 18:17:55,866 INFO  [stdout]
  (AsyncAppender-Dispatcher-Thread-144)       at
  com.siperian.dsapp.datasource.report.DBReportService.generateReport(DBReportService.java:34)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  com.siperian.dsapp.mde.domain.report.MDEReportService.generateReport(MDEReportService.java:68)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  ... 22 more 18:17:55,866 INFO  [stdout]
  (AsyncAppender-Dispatcher-Thread-144) Caused by:
  net.sf.jasperreports.engine.JRException: Class not found when loading
  object from InputStream 18:17:55,866 INFO  [stdout]
  (AsyncAppender-Dispatcher-Thread-144)       at
  net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:253)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:229)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:405)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:824)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  com.siperian.dsapp.datasource.report.DBReportService.getJasperPrint(DBReportService.java:40)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  com.siperian.dsapp.datasource.report.DBReportService.generateReport(DBReportService.java:25)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  ... 23 more 18:17:55,866 INFO  [stdout]
  (AsyncAppender-Dispatcher-Thread-144) Caused by:
  java.lang.ClassNotFoundException:
  com.jaspersoft.jasperreports.fusion.maps.StandardMapComponent from
  [Module "deployment.siperian-mrm.ear.zds-gui.war:main" from Service
  Module Loader] 18:17:55,866 INFO  [stdout]
  (AsyncAppender-Dispatcher-Thread-144)       at
  org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:213)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:459)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:408)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:389)
  18:17:55,866 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  at
  org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:134)
  18:17:55,856 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-144)
  [2015-03-04 18:17:55,846] [http-/192.168.1.14:8080-5] [ERROR]
  com.siperian.dsapp.mde.jsf.server.report.ReportHandler: SIP-49000

Following is the header in my jrxml:
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="SupplierStateWiseMap" pageWidth="900" pageHeight="250" orientation="Landscape" columnWidth="900" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="88aacb86-d339-42d7-9586-69cebc5e763f">

Any help would be highly appreciated

A: to me it appears related to missing required libraries for JasperReports PRO components. Fusion Charts/Widgets/Maps are with HTML5 charts part of the Jaspersoft Professional package.
I'm not sure how it is configured your server, but you should check to have the related jars + license information (even if trial) + jasperreports properties set.
Did you tried to test your reports into a test trial installation of JasperReports Server PRO ?
Regards,
Massimo.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sufficient conditions for a set to be a countable generator of a metrizable topology Let $(\Omega, \tau)$ be a metrizable topological space and $A$ be a countable, dense subset.
Just a question on the logic of proving that a set, say $\mathcal{E}:=\{B_{q}(a):a \in A, q \in \mathbb Q_{+}\}$ is a countable generator of $\Omega$.
I thought: We let a $B \in \tau$ and need to find a cover $(A_{n})_{n}\subseteq \tau$, so that $\bigcup\limits_{n \in \mathbb N} A_{n}=B$
But can I rather prove it by looking at individual elements of $\Omega$? i.e. Let $\omega\in \Omega$ arbitrary and then for any $B_{r}(\omega)$ if we can find a $q \in \mathbb Q_{+}$ and an $a \in A$ such that $B_{q}(a)\subseteq B_{r}(\omega)$ then we are done? Am I correct? I am just unsure whether this condition is enough because I am not sure whether the union then remains countable?
I just need a logic refresher.

A: Yes, this is enough. If for every $x \in B_r(\omega)$ you show that there are $a_x \in A$ and $q_x \in \mathbb{Q}_+$ such that $x \in B_{q_x}(a_x)\subset B_r(\omega)$, then of course $B_r(\omega)$ is the union of the family $\{ B_{q_x}(a_x)\}_{x \in B_r(\omega)}$. Why is this family countable? Well, because it is a subfamily of the family $\mathcal{E}$, which is countable.
The family $\mathcal{E}$ is countable because $\mathcal{E}=\bigcup_{a \in A}\{B_q(a):q\in \mathbb{Q}_+\}$, where $A$ is countable and, for every $a\in A$, it is the case that $\{B_q(a):q\in \mathbb{Q}_+\}$ is countable. Hence, if $\{a_n \}_{n \in \mathbb{N}}$ is an enumeration of $A$, the map: $$\mathcal{E} \ni B_q(a_n)\mapsto (n,q)\in \mathbb{N} \times \mathbb{Q}_+$$ is injective, and of course $\mathbb{N} \times \mathbb{Q}_+$ is countable.

A: It's enough to note that the set $\mathcal{E}$ is countable (it's indexed by the countable set $A \times \Bbb Q^+$) and that it is a base for the topology $\tau$.
And the latter indeed means
$$\forall O \in \tau: \forall \omega \in O: \exists E \in \mathcal{E}: \omega \in E \subseteq O\tag{1}$$
And this can easily be seen: first pick $r>0$ such that $B_r(\omega) \subseteq O$ by openness of $O$ in the metric topology. Also, find $a \in B_{\frac{r}{2}}(\omega)$ by density of $A$, and find a rational $q>0$ such that $d(a,\omega) < q < \frac{r}{2}$. Then $x \in B_q(a)$ implies
$$d(x,\omega) \le d(x,a) + d(a,\omega) < q + \frac{r}{2} < r$$
so that $$\omega \in B_q(a) \subseteq B_r(\omega) \subseteq O$$
as required, as $B_q(a) \in \mathcal{E}$.
$(1)$ implies that we can write any subset open $O$ as a union of elements from $\mathcal{E}$ and this union is automatically countable as $\mathcal{E}$ is (we will use many elements of $\mathcal{E}$ doubly in general, but in a set repeated elements don't matter). Or given $O$ in $\tau$, we define $$\mathcal{E}(O) = \{E \in \mathcal{E}: E \subseteq O\}$$
and then $(1)$ says that $O \subseteq \bigcup \mathcal{E}(O)$ and the reverse inclusion is clear from the definition (a union of subsets of $O$ is a subet of $O$) so
$$\bigcup \mathcal{E}(O) = O$$
as required, and $\mathcal{E}(O) \subseteq \mathcal{E}$ is of course countable.


text:
Q: QTableview how to save checkbox value c++ I am referring to the code in this answer and this to create a tableview with checkboxes.
I am trying to create a table, that shows a list of student in my database with checkbox alongside.
Now that i have done that,
Question is:

*

*How do I save the value of the checkboxes to my sql database?

*How do I present the initial state of checkboxes from the value in database? (Eg: 1 for checkbox is checked, 0 for unchecked)
(I am open to any ways of implementing the above requirement, so feel free to provide your solution other than the codes below)
Here is my code:
mysqlquerymodel.h
class MySqlQueryModel : public QSqlQueryModel
{
    Q_OBJECT
public:
    explicit MySqlQueryModel(QObject *parent = 0);
    Qt::ItemFlags flags(const QModelIndex & index) const;
    QVariant data(const QModelIndex & index, int role) const;
    bool setData(const QModelIndex & index, const QVariant & value, int role);
    QMap<int, Qt::CheckState> check_state_map;
};

mysqlquerymodel.cpp (ignore the qdebug its for checking)
MySqlQueryModel::MySqlQueryModel(QObject *parent) : QSqlQueryModel(parent), check_state_map()
{
}

Qt::ItemFlags MySqlQueryModel::flags(const QModelIndex & index) const
{
    if (!index.isValid()) {
        qDebug()<<("item1");
        return nullptr;
    }
    if (index.column() == 2){
        qDebug()<<("item2");
        return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable;
    }
    qDebug()<<("item3");
    return  Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

QVariant MySqlQueryModel::data(const QModelIndex & index, int role) const
{
    if (!index.isValid()){
        qDebug()<<("data1");
        return QVariant();
    }
    if(role== Qt::CheckStateRole)
    {
        if(index.column() == 2)
        {
            if (check_state_map.contains(index.row())){
                qDebug()<<("data2");
                return check_state_map[index.row()] == Qt::Checked ? Qt::Checked : Qt::Unchecked;
            }
            qDebug()<<("data3");
            return Qt::Unchecked;
        }
    }
    return QSqlQueryModel::data(index,role);//!!!!!
}

bool MySqlQueryModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
    if(!index.isValid()){
        qDebug()<<("set1");
        return false;
    }
    if (role == Qt::CheckStateRole && index.column() == 2)
    {
        qDebug()<<("set2");
        check_state_map[index.row()] = (value == Qt::Checked ? Qt::Checked : Qt::Unchecked);
    }
    qDebug()<<("set3");
    return true;
}

I am trying to implement it in tawindow.ui
tawindow.cpp
//load table
void TAWindow::on_loadBtn_clicked(){
            conn.connOpen();
            QSqlQuery* qry = new QSqlQuery(conn.mydb);

            qry->prepare("select * from students");
            qry->exec();
            tablemodel->setQuery(*qry);
            ui->tableView->setModel(tablemodel);

            conn.connClose();
        }

    //save table and update database
    void TAWindow::on_saveBtn_clicked()
    {

    }

Thanks in advance.

A: you can use ui->combobox->ischecked(); to check if the comboBox is checked or not.
and to store the state of the comboBox you can use a variable.
Something like this :
QString var;

if(ui->comboBox->isChecked())
{
    var = "Checked";
}
else
{
    var = "Not Checked";
}

and store var in you database.


text:
Q: How to catch a SyntaxError when f-strings are implemented - when obsolete python is used I am working on issue that I was thinking is a minor thing but I cannot get it to work.
As in the title - I wrote a program that requires usage of python3.6+ due to f-strings presence. My intention is to catch the SyntaxError when user for example have python3.5 on his OS.
My initial idea:
def main():
    var = "more"
    print(f'I like f-strings a lot and {var}')

if __name__ == "__main__":
    if (sys.version_info.major == 3) and (sys.version_info.minor < 6):
        print("This program requires python3.6 or newer")
        print(old_python_error_message)
    else:
        print("Program starts...")
        main()

The problem is that I still got that error before script even starts.
Reason - as far as I researched - is:

You can only catch SyntaxError if it's thrown out of an eval, exec, or import operation.

Link: Failed to catch syntax error python
I still have no idea how can I do that in f-strins usage case.
Thanks for your time

A: It looks like all you want to do on pre-3.6 versions is report an error and terminate the program, and you just want a more user-friendly error message than a SyntaxError stack trace. In that case, instead of trying to catch a SyntaxError, have an entry point file that doesn't use f-strings, and do the version check there, before loading any code that uses f-strings:
# entry point
import sys

if sys.version_info < (3, 6):
    # report error, terminate program
else:
    import whatever
    whatever.main()


text:
Q: Skip code in Qt Valgrind Function Profiler In Qt you can integrate valgrind to analyze your code. I'm using the Valgrind Function Profiler in the Analyze mode and hit the Start button. The problem is, that I have a huge startup sequence which I'm not interested in.
I found defines in the valgrind/callgrind.h that should help me:

*

*CALLGRIND_START_INSTRUMENTATION

*CALLGRIND_STOP_INSTRUMENTATION

*CALLGRIND_DUMP_STATS

According to this article I have to execute valgrind with the following options:
valgrind --tool=callgrind --instr-atstart=no ./application
But how do I do that within Qt? I still want to use the nice GUI and navigation.
Thanks!

A: Assume you have a project with a "main.cpp" and a sub-folder "build". Create a text file called "my_valgrind.sh" next to the "main.cpp" and put the following lines in it:
#!/bin/bash
valgrind --instr-atstart=no $@ ./build/[...]

replace the [...] with the name of your executable. Qt provides the remaining arguments through the $@
Afterwards make the sh file run-able: Rightclick on the .sh file->Properties->Permissions->Allow Execution as Program (or use command line solution)
Maybe you need to change the permissions ( chown [username] my_valgrind.sh )
In Qtcreator you go to the Tools->Options->Analyzer and replace the valgrind executable with the full path to the my_valgrind.sh file
Then it should work.
Important:

*

*If you change the name of the generated executeable you have to change the
.sh file.

*When valgrind is running your program with this method, it is not started from the build folder but from the folder where the .sh file is in (one level up). Hence you have to rename relative paths like "../data/" to "data/"

A: You could try this approach which I used once. Create a bash script.
#!/bin/bash
valgrind --tool=callgrind --instr-atstart=no $@

make this an executable (chmod +x) and use this as the executable Qt Creator -> Tools -> Options -> Analyzer.
Just worth a try.


text:
Q: zend onChange submit i'm trying to submit a form with the event "onchange" on a Zend_Form_Element_Select but i dont succeed. with a simple button Zend_Form_Element_Submit i dont have probleme, but impossible with the onchange on my liste.
the code on my form:
$this->setName('myparamcliform');
$this->setAttrib('id', 'myformm');
$this->setAction('/first/second/index');

$Liste5 = new zend_psai_Liste();
$ListeActivite = $Liste5->ListeActivite();
$activite = new Zend_Form_Element_Select('activite',array('onchange' => "alert('hello 6');;"));
    $activite->setLabel('')
          ->setMultiOptions($ListeActivite);

there is no problem with a simple alert message, but when i replace it by a submit function, it doesn't work.
different element found on the web (thanks stackoverflow :) ) i tryed :
    //documents.forms['myformm'].submit();
    //document.myparamcliform.submit();
    //->setAttrib('onChange', "this.form.submit();");
    //document.getElementById('myformm').submit()
    //,array('onchange' => 'this.form.submit();')

    $mysubmit = new Zend_Form_Element_Submit('mysubmit');
    $mysubmit->setLabel('RECHERCHER');

    $this->addElements(array($activite,$mysubmit));

with these different solution, it doesn't work. no error message and no action with the "onchange", but no probleme with the simple alert message.

A: Why you don't assign a class or id to a button and bind a function to it which will be in some.js file?
It will work for sure and this way you will increase maintainability of your scripts. Simple functions like alert() is ok to write inline, but more complex scripts better to put separately from the template.


text:
Q: Find the difference between two timestamps while considering the id of the rows in MySQL? So basically I have a table in MySQL:
+-----------+----------+------+-----+---------+-------+
| Field     | Type     | Null | Key | Default | Extra |
+-----------+----------+------+-----+---------+-------+
| ID        | int(11)  | NO   |     | NULL    |       |
| Query     | text     | YES  |     | NULL    |       |
| timestamp | datetime | YES  |     | NULL    |       |
+-----------+----------+------+-----+---------+-------+

And the ID represents a user id, the queries represent a query that he gives to a machine and timestamp when he gives. I am trying to find the sessions that a user could have with the machine, by checking each record of the table and comparing the current timestamp with the previous one. If the difference is below a threshold of 300 seconds then I consider it a session.
However, this way I do not take into consideration that the same user might be using the machine multiple times. How can I also check if the previous ID is the same with the current ID of the record that I am checking?
I have been searching around the internet and this is what I have come up with so far.
select Count(*) from(
select  t.*,
    TIMESTAMPDIFF(second, @prevQT, `timestamp`) as session,
    @prevQT:=t.`timestamp`
    from myTable t,
    (select @prevQT:=(Select min(`timestamp`) from myTable)) vars
    ORDER BY ID) subquery_alias
    where session < 300;

Thank you in advance.
UPDATE:
Sample Data:
1 , "google"        , '2013-08-02 08:58:06'
1 , "dogs"          , '2013-08-02 09:00:09'
1 , "dogs and cats" , '2013-08-02 09:02:02'
1 , "toys"          , '2013-08-02 09:10:09'
1 , "games for kids", '2013-08-02 09:12:25'
2 , "football"      , '2013-08-02 09:12:28'
2 , "manchester"    , '2013-08-02 09:14:37'
2 , "championship"  , '2013-08-02 09:17:48'
3 , "flowers"       , '2013-08-02 09:20:31'

Applying the query on it, the result should be 4, since the user with ID 1 used the machine twice with a time difference more than 5 minutes.


text:
Q: What is the most effective way of Inserting Python dictionaries / lists into SQL database? Imagine you have a key-value Python dictionary (or list) with larger amounts of items. Let's say you're reading a bigger JSON file and you'd like to store it's contents into MySQL table with keys as names of columns and values as values itself.
JSON Example:
"display_location": {
    "city":"Bratislava",
    "state_name":"Slovakia",
    "country_iso3166":"SK",
    "latitude":"48.20000076",
    "longitude":"17.20000076",
}

Then it is quite inefficient to write SQL insert like this manually:
INSERT INTO TABLE (city, state_name, country_iso3166, latitude, longitude) VALUES('%s','%s','%s','%s','%s')
% (Bratislava, Slovakia, SK, 48.20000076, 17.20000076);

(Well, it's ok with five values, but imagine there are for example five hundreds of them.)
Is there any Python class / method for effective and short-stringed SQL insert? I wrote this piece of code:
for key,value in list.iteritems():
  value_type = type(value)
    if value_type is unicode:
      vars_to_sql.append(value.encode('ascii', 'ignore'))
      keys_to_sql.append(key.encode('ascii', 'ignore'))
    else:
      vars_to_sql.append(value)
      keys_to_sql.append(key)

keys_to_sql = ', '.join(keys_to_sql)

After that the insert looks much more simple:
INSERT INTO conditions_bratislava(%s) VALUES %r" % (keys_to_sql,  tuple(vars_to_sql),)

There can be thousands of values and you will still be fine with this one insert statement.
Note that condition which will decode Unicode strings, so you won't have "u" letters before the each value.
So, is there any more effective and prepared class or method how to insert many values in the same simple approach with short INSERT string?

A: If your data is structured like that, it would lend itself more towards a document orientated database (Mongo/Couch etc...)
You can get away with something like this... I think using repr is being a little too clever...
insert_sql = 'INSERT INTO conditions_bratislava(%s) values(%s)'
cols = ', '.join(somedict)
vals = ', '.join('?' * len(somedict)) # or whatever qparam is required
to_execute = insert_sql % (cols, vals)
some_cursor.execute(to_execute, somedict.values())

On a side note:
value_type = type(value)
if value_type is unicode:

Should be written as:
if isinstance(value, unicode):


text:
Q: Can't get value of existing div of webpage I've been testing the Html Agility Pack for a while now, but don't understand the following problem.
Looks like I can only get a value with //body as XPATH, not with any other XPATH value. I already tested with several other websites, but always getting the same Nothing result.

*

*Website: http://www.yosoyke.be.

*Wanted: all li elements of the div with id equals to navigation.

My code:
Dim page As HtmlWeb = New HtmlWeb
Dim doc As HtmlDocument = page.Load("http://www.yosoyke.be")

Dim col As HtmlNodeCollection =
  doc.DocumentNode.SelectNodes("//DIV[@id='navigation']/UL/LI")

For Each node As HtmlNode In col
  Console.WriteLine(node.OuterHtml)
Next

What am I doing wrong here?

A: DocumentNode.SelectNodes (XPATH) is case sensitive by default. This works:
Dim col As HtmlNodeCollection =
  doc.DocumentNode.SelectNodes("//div[@id='navigation']/ul/li")

Also see these:

*

*HTML Agility Pack Parsing With Upper & Lower Case Tags?

*HtmlAgilityPack XPath case ignoring

when you use its XPATH feature, you must use tags written in lower case. It means the "//body" expression will match BODY, Body and body, and "//BODY" will match nothing.


text:
Q: Bag of words representation using sklearn plus Snowballstemmer I have a list with songs, something like
list2 = ["first song", "second song", "third song"...]

Here is my code:
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopwords

vectorizer = CountVectorizer(stop_words=stopwords.words('english'))
bagOfWords = vectorizer.fit(list2)
bagOfWords = vectorizer.transform(list2)

And it's working, but I want to stem a list of my words.
I've tried to make it this way
def tokeni(self,data):
        return [SnowballStemmer("english").stem(word) for word in data.split()]

vectorizer = CountVectorizer(stop_words=stopwords.words('english'),
                             tokenizer=self.tokeni)

but it didn't work. What am I doing wrong?
Update :
with tokenizer I have words like "oh...", "s-like..." , "knees,"
when without tokenizer I don't have any words with dots, commas, etc

A: You can pass a custom preprocessor which should work just as well, but retain the functionality of the tokenizer:
from sklearn.feature_extraction.text import CountVectorizer
from nltk.stem import SnowballStemmer

list2 = ["rain", "raining", "rainy", "rainful", "rains", "raining!", "rain?"]

def preprocessor(data):
        return " ".join([SnowballStemmer("english").stem(word) for word in data.split()])

vectorizer = CountVectorizer(preprocessor=preprocessor).fit(list2)
print vectorizer.vocabulary_

# Should print this:
# {'raining': 2, 'raini': 1, 'rain': 0}


text:
Q: Record screen for google's RL football simulator I'm trying to record the screen while simulating a football game with google's football simulator which is based on openAI-Gym. My code currently is:
import gfootball.env as football_env

env = football_env.create_environment(env_name='11_vs_11_stochastic', render=True)
env.reset()
done = False
while not done:
    action = env.action_space.sample()
    observation, reward, done, info = env.step(action)

which shows the game but I have no clue how to record it.
any help would be appreciated.

A: In case anyone else is wondering, there's a good documentation here. All you need to do is add write_video = True to the environment configs.
My code now looks like this and works:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from absl import app
from absl import flags
from absl import logging

from gfootball.env import config
from gfootball.env import football_env

FLAGS = flags.FLAGS

flags.DEFINE_string('players', 'keyboard:left_players=1',
                    'Semicolon separated list of players, single keyboard '
                    'player on the left by default')
flags.DEFINE_string('level', '', 'Level to play')
flags.DEFINE_enum('action_set', 'default', ['default', 'full'], 'Action set')
flags.DEFINE_bool('real_time', True,
                  'If true, environment will slow down so humans can play.')
flags.DEFINE_bool('render', True, 'Whether to do game rendering.')

def main(_):
  players = FLAGS.players.split(';') if FLAGS.players else ''
  assert not (any(['agent' in player for player in players])
             ), ('Player type \'agent\' can not be used with play_game.')
  cfg = config.Config({
      'action_set': FLAGS.action_set,
      'dump_full_episodes': True,
      'players': players,
      'real_time': FLAGS.real_time,
      'dump_full_episodes': True,
      'tracesdir': 'path/to/dir',
      'write_video': True,
      'render': True
  })
  if FLAGS.level:
    cfg['level'] = FLAGS.level
  env = football_env.FootballEnv(cfg)
  if FLAGS.render:
    env.render()
  env.reset()
  try:
    while True:
      _, _, done, _ = env.step([])
      if done:
        env.reset()
  except KeyboardInterrupt:
    logging.warning('Game stopped, writing dump...')
    env.write_dump('shutdown')
    exit(1)

if __name__ == '__main__':
  app.run(main)

Note that I've just added some configs to the file in official github repo.


text:
Q: Kotlin equivalent of Swift's defer keyword Is there anything similar in Kotlin that provides same ability as the Swift keyword 'defer' ?
What the defer key word does is, it ensure that the code inside a defer block get executed before returning from a function.
Below is an example imagining that defer keyword existed in Kotlin.
    class MyClass {

        var timeStamp = 0L

        fun isEdible(fruit: Fruit): Boolean {
          defer {
           timeStamp = System.currentTimeMillis()
          }
          if (fruit.isExpired) {
             return false
          }
          if (fruit.isRipe) {
            return true
          }
          return false
        }
     }

In the case above, regardless of at what point the function returns, the block inside defer will get executed and timestamp's value will get updated, just before the function ends.
I know Java there is the finally {} keyword used along with try{} catch{}, but it's is not exactly what defer offers.

A: There's no such keyword in Kotlin, but you can make a construct yourself that will work quite similarly. Something like this (note that this does not handle exceptions in the deferred blocks):
class Deferrable {
    private val actions: MutableList<() -> Unit> = mutableListOf()

    fun defer(f: () -> Unit) {
        actions.add(f)
    }

    fun execute() {
        actions.forEach { it() }
    }
}

fun <T> defer(f: (Deferrable) -> T): T {
    val deferrable = Deferrable()
    try {
        return f(deferrable)
    } finally {
        deferrable.execute()
    }
}

Then you can use it like this:
class MyClass {

    var timeStamp = 0L

    fun isEdible(fruit: Fruit): Boolean = defer { d ->
      d.defer {
       timeStamp = System.currentTimeMillis()
      }
      if (fruit.isExpired) {
         return false
      }
      if (fruit.isRipe) {
        return true
      }
      return false
    }
}

A: The closest equivalent is try/finally. catch is not necessary if there's no exceptions thrown.
try {
    println("do something")
    // ... the rest of your method body here
}
finally {
    println("Don't forget about me!");
}

In Swift, defer is usually used to ensure you don't forget to clean up some kind of resource or another (file handle, database connection, shared memory map, etc.). For this purpose, Kotlin use with, which takes a closure, to which the resource is passed as an argument. The resource is valid for the lifetime of the closure, and is automatically closed at the end.
FileWriter("test.txt")
  .use { it.write("something") }
// File is closed by now

A: Solution with exception handling:
class DeferContext {
    private val list = mutableListOf<() -> Unit>()

    fun defer(payload: () -> Unit) {
        list += payload
    }

    /** lombok `@Cleanup` analog */
    fun AutoCloseable.deferClose() = apply {
        defer { close() }
    }

    fun executeDeferred(blockError: Throwable?) {
        var error: Throwable? = blockError
        for (element in list.reversed()) {
            try {
                element()
            } catch (e: Throwable) {
                if (error == null) {
                    error = e
                } else {
                    error.addSuppressed(e)
                }
            }
        }
        error?.let { throw it }
    }
}

inline fun <T> deferBlock(payload: DeferContext.() -> T): T {
    val context = DeferContext()
    var error: Throwable? = null
    var result: T? = null
    try {
        result = context.payload()
    } catch (e: Throwable) {
        error = e
    } finally {
        context.executeDeferred(error)
    }
    return result as T
}

IMHO, main point of defer functionality is execution of deferred actions regardless of previously thrown exceptions.
usage:
deferBlock {
    defer { println("block exited") }
    val stream = FileInputStream("/tmp/a").deferClose()
}

A: I came across the same question today.
While I think the answer provided by marstran is good, I decided to refactor it a little bit.
fun <T> deferred(f: ((() -> Unit) -> Unit) -> T): T {
    val actions: MutableList<() -> Unit> = mutableListOf()
    try {
        return f(actions::add)
    } finally {
        actions.asReversed().forEach { it() }
    }
}

I got rid of the Deferrable  class by using the list directly in the deffered function. This also solves the fact that the whole Deferrable object was passed to the calling code needing to call it.defer/d.defer. In this version the add method of the mutable list is directly passed into the lambda allowing to have a code that is closer to its go/swift version.
To address the suggestion given by mvndaai to use Stack I decided to call .asReversed() on the list. Maybe there is a LI-FO type in kotlin that is also available in non JVM variants, but if not I think this is a good solution.
the given sample would look like:
class MyClass {

    var timeStamp = 0L

    fun isEdible(fruit: Fruit): Boolean = deferred { defer ->
      defer {
       timeStamp = System.currentTimeMillis()
      }
      if (fruit.isExpired) {
         return false
      }
      if (fruit.isRipe) {
        return true
      }
      return false
    }
}

A: If the class is Closeable you can use use block:
class MyClass : Closeable {
        var timeStamp = 0L

        override fun close() {
            timeStamp = System.currentTimeMillis()
        }

        fun test(): Boolean {
            this.use {
                if (fruit.isExpired) {
                    return false
                }
                if (fruit.isRipe) {
                    return true
                }
                return false
            }
        }
    }


text:
Q: Replacing lines in a file does not remove empty lines I've this function to remove lines from a txt file:
function replace_file($path, $string, $replace)
    {
        set_time_limit(0);

        if (is_file($path) === true)
        {
            $file = fopen($path, 'r');
            $temp = tempnam('./', 'tmp');

            if (is_resource($file) === true)
            {
                while (feof($file) === false)
                {
                    file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
                }

                fclose($file);
            }

            unlink($path);
        }

        return rename($temp, $path);
    }

Usage: replace_file("file.txt", "line to remove", '');
It is working perfectly but it always keep an empty line at the end of the file.
Is it possible to solve that?
Any help would be appreciated.
Thanks!

A: If you're only looking to remove the empty line at the end, have a look at rtrim.

A: I've edited the function to be like that:
function replace_file($path, $string, $replace)
    {
        set_time_limit(0);

        if (is_file($path) === true)
        {
            $file = fopen($path, 'r');
            $temp = tempnam('./', 'tmp');

            if (is_resource($file) === true)
            {
                while (feof($file) === false)
                {
                    file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
                    file_put_contents($temp,
                        implode('', file($path, FILE_SKIP_EMPTY_LINES)));
                }

                fclose($file);
            }

            unlink($path);
        }

        return rename($temp, $path);
    }

And now it works.


text:
Q: Printing array partially in C I am a newbie to C and want to print some special elements of an array.
//Partial code here
    char aaa[18] ;
    int i = 0;
    while(i < 18) {
        aaa[i] = '#' ;
        printf("%c", aaa[i]) ;
        i = i + 4 ;
   }

It's supposed to prints 4 # of aaa[0] ,aaa[4],aaa[8],aaa[12],aaa[16]. But it is not. It is printing them in a row like #####. But I don't want those .

A: I'm assuming you want to eventually print a string and get output like this
"#   #   #   #   #  "

minus the quotes.
You can do this by filling in a null-terminated string and then printfing that, like so:
// +1 for space for a null terminator
// = {0}; fills the array with 0s
char aaa[18+1] = {0};

// for loop is more idiomatic for looping over an array of known size
for (int i = 0; i < 18; i += 4) {
    // if the remainder of dividing i by 4 is equal to 0
    if (i % 4 == 0) {
        // then put a '#' character in the array at aaa[i]
        aaa[i] = '#';
    } else {
        // otherwise put a ' ' character in the array at aaa[i]
        aaa[i] = ' ';
    }
}

printf("%s", aaa);

A: As you're adding 4 to the i variable in each cycle you're printing the positions 0, 4, 8, 12, 16 of the array consecutively.
If you want to print the vector with # as the 4*nth element you should do something like:
while( i < 18 )
{
  if( i % 4 == 0 )
  {
    aaa[i] = '#';
    printf("%c" ,aaa[i]);
  }
  else
    printf(" "); // Assuming you want a space in between prints

  i++;
}


text:
Q: Square API - Possible to have a callback after a successful order? I have a business that uses the Square Stand and loves the functionality. They don't want to change anything about how they process orders.
However, they use CRM to do their email marketing and contact management. So they are currently manually inputting orders that are made from Square into their CRM.
What I would want to do for them is have them keep using their Square stand as usual, but on the back end have some script that gets called upon any time a successful order is made on their square stand, which will then use the CRM API to input the order automatically.
Is such a configuration possible? If not, what would be the workaround?

A: Square currently has a webhooks implementation that provides what you're asking for (notifications when a payment occurs). At present, it unfortunately does not include the full payment details, and so your script would need to call the payments API to obtain the full details when a payment occurs.
--da3mon


text:
Q: Grails redirect to include trailing forward slash I'm using Grails 2.3.6, and trying to redirect a URL to include a trailing forward slash, but to leave the rest of the URL as is. The reason is because I have dynamic content which will have images and attachments. I would like those images and attachments to appear as child pages of the dynamic content, for example:
http://example.com/content

Will point to a dynamically generated piece of content, no issues. But, if I then want to have an attachment, I'll include an href link that points to attachments/file1.pdf.
The problem is that with the above example it would produce http://example.com/attachments/file1.pdf (note that /content/ has been removed).
What I really want is for the path to look like:
http://example.com/content/attachments/file1.pdf

I figure the best workaround is to have the URLs for content be redirected to include a forward slash (if they don't already have one). Unfortunately I keep getting stuck with errors or redirect loops.
I've tried the suggestion here: Grails UrlMapping Redirect to keep DRY, but UrlMappings.groovy doesn't differentiate enough when I tell the same url to go to two different places (the only difference is the trailing slash)
static mappings = {
    "/${content}/"(controller: "application", action: "index")
    "/${content}"(controller: "application", action: "redirectToAddSlash")
}

I also know that Grails 2.3 includes UrlMapping redirects, but the examples provided do not include embedded variables.
Ideally I would like to have something like this:
static mappings = {
    "/${content}/"(controller: "application", action: "index") <=== Has trailing slash
    "/${content}"(redirect: "/${content}/")                    <=== Redirect to include trailing slash
}

Thanks in advance for any assistance!

A: This solution solves the need of the problem, but not the exact resolution I was looking for in the question.
Using the <base> element to provide the base href to use for all relative URLs appears to be the best workaround.
For the solution above I would use:
<base href="http://example.com/content">


text:
Q: HTTP Strict-Transport-Security on a subdomain Strict Transport Security policy allows for so-called preloading, that tells web browsers to use HTTPS even on the very first request to certain domains. Let's say our app is running at sub.example.com and we want to add this preloading. However, the second level domain example.com is not under our control.
Is it possible to use the preloading just for our app on the third level domain, without affecting the second level domain? Or do we have to use only the "usual" HSTS and keep the first request unsafe?


text:
Q: How to prevent some packages from automatically being removed? When I install transcriber 1.5.1.1-10 (which is a very old package last updated in 2004), My audio driver package which is current is depreciated to and older one:
Removing libsnack2-alsa (2.2.10-dfsg1-12build1) ...
Selecting previously unselected package libsnack-alsa.

When I try to reinstall libsnack2-alsa, then transcriber is removed. Is there a way to prevent this?  Transcriber does not seem to work with the depreciated audio driver anyhow.

A: You can use apt-mark to mark a package as manually installed so that it will not be automatically removed while removing some other package (because it is a dependency of this package hence is marked as auto installed).
For example, in my computer i am mark-ing zenity as manually installed:
% apt-mark showauto zenity
zenity

% sudo apt-mark manual zenity
zenity set to manually installed.

% apt-mark showmanual zenity
zenity

In you case, you need:
sudo apt-mark manual transcriber

A: sudo apt-mark hold <package>
For example:
sudo apt-mark hold transcriber
The opposite is:
sudo apt-mark unhold <package>
To show what packages are held:
sudo apt-mark showhold


text:
Q: Canon MF8580Cdw won't print on Ubuntu 16.04 I have had our two Canon MF8580Cdw printers work perfectly with Ubuntu until I upgraded to Ubuntu 16.04. Now we only get a printout with the following:
**** Unable to open the initial device, quitting.
I am using the latest version of the Canon drivers, the same I have used earlier.
Our HP printers work without problems, but it would be great to get the Canons back working again.

A: I found the answer: I had to install Skype to get the printer to work! The only difference between the laptop that could print and the one that didn't was Skype. Seems like this 64 bit Canon driver needs some 32 bit or QT stuff to work. Canon should add whatever it is to their packages. As soon as Skype, which is a 32 bit application) was installed with it's enormous amount of dependencies the printer works again. I am not knowledgeable enough to be able to find out exactly which part of Skype's dependencies makes the printer work, but maybe someone else can?


text:
Q: Why Ember don't renders the child resource? This simple Ember application should list posts. But Ember doesn't renders the post template.
JS:
App = Ember.Application.create();
App.ApplicationAdapter = DS.FixtureAdapter.extend();

App.Router.map(function() {
  this.resource('posts', function(){
    this.resource('post', { path: '/:post_id'});
  });
});

App.Post = DS.Model.extend({
  title: DS.attr('string')
});
App.Post.FIXTURES = [
  { id: 1, title: "First post" },
  { id: 2, title: "Second post" },
  { id: 3, title: "Last post" },
];

App.PostsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('post');
  }
});

HTML body tag:

JSBin of this example.
Note: If I remove the posts template and access /#/posts/1 URL, Ember renders the post template.
What's wrong with this code?

A: If an {{outlet}} is added to posts template then the post template will be rendered.
example 1
http://jsbin.com/yepica/1
However if you do not want the template to be nested then rename posts to posts/index.
example 2
http://jsbin.com/wedufo/1

from documentation
http://emberjs.com/guides/routing/defining-your-routes/#toc_resources
helpful article
http://ugisozols.com/blog/2013/11/05/understanding-nesting-in-emberjs/

example 1
hbs

example 2
hbs


text:
Q: Ordering of QMainWindows within a Qt Application I have an application where in the mainWindow(inherited from QMainWindow) creates a childWindow(also inherited from QMainWindow) and when run, both windows are launched with the childWindow masking the mainWindow.
In the mainWindow() constructor I have
setCentralWidget(this);

On Linux when the mainWindow->titleBar is clicked, the mainWindow is brought to the front whereas on Windows this doesn't seem to work.
To get a consistent behavior across platforms, I added a installEventFilter() and mouseEventHandler to account for left-button mouse events, but again none of methods I used within the mouse event handler helped me achieve the behavior I needed.
void mainWindow::mouseReleaseEvent(QMouseEvent* mevent)
{
  if (Qt::LeftButton == mevent->button())
  {
    //this->raise();
    //this->show();
    //setCentralWidget(this);

  }
}

How can I switch to the mainWindow() when I press(mouse-event) the Title bar?
Is there a reason why the behavior is different on Windows and Linux and how I do I make it consistent? I'm using the opensource versions of Qt-4.8.4 for Windows and Linux.

A: Have you tried using this function yet?
http://doc.qt.io/qt-4.8/qwidget.html#stackUnder
and I would use this in tandem with QFocusEvent
http://doc.qt.io/qt-4.8/qwidget.html#focusInEvent
http://doc.qt.io/qt-4.8/qfocusevent.html#details


text:
Q: selectpicker options not showing <script src="{{ asset('js/app.js') }}"></script>
<script src="{{ asset('js/bootstrap-select.min.js') }}"></script>
<script src="{{ asset('js/script.js') }}"></script>

<link rel="stylesheet" href="{{ asset('css/app.css') }}" >
<link rel="stylesheet" href="{{asset('css/bootstrap-select.min.css')}}">
<link rel="stylesheet" href="{{asset('css/style.css')}}">

script.js
$('.selectpicker').selectpicker();

There are not errors in the console but options inside select tag are not showing


text:
Q: An error occurred while updating the entries. see the inner exception for details for has many relationship I have 3 tables in my database:

*

*Plans

*PlanRoles

*Roles

A one-to-many relationship is established for tables Plans & PlanRoles
I set the entity framework settings to "Table First".
Now when I want to create a Plan with its PlanRoles, I get this error on calling the SaveChanges() method.

An error occurred while updating the entries. see the inner exception for details

This is the code I use:
PlanDB planDB = new PlanDB();
plan = new Plan();
plan.Name = name;
plan.Amount = amount;
plan.Status = Status;

foreach (Role item in enteredRoles)
{
    plan.PlanRoles.Add(new PlanRole() { RoleID = item.RoleID });
}

planDB.Create(plan);
planDB.Save();

Note: when I remove the written foreach and do not add the PlanRules to the plan object, this error does not occur but I need to add the PlanRoles as well.
PlanDB class:
public class PlanDB :
{
    My_ProjectEntities db = new My_ProjectEntities ();
    public bool Create(Plan record)
    {
        bool result = true;
        try
        {
            db.Plans.Add(record);
        }
        catch(Exception error)
        {
            result = false;
        }

        return result;
    }
    public bool Edit(Plan record)
    {
        try
        {
            db.Entry(record).State = System.Data.Entity.EntityState.Modified;
            db.PlanRoles.AddRange(record.PlanRoles);
        }
        catch
        {
            return false;
        }
        return true;
    }
    public void Save()
    {
        db.SaveChanges();
    }
}

Plan Model class:
public partial class Plan
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Plan()
    {
        this.PlanRoles = new HashSet<PlanRole>();
    }

    public int PlanID { get; set; }
    public string Name { get; set; }
    public int Amount { get; set; }
    public int Status { get; set; }
    public System.DateTime CreatedAt { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<PlanRole> PlanRoles { get; set; }
}

Also I changed Pluralization visual setup but no diffrent


text:
Q: jqGrid  custom button with record values as parameters I want to implement a custom EDIT button in jqGrid. This button needs to take the ID of the currently selected row and pass it to a new page (let's assume edit_record.php).
I have my custom button defined as:
.navButtonAdd("#pager",
    {caption:"Edit",
    buttonicon:"ui-icon-newwin",
    onClickButton:function() {
        // here is where I need a little help!
    },
    position: "first",
    title:"Edit Property",
    cursor: "pointer"
})

I just need a little help with the code for the function. I have found the following in another posting.
var grid = $("#customer_list");
var rowid = grid.jqGrid('getGridParam', 'selrow');
window.location = grid.jqGrid('getCell', rowid, 'dataUrl');

But I can't quite get it right for forwarding to edit_record.php...

A: As correctly pointed out by Oleg, all I needed inside my custom button function is:
window.location="edit_record.php?id="+rowid+"&oper=edit"


text:
Q: Need all results from double left join I have two tables.  One with transactions, including written cheques and corresponding ReceiptID, and another with written cheques only.  However, not all of the written cheques are in the transaction table. I want to join the two and get all of the written cheques and ReceiptID (which is only in the written cheques table).
Table - Cheques
Fields
 - LoanNo   ChequeNo    FieldA  FieldB  FieldC
Table - Transactions
Fields
 - LoanNo   ReceiptID   ChequeNo    FiledZ  FieldY
I was thinking that a
SELECT
      ..,
      ReceiptID
   FROM
      Cheques
         LEFT JOIN Transactions
            ON Transactions.LoanNO =Cheques.LoanNo
           AND Transactions.ChequeNo = Cheques.ChequeNo

should work, but it doesn't. At least not the way I had hoped. If a certain cheque is in the Cheques table but not in the Transactions table, it doesn't show in this query.  My expectation is that the record would show, but without a corresponding ReceiptNo, which is what I want.
Example
CHEQUES TABLE
╔════════╦══════════╦════════╗
║ LoanNo ║ ChequeNO ║ Amount ║
╠════════╬══════════╬════════╣
║   4444 ║    77777 ║     50 ║
║   5555 ║    99999 ║     60 ║
║   6666 ║   454545 ║    100 ║
╚════════╩══════════╩════════╝

TRANSACTIONS TABLE
+========+==========+========+===========+
| LoanNo | ChequeNO | Amount | ReceiptID |
+========+==========+========+===========+
|   4444 |    77777 |     50 | A5522     |
+--------+----------+--------+-----------+
|   5555 |    99999 |     60 | B6688     |
+--------+----------+--------+-----------+

The joined query does not give the record with ChequeNo 454545, What I want from the join is:
+========+==========+========+===========+
| LoanNo | ChequeNO | Amount | ReceiptID |
+========+==========+========+===========+
|   4444 |    77777 |     50 | A5522     |
+--------+----------+--------+-----------+
|   5555 |    99999 |     60 | B6688     |
+--------+----------+--------+-----------+
|   6666 |   454545 |    100 |           |
+--------+----------+--------+-----------+

A: Problem solved.  After being pretty sure that what I expected to happen should happen, I closed MS Access and relaunched it.  Then the SQL worked as expected.  No idea why it didn't work before.
SELECT Cheques.*, Transactions.ReceiptID
FROM Cheques LEFT JOIN Transactions ON Transactions.ChequeNo = Cheques.ChequeNo AND Transactions.LoanNo = Cheques.LoanNo


text:
Q: Measure distance to iBeacon from Android device I am working on an app that has to measure the distance to an iBeacon. When a user is within a distance (1 meter) the user should be notified.
It is working fine on iOS but on Android I get various results. I am using the Estimote Android SDK (https://github.com/Estimote/Android-SDK) and Android 4.3.
Below is measurement from a Nexus 4 and a Nexus 5. The iBeacon is placed one meter away from the phone (the measurements are consistent with more samples):
Nexus 4:
08-25 11:39:04.788: : Major: 27485 Accuracy: 0.36351308115918884 Power: -74 Rssi: -67
08-25 11:39:05.880: : Major: 27485 Accuracy: 0.31923897946172497 Power: -74 Rssi: -66
08-25 11:39:06.911: : Major: 27485 Accuracy: 0.31923897946172497 Power: -74 Rssi: -66
08-25 11:39:07.962: : Major: 27485 Accuracy: 0.41856988869951295 Power: -74 Rssi: -68
08-25 11:39:09.003: : Major: 27485 Accuracy: 0.31923897946172497 Power: -74 Rssi: -66

Nexus 5:
08-25 11:35:31.443: : Major: 27485 Accuracy: 0.14058401218665711 Power: -74 Rssi: -61
08-25 11:35:32.483: : Major: 27485 Accuracy: 0.14058401218665711 Power: -74 Rssi: -61
08-25 11:35:33.513: : Major: 27485 Accuracy: 0.17333602268971005 Power: -74 Rssi: -62
08-25 11:35:34.553: : Major: 27485 Accuracy: 0.17333602268971005 Power: -74 Rssi: -62
08-25 11:35:35.593: : Major: 27485 Accuracy: 0.17333602268971005 Power: -74 Rssi: -62

As noted none of them is close to one meter. The Nexus 4 has the closest result with 0.42 meters. The Accuracy is taken from Utils.computeAccuracy in the Estimote SDK.
The big problem is that different devices gives different results. Most devices I tried (Nexus 4, Nexus 7, HTC One Mine) gives results similar to Nexus 4. However the Nexus 5 indicates to be much closer than other devices.
Is there a way to make all devices give (close to) similar results? Alternative a way to know how different devices measure (so an algorithm can compensate for different results)
Also has anyone found a way to enhance the sampling rate on Android Bluetooth LE?
I really would like to prevent using some calibration when the user starts up the app.
I have to use iBeacons (customer demand) but another Library could be an option if this would help solving the problem.

A: The open source Android Beacon Library (the successor to the library mentioned by @tar contains a filter that keeps a 20 second running average of RSSI measurements, discarding the top and bottom 10 percent of samples.  This gives a distance estimate that is quite stable, with the tradeoff that it lags in time as the user moves relative to the beacon.  That said, it is similar to the behavior of iOS device estimates.
The other challenge with Android devices is that each model has a different Bluetooth antenna with a different gain.  This means that the average received signal level on two different device models in the exact same position relative to a beacon will be different. I can confirm from my testing that the Nexus 4 and the Nexus 5 have very different antenna gains.
The formula in the Android Beacon Library is designed for the Nexus 5, but it is open source so you can customize the code for any device model you wish.  To make a new formula for a different device, you need to take several 60 sec average RSSI measurements at various distances (0.5m, 1m, 2m, 3m,... 10m, 12m ... 20m) then do a best fit calculation.
The future plan for the open source library is to have a different formula built in for the most common device models, and key the distance formula used based on a device check.  This is a lot of work, so if you can help volunteer, please tap on my photo to contact me!

A: Well, for starters the distance is an estimation, and no SDK will give you consistent answers because the RSSI depends on so many factors that are out of its control. If you want some reading material, Shane Russell posted "A Semi-Technical Lowdown on Working with iBeacons".
Radius Networks used to have an open-source library for Android and iOS. You may be able to ask them nicely for it, although they took it down late this summer. Also, they seem to have made a replacement AltBeacon library that may suit your needs. Plus, being GitHub...that repo still contains all the code it used to, so feel free to look back through it and take what you need.
As for your concern that the measurements are so far from 1 meter, that may be due to the beacon being uncalibrated. Look at the documentation for your hardware and you will almost certainly find a way to input a calibration value. That value gets broadcast to anything listening so those devices can estimate the distance.
Note that some iBeacon devices have a configurable power level, so if you change that you will also need to recalibrate it.


text:
Q: No response from server when accessing database I am new here so I am not sure if I am asking this in the right way. Tell me if you need more information on anything.
I just started working on an MVC project. I am still new to it and having some connection problems. Problem is as following:
I made an internet application (with the build in login system).
When running the website in localhost I have no problems connecting to my database which is running at the hosting provider.
After publishing i stumble on a problem. I can view the website etc. but when I enter a page which is using the database I get a time-out with the following error message:

A connection attempt failed because the connected party did not
  properly respond after a period of time, or established connection
  failed because connected host has failed to respond

I did some research, but didn't really find anything useful.
The Connectionstring must be right since I can access the database while running in localhost.
Any ideas?
I disabled customerrors so it will show the full errormessage.
If you want to see the full errormessage the site is running at http://sports-records.nl/
I just wanted to start with getting the login system/ database connection to work before continuing with anything else.
Thanks in advance.


text:
Q: Self-Inductance of a coil: What is the logical reason to not just write $\Phi = L * I$ but we also add the factor $N$ to the left side? What is the reason to not just write $\Phi = L\cdot I$ but we also add the factor $N$ to the left side? ($N\cdot\Phi = L\cdot I$)
$\Phi$ is in Webers here, and is the induced magnetic flux.
$L$ is the self-inductance of a coil. $I$ is in Ampers, and is the current going through the coil. $N$ is the total number of turns.
I seek an intuitive explanation of the formula, rather than a mathematical one. Thanks!

A: it comes from ${\displaystyle \displaystyle L={\frac {\mu _{0}\ N^{2}\ A}{\ell }}.}$
and ${\displaystyle \displaystyle \Phi ={\frac {\mu _{0}\ N\ i\ A}{\ell }},}$
so essentially from the $N^2$ in L

A: You didn't define your notations properly, so I hope that I understood them correctly.
You can absolutetly write $\phi=LI$ for a coil, if $\phi$ is defined as the magnetic flux across the coil. In fact, that's the proper definition of self-inductance.
In order to compute this flux $\phi$, the usual trick is to remember that the coil can be modeled as a collection of $N$ coaxial circles. All those circles see the same magnetic flux $\phi_1$, which is usually easy to compute.
Maxwell-Thomson's equation implies that magnetic flux is additive, so $\phi=N\phi_1$.
Conclusion : $\phi=LI=N\phi_1$.


text:
Q: Nant Task For IlMerge 2.9.210.0 Anyone know where I can get a Nant task for ILMerge 2.9.210? I have tried this http://code.google.com/p/ilmerge-tasks/ but it is built against ILMerge 2.0.7.28 of ILMerge. It says that the new project is at ilmerge.xpdm.us (sorry new user, can't post 2 hyperlinks) but that link doesn't seem to work for me. Anyone got any other ideas?

A: 'ILMerge' these tips with these tips..
Basically - create a new nant task.
Worked fine for me. :)

A: ILMerge Tasks for NAnt & MSBuild can be found here:
http://code.google.com/p/ilmerge-tasks/


text:
Q: Flash and Firefox: can't click "Allow" on Privacy panel I've created a rather simple Flex application using Flex Builder 4, which connects to a webcam on the user's PC. To do so, Flash is presenting the user with the infamous privacy warning.
Now, the problem is that user can't click on the panel, as it seems unresponsive to any user interaction.
Some more details:

*

*Firefox 3.6.12 on Mac/OSX, Snow Leopard.

*Adobe Flash Plugin 10.1.85.3 / 10.1 r85

*The Flex app is working fine in its own window/tab but the problem shows up as soon as the html page with the Flex app is embedded into the iframe of another page.

*If I artificially put an Alert box before connecting the camera, the user is able to interact with the Flex application but as soon as the Privacy panel is shown, the Flex app stops interacting.

*The app works fine under Chrome and Safari but I have not tried this under Windows.

*I've read that there are problems with CSS positioning so I removed any CSS style impacting the Flex app.

Before I change my strategy and get rid of the iframe (which will cost me quite some effort) I'd be happy to know whether others have experienced the same problem and if there are workarounds.
Thanks.

A: I had the same issue for weeks now. I found what may be the problem. It has something to do with the css alignment. try to remove the text-align:center; from the div flash is in and it will work again. Somehow the active areas from the security panel don´t shift with the display image…

A: In my application, this problem is apparently caused by an element containing the flash having the css margin: 0 auto. This leads to the left edge of the flash object sometimes being reported as a decimal, e.g. $('.flash').position().left --> 450.5px. Whenever it's not a whole number, the security panel failed to react to clicks.
The fix described in https://bugs.adobe.com/jira/browse/FP-4183 and linked to by Christiano almost works. However, it failed whenever the browser was resized to be so small that the left margin disappeared.
Here's what fixed the issue for me:
function registerMozillaFlashFix() {
 if ($.browser.mozilla) {
   $(window).resize(function() {
      $(".flash").each(function(ii, e) {
        var $e = $(e);
        $e.css('margin-left', $e.position().left % 1 === 0 ? '0' : '0.5px');
      });
   });
 }
}

Then just call window.resize() once your flash has been set up.


text:
Q: setting up a React Sandbox for beginners...dependencies error? Basically spent half a day trying to set this up with no luck.
I have been using npx create-react-app like in this video but I receive the following:
Installing template dependencies using npm...
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: testfile@0.1.0
npm ERR! Found: react@18.0.0
npm ERR! node_modules/react
npm ERR!   react@"^18.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"<18.0.0" from @testing-library/react@12.1.5
 broken) dependency resolution.
npm ERR!                                         the root project

I have seen here create-react-app dependency version issues with React 18 that there may be dependency issues. I have tried the following fix from the post:

*

*delete both node_modules and package-lock.json

*run npm i web-vitals --save-dev

*run npm install

*and then you can use npm run build and npm start again

But I am still receiving error messages. I also uninstalled node.js and installed v16.14.2.
Any help would be really appreciated...
Many thanks

A: It seems that you're already in a folder that have package.json file which messes things up with dependencies.
Try to begin again in a new fresh folder.
The second thing you can try is to upgrade @testing-library/react by using this command :
npm install @testing-library/react@latest
Why ?
As you can see on you dependencies you have a React version > 18 that's what "^" mean in react@"^18.0.0"
BUT @testing-library is requiering a reatc version that is strictly inferior to 18.0.0 that's what mean the "<" in react@"<18.0.0"
More on dependencies semantics : HERE


text:
Q: Store extracted value in csv file using jsr223 postprocessor in jmeter How can i store extracted value of a variable in a csv/text file using JSR223 post processor

A: If this is something you really need to do in the JSR223 PostProcessor the minimal code would be:
new File('/path/to/your/file.csv') << vars.get('YOUR_VARIABLE_NAME_HERE') << System.getProperty('line.separator')

However if there will be a minimal concurrency you will run into the race condition when 2 or more threads (virtual users) will be writing into the same file resulting in data corruption

The approach which I would recommend is using:

*

*Declare the variable you want to store via Sample Variables JMeter Property by adding the next line to user.properties file (lives in "bin" folder of your JMeter installation):
sample_variables=YOUR_VARIABLE_NAME_HERE

*Once done you will be able to write the values using Flexible File Writer configured like:

A: You basically need to write the code to write into file.
Something like:
import org.apache.commons.io.FilenameUtils;

attr1 = vars.get("attr1");
attr2 = vars.get("attr2");

f = new FileOutputStream(locationOfCSVOutputfile, true);

p = new PrintStream(f);

p.println(attr2+","+attr2);

p.close();
f.close();

Like wise get the values you need and write into the file by comma separated.
Beware that in multiple threads scenario, Many threads will be accessing same file. therefore the file output may not be what you expected. To overcome this I used a critical section controller.
Hope this helps.

A: 1/ Consider for example a node in your test plan with your request :
A regular expression extractor and a JR223 post processor component as child of your request.
2/ If you extract for example a multiple variable named "blabla" positioning the match number to "-1"
3/ Here's the piece of Groovy code that you can use in your post processor component to write your variable in a file :
import org.apache.jmeter.*;

File outputFile = new File("MY_FILE.csv")

int max = Integer.parseInt(vars.get("blabla_matchNr"));

for (i=1;i<max;i++)  {

    def word = vars.get("blabla_"+i);
    outputFile << word  << "\r\n"

}


text:
Q: mintty does not find my theme directory If I understand the tty manpage correctly, theme files are by default looked up in a subdirectory named themes under the config directory, and in the absence of a --config option, one default location for the config directory is ~/.mintty/config.
I have created a directory ~/.mintty/config/themes and placed some theme files into it. Then I started mintty. In the mintty configuration (Options/Looks) is a selector for themes, but it just says "No Themes", and none of the files in my themes directory are shown.
What could be the reason?
I'm using mintty 2.7.6 on Cygwin.

A: You need to put them in ~/.mintty/themes


text:
Q: C++ boost::multi_index: order of iterator_to member function Reading the boost::multi_index reference, I discovered that the iterator_to method has constant order. How is that possible? I mean, if an iterator is a different object than the value_type it represents, how is possible the container finds their corresponding internal node without searching on the index?
The only solution I can think of is that the address of the container's "internal node" (or whatever it is) is the same as the value_type it holds (for example, putting the node header just below the value_type or something). If the passed argument is a reference to an interal value_type, the corresponding iterator can be construct easily through the argument's address to get the red-black node.
But!! What about the C++ standard restricction that there's cannot be two objects with same address? What about alignment, padding, fill or any of those things that can happen at memory level?

A: Your intuition is correct: the value is part of a larger node structure (as explained for instance here) and iterator_to merely calculates the address of the node from the address of the value_type subobject. Now, the pointer arithmetics involved rely on the fact that the node (or the base class where the value is stored) is standard-layout, which guarantees that a pointer to first subobject (the value) can be cast to a pointer to the structure (the node): the relevant code can be looked at here.


text:
Q: Solr Distance Filter from a Radius Field Hi I am very new to Solr queries (like a few hours), so please excuse me if this is a naive question, but is there a way on the geo filter to set the radius from a field.
{!geofilt pt=35.3459327,-97.4705935 sfield=locs_field_location$latlon d=fs_radius}

Or do a subquery to return the value of that field fs_field_job_search_radius and place it in there. I can return the value from the field list so I was hoping it could go in there, in some method.
This is similar to this Filtering by distance vs. field value in Solr but I do not know if he got it working or where I would need to start to write a function as was suggested.  Also this is on a Solr server I do not control. It is controlled by my hosting company, so I do not know if I can even create functions.  Thanks.

A: Took a work around, but I got what I was trying to accomplish I believe.
fq={!frange l=0 h=12742}sub(radius_field,geodist(field,point))

The 12742 is the diameter of the earth in km as I still needed a hard number for that, but I doubt most are searching in space. So basically we subtract the distance from radius_field to find out if it is in range.
radius_field - distance
If the results are a positive number than it is within range. If it is a negative number than it is not. Please let me know if I screwed up my logic. Thanks.


text:
Q: Jquery click on anchor and get value I have these anchors generated by php script:
 Leaf
 Flower
 Branches
 Seeds

I need to click on e.g. Flower and alert "flower";
I used jquery:
alert( $(".remFile").html()); // output 1st item "Leaf" on any anchor clicked

I also tried:
alert( $(".remFile").text()); // output all values on any anchor clicked

If it is not possible, can you please suggest some other solutions? like using
 ?

A: $('a.remFile').click(function(){ alert($(this).text()) })

jsFiddle example

A: You can use $(this) to target current clicked anchor as well as text() to get the text of your anchor:
$('a.remFile').click(function(e) {
    e.preventDefault(); // Prevent default action of your anchor which will reload the page
    alert($(this).text());
});

Fiddle Demo

A: just use this to refer to current anchor
alert($(this).text();

$('a').click(function(){
alert($(this).text());
});

Fiddle

A: try
$(".remFile").click(function(){ alert($(this).html())});

A: use this -
$('.remFile').click(function(e) {
   e.preventDefault(); // or return false;
   alert($(this).html());
});

Live demo : click here

A: As I can understand you want to do this:
$(".remFile").click(function(){
    alert($(this).html());
});


text:
Q: Как скриптом взять текст в одном span и вставить в другой в место текста который в нем? Как с помощью скрипта взять текст из одного тега span и вставить в span с другим классом (с предварительной очисткой span, в который добавляется текст)?
Как сейчас:

Холодильник Bosch

Произвольный текст

Как нужно:

Холодильник Bosch

Холодильник Bosch

Значение в span с классом .ctm изначально неизвестно (на всех страницах по разному).
Подскажите, пожалуйста, как должен выглядеть готовый скрипт?

A: Нужно сначала определить общего родителя, например, через .closest(), а потом внутри родителя найти нужный span через .find():

$('span.ctm').each(function() {
  var text = $(this).text();
  $(this).closest('.block').find('span.mprice').text(text);
});

  Холодильник Bosch

  Произвольный текст

  Холодильник Philips

  Произвольный текст

  Холодильник LG

  Произвольный текст


text:
Q: Luhn's Algorithm Pseudocode to code Hey guys I'm fairly new to the programming world. For a school practice question I was given the following text and I'm suppose to convert this into code. I've spent hours on it and still can't seem to figure it out but I'm determine to learn this. I'm currently getting the error
  line 7, in <module> if i % 2 == 0: TypeError: not all arguments converted during string formatting

What does this mean? I'm still learning loops and I'm not sure if it's in the correct format or not. Thanks for your time.
# GET user's credit card number
# SET total to 0
# LOOP backwards from the last digit to the first one at a time
    # IF the position of the current digit is even THEN
        # DOUBLE the value of the current digit
        # IF the doubled value is more than 9 THEN
            # SUM the digits of the doubled value
        # ENDIF
       # SUM the calculated value and the total
    # ELSE
        # SUM the current digit and the total
    # ENDIF
# END loop
# IF total % 10 == 0 THEN
    # SHOW Number is valid
# ELSE
    # SHOW number is invalid
# ENDIF

creditCard = input("What is your creditcard?")
total = 0
for i in creditCard[-1]:
    if i % 2 == 0:
        i = i * 2
        if i > 9:
            i += i
    total = total + i

    else:
        total = total + i

if total % 10 == 0:
    print("Valid")

else:
    print("Invalid")

A: well, i can see 2 problems:
1)when you do:
for i in creditCard[-1]

you dont iterate on the creditCard you simply take the last digit.
you probably meant to do
for i in creditCard[::-1]

this will iterate the digits from the last one to the first one
2)
the pseudocode said to double the number if its POSITION is even, not if the digit itself is even
so you can do this:
digit_count = len(creditCard)
for i in range(digit_count -1, -1, -1):
    digit = creditCard[i]

or have a look at the enumerate  built-in function
edit:
complete sample:
creditCard = input("What is your creditcard?")
total = 0
digit_count = len(creditCard)
for i in range(0, digit_count, -1):
    digit = creditCard[i]

    if i % 2 == 0:
        digit = digit  * 2
        if digit  > 9:
            digit = digit / 10 + digit % 10 # also noticed you didnt sum the digits of the number

    total = total + digit

if total % 10 == 0:
    print("Valid")

else:
    print("Invalid")


text: Q: How we can skip a SCM project in Jenkins in case of multiple SCM projects? I have multiple SCM set in your Jenkins SCM projects and running Poll SCM for triggering a build but the issue is some time if anyone of the git servers is down for maintenance the whole build gets to failure which is impacting other SCM projects. Jenkins has a procedure of checking and executing git fetch for every SCM projects which is set in the SCM section and when it encounters a git server which is down it abort as a failure, I'm looking for a solution where I can set some setting which results in Jenkins skip specific git SCM projects while checking for commits and move to another one. Is any feature available for this?


text:
Q: Merging two float dataframes into one string dataframe So let's say I have two dataframe, where one contains the nominal values and the other contains uncertainties to the nominal values:
import pandas as pd

df_nom = pd.DataFrame([1.5, 2.5],
                      [3.5, 4.5])

df_err = pd.DataFrame([5.1, 6.1],
                      [7.1, 8.1])

I'd like to merge the two to become string dataframe as such:
df_merged = pd.DataFrame(['1.5 $\pm$ 5.1', '2.5 $\pm$ 6.1'],
                         ['3.5 $\pm$ 7.1', '4.5 $\pm$ 8.1'])

Can anybody help me with this? Preferably in a vectorize and efficient way.
I am also open if there is a smarter way of doing this than converting them to strings.
What I want in the end is to output the dataframe as latex table using DataFrame.to_latex()
Appreciate the help!

A: Use:
df = df_nom.astype(str) + ' $\pm$ ' + df_err.astype(str)
print (df)
               0              1
0  1.5 $\pm$ 5.1  2.5 $\pm$ 6.1
1  3.5 $\pm$ 7.1  4.5 $\pm$ 8.1


text:
Q: Passing custom project properties from Visual Studio Extension during build How can I pass a custom MsBuild property to Visual Studio build engine from Visual Studio Extension (I want to write a custom add-in) ? Just like Visual Studio itself is passing properties like $(Configuration) and $(Platform), I would like to attach to a build process and pass my own property (e.g. $(MyCustomProperty) = "foobar"). I know it can be accomplished using MsBuild command line (/p:Property), but I want to do it from an extension.
Here is an example of what I would like to accompilsh: a textbox on visual studio toolbar, where user can type in some text - a value, that I would like to pass to build engine.
Then in .csproj:
<PropertyGroup>
  <MyCustomProperty Condition=" '$(MyCustomProperty)' == '' ">DefaultValue</MyCustomProperty>
</PropertyGroup>

<Target Name="AfterBuild" Condition=" '$(MyCustomProperty)' = 'DoAfterBuild' ">
  ...
</Target>

So target AfterBuild would be exectued only if user typed DoAfterBuild into my extension's text box

A: You can request service IVsBuildPropertyStorage, it has following method:

SetPropertyValue:  Used by a project subtype to set an MSBuild property value.

Something like this:
EnvDTE.Project proj = ...;
var sol = Package.GetGlobalService(typeof(VsSolution)) as IVsSolution;
IVsHierarchy hier;
sol.GetProjectOfUniqueName(p.UniqueName, out hier);
var storage = hier as IVsBuildPropertyStorage;
storage.SetPropertyValue(..);


text:
Q: field name as argument Suppose there is a shell function called getfield that takes the field name as argument and writes the corresponding field (or column) number on the standard output.
#!/bin/bash

fieldname=$1

function getfield {

}

cut -f$(getfield $fieldname) -d\| 2album

Here is my file 2album:
artist|title|name|year
Depeche Mode|Speak and Spell|Mute Records|1991
Depeche Mode|Speak and Spell|Mute Records|1991
Depeche Mode|Speak and Spell|Mute Records|1991
Depeche Mode|Speak and Spell|Mute Records|1991
Depeche Mode|Speak and Spell|Mute Records|1991
Depeche Mode|Speak and Spell|Mute Records|1991

How should my function look like. In my example is empty.

A: You can use a case statement to do the equivalent of a switch block in other languages. The default case is written *) to display an error on stderr and return a non-zero error code if none of the cases matched.
getfield() {
    local name="$1"

    case "$name" in
        artist) echo 1;;
        title) echo 2;;
        name) echo 3;;
        year) echo 4;;

        *) echo "$0: $name: unknown field" >&2; return 1;;
    esac
}


text:
Q: modalPopupExtender when shown from code-behind doesnt apply the transparency to the background While wanting modalPopupExtender to show from code-behind, everything works well except

*

*the opacity and alpha(filter) properties of the CSS are not applied meaning i get a modal popup with the color i set in my BackgroundCSSClass and hence cannot see my original controls in the background.

anyone facing this weird behavior and have a solution for this?
B.t.w, Everything works well when the TargetControlID is not hidden.

A: I battled this same issue for most of the day today. I have 3 pages with this identical code in them.  two of the pages worked as expected, with transparent background, one did not. In that one, the background was always 100% opaque.
Finally,  I realised i had accidentally deleted the < !DOCTYPE html > line in that page.  Adding that one line back into the page fixed the problem instantly.  Simple. and a little unexpected. HTH


text:
Q: UIStackView subview doesn't get reinstalled I have an UIStackView with a subview that is supposed to be uninstalled in wAny hC and installed in other cases. But what happens is once the subview is uninstalled (if I rotate the device or if it's at hC at load) the subview doesn't reappear once the height is no longer compact.
Why doesn't the view show up? There are no warnings in the console or anywhere else. The problem is identical on the simulator and physical device.
If it makes any difference, the stack view is initially hidden.

A: By default all Interfacebuilder properties are weak. When the view is removed from the layout there is no reference to it and the property will be released (set to nil). A strong pointer should solve your problem.
weak var myStackView: UIStackView

should be changed to
var myStackView: UIStackView

For reference:

Because a weak reference does not keep a strong hold on the instance it refers to, it is possible for that instance to be deallocated while the weak reference is still referring to it. Therefore, ARC automatically sets a weak reference to nil when the instance that it refers to is deallocated. Because weak references need to allow nil as their value, they always have an optional type. You can check for the existence of a value in the weak reference, just like any other optional value, and you will never end up with a reference to an invalid instance that no longer exists.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID48


text:
Q: Release hash of a repo does not show in its "git log" To mine repositories. I'm basically traversing its git commits to extracting info. However, in many repositories, I see that the hash of a release is not present in the git log.
For example in project bitcoin, the hash of release v0.19.0.1 is 1bc9988. The git log does not show this commit hash. However, "git log --all" contains this commit hash.
I'd like to know the reasoning behind this. Why is this hash not present in a git log? My mining work is dependent on extracting data from major releases of a project. I'm using PyDriller to do this.
from pydriller import RepositoryMining

commits = RepositoryMining(repo_path, only_in_branch=repo_branch).traverse_commits()
for commit in commits:
    // working with a commit

How can I get the commits of the major releases?


text:
Q: Tensorflow data.Dataset.map and memory storage I have a dataset of images that is too large to store on memory. What I plan to do is loading pairs of the paths to the images and corresponding labels as my dataset, then use a generator function during training to convert only the paths in my batch to images before feeding them to the network.
Is data.Dataset.map() a good way to do this? Does it return a mapping function, that can be applied only to the current batch during training, or does it perform the mapping operation on the whole dataset at once, occupying lots of memory? In the second case, what is an alternative?
A few tutorials I went through made me believe the mapping takes place per batch, but this quote from the documentation suggests a whole new dataset is returned: "This transformation applies map_func to each element of this dataset, and returns a new dataset containing the transformed elements, in the same order as they appeared in the input."

A: The key thing to understand here is that tf.data.Dataset objects are generally "lazy" in that elements are only processed as needed (in a batched Dataset, elements == batches). When iterating over a dataset, this usually means that only the next requested element is prepared and then returned. So to answer your question: When using map to load data from disk, and applying this to a dataset of file names, only one batch of the loaded data should be stored in memory at the same time, and you should be able to process the dataset just fine. However, this can significantly slow down training if loading the files is a bottleneck in terms of speed.
There are some exceptions though, for example:

*

*When you use the shuffle method, you need to provide a buffer size, and AFAIK the entire buffer is preprocessed at once. This can lead to issues since you want a large buffer for good shuffling, but this requires more memory. Thus you probably want to use shuffle before applying map.

*The prefetch method results in multiple elements being prepared in order to avoid the model having to wait for the next batch to be processed.

Note that this lazy behavior also has some disadvantages, e.g.

*

*You can only iterate over datasets sequentially; there is no random access.

*A dataset doesn't even know how many elements it contains (this would require iterating over the entire set).


text:
Q: renaming the extracted file from zipfile I have lots of zipped files on a Linux server and each file includes multiple text files.
what I want is to extract some of those text files, which have the same name across zipped files and save it a folder; I am creating one folder for each zipped file and extract the text file to it. I need to add the parent zipped folder name to the end of file names and save all text files in one directory. For example, if the zipped folder was March132017.zip and I extracted holding.txt, my filename would be holding_march13207.txt.
My problem is that I am not able to change the extracted file's name.
I would appreciate if you could advise.
import os
import sys
import zipfile
os.chdir("/feeds/lipper/emaxx")

pwkwd = "/feeds/lipper/emaxx"

for item in os.listdir(pwkwd): # loop through items in dir
    if item.endswith(".zip"): # check for ".zip" extension
        file_name = os.path.abspath(item) # get full path of files
        fh = open(file_name, "rb")
        zip_ref = zipfile.ZipFile(fh)

        filelist = 'ISSUERS.TXT' , 'SECMAST.TXT' , 'FUND.TXT' , 'HOLDING.TXT'
        for name in filelist :
            try:
                outpath = "/SCRATCH/emaxx" + "/" + os.path.splitext(item)[0]
                zip_ref.extract(name, outpath)

            except KeyError:
                {}

        fh.close()

A: import zipfile

zipdata = zipfile.ZipFile('somefile.zip')
zipinfos = zipdata.infolist()

# iterate through each file
for zipinfo in zipinfos:
    # This will do the renaming
    zipinfo.filename = do_something_to(zipinfo.filename)
    zipdata.extract(zipinfo)

Reference:
https://bitdrop.st0w.com/2010/07/23/python-extracting-a-file-from-a-zip-file-with-a-different-name/

A: You could simply run a rename after each file is extracted right? os.rename should do the trick.
zip_ref.extract(name, outpath)
parent_zip = os.path.basename(os.path.dirname(outpath)) + ".zip"
new_file_name = os.path.splitext(os.path.basename(name))[0] # just the filename

new_name_path = os.path.dirname(outpath) + os.sep + new_file_name + "_" + parent_zip
os.rename(outpath, new_namepath)

For the filename, if you want it to be incremental, simply start a count and for each file, go up by on.
count = 0
for file in files:
    count += 1
    # ... Do our file actions
    new_file_name = original_file_name + "_" + str(count)
    # ...

Or if you don't care about the end name you could always use something like a uuid.
import uuid
random_name = uuid.uuid4()

A: Why not just read the file in question and save it yourself instead of extracting? Something like:
import os
import zipfile

source_dir = "/feeds/lipper/emaxx"  # folder with zip files
target_dir = "/SCRATCH/emaxx"  # folder to save the extracted files

# Are you sure your files names are capitalized in your zip files?
filelist = ['ISSUERS.TXT', 'SECMAST.TXT', 'FUND.TXT', 'HOLDING.TXT']

for item in os.listdir(source_dir):  # loop through items in dir
    if item.endswith(".zip"):  # check for ".zip" extension
        file_path = os.path.join(source_dir, item)  # get zip file path
        with zipfile.ZipFile(file_path) as zf:  # open the zip file
            for target_file in filelist:  # loop through the list of files to extract
                if target_file in zf.namelist():  # check if the file exists in the archive
                    # generate the desired output name:
                    target_name = os.path.splitext(target_file)[0] + "_" + os.path.splitext(file_path)[0] + ".txt"
                    target_path = os.path.join(target_dir, target_name)  # output path
                    with open(target_path, "w") as f:  # open the output path for writing
                        f.write(zf.read(target_file))  # save the contents of the file in it
                # next file from the list...
    # next zip file...

A: outpath = '/SCRATCH/emaxx'
suffix = os.path.splitext(item)[0]

for name in filelist :
    index = zip_ref.namelist().find(name)
    if index != -1: # check the file exists in the zipfile
        filename, ext = os.path.splitext(name)
        zip_ref.filelist[index].filename = f'{filename}_{suffix}.{ext}' # rename the extracting file to the suffix file name
        zip_ref.extract(zip_ref.filelist[index], outpath) # use the renamed file descriptor to extract the file

A: I doubt this is possible to rename file during their extraction.
What about renaming files once they are extracted ?
Relying on linux bash, you can achieve it in a one line :
os.system("find "+outpath+" -name '*.txt' -exec echo mv {} `echo {} | sed s/.txt/"+zipName+".txt/` \;")

So, first we search all txt files in the specified folder, then exec the renaming command, with the new name computed by sed.
Code not tested, i'm on windows now ^^'


text:
Q: Creating more dynamic queries with objects I have an API with a Post endpoint where the body is quite flexible. Basically I allow anything to be posted there and then I will serialize this body to an object, like this:
  public class PostBody
    {
        public string Id{ get; set; }
        public string SomeOtherValue{ get; set; }
        public string AnotherValue{ get; set; }
    }

    string body =
   "{
            "id": "335",
            "someOtherValue": "fsdfds"
    }"

PostBody body = JsonConvert.DeserializeObject<PostBody>(body);

As you can see here Postbody can be populated with "AnotherValue" but it also might not depending on what the client wants to insert/update.
And lets say that my database table contains all three, "Id", "SomeOtherValue" and "AnotherValue" as columns.
Now, how can I use dapper to dynamically insert/update this table, depending if the properties in the PostBody object are null or not? I mean if "AnotherValue" is null, the query should only be like this:
INSERT INTO table
(
[Id], [SomeOtherValue]
)
VALUES
(
@Id, @SomeOtherValue
)

But if "AnotherValue" is not null, the query should be like this:
INSERT INTO table
    (
    [Id], [SomeOtherValue], [AnotherValue]
    )
    VALUES
    (
    @Id, @SomeOtherValue, @AnotherValue
    )

Is there a nice way to do this automatically like with a mapper or similar? Or else I would have to code a very long if statement, concatenating a query together. It would me messy and difficult to maintain.
Edit:
This is how my insert looks today:
using System;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace Api.Actions.Commands
{
    class InsertStuffRequest
    {
        public InsertStuffRequest( string id, string SomeOtherValue, string AnotherValue)
        {
            Id=id;
            SomeOtherValue = someOtherValue;
            AnotherValue = ;notherValue;
        }

        public string Id { get; }

        public string SomeOtherValue { get; }

        public string AnotherValue { get; }

        public interface IInsertStuffCommand : IQuery<InsertStuffRequest, bool>
        {
        }

        public class InsertStuffCommand : IInsertStuffCommand
        {
            private const string Command =
                @"INSERT INTO table
    (
    [Id], [SomeOtherValue], [AnotherValue]
    )
    VALUES
    (
    @Id, @SomeOtherValue, @AnotherValue
    )";

            public async Task<Result<bool>> ExecuteAsync(InsertStuffRequest request,
                IApplicationContext context)
            {
                using (SqlConnection connection = new SqlConnection(context.StuffConnectionString))
                {
                    await connection.OpenAsync();

                    var rowsAffected = await connection
                        .ExecuteAsyncWithRetry
                        (
                            Command, request
                        );

                    return Result.From(rowsAffected > 0);
                }
            }
        }
    }
}

This will of course work fine for inserts but its more difficult for updates. Also my Post endpoint will work with different tables that have different columns.

A: If your classes match your tables you could use Dapper.Contrib. The library will create the appropriate INSERT or UPDATE queries based on the objects passed to it.
From the examples, for this class :
public class Car
{
    public int Id { get; set; } // Works by convention
    public string Name { get; set; }
}

You can insert new rows with :
connection.Insert(new Car { Name = "Volvo" });

or insert a list with
connection.Insert(cars);

You can update the same way:
connection.Update(new Car() { Id = 1, Name = "Saab" });

A: I think your question is just a mistake
Use your second insert:
INSERT INTO table
    (
    [Id], [SomeOtherValue], [AnotherValue]
    )
    VALUES
    (
    @Id, @SomeOtherValue, @AnotherValue
    )

and pass a null value (or empty string) to @AnotherValue when you haven't got value.
For the update query, you must generate a dynamic string by sqlbuilder:
(this code not tested and wrote as sample only)
SqlBuilder builder = new SqlBuilder();
    var update = builder.AddTemplate("UPDATE table /**set**/ OUTPUT inserted.id /**where**/");
    builder.Set("SomeOtherValue= SomeOtherValue", new { StrSomeOtherValue});
    if (!string.IsNullOrEmpty(StrAnotherValue))
    {
        builder.Set("AnotherValue= @AnotherValue", new { StrAnotherValue });
    }

    builder.Where("id = @id", new { id = entityId});

    var result = new Result<long?>(sqlConn.ExecuteScalar<long?>(update.RawSql, update.Parameters));