Friday 31 August 2018

Decimal separator key not visible when DigitsKeyListener is set

I want to allow the user to enter numbers with a decimal separator (comma or dot) depending on the region.

Now I'm using DigitsKeyListener to enable comma as separator for some locales (e.g. Poland, Germany).

val separator = DecimalFormatSymbols.getInstance().decimalSeparator
editTextValue.keyListener = DigitsKeyListener.getInstance("-0123456789$separator")

This code is written in .

If software keyboard is Gboard or other third party keyboard, then everything is fine and user can use comma or dot as separator.

But when user use stock keyboard and DigitsKeyListener is set, then not all keys are visible and user is not able to add separator.

This is my EditText code:

<android.support.design.widget.TextInputLayout
    android:id="@+id/textInput"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    app:hintTextAppearance="@style/Lorin.Theme.TextInputLayout"
    app:layout_constraintLeft_toRightOf="@id/imageInfo"
    app:layout_constraintRight_toLeftOf="@id/buttonHistoryNumeric">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/editTextValue"
        style="@style/Lorin.EditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:imeOptions="flagNavigateNext"
        android:inputType="number|numberSigned|numberDecimal"
        android:maxLines="1"
        tools:hint="Range"/>
</android.support.design.widget.TextInputLayout>

Keyboard without separator key


val separator = DecimalFormatSymbols.getInstance().decimalSeparator
//editTextValue.keyListener = DigitsKeyListener.getInstance("-0123456789$separator")

When line with DigitsKeyListener is commented, key for separator is visible but only available separator is dot Keyboard with separator key

Do you have any ideas how to use comma as separator on stock keyboard?



from Decimal separator key not visible when DigitsKeyListener is set

How to publish artifacts in gradle 4.4 in android studio (Upload APK to nexus)

I am trying to upload my APK to Nexus repository. Below code work fine until I have change gradle version

from

classpath 'com.android.tools.build:gradle:2.3.3' distributionUrl=https://ift.tt/2ndVD4z mCompileSdkVersion=23 mBuildToolsVersion='25.0.0'

To

classpath 'com.android.tools.build:gradle:3.1.0' distributionUrl=https://ift.tt/2vx88RC mCompileSdkVersion=27 mBuildToolsVersion='27.0.0'

After changing versions same code is not work I am not able to understand where I found an error, Terminal not showing any error message but my APK is not uploaded in given location

following is the current configuration of my App build.gradle file

apply plugin: 'com.android.application'
apply plugin: 'maven'


task uploadRelease (type: Upload){
    configuration = project.getConfigurations().getByName('archives');
    repositories {
        mavenDeployer {
            repository(  url: "http://XXXXXXXX:8081/nexus/XXXXXXXX/repositories/releases"  ) {
                authentication(userName: "MyuserName", password: "Mypassword")
            }
            pom.project {
                version "${android.defaultConfig.versionName}"
                artifactId "Collection"
                name "xxxxxxxx"
                groupId "com.xxxxxxxx.mobile.xxxxxxxx.collections"
            }
        }
    }
}

task uploadSnapshot (type: Upload){
    configuration = project.getConfigurations().getByName('archives');

    repositories {
        mavenDeployer {
            repository(  url: "http://XXXXXXXX:8081/nexus/XXXXXXXX/repositories/snapshots"  ) {
                authentication(userName: "MyuserName", password: "Mypassword")
            }
            pom.project {
                version "${android.defaultConfig.versionName}-SNAPSHOT"
                artifactId "Collection"
                name "Collection"
                groupId "com.xxxxxxxx.mobile.xxxxxxxx.collections"
            }
        }
    }
}

I use Command as - gradle assemblerelease uploadsnapshot

to build and upload APK but It does not work for gradle 4.4 Please let me know what went wrong



from How to publish artifacts in gradle 4.4 in android studio (Upload APK to nexus)

Can't call any fineUploader methods in callback function

I have autoUpload set to false, as I want to upload the images myself to my backend. However, to do this I first need the file object. In the callbacks onSubmitted event I'm trying to pass the images id to the getFile method, to return the object. However, when I try to do this I get the below error message.

in onSubmitted: id=0 | name=28603454_15219061700_r.jpg index.js:2178

[Fine Uploader 5.16.2] Caught exception in 'onSubmitted' callback - Cannot read property 'uploader' of null

I'm guessing I get this because I'm declaring a const object and referencing it at the same time, which I believe you cannot do...

So, any ideas on how I can call methods within the callbacks function? Or is there another way?

const uploader = new FineUploaderTraditional({
  options: {
    maxConnections: 1,
    autoUpload: false,
    deleteFile: { enabled: true, endpoint: "/uploads" },
    request: { endpoint: "/uploads" },
    retry: { enableAuto: true },
    callbacks: {
      onSubmitted: function(id, name) {
        console.log("in onSubmitted: id=" + id + " | name=" + name);
        // getFile(id) returns a `File` or `Blob` object.
        console.log(this.uploader.getFile(id));
      }
    }
  }
});

Update I've now taken all of my fine-uploader code and created a new component with it. I'm still facing the same problems. Starting a bounty. Component code below:

FineUploader.jsx

import React, { Component } from "react";
import FineUploaderTraditional from "fine-uploader-wrappers";
import Gallery from "react-fine-uploader";
import Filename from "react-fine-uploader/filename";
import "react-fine-uploader/gallery/gallery.css";

const util = require("util");

const uploader = new FineUploaderTraditional({
  options: {
    // debug: true,
    maxConnections: 1,
    autoUpload: false,
    deleteFile: { enabled: true, endpoint: "/uploads" },
    request: { endpoint: "/uploads" },
    retry: { enableAuto: true },
    validation: {
      acceptFiles: ".jpg,.png,.gif,.jpeg",
      allowedExtensions: ["jpg", "png", "gif", "jpeg"],
      itemLimit: 5,
      sizeLimit: 5000000
    },
    callbacks: {
      onCancel: function() {
        console.log("in onCancel: ");
      },
      onComplete: function(id, name, responseJSON, xhr) {
        console.log("in onComplete: " + id + " | " + name + " | " + responseJSON + " | " + xhr);
      },
      onAllComplete: function(succeeded, failed) {
        console.log("in onAllComplete: " + succeeded + " | " + failed);
      },
      onProgress: function(id, name, uploadedBytes, totalBytes) {
        console.log("in onProgress: " + id + " | " + name + " | " + uploadedBytes + " | " + totalBytes);
      },
      onError: function(id, name, errorReason, xhr) {
        console.log("in onError: " + id + " | " + name + " | " + errorReason + " | " + xhr);
      },
      onDelete: function(id) {
        console.log("in onDelete: " + id);
      },
      onDeleteComplete: function(id, xhr, isError) {
        console.log("in onDeleteComplete: " + id + " | " + xhr + " | " + isError);
      },
      onPasteReceived: function(blob) {
        console.log("in onPasteReceived: " + blob);
      },
      onResume: function(id, name, chunkData, customResumeData) {
        console.log("in onResume: " + id + " | " + name + " | " + chunkData + " | " + customResumeData);
      },
      onStatusChange: function(id, oldStatus, newStatus) {
        console.log("in onStatusChange: " + id + " | " + oldStatus + " | " + newStatus);
      },
      onSubmit: function(id, name) {
        console.log("in onSubmit: " + id + " | " + name);
      },
      onSubmitted: function(id, name) {
        console.log("in onSubmitted: id=" + id + " | name=" + name);
        // getFile(id) returns a `File` or `Blob` object.
        // console.log(this.uploader.getFile(id));
        // console.log(uploader.getFile(id));
        // nothing here is working.... :(
      },
      onUpload: function(id, name) {
        console.log("in onUpload: " + id + " | " + name);
      },
      onValidate: function(data, buttonContainer) {
        console.log(
          "in onValidate: " + util.inspect(data, { showHidden: true, depth: null }) + " | " + buttonContainer
        );
      },
      onSessionRequestComplete: function(response, success, xhrOrXdr) {
        console.log("in onSessionRequestComplete: " + response + " | " + success + " | " + xhrOrXdr);
      }
    }
  }
});

const fileInputChildren = <span>Click to Add Photos</span>;
const statusTextOverride = {
  upload_successful: "Success!"
};

class FineUploader extends Component {
  constructor() {
    super();

    this.state = {
      submittedFiles: []
    };
  }

  componentDidMount() {
    uploader.on("submitted", id => {
      const submittedFiles = this.state.submittedFiles;
      console.log("submittedFiles: " + submittedFiles);

      submittedFiles.push(id);
      this.setState({ submittedFiles });
    });
  }

  render() {
    return (
      <div>
        {this.state.submittedFiles.map(id => (
          <Filename id={id} uploader={uploader} />
        ))}
        <Gallery
          fileInput-children={fileInputChildren}
          status-text=
          uploader={uploader}
        />
      </div>
    );
  }
}

export default FineUploader;

And -- On the main page now, I'm importing FineUploader.jsx, and using the component.

import FineUploader from "../../components/FineUploader";

In my render method I have:

<FineUploader />



from Can't call any fineUploader methods in callback function

Sending notification via AlarmManager and BroadcastReceiver does not work?

I'm scheduling a notification for 5 days ahead, so I create an alarm using the AlarmManager who fires a PendingIntent which triggers my BroadcastReceiver.

If I try the code for 10 seconds, it works. When I try it for 5 days, nothing happens.

The class NotificationScheduler is a helper class for setting and updating alarms.

The fire-dates are correct since I store them in a database, and I already proofed it.

Manifest:

<receiver android:name=".reminder.ReminderReceiver" />

NotificationScheduler:

class NotificationScheduler {

    companion object {

        const val NOTIFICATION_EXTRA_CLAIM_ID = "notification_extra_bookentry_id"

        const val INTENT_ACTION_REMINDER = "at.guger.moneybook.reminder"

        fun setReminder(context: Context, bookEntryId: Long, fireDate: Date? = null) {
            val mCalendar = Calendar.getInstance()

            val lFireDate = if (fireDate == null) {
                mCalendar.timeInMillis += 5 * 24 * 3600 * 1000
                mCalendar.set(Calendar.HOUR_OF_DAY, 12)

                mCalendar.time
            } else {
                fireDate
            }

            create(context, bookEntryId, lFireDate.time)

            AppDatabase.getInstance(context).reminderDao().insert(Reminder(bookEntryId, lFireDate))
        }

        fun updateReminder(context: Context, bookEntryId: Long) {
            cancel(context, bookEntryId)

            val mCalendar = Calendar.getInstance()
            mCalendar.timeInMillis += 5 * 24 * 3600 * 1000
            mCalendar.set(Calendar.HOUR_OF_DAY, 12)

            create(context, bookEntryId, mCalendar.timeInMillis)

            AppDatabase.getInstance(context).reminderDao().update(Reminder(bookEntryId, mCalendar.time))
        }

        fun cancelReminder(context: Context, bookEntryId: Long) {
            cancel(context, bookEntryId)

            AppDatabase.getInstance(context).reminderDao().delete(Reminder(bookEntryId))
        }

        private fun create(context: Context, bookEntryId: Long, fireDate: Long) {
            val mAlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

            val mComponentName = ComponentName(context, ReminderReceiver::class.java)
            context.packageManager.setComponentEnabledSetting(mComponentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP)

            val mIntent = Intent(context, ReminderReceiver::class.java)
            mIntent.action = INTENT_ACTION_REMINDER
            mIntent.putExtra(NOTIFICATION_EXTRA_CLAIM_ID, bookEntryId)

            val mPendingIntent = PendingIntent.getBroadcast(context, bookEntryId.toInt(), mIntent, PendingIntent.FLAG_UPDATE_CURRENT)

            if (Utils.isKitKat()) {
                mAlarmManager.setWindow(AlarmManager.RTC, fireDate, AlarmManager.INTERVAL_HOUR, mPendingIntent)
            } else {
                mAlarmManager.set(AlarmManager.RTC, fireDate, mPendingIntent)
            }
        }

        private fun cancel(context: Context, bookEntryId: Long) {
            val mAlarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

            val mComponentName = ComponentName(context, ReminderReceiver::class.java)
            context.packageManager.setComponentEnabledSetting(mComponentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP)

            val mIntent = Intent(context, ReminderReceiver::class.java)
            mIntent.putExtra(NOTIFICATION_EXTRA_CLAIM_ID, bookEntryId)

            val mPendingIntent = PendingIntent.getBroadcast(context, bookEntryId.toInt(), mIntent, PendingIntent.FLAG_UPDATE_CURRENT)

            mAlarmManager.cancel(mPendingIntent)
            mPendingIntent.cancel()
        }
    }
}

