Stack Overflow

Subscribe to Stack Overflow feed
most recent 30 from stackoverflow.com 2018-02-21T10:21:19Z
Updated: 4 hours 27 min ago

Scanner and ArrayList with letters

Tue, 02/20/2018 - 21:09

I would like to declare an arrayList named "courses" but I have a problem in my code. I also want to do a print of the note and of the course.

ArrayList<Integer> listNotes = new ArrayList(); ArrayList<String> listCourses = new ArrayList(); int notes; String[] courses = {"Science", "History", "English"}; for(int i=0; i<5;i++){ //System.out.print((i+1) + " note(s) : "); System.out.print((courses[i]) + " Note : "); notes = INPUT.nextInt(); listNotes.add(notes); } System.out.print("Display : " );

Thank you for your help.

Error recomposing Input components for admin-on-rest

Tue, 02/20/2018 - 21:08

I'm using one of admin on rest's input components. And I have a form which looks like this:

<FormTab label="Identity"> ... ... <SelectInput source="status" choices={[ { id: 'draft', name: 'Draft' }, { id: 'official', name: 'Official' } ]} /> </FormTab>

Which works fine. But I want to DRY up my code because I use this specific <SelectInput> configuration in a few places. So I created a new component which looks like this:

export class StatusInput extends Component { render() { return ( <SelectInput {...this.props} source="status" choices={[ { id: 'draft', name: 'Draft' }, { id: 'official', name: 'Official' } ]} /> ); } }

But when I go to replace the original code with my new component like so:

<FormTab label="Identity"> ... ... <StatusInput /> </FormTab>

I receive an error: Uncaught TypeError: Cannot read property 'value' of undefined inside the SelectInput component that I'm recomposing where a prop ("input"), that is normally defined, is now undefined in my recomposed component. I'm new to react so I'm assuming that there is some nuance I'm not understanding. But my question is:

  1. Isn't the original way, and the new way (recomposing) logically equivalent? I don't understand what props are being passed into SelectInput, that I'm not in turn passing through my recomposed component. Why one works and the other doesn't is confounding me.

  2. If this isn't the appropriate way to extend SelectInput what are my other options?

Are function local statics default- or value- initialized?

Tue, 02/20/2018 - 21:05

A common pattern I use is:

const string& GetConstString() { static const auto* my_string = new string("useful const string"); return *my_string; }

[This is not a leak! See this video] This resolves many lifetime issues. string can be replaced with any type with a nontrivial dtor.

If you had a type with a default ctor & trivial dtor, you could simply do

const MyType& GetConstMyType() { static MyType my_type; return my_type; }

I was working with a class that has a default ctor and trivial dtor. And I wondered whether that class would be default- or value- initialized. It turns out, it doesn't really matter for class-types. So this becomes an academic question [eg if you had an array of this class].

But would it be default- or value- initialized?

Symfony4 sqlite3 connection

Tue, 02/20/2018 - 20:53

I'm trying to play with Symfony4 and SQlite3. After:

composer create-project symfony/website-skeleton my-project

and something like LuckyNumber, I try to define DB-connection. in: config/packages/doctrine.yaml is:

doctrine: dbal: # configure these for your database server url: '%env(DATABASE_URL)%'

and in .env :

DATABASE_URL="sqlite:///%kernel.project_dir%/db/sqlite3.db3"

Is there any console-command to test connection? Or maybe:

php bin/console doctrine:query:sql "select * from all_files"

should return resource or something else way to simply test the connection? Unfortunatelly Google is silent like a grave :-( How do you test DB connections in Symfony4/Doctrine?

after: php bin/console doctrine:query:sql "select * from all_files"

I got: In AbstractSQLiteDriver.php line 89: An exception occurred in driver: could not find driver
In PDOConnection.php line 47: could not find driver

php7.2-sqlite3-dbgsym is installed and apache2 restarted (but I guess Symfony console do nto use Apache?)...

edit:

after Mike`s prompt, (there wasn't pdo_sqlite for this php ver.) I get:

~/Dokumenty/projects/symfony_mdb/my-project$ php bin/console doctrine:query:sql "select * from all_files" In AbstractSQLiteDriver.php line 86: An exception occurred in driver: SQLSTATE[HY000] [14] unable to open database file In PDOConnection.php line 47: SQLSTATE[HY000] [14] unable to open database file

but this is new file and none of process using it (I guess). It is possible to open it with SQlite GUI and run query with expected answer...

"NOT EXISTS" Query with Many to Many Relation Doctrine Symfony3

Tue, 02/20/2018 - 19:24

I would like to build a query that brings me all the games for a logged in user that he has not yet joined. For this I have built these 2 Entities. They are connected by many to many.

class Game { public function __construct() { $this->users = new ArrayCollection(); } /** * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * * @var Users[] * * @ORM\ManyToMany( * targetEntity="Domain\Entity\User", * inversedBy="user", * fetch="EAGER" * ) */ private $users; /** * @return array */ public function getUsers() : array { return $this->users->getValues(); } /** * @param User $users */ public function setUser($users) { if(is_array($users)){ /** @var User $user */ foreach ($users as $user){ $this->users->add($user); } } else { $this->users->add($users); } } }

And the User Entity

class User implements AdvancedUserInterface { /** * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; }

The Entities has more attributes but i think they are not important. Also I tried these Query, but it doesn't work.

/** * @param User $user * @return array */ public function fetchAllNonActivatedWhereYouNotJoin(User $user): array { $qb = $this->createQueryBuilder('g'); $qb->select('g') ->innerJoin('g.users', 'u') ->where('u.id != :user') ->andWhere('g.activate = 0') ->setParameter('user', $user->getId()) ->getQuery()->getResult(); return $qb->getQuery()->getResult(); }

Does anyone know a solution? Its Symfony 3 and Doctrine in PHP 7.1

Populating description of revision from LookBackAPI

Tue, 02/20/2018 - 15:58

I am trying to come up with something similar to the "Revisions" tab for a user story. I have everything I need but the description.

Should I be able to take the revision number or ID and search the "Revision History" residing in the story?

I wasn't sure if the revision contents would be time sensitive.

Mongodb refers in query

Tue, 02/20/2018 - 14:53

I'm newbie in mongo, so: I have a collection 'my_collection' like this:

{ "_id" : ObjectId("5546329a470000850084a621"), "company_name" : "Microsoft", "type" : 'company', } { "_id" : ObjectId("5546329a470000850084a622"), "company_name" : "Google", "type" : 'company', } { "_id" : ObjectId("5546329a470000850084a623"), "company_name" : "Apple", "type" : 'company', } { "_id" : ObjectId("5546329a470000850084a624"), "name" : "John", "surname" : "Smith", "type" : 'person', } { "_id" : ObjectId("5546329a470000850084a625"), "name" : "Eugene", "surname" : "Harper", "type" : 'person', "company_id" : '5546329a470000850084a622', } { "_id" : ObjectId("5546329a470000850084a626"), "name" : "Philipp", "surname" : "Hoffman", "type" : 'person', "company_id" : '5546329a470000850084a622', } { "_id" : ObjectId("5546329a470000850084a627"), "name" : "Adam", "surname" : "Jonson", "type" : 'person', } { "_id" : ObjectId("5546329a470000850084a628"), "name" : "Bruse", "surname" : "Willis", "type" : 'person', "company_id" : '5546329a470000850084a623', }

I need to get a list of companies that have employees. (ie if an employee refers to a company, it must be listed)

I think in MySQL my query would be something like this:

SELECT * from my_collectionWHERE type = company AND (type = person AND company_id = _id)

So, in the result I expect two companies: 1. Google 2. Apple

What query it needed in mongo to get this result?

{ "_id" : ObjectId("5546329a470000850084a621"), "company_name" : "Microsoft", } { "_id" : ObjectId("5546329a470000850084a622"), "company_name" : "Google", }

It's wrong

$collection = $db -> my_collection->find( array( "type" => 'company', "_id" => { $in: [ "type" => 'person', "_id" => ???, ] } ) );

Launcher Icon android not showing

Tue, 02/20/2018 - 10:15

Are there any special guidelines to put launcher icon in android 7.1.1 ? Because i added logo in manifest file and its showing in all android versions but not in my phone. Anyone got a clue?

Type Error: Cannot call a class as a function DatePickerAndroid react native

Tue, 02/20/2018 - 10:15

Calling the class FormDatePickerOverlay using the code below.

render() { const { input, input: {onChange, onFocus, onBlur, ...otherInput}, title, pickerItems, style, ...otherProps } = this.props return ( <View style={[FormStyles.inputView, style, {flex:1, flexDirection:'column'}]}> <TextInput style={FormStyles.input} ref="TextInput" returnKeyType='next' onChangeText={onChange} onFocus={this.handleFocus} onBlur={() => onBlur()} {...otherInput} {...otherProps} /> <Modal animationType="slide" transparent={true} visible={this.state.showPicker}> <FormDatePickerOverlay title={this.props.placeholder} date={ moment(input.value, 'DD MMM YYYY').toDate() } onDateChange={(date)=>{ this.props.meta.dispatch(change(this.props.meta.form, input.name, moment(date).format('DD MMM YYYY') )) }} /> </Modal> </View> ) }

And I'm getting Type Error: Cannot call a class as a function And if the DatePickerAndroid is removed from the View in the render() method below the screen just hangs up with having no further action can be taken.

I've tried changing extends to React.Component but didn't help.

import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, DatePickerAndroid } from 'react-native' import { FormStyles } from './FormStyles' export default class FormDatePickerOverlay extends Component { constructor(props) { super(props); this.handleDatePicker = this.handleDatePicker.bind(this); this.state = { date: this.props.date == null ? new Date() : this.props.date} } static propTypes = { /** * Date picked handler. * * This method will be called when the user selected the date from picker * The first and only argument is a Date object representing the picked * date and time. */ onDatePicked: PropTypes.func, /** * Date Cancelled handler. * * This method will be called when the user dismissed the picker. */ onCancel: PropTypes.func, } /** * Opens the standard Android date picker dialog. * * The available keys for the `options` object are: * * `date` (`Date` object or timestamp in milliseconds) - date to show by default * * `minDate` (`Date` or timestamp in milliseconds) - minimum date that can be selected * * `maxDate` (`Date` object or timestamp in milliseconds) - minimum date that can be selected * * Note the native date picker dialog has some UI glitches on Android 4 and lower * when using the `minDate` and `maxDate` options. */ open(options: Object){ DatePickerAndroid.open(options).then(this.handleDatePicker); } handleDatePicker({action, year, month, day}){ if (action !== DatePickerAndroid.dismissedAction) { this.setState({ date: new Date(year, month, day) }); if(this.props.onDatePicked){ this.props.onDatePicked(new Date(year, month, day)); } }else if(this.props.onCancel){ this.props.onCancel(); } } getSelectedDate(){ return this.state.date; } render(){ const { title, onDone, onDateChange } = this.props return( <View style={{flex: 1}, FormStyles.pickerContainer}> <DatePickerAndroid date={this.state.date} mode='date' onDateChange={(date) => { this.setState({date:date}); onDateChange(date)}}/> </View> ); } }[![This is the error on the emulator][1]][1]

Dotnetnuke support only MSSQL database product. Why other database is not the supported?

Tue, 02/20/2018 - 10:15

Dotnetnuke support only MSSQL database product. Why is it please explain?

phpoffice/phpword laravel how to add html dynamically

Tue, 02/20/2018 - 10:15

I want to generate word from my html.My html is generating dynamically with all css and tags..How do i integrate dynamic html in phpoffice/word. BY adding text to the section the word is downloaded as a corrupt file.. Please help

How to save Postgres DB entire state and restore it?

Tue, 02/20/2018 - 10:15

I regularly explore different data models in dev, while I have one that is in prod that I should preserve.

Once I'm sure of the model I want, I have to craft a migration so that my production setup becomes this.

Unfortunatly, while I can easily git commit my data model definition, explore, then reset it as many time as I want, I don't know how to do that with postgres.

What I need is to say "my current schema, tables, functions, triggers and data are currently in a state I want to save". Then explore with it, destroy it, alter it. Then go back the way it was when I saved it.

Is there some kind of "save checkpoint" and "restore checkpoint" for the entire database ?

HTTP Status 500 - JDBC rollback failed using hibernate

Tue, 02/20/2018 - 10:15

I have a java application using Hibernate and tomcat server.my app is working fine for hours.Then is stop working..showing the following error.I have no idea what is happening and i m really new to hibernate technology.I read something about c3p0 lib but i dont know exacly how is working..

HTTP Status 500 - JDBC rollback failed type Exception report message JDBC rollback failed description The server encountered an internal error that prevented it from fulfilling this request. exception org.hibernate.TransactionException: JDBC rollback failed org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:200) com.javawebtutor.service.LoginService.getUserByUserId(LoginService.java:37) com.javawebtutor.service.LoginService.authenticateUser(LoginService.java:17) com.javawebtutor.controller.LoginServlet.doPost(LoginServlet.java:33) javax.servlet.http.HttpServlet.service(HttpServlet.java:648) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed. sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) java.lang.reflect.Constructor.newInstance(Constructor.java:423) com.mysql.jdbc.Util.handleNewInstance(Util.java:411) com.mysql.jdbc.Util.getInstance(Util.java:386) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927) com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1251) com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1243) com.mysql.jdbc.ConnectionImpl.rollback(ConnectionImpl.java:4723) org.hibernate.transaction.JDBCTransaction.rollbackAndResetAutoCommit(JDBCTransaction.java:213) org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:192) com.javawebtutor.service.LoginService.getUserByUserId(LoginService.java:37) com.javawebtutor.service.LoginService.authenticateUser(LoginService.java:17) com.javawebtutor.controller.LoginServlet.doPost(LoginServlet.java:33) javax.servlet.http.HttpServlet.service(HttpServlet.java:648) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet successfully received from the server was 33,669,634 milliseconds ago. The last packet sent successfully to the server was 6 milliseconds ago. sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) java.lang.reflect.Constructor.newInstance(Constructor.java:423) com.mysql.jdbc.Util.handleNewInstance(Util.java:411) com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116) com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3589) com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3478) com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4019) com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490) com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651) com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2683) com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2144) com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2310) org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208) org.hibernate.loader.Loader.getResultSet(Loader.java:1953) org.hibernate.loader.Loader.doQuery(Loader.java:802) org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274) org.hibernate.loader.Loader.doList(Loader.java:2533) org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276) org.hibernate.loader.Loader.list(Loader.java:2271) org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:452) org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363) org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196) org.hibernate.impl.SessionImpl.list(SessionImpl.java:1268) org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) org.hibernate.impl.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:890) com.javawebtutor.service.LoginService.getUserByUserId(LoginService.java:33) com.javawebtutor.service.LoginService.authenticateUser(LoginService.java:17) com.javawebtutor.controller.LoginServlet.doPost(LoginServlet.java:33) javax.servlet.http.HttpServlet.service(HttpServlet.java:648) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost. com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3039) com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3489) com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3478) com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4019) com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490) com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651) com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2683) com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2144) com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2310) org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208) org.hibernate.loader.Loader.getResultSet(Loader.java:1953) org.hibernate.loader.Loader.doQuery(Loader.java:802) org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274) org.hibernate.loader.Loader.doList(Loader.java:2533) org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276) org.hibernate.loader.Loader.list(Loader.java:2271) org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:452) org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363) org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196) org.hibernate.impl.SessionImpl.list(SessionImpl.java:1268) org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) org.hibernate.impl.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:890) com.javawebtutor.service.LoginService.getUserByUserId(LoginService.java:33) com.javawebtutor.service.LoginService.authenticateUser(LoginService.java:17) com.javawebtutor.controller.LoginServlet.doPost(LoginServlet.java:33) javax.servlet.http.HttpServlet.service(HttpServlet.java:648) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) note The full stack trace of the root cause is available in the Apache Tomcat/8.0.50 logs. Apache Tomcat/8.0.50

my hibernate.cfg.xml is

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/dbname?UseUnicode=true&amp;characterEncoding=utf8 </property> <property name="hibernate.connection.username">dbusername</property> <property name="hibernate.connection.password">dbpass</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping class="com.javawebtutor.model.User" /> <mapping class="com.javawebtutor.model.Questionaire" /> </session-factory> </hibernate-configuration>

Please help..

Unable to clear the Multiselect dropdown and populate values in it dynamically

Tue, 02/20/2018 - 10:15

I have made 2 multiselect dropdown using multiselect js plugin. 2nd dropdown gets populated on the option selection of 1st dropdown. I have use ajax for this purpose. But on ajax callback, 2nd dropdown elements are not getting clear, and new options are not populating. This is my html code:

<div class="row col-md-6" > <select id="multidropdown" multiple="multiple" onchange="ChangedView()"> @foreach (var item in clients) { <option value=@item.ToString() class="col-md-5"> @item.ToString() </option> } </select> </div> <div class="row col-md-6" id="ProgramsDiv"> <select id="programIDs" multiple="multiple" onchange="SelectSensorsFromPrograms()"> @foreach (var item in programs) { <option value=@item.ToString() class="col-md-5"> @item.ToString() </option> } </select> </div>

and this is my js code:

function ChangedView() { $(".mtable").remove(); var multiclients = $("#multidropdown option:selected").text(); var program = $("#programIDs option:selected").text(); var sensors = $("#sensorIDs option:selected").text(); var request = $.ajax({ url: '@Url.Action("GetselectedProgramClient")', type: 'POST', data: { "ClientNames": multiclients }, dataType: 'json', success: function (data) { debugger; if (data.length > 0) { $('#programIDs').html(''); var options = ''; console.log(data.length+"\n"); for (var i = 0; i < data.length; i++) { options += '<option value="' + data[i] + '">' + data[i] +" " + '</option>'; console.log(options); } $('#programIDs').append(options); $('#programIDs').multiselect('rebuild'); } }, error: function (xhr) { console.log("Error: " + xhr.statusText); if (xhr.statusText == 'error') { return; } else if (xhr.statusText == 'OK') { return; } } }); }

Will it be feasible to use gcc's function multi-versioning without code changes?

Tue, 02/20/2018 - 10:14

According to most benchmarks, Intel's Clear Linux is way faster than other distributions, mostly thanks to a gcc feature called Function Multi-Versioning. Right now the method they use is to compile the code, analyze which function contains vectorized loops, then patch the code with FMV attributes and compile it again.

How feasible will it be for gcc to do it automatically? For example, by passing -mmultiarch=sandybridge,skylake (or a similar -m option listing CPU extensions like AVX and AVX2).

Right now I'm interested in two usage scenarios:

  1. Use this option for our large math-heavy program for delivering releases to our customers. I don't want to pollute the code with non-standard attributes and I don't want to modify the third-party libraries we use.
  2. The other Linux distributions will be able to do this easily, without patching the code like Intel does. This should give all Linux users massive performance gains.

wpcf7 and GTM event listener issue

Tue, 02/20/2018 - 10:14

I have a Tag set up in GTM, custom html like this;

<script> document.addEventListener( 'wpcf7submit', function( event ) { dataLayer.push({ 'event' : 'wpcf7successfulsubmit', 'CF7formID' : event.detail.contactFormId }); }, false ); </script>

Doesn't work. Not at all. So I put a script on the page.

var wpcf7Elm = document.querySelector( '.wpcf7' ); wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) { dataLayer.push({ 'event' : 'wpcf7successfulsubmit', 'CF7formID' : event.detail.contactFormId }); }, false );

from a basic example on contactform7.com. This, in GTM preview, triggers fine. The first time it triggers the tag once, the 2nd and subsequent times it triggers twice (implying that both my script and the GTM tag are firing). Guessing at a problem with the event bubbling up. I put the specific selector wpcf7Elm into the tag's custom html but this doesn't work - like the first example.

I have no problem with running from a script but the problem is firing the tag twice so that the analytics shows two events. I would like to use GTM but at the moment the only solution I can see is to go back to on page scripts.

Can anyone suggest what I might be doing wrong? Just to note that I have disabled all plugins and that I am using, on a different page, a wpcf7 event listener successfully (from a script on the page) to perform a presentation function.

Javascript equivalent for Ruby's __LINE__ and __FILE__ constants

Tue, 02/20/2018 - 10:14

I primarely code in Ruby but occasionally need javascript for the browser frontend and use the Chrome console to debug the javascript code.

Sometimes it is difficult to follow what code line produces the output, I have to crosscheck at the right end of the line to see the linenumber which is not easy if there is a lot of content, also this linenumber not always corresponds with the line in the sourcefile, there is often an offset when using a template.

In Ruby you have the __FILE__ constant which contains the sourcecode filepath and the __LINE__ constant with the linenumber of the code being executed.

So a p [__LINE__, "what i want to view"] gives me the linenumber followed by "what i want to view". Is there a javascript/Chrome equivalent ?

For the moment I use

console.log(20, "what I want to view")

for code on line 20 but you can imagine that has to be changed a lot.

(bash) Delete elements from xml if a value is missing

Tue, 02/20/2018 - 10:14

I'd like to remove some elements in a big xml file, if a value is missing.

I have found a topic where it says how to extract the elements where the value is present but not the other way around. Solution could be sed or xmlstartlet but I can't figure it out.

xmlstarlet ed -d '//eslXmlDto[.//itemAssociations]' < file1.xml >> file2.xml

Here is the file I have

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <screens> <screenXmlDto> <articleCodeType>EAN</articleCodeType> <creationDate>2017-04-25T12:23:18.746+02:00</creationDate> <domain>toto.tata</domain> <screenCode>16201000032884264000</screenCode> <itemAssociations> <itemCode>2118550000000</itemCode> <position>1</position> </itemAssociations> </screenXmlDto> <screenXmlDto> <articleCodeType>EAN</articleCodeType> <creationDate>2016-07-27T03:59:17.328+02:00</creationDate> <domain>toto.tata</domain> <screenCode>17201000030538183370</screenCode> </screenXmlDto> <screenXmlDto> <articleCodeType>EAN</articleCodeType> <creationDate>2016-07-26T12:28:20.815+02:00</creationDate> <domain>toto.tata</domain> <screenCode>17201000030538091000</screenCode> <itemAssociations> <itemCode>4008033444958</itemCode> <position>1</position> </itemAssociations> </screenXmlDto> </screens>

Here is the output I want

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <screens> <screenXmlDto> <articleCodeType>EAN</articleCodeType> <creationDate>2017-04-25T12:23:18.746+02:00</creationDate> <domain>toto.tata</domain> <screenCode>16201000032884264000</screenCode> <itemAssociations> <itemCode>2118550000000</itemCode> <position>1</position> </itemAssociations> </screenXmlDto> <screenXmlDto> <articleCodeType>EAN</articleCodeType> <creationDate>2016-07-26T12:28:20.815+02:00</creationDate> <domain>toto.tata</domain> <screenCode>17201000030538091000</screenCode> <itemAssociations> <itemCode>4008033444958</itemCode> <position>1</position> </itemAssociations> </screenXmlDto> </screens>

Pandas merge with multiple conditions

Tue, 02/20/2018 - 10:10

I have two dataframes and i need to merge them based on 4 conditions.

df1: Category Locale Provider Traffic Weeknumber Clickout AT A 1200 1 Clickout DE B 3400 2 Popunder COM A 50 1 Popunder COM B 50 2 df2: Category Locale Provider Weeknumber Mobile Desktop Clickout AT A 1 500 700 Clickout DE A 2 2000 1400 Popunder COM B 1 250 500 Popunder COM B 2 100 850

What the new dataframe should look like

df3: Category Locale Provider Traffic Weeknumber Mobile Desktop Clickout AT A 1200 1 500 700 Clickout DE A 3400 2 2000 1400 Popunder COM B 750 1 250 500 Popunder COM B 950 2 100 850

I'm just not entirely certain how to do this. I've used the following before:

cond_list = df.loc[df['Col1']=='A', 'Col2'].tolist() df['Solution'] = df['col2'].apply(lambda x: 'Yes' if x in cond_list else 'No')

But I do not know how to apply this to the new problem. Any help would be great, thank you!

Database sql count wins and loses

Tue, 02/20/2018 - 10:09

I have table like this:

home | away | home_round_1 | away_round_1 | home_round_2 | away_round_2 team1 team2 20 10 5 -2 team3 team1 1 2 -11 4 team2 team3 20 -1 -1 10

I'm trying to figure out how to calculate wins, loses, evens and average game result group by teams. Game result sit counted as home round 1 + round 2 or away round 1 + round 2 and winner is team that has less points in the end. I have made counter that count certain teams average in mysql with cases but is it possible to count all this inside mysql, that it will count values by team.

Pages