BroadcastReceiver:

class ReminderReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        if (context != null && intent != null) {
            when (intent.action) {
                NotificationScheduler.INTENT_ACTION_REMINDER -> {
                    val mPowerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
                    val mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this::class.simpleName)

                    mWakeLock.acquire(WAKELOCK_TIME)

                    val iClaimEntryId = intent.getLongExtra(NotificationScheduler.NOTIFICATION_EXTRA_CLAIM_ID, -1)

                    showNotification(context, iClaimEntryId)
                    AppDatabase.getInstance(context).reminderDao().delete(Reminder(iClaimEntryId))

                    mWakeLock.release()
                }
            }
        }
    }

    private fun showNotification(context: Context, claimEntryId: Long) {
        val mNotificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val nBuilder: Notification.Builder

        if (Utils.isOreo()) {
            val mNotificationChannel = NotificationChannel(NOTIFICATIONCHANNEL_CLAIMREMINDERID, context.getString(R.string.notificationchannel_claimreminder_title), NotificationManager.IMPORTANCE_DEFAULT)
            mNotificationChannel.description = context.getString(R.string.notificationchannel_claimreminder_description)

            mNotificationManager.createNotificationChannel(mNotificationChannel)

            nBuilder = Notification.Builder(context, NOTIFICATIONCHANNEL_CLAIMREMINDERID)
        } else {
            nBuilder = Notification.Builder(context)
        }

        val mClaimEntry: BookEntry = AppDatabase.getInstance(context).bookEntryDao().get(claimEntryId)

        val mCurrencyFormatter = DecimalFormat.getCurrencyInstance(Preferences.getInstance(context).currency.locale)

        nBuilder.setSmallIcon(R.drawable.ic_money)
        nBuilder.setContentTitle(context.getString(R.string.notification_claimreminder_title, mCurrencyFormatter.format(mClaimEntry.dValue)))
        val sContacts = mClaimEntry.getContacts(context).joinToString().takeIf { it.isNotEmpty() }
                ?: "-"
        nBuilder.setContentText(context.getString(R.string.notification_claimreminder_content, sContacts))
        nBuilder.setContentIntent(PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT))
        nBuilder.setAutoCancel(true)

        mNotificationManager.notify(mClaimEntry.lId!!.toInt(), nBuilder.build())
    }

    companion object {
        const val NOTIFICATIONCHANNEL_CLAIMREMINDERID = "notification_channel_claimreminder"

        const val WAKELOCK_TIME: Long = 1000
    }
}



from Sending notification via AlarmManager and BroadcastReceiver does not work?

Node.js 10 HTTPS server is rejecting connections

I have simple Node.js HTTPS server

const https = require('https');
const fs = require('fs');

const config = {
  key: fs.readFileSync('cert/server-key.pem'),
  cert: fs.readFileSync('cert/server-crt.pem'),
  ca: fs.readFileSync('cert/ca-crt.pem'),
};

const server = https.createServer(config, ((req, res) => {
  console.log('Got request');

  res.end();
}));

server.listen(3333);

I use curl on embedded system.

# curl -V
curl 7.52.1 (arm-unknown-linux-gnu) libcurl/7.52.1 wolfSSL/3.9.8
Protocols: file ftp ftps http https smtp smtps telnet tftp 
Features: IPv6 Largefile SSL UnixSockets  

When I use Node.js other then version 10 - everything works nicely.

HTTPS server running on Node.js v8.2.1

# curl -k -v "https://10.43.11.128:3333/"
*   Trying 10.43.11.128...
* TCP_NODELAY set
* Connected to 10.43.11.128 (10.43.11.128) port 3333 (#0)
* SSL connected
> GET / HTTP/1.1
> Host: 10.43.11.128:3333
> User-Agent: curl/7.52.1
> Accept: */*

HTTPS server running on Node.js v10.1.0

# curl -k -v "https://10.43.11.128:3333/"
*   Trying 10.43.11.128...
* TCP_NODELAY set
* Connected to 10.43.11.128 (10.43.11.128) port 3333 (#0)
* SSL_connect failed with error -313: revcd alert fatal error
* Curl_http_done: called premature == 1
* Closing connection 0
curl: (35) SSL_connect failed with error -313: revcd alert fatal error

What has changed in Node.js 10 with regards to HTTPS? I suspect I'll have to change SSL settings but I am to sure how.



from Node.js 10 HTTPS server is rejecting connections

LabelPropagation - How to avoid division by zero?

When using LabelPropagation, I often run into this warning (imho it should be an error because it completely fails the propagation):

/usr/local/lib/python3.5/dist-packages/sklearn/semi_supervised/label_propagation.py:279: RuntimeWarning: invalid value encountered in true_divide self.label_distributions_ /= normalizer

So after few tries with the RBF kernel, I discovered the paramater gamma has an influence.

EDIT:

The problem comes from these lines:

        if self._variant == 'propagation':
            normalizer = np.sum(
                self.label_distributions_, axis=1)[:, np.newaxis]
            self.label_distributions_ /= normalizer

I don't get how label_distributions_ can be all zeros, especially when its definition is:

self.label_distributions_ = safe_sparse_dot(
graph_matrix, self.label_distributions_)

Gamma has an influence on the graph_matrix (because graph_matrix is the result of _build_graph() that call the kernel function). OK. But still. Something's wrong

OLD POST (before edit)

I remind you how graph weights are computed for the propagation: W = exp(-gamma * D), D the pairwise distance matrix between all points of the dataset.

The problem is: np.exp(x) returns 0.0 if x very small.
Let's imagine we have two points i and j such that dist(i, j) = 10.

>>> np.exp(np.asarray(-10*40, dtype=float)) # gamma = 40 => OKAY
1.9151695967140057e-174
>>> np.exp(np.asarray(-10*120, dtype=float)) # gamma = 120 => NOT OKAY
0.0

In practice, I'm not setting gamma manually but I'm using the method described in this paper (section 2.4).

So, how would one avoid this division by zero to get a proper propagation ?

The only way I can think of is to normalize the dataset in every dimension, but we lose some geometric/topologic property of the dataset (a 2x10 rectangle becoming a 1x1 square for example)


Reproductible example:

In this example, it's worst: even with gamma = 20 it fails.

In [11]: from sklearn.semi_supervised.label_propagation import LabelPropagation

In [12]: import numpy as np

In [13]: X = np.array([[0, 0], [0, 10]])

In [14]: Y = [0, -1]

In [15]: LabelPropagation(kernel='rbf', tol=0.01, gamma=20).fit(X, Y)
/usr/local/lib/python3.5/dist-packages/sklearn/semi_supervised/label_propagation.py:279: RuntimeWarning: invalid value encountered in true_divide
  self.label_distributions_ /= normalizer
/usr/local/lib/python3.5/dist-packages/sklearn/semi_supervised/label_propagation.py:290: ConvergenceWarning: max_iter=1000 was reached without convergence.
  category=ConvergenceWarning
Out[15]: 
LabelPropagation(alpha=None, gamma=20, kernel='rbf', max_iter=1000, n_jobs=1,
         n_neighbors=7, tol=0.01)

In [16]: LabelPropagation(kernel='rbf', tol=0.01, gamma=2).fit(X, Y)
Out[16]: 
LabelPropagation(alpha=None, gamma=2, kernel='rbf', max_iter=1000, n_jobs=1,
         n_neighbors=7, tol=0.01)

In [17]: 



from LabelPropagation - How to avoid division by zero?

How to reinit Pipe in Angular4

How to reinit Pipe in Angular4?

I have a component which use a Pipe

Component render once with some data which use Pipe

Some data was changed, and Pipe will be changed

How to reinit pipe or reinit Component?



from How to reinit Pipe in Angular4

Uncaught Error: [$injector:modulerr] when using Angular JS with planet 9

I am getting the below error, Once I used Angularjs in planet 9.
Planet 9 is a tool build on top of sap ui5, which includes drag and drop along with we can also include html, css, js.
Hence for an application I had a need of ng-repeat kind of thing. So I thought of using AngularJS. where I can use the routing from that tool. I will not use the route from angular js. So, not necessary to load ngRoute. I checked the solution in SO for the above error. almost every answer was saying to use ngRoute. Even after adding ngRoute, no luck.
What I feel is, angular application is trying to initialize before angular js script loaded. But i am not sure that is the issue. But i am not able to see any angular js related functionality working. But sometimes depends on the internet speed, it will work.
Even i thought of bootstrapping the angular application manually. But that tool has already added ng-app="angularApp" by default. What is causing the below error, If the manual bootstrapping is the solution for this, how to remove that first ng-app auto bootstrap then do manual bootstrap once the necessary angular js is loaded.

angular.min.js:6 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.6/$injector/modulerr?p0=angularApp&p1=Error%3A%20%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.5.6%2F%24injector%2Fnomod%3Fp0%3DangularApp%0A%20%20%20%20at%20http%3A%2F%2F10.37.142.201%3A8080%2Fmedia%2Froot%2Fhurricane%2Fjs%2Fangular.min.js%3A6%3A412%0A%20%20%20%20at%20http%3A%2F%2F10.37.142.201%3A8080%2Fmedia%2Froot%2Fhurricane%2Fjs%2Fangular.min.js%3A25%3A235%0A%20%20%20%20at%20b%20(http%3A%2F%2F10.37.142.201%3A8080%2Fmedia%2Froot%2Fhurricane%2Fjs%2Fangular.min.js%3A24%3A282)%0A%20%20%20%20at%20http%3A%2F%2F10.37.142.201%3A8080%2Fmedia%2Froot%2Fhurricane%2Fjs%2Fangular.min.js%3A25%3A20%0A%20%20%20%20at%20http%3A%2F%2F10.37.142.201%3A8080%2Fmedia%2Froot%2Fhurricane%2Fjs%2Fangular.min.js%3A39%3A374%0A%20%20%20%20at%20q%20(http%3A%2F%2F10.37.142.201%3A8080%2Fmedia%2Froot%2Fhurricane%2Fjs%2Fangular.min.js%3A7%3A355)%0A%20%20%20%20at%20g%20(http%3A%2F%2F10.37.142.201%3A8080%2Fmedia%2Froot%2Fhurricane%2Fjs%2Fangular.min.js%3A39%3A222)%0A%20%20%20%20at%20db%20(http%3A%2F%2F10.37.142.201%3A8080%2Fmedia%2Froot%2Fhurricane%2Fjs%2Fangular.min.js%3A43%3A246)%0A%20%20%20%20at%20c%20(http%3A%2F%2F10.37.142.201%3A8080%2Fmedia%2Froot%2Fhurricane%2Fjs%2Fangular.min.js%3A21%3A19)%0A%20%20%20%20at%20Ac%20(http%3A%2F%2F10.37.142.201%3A8080%2Fmedia%2Froot%2Fhurricane%2Fjs%2Fangular.min.js%3A21%3A332)
at angular.min.js:6
at angular.min.js:40
at q (angular.min.js:7)
at g (angular.min.js:39)
at db (angular.min.js:43)
at c (angular.min.js:21)
at Ac (angular.min.js:21)
at fe (angular.min.js:20)
at HTMLDocument.<anonymous> (angular.min.js:315)
at p (sap-ui-core.js:127)

Error which i got when i used Uncomp

Uncaught Error: [$injector:modulerr] Failed to instantiate module angularApp due to:
Error: [$injector:nomod] Module 'angularApp' is not available! You either 
misspelled the module name or forgot to load it. If registering a module 
ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.5.7/$injector/nomod?p0=angularApp

Could anyone please help me.



from Uncaught Error: [$injector:modulerr] when using Angular JS with planet 9

Migrated JDO project to google cloud endpoints v2, server returns NoClassDefFoundError

I've tried to migrate a google cloud project using JDO from endpoints v1 to v2. I've followed the migration guide and some solutions here to try to make the datanucleous plugin enhance my classes, and upload them to the google cloud, but there is no luck.

I'm gonna post the build.gradle followed by the server error returned when a client tries to connect to an endpoint, which is a NoClassFound error.

build.gradle:

buildscript {
    repositories {
        mavenCentral()
        mavenLocal()
    }
    dependencies {
        // App Engine Gradle plugin
        classpath 'com.google.cloud.tools:appengine-gradle-plugin:1.3.3'

        // Endpoints Frameworks Gradle plugin
        classpath 'com.google.cloud.tools:endpoints-framework-gradle-plugin:1.0.2'

    }
}

repositories {
    mavenCentral();
    jcenter()
}

apply plugin: 'java'
apply plugin: 'war'

// [START apply_plugins]
apply plugin: 'com.google.cloud.tools.appengine'
apply plugin: 'com.google.cloud.tools.endpoints-framework-server'
// [END apply_plugins]

dependencies {
    compile ('com.google.endpoints:endpoints-framework:2.0.8') {
        exclude group: 'com.google.guava', module: 'guava-jdk5'
    }

    compile 'javax.servlet:servlet-api:2.5'
    compile 'com.ganyo:gcm-server:1.0.2'
    compile 'javax.jdo:jdo-api:3.0.1'
    compile 'org.datanucleus:datanucleus-core:3.1.3'
    compile 'org.datanucleus:datanucleus-api-jdo:3.1.3'
    compile 'org.datanucleus:datanucleus-accessplatform-jdo-rdbms:4.1.1'
    compile 'com.google.appengine.orm:datanucleus-appengine:2.1.2'
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'org.apache.commons:commons-lang3:3.5'
}

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

appengine {  // App Engine tasks configuration
    deploy {   // deploy configuration
        version = findProperty("appengine.deploy.version")

        def promoteProp = findProperty("appengine.deploy.promote")
        if (promoteProp != null) {
            promote = new Boolean(promoteProp)
        }

    }
}

endpointsServer {
    // Endpoints Framework Plugin server-side configuration
    hostname = "komilibro.appspot.com"
}

task datanucleusEnhance {
    description "Enhance JDO model classes using DataNucleus Enhancer"
    dependsOn processResources

    doLast {
        // define the entity classes
        def entityFiles = fileTree(sourceSets.main.output.classesDir).matching {
            include 'com/meanwhile/komi/head/**/*.class'
        }

        println "Enhancing with DataNucleus the following files"
        entityFiles.getFiles().each {
            println it
        }

        // define Ant task for DataNucleus Enhancer
        ant.taskdef(
                name : 'datanucleusenhancer',
                classpath : sourceSets.main.runtimeClasspath.asPath,
                classname : 'org.datanucleus.enhancer.EnhancerTask'
                // the below is for DataNucleus Enhancer 3.1.1
                //classname : 'org.datanucleus.enhancer.tools.EnhancerTask'
        )

        // run the DataNucleus Enhancer as an Ant task
        ant.datanucleusenhancer(
                classpath: sourceSets.main.runtimeClasspath.asPath,
                verbose: true,
                api: "JDO") {
            entityFiles.addToAntBuilder(ant, 'fileset', FileCollection.AntType.FileSet)
        }
    }
}

classes.dependsOn(datanucleusEnhance)

Taking a look to the server logs after a user request, I can see two errors: first:

    org.datanucleus.store.types.TypeManagerImpl loadJavaTypes: User-defined type
 mapping class "org.datanucleus.store.types.sco.simple.Collection" was not found.
 Please check the mapping file class specifications and your CLASSPATH. The class
 must be in the CLASSPATH. 

And this is the second. PMF is just a class used to load and instance of the PersistenceManager.

com.google.api.server.spi.SystemService invokeServiceMethod: exception occurred while calling backend method (SystemService.java:375)
java.lang.NoClassDefFoundError: Could not initialize class com.meanwhile.komi.head.PMF

So, seems like the classes needed are not in place, but also the TypeManagerImpl does not find the Collection class (default java Collection is used in the endpoints). I'm a little lost here, so help is really welcome.

Thanks!



from Migrated JDO project to google cloud endpoints v2, server returns NoClassDefFoundError

PHP + JCrop - Cropping wrong area

I'm trying to save an cropped image with jcrop, based on x,y,w,h. I send to my PHP file, the axis x,y and width/height, but the cropped area is wrong.

this is my php function

$axis_x = $_POST["x"];
$axis_y = $_POST["y"];
$width = $_POST["w"];
$height = $_POST["h"];
$path_foto = "imgs/3.jpg";
$targ_w = $width;
$targ_h =  $height;
$jpeg_quality = 90;
$src = $path_foto;
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor($targ_w, $targ_h);

imagecopyresampled($dst_r, $img_r, 0, 0, $axis_x, $axis_y, $width, $targ_w, $targ_h, $height);

imagejpeg($dst_r, $path_foto, $jpeg_quality);

This coords is set by jcrop in an input hidden everytime when the image is redized. The problem is always crop the wrong area.

What i'm doing wrong?



from PHP + JCrop - Cropping wrong area

Android - Rotate video frames before sending to Wowza Streaming Engine using WebRTC

I want to stream video from android camera to Wowza Streaming Engine (WSE) using WebRTC. When device in landscape mode, everything work well. Then I try to stream by putting the device in portrait mode.

The first thing I notice in WSE player is the video stream has been rotated 90 counter-clockwise. I figured out that WebRTC do not rotate each video frame that comes out from onPreviewFrame API before sending to WSE and unfortunately WSE do not support any mechanisms to rotate video frame at their side at least so far.

So I checked out WebRTC android native source code and modify it to rotate each video frame before sending to WSE. And right now I can see the video stream in portrait mode in WSE player.

But it has an issue is sometimes video stream look so weird. Please see the following images.

A normal image

A weird image

I put camera to a fix position. At the first time WSE player displays the first one, but sometimes the second one is showed up.

And here is the file in WebRTC source code that I changed. ~/webrtc/src/sdk/android/src/jni/androidvideotracksource.cc

void AndroidVideoTrackSource::OnByteBufferFrameCaptured(const void* frame_data,
                                                        int length,
                                                        int width,
                                                        int height,
                                                        VideoRotation rotation,
                                                        int64_t timestamp_ns) {
  RTC_DCHECK(camera_thread_checker_.CalledOnValidThread());

  int64_t camera_time_us = timestamp_ns / rtc::kNumNanosecsPerMicrosec;
  int64_t translated_camera_time_us =
      timestamp_aligner_.TranslateTimestamp(camera_time_us, rtc::TimeMicros());

  int adapted_width;
  int adapted_height;
  int crop_width;
  int crop_height;
  int crop_x;
  int crop_y;

  if (!AdaptFrame(width, height, camera_time_us, &adapted_width,
                  &adapted_height, &crop_width, &crop_height, &crop_x,
                  &crop_y)) {
    return;
  }

  const uint8_t* y_plane = static_cast<const uint8_t*>(frame_data);
  const uint8_t* uv_plane = y_plane + width * height;
  const int uv_width = (width + 1) / 2;

  RTC_CHECK_GE(length, width * height + 2 * uv_width * ((height + 1) / 2));

  // Can only crop at even pixels.
  crop_x &= ~1;
  crop_y &= ~1;
  // Crop just by modifying pointers.
  y_plane += width * crop_y + crop_x;
  uv_plane += uv_width * crop_y + crop_x;

  rtc::scoped_refptr<I420Buffer> buffer =
      buffer_pool_.CreateBuffer(adapted_width, adapted_height);

  nv12toi420_scaler_.NV12ToI420Scale(
      y_plane, width, uv_plane, uv_width * 2, crop_width, crop_height,
      buffer->MutableDataY(), buffer->StrideY(),
      // Swap U and V, since we have NV21, not NV12.
      buffer->MutableDataV(), buffer->StrideV(), buffer->MutableDataU(),
      buffer->StrideU(), buffer->width(), buffer->height());

  // TODO: Rotate I420 frame 90 degrees clockwise.
  rtc::scoped_refptr<I420Buffer> rotated_buffer =
      I420Buffer::Rotate(*buffer, kVideoRotation_90);

  OnFrame(VideoFrame(rotated_buffer, rotation, translated_camera_time_us));
}

I added this line of code to rotate I420 frame 90 degrees clockwise.

// TODO: Rotate I420 frame 90 degrees clockwise.
  rtc::scoped_refptr<I420Buffer> rotated_buffer =
      I420Buffer::Rotate(*buffer, kVideoRotation_90);

I would appreciate any help!



from Android - Rotate video frames before sending to Wowza Streaming Engine using WebRTC

How to sort records by sequence insted of name in Odoo OCA widget web_widget_x2many_2d_matrix?

I already try with no success to sort by sequence a dict of records by jquery I dont know where sorted again by name.

I ask the community on git but nobody answer me, I'm trying to sort by odoo sequence. using modules web_widget_x2many_2d_matrix, and sale_order_variant_mgmt

I modify python code, and if I debug the list of records the sort is the intended, but when the javascript code is loaded, it sorted by name and cant debug where the problem is

@api.onchange('product_tmpl_id')
    def _onchange_product_tmpl_id(self):
        self.variant_line_ids = [(6, 0, [])]
        template = self.product_tmpl_id
        context = self.env.context
        record = self.env[context['active_model']].browse(context['active_id'])
        if context['active_model'] == 'sale.order.line' or context['active_model'] == 'sale.order.line_group': #TODO check this modify for lentex group_sale_lines module
            sale_order = record.order_id
        else:
            sale_order = record

        num_attrs = len(template.attribute_line_ids)
        if not template or not num_attrs:
            return
        line_x = template.attribute_line_ids[0]
        line_y = False if num_attrs == 1 else template.attribute_line_ids[1]
        lines = []

        for value_x in line_x.value_ids.sorted(key=lambda r: r.sequence):  
            for value_y in line_y and line_y.value_ids.sorted(key=lambda r: r.sequence) or [False]: #I modify this and in python the sort is the intended, but not in JS
                # Filter the corresponding product for that values
                values = value_x
                if value_y:
                    values += value_y
                product = template.product_variant_ids.filtered(lambda x: not(values - x.attribute_value_ids))[:1]
                order_line = sale_order.order_line.filtered(lambda x: x.product_id == product)[:1]
                lines.append((0, 0, {
                    'product_id': product,
                    'disabled': not bool(product),
                    'value_x': value_x,
                    'value_y': value_y,
                    'product_uom_qty': order_line.product_uom_qty,
                }))
        self.variant_line_ids = lines

I think the problem is here

 // get x axis values in the correct order
        get_x_axis_values: function()
        {
            return _.keys(this.by_x_axis); //I think here is where the order is defined
        },
        // get y axis values in the correct order
        get_y_axis_values: function()
        {
            return _.keys(this.by_y_axis); //I think here is where the order is defined
        },



from How to sort records by sequence insted of name in Odoo OCA widget web_widget_x2many_2d_matrix?

Network Changed Broadcast Reciver does not executes in One Plus Phones

I have a Broadcast Reciever name "NetworkReciver.java" that executes when Internet is Connected or Disconnected. And it is working well.

But when app is closed from recent apps, then NetworkReciver.java does not executes in One Plus 6 Phone while it works proper in Samsung Phones.

I am not getting why the behaviour is different in One Plus Device

My Code

Manifest

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


  <receiver android:name=".NetworkReciever" >
       <intent-filter>
          <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
       </intent-filter>
  </receiver>

NetworkReciever.java:

  public class NetworkReciever extends BroadcastReceiver 
  {

       @Override
     public void onReceive(Context context, Intent intent)
     {
            Log.i("TAG", "Network REceiver Executed");
     }
}

Problem : NetworkReciever does not execute when app is closed from recent apps in One Plus Device.



from Network Changed Broadcast Reciver does not executes in One Plus Phones

Kivy - duplicate class instance on super()

Immediately after the super() function is called, it creates a duplicate WidgetClass instance.

My understanding of the super() I've used is that it refers to the EditImageLayout class to inherit from. To this end I've tried to implement different variations of the super() but admittedly I'm only guessing at this stage.

Updated to full working, I've cut out a few hundred lines

Run as > OK > Select an Image > Open > Crop (dual instances start running here)

App_R3App.py

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.widget import Widget
from kivy.graphics import Line, Color
from kivy.properties import NumericProperty, ObjectProperty, StringProperty, ListProperty
from kivy.uix.image import Image
import io
from kivy.core.image import Image as CoreImageKivy
from kivy.uix.bubble import Bubble
from kivy.core.window import Window

__version__ = '0.1'


class FirstScreen(Screen):
    pass


class SecondScreen(Screen):
    def hl(self, image_address):
            self.new_image_address = image_address # for the sake of this
            self.callback_image(self.new_image_address, image_address, "Auto-cropped image")

    def callback_image(self, new_image_address_tmp, image_address_tmp, title):
        if new_image_address_tmp:

            third_screen = self.manager.get_screen("_third_screen_")
            new_image_address_tmp = [k.replace("\\", "/") for k in new_image_address_tmp]

            third_screen.callback_image(new_image_address_tmp[0], image_address_tmp[0], title)


class ThirdScreen(Screen, BoxLayout):
    # class attribute references
    image_size = (0, 0)
    image_pos = (0, 0)
    image_address = ""
    new_image_address = ""
    title = "Upload"

    rect_box = ObjectProperty(None)
    t_x = NumericProperty(0.0)
    t_y = NumericProperty(0.0)
    x1 = y1 = x2 = y2 = NumericProperty(0.0)

    def __init__(self, **kwargs):
        super(ThirdScreen, self).__init__(**kwargs)
        pass

    def callback_image(self, new_image_address, image_address, title):
        sm.current = "_third_screen_"

        self.new_image_address = new_image_address
        self.image_address = image_address
        self.title = title
        self.ids.main_image.source = self.new_image_address
        self.ids.main_title.text = self.title

    def enable_cropping(self):
        # overwrite class attributes
        ThirdScreen.image_address = self.image_address
        ThirdScreen.new_image_address = self.new_image_address

        print("enable_cropping")
        sm.current = "_edit_image_screen_"

        return True


class EditImageScreen(Screen):

    def __init__(self, **kwargs):
        print("EditImageScreen")
        super(EditImageScreen, self).__init__(**kwargs)
        self.layout = None

    def on_pre_enter(self):
        print("on_pre_enter")
        self.layout = EditImageLayout()
        self.add_widget(self.layout)


class EditImageLayout(FloatLayout):
    color_button = ListProperty([1, .3, .4, 1])
    button_color = ListProperty([0, 0, 0, 1])

    rectangle_selector = ObjectProperty()
    text_size_rectangle = ObjectProperty()
    image_layout = ObjectProperty()
    bubble_buttons = ObjectProperty()
    bubble_buttons_undo_confirm = ObjectProperty()

    def __init__(self, **kwargs):
        print("EditImageLayout")
        self.sm = kwargs.pop('sm', None)
        self.crop_image_screen = kwargs.pop('crop_image_screen', None)

        # This is where the problem occurs
        super(EditImageLayout, self).__init__(**kwargs)

        self.rectangle_selector.bind(size_selected=self.on_change_size_rectangle_selector)
        self.rectangle_selector.bind(size_selected_temp=self.update_text_size_rectangle)
        self.bind(on_touch_down=self.bubble_buttons.hide)

        self.bubble_buttons.resize_button.bind(on_press=self.on_press_resize_button)
        self.bubble_buttons_undo_confirm.undo_button.bind(on_press=self.on_press_undo_button)
        self.bubble_buttons_undo_confirm.confirm_button.bind(on_press=self.on_press_confirm_button)

    def on_change_size_rectangle_selector(self, instance, size_selected):
        print("on_change_size_rectangle_selector")
        if not self.rectangle_selector.tap_not_draw_a_line():
            self.bubble_buttons.show()
        else:
            self.text_size_rectangle.text = ''

    def on_press_resize_button(self, instance):
        print("on_press_resize_button")
        self.image_layout.resize_image(width=self.rectangle_selector.size_selected[0],
                                       height=self.rectangle_selector.size_selected[1])

        self.rectangle_selector.delete_line()
        self.text_size_rectangle.text = ''

        self.bubble_buttons_undo_confirm.show()

    def on_press_undo_button(self, instance):
        print("on_press_undo_button")
        size = self.image_layout.old_size
        self.image_layout.resize_image(width=size[0], height=size[1])
        self.bubble_buttons_undo_confirm.hide()

    def on_press_confirm_button(self, instance):
        print("on_press_confirm_button")
        self.bubble_buttons_undo_confirm.hide()

    def update_text_size_rectangle(self, instance, size):
        print("update_text_size_rectangle")
        self.text_size_rectangle.text = str('({0}, {1})'.format(int(size[0]), int(size[1])))


class ImageLayout(Image):
    image = ObjectProperty()
    path_image = StringProperty('image_tmp.jpg')
    path_image_tmp = StringProperty('image_tmp.jpg')

    old_size = ListProperty([0, 0])

    def __init__(self, **kwargs):
        print("ImageLayout")
        super(ImageLayout, self).__init__(**kwargs)

        self.path_image = ThirdScreen.image_address

        self.image = CoreImage(self.path_image,
                               data=io.BytesIO(open(self.path_image, "rb").read()),
                               ext=self.path_image[self.path_image.rfind('.') + 1::])
        self.source = self.path_image

    def resize_image(self, width, height, pos_x=None, pos_y=None):
        pos_x, pos_y = abs(Window.width - width)/2 , abs(Window.height - height)/2
        self.image.resize(self.path_image,
                         self.path_image_tmp,
                         int(width),
                         int(height))

        self.source = self.path_image_tmp
        self.pos = pos_x, pos_y
        self.old_size = self.size
        self.size = width, height
        self.reload()


class CoreImage(CoreImageKivy):

    def __init__(self, arg, **kwargs):
        print("CoreImage")
        super(CoreImage, self).__init__(arg, **kwargs)

    def resize(self, fname, fname_scaled, width, height):

        try:
            img = Image.open(fname)
        except Exception as e:
            print('Exception: ', e)
            return

        img = img.resize((width, height), Image.ANTIALIAS)
        try:
            img.save(fname_scaled)
        except Exception as e:
            print('Exception: ', e)
            return


class TouchSelector(Widget):
    # Points of Line object
    Ax = NumericProperty(0)
    Ay = NumericProperty(0)
    Bx = NumericProperty(0)
    By = NumericProperty(0)
    Cx = NumericProperty(0)
    Cy = NumericProperty(0)
    Dx = NumericProperty(0)
    Dy = NumericProperty(0)

    # Object line
    line = ObjectProperty()

    # List of line objects drawn
    list_lines_in_image = ListProperty([])

    # Size of the selected rectangle
    size_selected = ListProperty([0, 0])

    # Size previous of the selected rectangle
    size_selected_previous = ListProperty([0, 0])

    # Size temporary of the selected rectangle
    size_selected_temp = ListProperty([0, 0])

    # Line Color and width
    line_color = ListProperty([0.2, 1, 1, 1])
    line_width = NumericProperty(1)

    # First tap in TouchSelector
    first_tap = True

    def __init__(self, *args, **kwargs):
        super(TouchSelector, self).__init__(*args, **kwargs)
        self.bind(list_lines_in_image=self.remove_old_line)

    def on_touch_up(self, touch): # on button up
        self.size_selected = abs(self.Cx - self.Dx), abs(self.Cy - self.By)
        self.size_selected_previous = self.size_selected
        print(self.Dx, self.Dy, self.Cx, self.Cy)

    def on_touch_down(self, touch):
        with self.canvas:
            Color(self.line_color)

            # Save initial tap position
            self.Ax, self.Ay = self.first_touch_x, self.first_touch_y = touch.x, touch.y

            # Initilize positions to save
            self.Bx, self.By = 0, 0
            self.Cx, self.Cy = 0, 0
            self.Dx, self.Dy = 0, 0

            # Create initial point with touch x and y postions.
            self.line = Line(points=([self.Ax, self.Ay]), width=self.line_width, joint='miter', joint_precision=30)

            # Save the created line
            self.list_lines_in_image.append(self.line)

            print("on_touch_down")

    def remove_old_line(self, instance=None, list_lines=None):
        if len(self.list_lines_in_image) > 1:
            self.delete_line()

    def delete_line(self, pos=0):
        try:
            self.list_lines_in_image.pop(pos).points = []
        except:
            pass

    def on_touch_move(self, touch):
        # Assign the position of the touch at the point C
        self.Cx, self.Cy = touch.x, touch.y

        # There are two known points A (starting point) and C (endpoint)
        # Assign the  positions x and y  known of the points
        self.Bx, self.By = self.Cx, self.Ay
        self.Dx, self.Dy = self.Ax, self.Cy

        # Assign points positions to the last line created
        self.line.points = [self.Ax, self.Ay,
                            self.Bx, self.By,
                            self.Cx, self.Cy,
                            self.Dx, self.Dy,
                            self.Ax, self.Ay]

        self.size_selected_temp = abs(self.Cx - self.Dx), abs(self.Cy - self.By)

    def tap_not_draw_a_line(self):
        return (self.size_selected[0] == 0 and self.size_selected[1] == 0)


class BaseBubbleButtons(Bubble):

    def __init__(self, **kwargs):
        super(BaseBubbleButtons, self).__init__(**kwargs)

    def hide(self, instance=None, value=None):
        self.opacity = 0

    def show(self, instance=None, value=None):
        self.opacity = 1


class BubbleButtons(BaseBubbleButtons):
    resize_button = ObjectProperty()
    cut_button = ObjectProperty()
    rotate_button = ObjectProperty()


class BubbleButtonsUndoConfirm(BaseBubbleButtons):
    undo_button = ObjectProperty()
    confirm_button = ObjectProperty()


class App_R3App(App):
    Builder.load_file('App_R3.kv')

    def build(self):
        return sm

    def on_start(self):
        return True

    def on_pause(self):
        return True

    def on_resume(self):
        return True

    def on_stop(self):
        return True


if __name__ == '__main__':

    # Create the screen manager
    sm = ScreenManager()
    sm.add_widget(FirstScreen(name='_first_screen_'))
    sm.add_widget(SecondScreen(name='_second_screen_'))
    sm.add_widget(ThirdScreen(name='_third_screen_'))
    sm.add_widget(EditImageScreen(name='_edit_image_screen_'))

    App_R3App().run()

App_R3.kv

#:import Window kivy.core.window.Window

<MyScreenManager>:
    FirstScreen:
        id: first_screen
    SecondScreen:
        id: second_screen
    ThirdScreen:
        id: third_screen
    EditImageScreen:
        id: edit_image_screen

<FirstScreen>:
    name: '_first_screen_'
    BoxLayout:
        orientation: "horizontal"
        Label:
            id: first_screen_label
            text: "Hi, I'm the home page"
        BoxLayout:
            orientation: "vertical"
            Button:
                text: "Okay!"
                on_press: root.manager.current = '_second_screen_'
            Button:
                text: "Cancel!"
                on_press: app.stop()

<SecondScreen>:
    name: '_second_screen_'
    id: file_chooser
    BoxLayout:
        id: file_chooser_box_layout
        orientation: "horizontal"
        Button
            text: "Open"
            on_press: root.hl(file_chooser_list_view.selection)
        FileChooserListView:
            id: file_chooser_list_view

<ThirdScreen>:
    name: '_third_screen_'
    id: third_screen

    xx1: root.x1
    yy1: root.y1
    tt_x: root.t_x
    tt_y: root.t_y

    BoxLayout:
        orientation: "vertical"
        id: third_screen_boxlayout

        Label:
            id: main_title
            text: root.title
            size_hint: (1, 0.1)
        BoxLayout:
            id: image_box_layout
            # limits the box layout to the position of the image
            Image:
                id: main_image
                source: root.image_address
                pos_hint: {'center_x': 0.5, 'center_y': 0.5}
        BoxLayout:
            id: button_boxlayout
            orientation: "horizontal"
            padding: 10
            size_hint: (1, 0.15)
            Button:
                id: accept_button
                text: "Okay"
                size_hint: (0.33, 1)
                on_press: root.image_accepted_by_user(root.image_address)
            Button:
                id: crop_button
                text: "Crop"
                size_hint: (0.33, 1)
                on_press: root.enable_cropping()
            Button:
                id: cancel_button
                text: "Cancel"
                size_hint: (0.33, 1)
                on_press: root.manager.current = '_first_screen_'


<EditImageLayout>:
    rectangle_selector: rectangle_selector
    text_size_rectangle: text_size_rectangle
    image_layout: image_layout
    bubble_buttons: bubble_buttons
    bubble_buttons_undo_confirm: bubble_buttons_undo_confirm
    canvas.before:
        Color:
            rgba: (1, 1, 1, 0.2)
        Rectangle:
            pos: self.pos
            size: Window.width, Window.height

    Label:
        id: text_size_rectangle
        pos_hint_x: None
        pos_hint_y: None
        pos: Window.width*.45, Window.height*.45
        color: (1, 1, 1, 1)
    ImageLayout:
        id: image_layout
        size: Window.width*.8, Window.height*.8
        pos: Window.width*.1, Window.height*.1
        size_hint: None, None
        pos_hint_x: None
        pos_hint_y: None
    TouchSelector:
        id: rectangle_selector
    BubbleButtons:
        id: bubble_buttons
        size_hint: (None, None)
        size: (200, 40)
        pos_hint_x: None
        pos_hint_y: None
        pos: Window.width*.4, Window.height*.1
        opacity: 0
        arrow_pos: 'top_mid'
    BubbleButtonsUndoConfirm:
        id: bubble_buttons_undo_confirm
        size_hint: (None, None)
        size: (200, 40)
        pos_hint_x: None
        pos_hint_y: None
        pos: Window.width*.4, Window.height*.9
        opacity: 0
        arrow_pos: 'top_mid'

<BubbleButtons>:
    resize_button: resize_button
    cut_button: cut_button
    rotate_button: rotate_button
    BubbleButton:
        id: resize_button
        text: 'Resize'
    BubbleButton:
        id: cut_button
        text: 'Cut'
    BubbleButton:
        id: rotate_button
        text: 'Rotate'

<BubbleButtonsUndoConfirm>:
    undo_button: undo_button
    confirm_button: confirm_button
    BubbleButton:
        id: undo_button
        text: 'Undo'
    BubbleButton:
        id: confirm_button
        text: 'Confirm'

Console output, aka what the code prints (you can see that ImageLayout and CoreImage run twice)

EditImageScreen
enable_cropping
on_pre_enter
EditImageLayout
ImageLayout
CoreImage
ImageLayout
CoreImage

What I suspect is happening is that the super() is calling the base class EditImageLayout, the static elements of that base class are calling the .kv file and initating the ImageLayout and CoreImage classes from there. At the same time, "self" goes into action and does the exact same thing. This causes trouble later on when I implement on_touch_down over it (on_touch_down then appears twice, etc. )

Output



from Kivy - duplicate class instance on super()

Display dynamic html content like an epub/ebook, without converting html to epub format?

I want to create a responsive, mobile optimized reading experience similar to an epub/ebook reader, like the Kindle app, or iBooks, using dynamic html as the source.

Imagine a long article or blog post that requires a lot of vertical scrolling to read, especially on a small mobile device. What I would like to do is break the long page into multiple full-screen sections, allowing the user to use left/right navigation arrows and/or the swipe gesture to "page" through the article.

There are many JS libraries available that can create a "slide show" or "carrousel" of pre-defined slides (using divs or other container elements). But I want the text and html content to dynamically re-flow to fit any device viewport and still be readable... just like an epub/ebook user interface, like the Kindle app or iBooks. So, for the same article, there would be many more "pages" on a phone than there would be on a tablet or desktop viewport, and those "pages" would need to be dynamically created/adjusted if/when the viewport size changes (like switching from portrait to landscape on a mobile device).

Here is an example of a javascript .epub reader: epub.js

... notice the responsive behavior. When you resize your viewport, all the text re-flows to fit the available space, increasing or decreasing the total number of "pages". The problem is that epub.js requires an .epub file as its source.

What I want is the same user interface and functionality for an html page.

I have searched and searched for some kind of library that can do this out of the box, but haven't been able to find anything.

I realize that I could use a conversion script to convert my html page into an .epub file, and then use epub.js to render that file within the browser, but that seems very round-about and clunky. It would be so much better to mimic or simulate the .epub reader user experience with html as the direct source, rendering/mimicking a client side responsive ebook user experience.

Does anyone know if something like this already exists, or how I could go about building it myself?

The crucial functionality is the dynamic/responsive text-reflow. When the viewport dimensions are reduced, the text/content needs to reflow to the next "page" to avoid any need for vertical scrolling. I don't know how to do this efficiently. If I were to code it myself, I might use something like the jQuery Columnize plugin, setting all columns to width: 100vw; height: 100vh, so that each column is like a "page", and then figuring out how to create a swipe UI between those "pages".

Any help is much appreciated!



from Display dynamic html content like an epub/ebook, without converting html to epub format?

How to fetch (join) two records from database using doctrine/symfony4

I am learning about Symfony and Doctrine and created a simple site but I am stuck at this step.

I have two tables: users and languages

Users Contains: id, username ...
Languages Contains: user_id, language...

Here is a image of the twoenter image description here

enter image description here

Now I am trying to fetch by language, like: get user who speaks both english and french and the result would return user id 2

In plain PHP i can do inner join with PDO, but I am trying to follow the doctrine syntax and this does not return the correct result

public function getMatchingLanguages ($a, $b) {
  return $this->createQueryBuilder('u')
    ->andWhere('u.language = :val1 AND u.language = :val2')
    ->setParameter('val1', $a)
    ->setParameter('val2', $b)
    ->getQuery()
    ->execute();
}

I call this method in my controllers, and the query is pretty basic since I can not find a documentation how to do the joins as per my example



from How to fetch (join) two records from database using doctrine/symfony4

Windows Notification from node service from electron

I can send windows notification from electron using node-notifier

notifier.notify({
    appName: "myapp",
    title: 'My notification',
    message: 'Hello, there!'
  });

I can run service from electron using node-windows

from my main process

var svc = new Service({
    name: 'MyService',
    description: '',
    script: 'MyService.js',
  });
svc.on('install', function () {
    console.log('Install complete.');
    svc.start();
  });
svc.install();

But when I try to send notification from a service that was created from electron doesn't shows up. Although I checked that code inside the service is ran without any error in the log!

I know this is possible in c# but how do I do that in electron?

Any guide how can I send notification from a service?

Thanks



from Windows Notification from node service from electron

Modify nested ForeignKey fields in add/change view - Django admin

Say I have these models as a simple example:

class First(models.Model):
    first_name = models.CharField(max_length=50, default='')
    second = models.ForeignKey(Second)

class Second(models.Model):
    second_name = models.CharField(max_length=50, default='')
    third = models.ForeignKey(Third)

class Third(models.Model):
    third_name = models.CharField(max_length=50, default='')

I want to create an Admin page with add/change forms for First that will allow me to select a Second and create a Third with all its fields.

Basically, to have a form with a dropdown to choose a Second and below it a form to fill in Thirds fields.

I saw many examples of how to add this to the list_display (such as this) but couldn't manage to do the same with fields or fieldsets in order to have it in the add/change form as well.

Any suggestions will be appreciated. Thanks!

Note: I know that this might be easily solved if I also had Third as a foreign key in First but it is not my case.

Edit: My Django and Python versions:
Python: 2.7.x
Django: 1.7.4



from Modify nested ForeignKey fields in add/change view - Django admin

Subviews of UIView misplaced when the parent view is in StackView

I want to create a button with a gradient border, everything works fine until I nest the GradientButton in a StackView. Then, I get this result for the last button in the horizontal StackView. Why is the subview becomes misplaced always for the last item?

enter image description here

Here is the GradientButton I created:

import Foundation
import UIKit

@IBDesignable class GradientButton: UIButton {

    @IBInspectable var startColor:  UIColor = UIColor.momaBackgroundGradient.begin
    @IBInspectable var endColor:    UIColor = UIColor.momaBackgroundGradient.end
    @IBInspectable var borderWidth: CGFloat = 2
    @IBInspectable var cornerRadius: CGFloat = 4

    override func awakeFromNib() {
        super.awakeFromNib()
        let gradientBorder = UIView(frame: self.frame)
        gradientBorder.configureGradient(withColors: [self.startColor, self.endColor], isHorizontal: true)
        gradientBorder.mask(withPath: UIBezierPath(roundedRect: self.frame.insetBy(dx: self.borderWidth, dy: self.borderWidth), cornerRadius: self.frame.height/2), inverse: true)
        gradientBorder.layer.cornerRadius = self.frame.height/2
        gradientBorder.layer.masksToBounds = true
        self.addSubview(gradientBorder)
    }
}



from Subviews of UIView misplaced when the parent view is in StackView

Trouble parsing product names out of some links with different depth

I've written a script in python to reach the target page where each category has their avaiable item names in a website. My below script can get the product names from most of the links (generated through roving category links and then subcategory links).

The script can parse sub-category links revealed upon clicking + sign located right next to each category which are visible in the below image and then parse all the product names from the target page. This is one of such target pages.

However, few of the links do not have the same depth as other links. For example this link and this one are different from usual links like this one.

How can I get all the product names from all the links irrespective of their different depth?

This is what I've tried so far:

import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

link = "https://www.courts.com.sg/"

res = requests.get(link)
soup = BeautifulSoup(res.text,"lxml")
for item in soup.select(".nav-dropdown li a"):
    if "#" in item.get("href"):continue  #kick out invalid links
    newlink = urljoin(link,item.get("href"))
    req = requests.get(newlink)
    sauce = BeautifulSoup(req.text,"lxml")
    for elem in sauce.select(".product-item-info .product-item-link"):
        print(elem.get_text(strip=True))

How to find trget links:

enter image description here



from Trouble parsing product names out of some links with different depth

Input Material Chips -- Init Form Array

I want to init my mat chips input with input data but when I have two chips, it forms only one form :

enter image description here

*.component.ts

@Component({
  selector: 'app-pps-dialog',
  templateUrl: './pps-dialog.component.html',
})

export class PPSDialogComponent  implements OnInit {

patientid: string;
ppsForm: FormGroup;
ppssToDisplay;


visible: boolean = true;
selectable: boolean = true;
removable: boolean = true;
addOnBlur: boolean = true;
// Enter, comma
separatorKeysCodes = [ENTER, COMMA];


constructor(
private route: ActivatedRoute, 
private ppssService:PPSsService,
private _changeDetectorRef: ChangeDetectorRef,
private location: Location,
private router: Router, 
public dialog: MatDialog, 
private formBuilder: FormBuilder,
public dialogRef: MatDialogRef<PPSDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) 

{ this.initForm(); }

ngOnInit(): void {
    this.ppssToDisplay = this.ppssService.getSinglePPS(this.key)
      .subscribe(res => {
        this.ppssToDisplay = res;
        this.ppsForm.controls['requirements'].setValue(Array(this.ppssToDisplay.effetsind));
            console.log(this.ppssToDisplay.effetsind)); 
      });


  add(event: MatChipInputEvent): void {
        let input = event.input;
        let value = event.value;
        // Add our requirement
        if ((value || '').trim()) {
            this.requirements = this.ppsForm.get('requirements') as FormArray;
            this.requirements.push(this.formBuilder.control(value.trim()));
        }
        // Reset the input value
        if (input) {
            input.value = '';
        }
    }

    remove(index: number): void {
        const requirements = this.ppsForm.get('requirements') as FormArray;

        if (index >= 0) {
            requirements.removeAt(index);
        }
    }

        initForm(): void {
            this.ppsForm = this.formBuilder.group({
               requirements: this.formBuilder.array(['']),
               // I don't know why, but I must init my form with empty chips if I want to receive data from service.
            });
        }

        get formData() {
          return <FormArray>this.ppsForm.get('requirements');
        }

*ppss.service

import { Injectable } from '@angular/core';
import { Patient } from '../models/patient.model';
import { PPS } from '../models/pps.model';
import { AngularFireDatabase, AngularFireList, AngularFireObject} from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import {switchMap, map} from 'rxjs/operators';
import * as firebase from 'firebase';
import DataSnapshot = firebase.database.DataSnapshot;


@Injectable({
  providedIn: 'root'
})
export class PPSsService {
ppss: AngularFireList<any>;

constructor(private database: AngularFireDatabase) {this.ppss = database.list('ppss');}
getSinglePPS(key: string){
    return this.database.object('ppss/' + key).valueChanges();
   }

}

console.log(this.ppssToDisplay.effetsind):

 (2) ["Troubles de la vessie", "Troubles de l'érection"]

I've used the example of Angular Material:

*.component.html

<mat-form-field style="width:50%" appearance="outline">
  <mat-label>Description du traitement</mat-label>
  <textarea matInput formControlName="description"></textarea>
</mat-form-field>

<mat-form-field style="width:50%" appearance="outline">
  <mat-label>Effets indésirables du traitement</mat-label>
  <mat-chip-list #chipList>
    <mat-chip *ngFor="let requirement of formData.controls; let i = index;" [selectable]="selectable"
              [removable]="removable" (removed)="remove(i)">
      
      <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
    </mat-chip>
    <input placeholder="Nouvel effet indésirable..."
           [matChipInputFor]="chipList"
           [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
           [matChipInputAddOnBlur]="addOnBlur"
           (matChipInputTokenEnd)="add($event)"/>
  </mat-chip-list>
</mat-form-field>

ERROR Error: Must supply a value for form control at index: 0:

> core.js:1598 ERROR Error: Must supply a value for form control at index: 0.
        at forms.js:4304
        at forms.js:4274
        at Array.forEach (<anonymous>)
        at FormArray.push../node_modules/@angular/forms/fesm5/forms.js.FormArray._forEachChild (forms.js:4274)
        at FormArray.push../node_modules/@angular/forms/fesm5/forms.js.FormArray._checkAllValuesPresent (forms.js:4302)
        at FormArray.push../node_modules/@angular/forms/fesm5/forms.js.FormArray.setValu

I have the same problem if I init my form with :["Troubles de la vessie", "Troubles de l'érection",...]



from Input Material Chips -- Init Form Array

Thursday 30 August 2018

How to sort records by sequence insted of name in Odoo OCA widget web_widget_x2many_2d_matrix?

I already try with no success to sort by sequence a dict of records by jquery I dont know where sorted again by name.

I ask the community on git but nobody answer me, I'm trying to sort by odoo sequence. using modules web_widget_x2many_2d_matrix, and sale_order_variant_mgmt

I modify python code, and if I debug the list of records the sort is the intended, but when the javascript code is loaded, it sorted by name and cant debug where the problem is

@api.onchange('product_tmpl_id')
    def _onchange_product_tmpl_id(self):
        self.variant_line_ids = [(6, 0, [])]
        template = self.product_tmpl_id
        context = self.env.context
        record = self.env[context['active_model']].browse(context['active_id'])
        if context['active_model'] == 'sale.order.line' or context['active_model'] == 'sale.order.line_group': #TODO check this modify for lentex group_sale_lines module
            sale_order = record.order_id
        else:
            sale_order = record

        num_attrs = len(template.attribute_line_ids)
        if not template or not num_attrs:
            return
        line_x = template.attribute_line_ids[0]
        line_y = False if num_attrs == 1 else template.attribute_line_ids[1]
        lines = []

        for value_x in line_x.value_ids.sorted(key=lambda r: r.sequence):  
            for value_y in line_y and line_y.value_ids.sorted(key=lambda r: r.sequence) or [False]: #I modify this and in python the sort is the intended, but not in JS
                # Filter the corresponding product for that values
                values = value_x
                if value_y:
                    values += value_y
                product = template.product_variant_ids.filtered(lambda x: not(values - x.attribute_value_ids))[:1]
                order_line = sale_order.order_line.filtered(lambda x: x.product_id == product)[:1]
                lines.append((0, 0, {
                    'product_id': product,
                    'disabled': not bool(product),
                    'value_x': value_x,
                    'value_y': value_y,
                    'product_uom_qty': order_line.product_uom_qty,
                }))
        self.variant_line_ids = lines

I think the problem is here

 // get x axis values in the correct order
        get_x_axis_values: function()
        {
            return _.keys(this.by_x_axis); //I think here is where the order is defined
        },
        // get y axis values in the correct order
        get_y_axis_values: function()
        {
            return _.keys(this.by_y_axis); //I think here is where the order is defined
        },



from How to sort records by sequence insted of name in Odoo OCA widget web_widget_x2many_2d_matrix?

Isotope - Cannot read property 'filteredItems' of undefined

I am trying to get my isotope post page to work with a Load More button (as seen here: https://codepen.io/bebjakub/pen/jWoYEO). I have the code working on Codepen, but I couldn't get it working on the website.

Working Codepen (My (Filtering & Load More) - https://codepen.io/whitinggg/pen/qyvVwz

Live Page Link - Here

I am currently seeing this error in console in regards to my isotope.js file:

Uncaught TypeError: Cannot read property 'filteredItems' of undefined
    at loadMore (isotope.js?v=2.2.7:53)
    at HTMLDocument.<anonymous> (isotope.js?v=2.2.7:48)
    at i (jquery.js?ver=1.12.4:2)
    at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4:2)
    at Function.ready (jquery.js?ver=1.12.4:2)
    at HTMLDocument.K (jquery.js?ver=1.12.4:2)

Can anyone help with what this error means? Please help me to resolve the it.

My Isotope.js File

jQuery(function ($) {


    // with jQuery
    var $container = $('.grid').isotope({
      itemSelector: '.grid-item',
      layoutMode: 'packery',
      columnWidth: '.grid-sizer',
      packery: {
        gutter: '.gutter-sizer'
      }
    });

     //Add the class selected to the item that is clicked, and remove from the others
     var $optionSets = $('#filters'),
     $optionLinks = $optionSets.find('a');

     $optionLinks.click(function(){
     var $this = $(this);
     // don't proceed if already selected
     if ( $this.hasClass('selected') ) {
       return false;
     }
     var $optionSet = $this.parents('#filters');
     $optionSets.find('.selected').removeClass('selected');
     $this.addClass('selected');

     //When an item is clicked, sort the items.
     var selector = $(this).attr('data-filter');
     $container.isotope({ filter: selector });

     return false;
     });

    // layout Isotope after each image loads
    $container.imagesLoaded().progress( function() {
      $container.isotope('layout');
    });


//****************************
  // Isotope Load more button
  //****************************
  var initShow = 15; //number of items loaded on init & onclick load more button
  var counter = initShow; //counter for load more button
  var iso = $container.data('grid'); // get Isotope instance

  loadMore(initShow); //execute function onload

  function loadMore(toShow) {
    $container.find(".hidden").removeClass("hidden");

    var hiddenElems = iso.filteredItems.slice(toShow, iso.filteredItems.length).map(function(item) {
      return item.element;
    });
    $(hiddenElems).addClass('hidden');
    $container.isotope('layout');

    //when no more to load, hide show more button
    if (hiddenElems.length == 0) {
      jQuery("#load-more").hide();
    } else {
      jQuery("#load-more").show();
    };

  }

  //append load more button
  $container.after('<button id="load-more"> Load More</button>');

  //when load more button clicked
  $("#load-more").click(function() {
    if ($('#filters').data('clicked')) {
      //when filter button clicked, set initial value for counter
      counter = initShow;
      $('#filters').data('clicked', false);
    } else {
      counter = counter;
    };

    counter = counter + initShow;

    loadMore(counter);
  });

  //when filter button clicked
  $("#filters").click(function() {
    $(this).data('clicked', true);

    loadMore(initShow);
  })


});



from Isotope - Cannot read property 'filteredItems' of undefined

Codeigniter Session resets when refreshing

After a month trying to solve this, and trying all kind of answers in realted questions I decided to ask it myself.

This problems occurs on a new server we recently bought, the same code it's working fine on localhost and last server. But it's probably code related.

The Session is correctly created and the token is set, a var_dump shows that. But when the users tries to login, after redirecting to the access function, the Session token is not set, so the login doesn't occurs.

Even on the same page, if you refresh, the __ci_last_regenerate (which get the time when the Session was regenerated for last time) is the current time, and change after every single refresh.

In var/lib/php/session two different files are created after every refresh, don't know why. Here the pic:

enter image description here

The one at 19 secs hast the correct dasta (time and token), the last one only the time.

Also, we recently add a new subdomain to the site, so we have in the same server two different subdomains.

This is the Session coniguration:

$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

Tried also with DB driver, and it generated 2 (or 3 rows sometimes) on the table. The config was:

$config['sess_driver']= 'database';
$config['sess_cookie_name']= 'ci_session';
$config['sess_expiration']= 0;
$config['sess_save_path']= 'ci_sessions';
$config['sess_match_ip']= FALSE;
$config['sess_time_to_update']= 300;
$config['sess_regenerate_destroy']= FALSE;
$config['sess_use_database']= TRUE;
$config['sess_expire_on_close']= TRUE;
$config['sess_table_name']= 'ci_sessions';

And the output of database being its columns (id, ip, timestamp, data):

enter image description here

The data is always the same, a last regenerate containing the time and a token in one case, and only the last regenerate in the other (2 rows on each refresh).

PHP is 7.2.7 . CodeIgniter is 3.1.5.

Any further code needed or server information will be suplied if asked.



from Codeigniter Session resets when refreshing

Input Material Chips -- Init Form Array

I want to init my mat chips input with input data but when i have two chips, it form only one form :

enter image description here

TS

this.ppssToDisplay = this.ppssService.getSinglePPS(this.key)
    .subscribe(res=>{
        this.ppssToDisplay = res;
        this.ppsForm.controls['requirements'].setValue(Array(this.ppssToDisplay.effetsind));

        console.log(this.ppssToDisplay.effetsind)); 
    });

initForm(): void {
    this.ppsForm = this.formBuilder.group({
       requirements: this.formBuilder.array(['']),

// I dont know why but i must init my form with an empty chips if i want receive data from service.

    });
}

get formData () { return this.ppsForm.get('requirements'); }

Log

 (2) ["Troubles de la vessie", "Troubles de l'érection"]
        0:"Troubles de la vessie"
        1:"Troubles de l'érection"
        length:2

I construct the html code with the example of angular material.io : https://material.angular.io/components/chips/overview

HTML

<mat-form-field style="width:50%" appearance="outline">
<mat-label>Description du traitement</mat-label>
<textarea matInput formControlName="description"></textarea>
</mat-form-field>&nbsp;&nbsp;
<mat-form-field style="width:50%" appearance="outline">
<mat-label>Effets indésirables du traitement</mat-label>
<mat-chip-list #chipList>
<mat-chip *ngFor="let requirement of formData.controls; let i = index;" [selectable]="selectable"
[removable]="removable" (removed)="remove(i)">

<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
<input placeholder="Nouvel effet indésirable..."

[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)" />
</mat-chip-list>
<!-- <mat-autocomplete #auto2="matAutocomplete">
<mat-option *ngFor=" let option2 of filteredOptions2 | async" [value]="option2">

</mat-option>
</mat-autocomplete> -->
</mat-form-field>

Error

> core.js:1598 ERROR Error: Must supply a value for form control at index: 0.
        at forms.js:4304
        at forms.js:4274
        at Array.forEach (<anonymous>)
        at FormArray.push../node_modules/@angular/forms/fesm5/forms.js.FormArray._forEachChild (forms.js:4274)
        at FormArray.push../node_modules/@angular/forms/fesm5/forms.js.FormArray._checkAllValuesPresent (forms.js:4302)
        at FormArray.push../node_modules/@angular/forms/fesm5/forms.js.FormArray.setValu

I have the same problem if i init my form with :["Troubles de la vessie", "Troubles de l'érection",...]



from Input Material Chips -- Init Form Array

Show tooltip on the D3 map

I've created a basic map using D3 with countries geojson. Here is the demo.

Now when the user clicks on any coordinate on the map, I am showing a weather info within a tooltip with weather icon as a marker.

countries = countriesGroup
    .selectAll("path")
    .data(json.features)
    .enter()
    .append("path")
    .attr("d", path)
    .attr("id", function(d, i) {
        return "country" + d.properties.iso_a3;
    })
    .attr("class", "country")
    // add a mouseover action to show name label for feature/country
    .on("mouseover", function(d, i) {
        d3.select("#countryLabel" + d.properties.iso_a3).style("display", "block");
    })
    .on("mouseout", function(d, i) {
        d3.select("#countryLabel" + d.properties.iso_a3).style("display", "none");
    })
    // add an onclick action to zoom into clicked country
    .on("click", function(d, i) {
        var eventLocation = d3.mouse(this);
        var coordinates = projection.invert(eventLocation);
        var proxy = "https://cors-anywhere.herokuapp.com/";
        var wetherInfoUrl =
            "https://api.darksky.net/forecast/c68e9aaf0d467528b9363e383bde6254/" + coordinates[1] + "," + coordinates[0] + "?exclude=minutely,hourly,daily";
        $.ajax({
            url: proxy + wetherInfoUrl,
            success: function(response) {
                tooltipDiv
                    .transition()
                    .duration(200)
                    .style("opacity", 0.9);
                tooltipDiv
                    .html('<h3>Dynamic Weather info: '+ response.currently.humidity +'</h3><br/><img src="https://darksky.net/images/weather-icons/' + response.currently.icon + '.png" alt="clear-night Icon" width="50" height="50">')
                    .style("left", (eventLocation[0] - 250) + "px")
                    .style("top", (eventLocation[1] - 100) + "px");
            }
        });
        d3.selectAll(".country").classed("country-on", false);
        d3.select(this).classed("country-on", true);
        boxZoom(path.bounds(d), path.centroid(d), 20);
    });

Now the issue is, the tooltip remains at the absolute position relative to the body (It stays at the exact position on the screen which is misleading if we pan and zoom the map) whereas I want the tooltip to be relative to the coordinate clicked on the map and should be fixed to the clicked coordinate no matter where we zoom or pan in the map, similar to this leaflet example (In short I want tooltip to behave similarly to the typical map pin markers).



from Show tooltip on the D3 map

How to Filter Parsed XML data by Element Content [jQuery]

So I have a xml housing property feed [on a WordPress site] currently that is pretty simple, it just gathers the fields i want to show and displays that as a list [pretty normal stuff] But i now need to be able make two lists, one that shows only sold properties, and one does not show sold properties. Currently my code is as follows:

jQuery(function( $ ){

$(document).ready(function()
{
    $.ajax({
        type: "GET",
        url: "/properties2.xml",
        dataType: "xml",
        success: parseXml
    });
});

function parseXml(xml)
{
    $("#xmlmain").html("<div id='content' data-role='listview' data-inset='true'></div>");
    $(xml).find("property").each(function() {
        $("#content").append("<div class='xmlwrapper'><div class='xmlleft'><img src='"+$(this).find('[name="Photo 1"]').text()+"'/></div><div class='xmlright'><h2>"+$(this).find("advert_heading").text()+"</h2><p class='price'>"+$(this).find
        ("price_text").text()+"</p><p class='priority'>"+$(this).find("priority").text()+"</p><p>"+$(this).find("main_advert").text()+"</p><a href='"+$(this).find("web_link").text()+"' target='_blank'>VIEW > </a></div></div>");
    });
}
});

Im pretty novice at Javascript and Jquery so im really not sure how i go about filtering the lists to exclude sold and only include sold properties. How do i adapt/filter this to get the required result? I tried some attemps with filter(); function but it just kept stopping the feed from displaying at all.

This was the snippet/example i was trying to incorporate/work with:

var getTextNodesIn = function(el) {
return $(el).find(":not(iframe)").addBack().contents().filter(function() {
    return this.nodeType == 3;
    });
};

getTextNodesIn(el);

The data i need to use is in the Priority Field shown below. Here is an extract from the xml feed:

<properties>
<property reference="MR139">
    <instructedDate>06/08/2018 17:07:05</instructedDate>
    <price_text>£600,000</price_text>
    <numeric_price>600000.0000</numeric_price>

    <priority>On Market</priority>

    <advert_heading>house for sale</advert_heading>
    <main_advert>some text about the property</main_advert>
    <web_link>www.example.com</web_link>
    <property_style>Detached</property_style>
    <property_reference>111111</property_reference>
    <newHome>NO</newHome>
    <noChain>NO</noChain>
    <furnished>Unknown</furnished>
    <currency>GBP</currency>
    <featuredProperty>NO</featuredProperty>
    <pictures>
        <picture name="Photo 1" lastchanged="2018-08-06T15:44:48.5800534Z">
            <filename>example.jpg</filename>
        </picture>
    </pictures>
</property>
</properties>

[The text in the priority field for sold properties will either be "Sold" or "Sold STC" if that makes a difference.]

Any help would be much appreciated, even if its just pointing me to resources i can use that are relevant to my problem. My searches seem to turn up unrelated information, potentially due to me wording things wrong due to not knowing the terminology properly.



from How to Filter Parsed XML data by Element Content [jQuery]

Best practice - Building/deploy my front end app - repo for builds?

I have a front-end React web application that I develop and test with using Nodejs. When I deploy to prod or test, I build with some basic Webpack scripts and that spits out a /dist folder with an optimized index.html and and whatever JS and static files my application needs.

Pretty basic stuff - my question is, I'm wondering what the best practice is for deploying builds to prod. At the moment, all builds are done manually. I pull the latest build tag from master, run build scripts, stop apache, and replace htdocs with the /dist folder.

What would be the next natural step up from this process in terms of automation? Updates occur roughly once a month or less. Is there something lighter that CI I can use? Is a new repository that just holds builds, and I can just pull from that instead, a common solution to my issue? Looking for best practice advice.



from Best practice - Building/deploy my front end app - repo for builds?

Ngnix or PHP slow http response on missing images, 502 and upstream timed out

I'm setting up a new server with Ubuntu 18.04.1 and nginx 1.14.0 Everything works fine except a test page where I set up a lot of broken links to missing images. It seems to take forever for the server to realise they are missing and respond to the http request. Some missing files give a HTTP status of 404 and some give 502. What causes these delays and 502 errors? Did I do something wrong in the nginx or php configuration?

A part of the nginx error.log:

2018/08/28 13:02:27 [error] 5979#5979: *487 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 2a02:a440:91e3:1:5856:a644:6955:3dd0, server: test.vuyk.eu, request: "GET /images/klanten/Praatmaatgroep.gif HTTP/2.0", upstream: "fastcgi://unix:/run/php/php7.2-fpm.sock", host: "test.vuyk.eu", referrer: "https://test.vuyk.eu/portfolio-2"

A line of the php7.2-fpm.log

[28-Aug-2018 13:39:59] WARNING: [pool www] child 8246, script '/var/www/vuyk.eu/webroot/index.php' (request: "GET /index.php?page=/images/klanten/JHoogeveen.gif") execution timed out (22.813907 sec), terminating

The timeline of HTTP requests and replies, that shows the requests on non-existent files and the response of the server, some give a 404 which is good, some give 502 bad gateway:

GET https://test.vuyk.eu/portfolio-2 [HTTP/2.0 200 OK 132ms]
GET https://test.vuyk.eu/templates/purity_iii/css/bootstrap.css [HTTP/2.0 200 OK 40ms]
GET https://test.vuyk.eu/templates/system/css/system.css [HTTP/2.0 200 OK 50ms]
GET https://test.vuyk.eu/templates/purity_iii/css/template.css [HTTP/2.0 200 OK 50ms]
GET https://test.vuyk.eu/templates/purity_iii/fonts/font-awesome/css/font-awesome.min.css [HTTP/2.0 200 OK 50ms]
GET https://test.vuyk.eu/templates/purity_iii/css/layouts/corporate.css [HTTP/2.0 200 OK 50ms]
GET https://test.vuyk.eu/media/jui/js/jquery.min.js?48b6d1b3850bca834b403c58682b4579 [HTTP/2.0 200 OK 60ms]
GET https://test.vuyk.eu/media/jui/js/jquery-noconflict.js?48b6d1b3850bca834b403c58682b4579 [HTTP/2.0 200 OK 60ms]
GET https://test.vuyk.eu/media/jui/js/jquery-migrate.min.js?48b6d1b3850bca834b403c58682b4579 [HTTP/2.0 200 OK 60ms]
GET https://test.vuyk.eu/media/system/js/caption.js?48b6d1b3850bca834b403c58682b4579 [HTTP/2.0 200 OK 70ms]
GET https://test.vuyk.eu/plugins/system/t3/base-bs3/bootstrap/js/bootstrap.js? 8b6d1b3850bca834b403c58682b4579 [HTTP/2.0 200 OK 80ms]
GET https://test.vuyk.eu/plugins/system/t3/base-bs3/js/jquery.tap.min.js [HTTP/2.0 200 OK 80ms]
GET https://test.vuyk.eu/plugins/system/t3/base-bs3/js/script.js [HTTP/2.0 200 OK 70ms]
GET https://test.vuyk.eu/plugins/system/t3/base-bs3/js/menu.js [HTTP/2.0 200 OK 70ms]
GET https://test.vuyk.eu/templates/purity_iii/js/script.js [HTTP/2.0 200 OK 70ms]
GET https://test.vuyk.eu/plugins/system/t3/base-bs3/js/nav-collapse.js [HTTP/2.0 200 OK 70ms]
GET https://test.vuyk.eu/templates/purity_iii/css/custom-vuyk.css [HTTP/2.0 200 OK 70ms]
GET https://test.vuyk.eu/images/klanten1/schipper2.gif [HTTP/2.0 502 Bad Gateway 23988ms]
GET https://test.vuyk.eu/images/klanten1/Kuiper.gif [HTTP/2.0 502 Bad Gateway 24038ms]
GET https://test.vuyk.eu/images/klanten1/WindMatch.gif [HTTP/2.0 502 Bad Gateway 24008ms]
GET https://test.vuyk.eu/images/klanten1/Tuinland.gif [HTTP/2.0 502 Bad Gateway 24018ms]
GET https://test.vuyk.eu/images/klanten1/Wezenberg.gif [HTTP/2.0 502 Bad Gateway 24038ms]
GET https://test.vuyk.eu/images/klanten1/Morgenster.gif [HTTP/2.0 502 Bad Gateway 23998ms]
GET https://test.vuyk.eu/images/klanten1/Harrie-boerhof.gif [HTTP/2.0 502 Bad Gateway 24028ms]
GET https://test.vuyk.eu/images/klanten1/Lococensus.gif [HTTP/2.0 502 Bad Gateway 23998ms]
GET https://test.vuyk.eu/images/klanten1/JHoogeveen.gif [HTTP/2.0 502 Bad Gateway 23978ms]
GET https://test.vuyk.eu/images/klanten1/DeDeur.gif [HTTP/2.0 502 Bad Gateway 23988ms]
GET https://test.vuyk.eu/images/klanten1/Runhaar.gif [HTTP/2.0 502 Bad Gateway 23958ms]
GET https://test.vuyk.eu/images/klanten1/Schunselaar-schildersbedrijf.gif [HTTP/2.0 502 Bad Gateway 23948ms]
GET https://test.vuyk.eu/images/klanten1/Capelle.gif [HTTP/2.0 502 Bad Gateway 23958ms]
GET https://test.vuyk.eu/images/klanten1/Distantlake.gif [HTTP/2.0 502 Bad Gateway 24038ms]
GET https://test.vuyk.eu/images/klanten1/Eikenaar.gif [HTTP/2.0 502 Bad Gateway 24018ms]
GET https://test.vuyk.eu/images/klanten1/FFWD.gif [HTTP/2.0 404 Not Found 26274ms]
GET https://test.vuyk.eu/images/klanten1/Veltec.gif [HTTP/2.0 404 Not Found 26791ms]
GET https://test.vuyk.eu/images/klanten1/Heutink.gif [HTTP/2.0 404 Not Found 26811ms]
GET https://test.vuyk.eu/images/klanten1/Lindeboom.gif [HTTP/2.0 404 Not Found 26777ms]
GET https://test.vuyk.eu/images/klanten1/aataxi.gif [HTTP/2.0 404 Not Found 26828ms]
GET https://test.vuyk.eu/images/klanten1/Aewind.gif [HTTP/2.0 404 Not Found 26811ms]
GET https://test.vuyk.eu/images/klanten1/Praatmaatgroep.gif [HTTP/2.0 404 Not Found 26800ms]
GET https://test.vuyk.eu/media/system/css/system.css [HTTP/2.0 200 OK 20ms]
JQMIGRATE: Migrate is installed, version 1.4.1 jquery-migrate.min.js:2:542
GET https://test.vuyk.eu/images/logo.gif [HTTP/2.0 200 OK 20ms]
GET https://test.vuyk.eu/images/reclame-en-communicatie.gif [HTTP/2.0 200 OK 20ms]
GET https://test.vuyk.eu/fonts/opensans-regular-webfont.woff [HTTP/2.0 200 OK 40ms]
GET https://test.vuyk.eu/templates/purity_iii/fonts/font-awesome/fonts/fontawesome-webfont.woff2?v=4.7.0 [HTTP/2.0 200 OK 70ms]

The nginx server configuration:

server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        ssl_certificate /etc/letsencrypt/live/test.vuyk.eu/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/test.vuyk.eu/privkey.pem;
        include snippets/ssl-params.conf;

        server_name test.vuyk.eu;
        root /var/www/vuyk.eu/webroot;
        index index.php index.html index.htm ;

        location / {
            try_files $uri $uri/ /index.php?$args;
        }

        location ~ \.php$ {
            include fastcgi.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        }
}

nginx.conf

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 2048;
    multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    #   keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip             on;
    gzip_comp_level  2;
    gzip_min_length  1000;
    gzip_proxied     expired no-cache no-store private auth;
    gzip_types       text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 100m;
    large_client_header_buffers 4 8k;
    fastcgi_buffers 16 16k;
    fastcgi_buffer_size 32k;
    fastcgi_read_timeout 500; #gateway probleem
    client_body_timeout 12;
    client_header_timeout 12;
    keepalive_timeout 25;
    send_timeout 10;
}

fastcgi.conf

fastcgi_param  PATH_TRANSLATED    $document_root$fastcgi_path_info;
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  PATH_INFO          $fastcgi_path_info;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

php.ini

[PHP]

engine = On
short_open_tag = Off
precision = 14
output_buffering = 4096
zlib.output_compression = Off
implicit_flush = Off
unserialize_callback_func =
serialize_precision = -1
disable_functions = pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,
disable_classes =
zend.enable_gc = On
expose_php = Off
max_execution_time = 30
max_input_time = 60
memory_limit = 128M
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
html_errors = On
variables_order = "GPCS"
request_order = "GP"
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 28M
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
default_charset = "UTF-8"
doc_root =
user_dir =
enable_dl = Off
cgi.fix_pathinfo=1
file_uploads = On
upload_max_filesize = 20M
max_file_uploads = 20
allow_url_fopen = On
allow_url_include = Off
default_socket_timeout = 60
cli_server.color = On
date.timezone = "Europe/Amsterdam"

[Pdo_mysql]
pdo_mysql.cache_size = 2000
pdo_mysql.default_socket=
[mail function]
SMTP = localhost
smtp_port = 25
mail.add_x_header = Off

[ODBC]
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 4096
odbc.defaultbinmode = 1

[Interbase]
ibase.allow_persistent = 1
ibase.max_persistent = -1
ibase.max_links = -1
ibase.timestampformat = "%Y-%m-%d %H:%M:%S"
ibase.dateformat = "%Y-%m-%d"
ibase.timeformat = "%H:%M:%S"

[MySQLi]
mysqli.max_persistent = -1
mysqli.allow_persistent = On
mysqli.max_links = -1
mysqli.cache_size = 2000
mysqli.default_port = 3306
mysqli.default_socket =
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off
[mysqlnd]
mysqlnd.collect_statistics = On
mysqlnd.collect_memory_statistics = Off

[PostgreSQL]
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0

[bcmath]
bcmath.scale = 0

[Session]
session.save_handler = files
session.use_strict_mode = 0
session.use_cookies = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.serialize_handler = php
session.gc_probability = 0
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.referer_check =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.sid_length = 26
session.trans_sid_tags = "a=href,area=href,frame=src,form="
session.sid_bits_per_character = 5

[Assertion]
zend.assertions = -1

[mbstring]
mbstring.func_overload = 0

[Tidy]
tidy.clean_output = Off

[soap]
soap.wsdl_cache_enabled=1
soap.wsdl_cache_dir="/tmp"
soap.wsdl_cache_ttl=86400
soap.wsdl_cache_limit = 5
[ldap]
ldap.max_links = -1



from Ngnix or PHP slow http response on missing images, 502 and upstream timed out