问:
ClassCastException with CoordinatorLayout in AndroidX project
My project uses AndroidX, and has a CoordinatorLayout, AppbarLayout... I have the dependencies listed in the gradle file but the layout editor is throwing error and keeps saying classes couldn't be found. This causing a render problem but the project compiles and the app is working well.

Gradle (app):

```<code>    dependencies {
//...
//...
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.core:core:1.2.0-alpha01'
    implementation 'androidx.media:media:1.1.0-beta01'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0-alpha01'
    implementation group: 'androidx.coordinatorlayout', name: 'coordinatorlayout', version: '1.0.0'
}
</code>```

XML layout file:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl_parent_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorBackgroundGrey"
        ads:layout_constraintEnd_toEndOf="parent"
        ads:layout_constraintStart_toStartOf="parent"
        ads:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appBarlayout"
            android:layout_width="match_parent"
            android:layout_height="280dp"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsingToolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                ads:contentScrim="?attr/colorPrimary"
                ads:layout_scrollFlags="scroll|exitUntilCollapsed">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    ads:layout_collapseMode="parallax">

                    <com.balysv.materialripple.MaterialRippleLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        ads:mrl_rippleAlpha="0.2"
                        ads:mrl_rippleColor="@color/colorRipple"
                        ads:mrl_rippleHover="true"
                        ads:mrl_rippleOverlay="true">

                        <ImageView
                            android:id="@+id/imv_image"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:contentDescription="@string/text_image_view_descrip"
                            android:scaleType="centerCrop"
                            ads:layout_collapseMode="none"
                            ads:srcCompat="@drawable/ic_launcher_foreground" />

                    </com.balysv.materialripple.MaterialRippleLayout>

                </RelativeLayout>

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="@color/demo_dark_transparent"
                    ads:layout_collapseMode="pin"
                    ads:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

            </com.google.android.material.appbar.CollapsingToolbarLayout>

        </com.google.android.material.appbar.AppBarLayout>

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:foreground="?android:attr/selectableItemBackground"
            ads:behavior_overlapTop="64dp"
            ads:cardCornerRadius="3dp"
            ads:cardElevation="3sp"
            ads:cardPreventCornerOverlap="false"
            ads:cardUseCompatPadding="true"
            app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">

            <androidx.core.widget.NestedScrollView
                android:id="@+id/nestedScrollView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clipToPadding="false">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <include
                        android:id="@+id/lyt_main_content"
                        layout="@layout/include_news_content"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentStart="true"
                        android:layout_alignParentTop="true"
                        android:visibility="visible" />

                    <ViewFlipper
                        android:id="@+id/view_flipper2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:background="#F44336">

                    </ViewFlipper>

                </RelativeLayout>

            </androidx.core.widget.NestedScrollView>

        </androidx.cardview.widget.CardView>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Tried almost everything I could without success.

EDIT:

Java class (import):

```<code>import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.core.widget.NestedScrollView;
</code>```

答: Drop all three of your implementation 'com.google.android.material:material:1.1.0-alpha06'

Body:
My project uses AndroidX, and has a CoordinatorLayout, AppbarLayout... I have the dependencies listed in the gradle file but the layout editor is throwing error and keeps saying classes couldn't be found. This causing a render problem but the project compiles and the app is working well.

Gradle (app):

    dependencies {
//...
//...
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.core:core:1.2.0-alpha01'
    implementation 'androidx.media:media:1.1.0-beta01'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0-alpha01'
    implementation group: 'androidx.coordinatorlayout', name: 'coordinatorlayout', version: '1.0.0'
}

XML layout file:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl_parent_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorBackgroundGrey"
        ads:layout_constraintEnd_toEndOf="parent"
        ads:layout_constraintStart_toStartOf="parent"
        ads:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appBarlayout"
            android:layout_width="match_parent"
            android:layout_height="280dp"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsingToolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                ads:contentScrim="?attr/colorPrimary"
                ads:layout_scrollFlags="scroll|exitUntilCollapsed">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    ads:layout_collapseMode="parallax">

                    <com.balysv.materialripple.MaterialRippleLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        ads:mrl_rippleAlpha="0.2"
                        ads:mrl_rippleColor="@color/colorRipple"
                        ads:mrl_rippleHover="true"
                        ads:mrl_rippleOverlay="true">

                        <ImageView
                            android:id="@+id/imv_image"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:contentDescription="@string/text_image_view_descrip"
                            android:scaleType="centerCrop"
                            ads:layout_collapseMode="none"
                            ads:srcCompat="@drawable/ic_launcher_foreground" />

                    </com.balysv.materialripple.MaterialRippleLayout>

                </RelativeLayout>

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="@color/demo_dark_transparent"
                    ads:layout_collapseMode="pin"
                    ads:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

            </com.google.android.material.appbar.CollapsingToolbarLayout>

        </com.google.android.material.appbar.AppBarLayout>

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:foreground="?android:attr/selectableItemBackground"
            ads:behavior_overlapTop="64dp"
            ads:cardCornerRadius="3dp"
            ads:cardElevation="3sp"
            ads:cardPreventCornerOverlap="false"
            ads:cardUseCompatPadding="true"
            app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">

            <androidx.core.widget.NestedScrollView
                android:id="@+id/nestedScrollView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clipToPadding="false">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <include
                        android:id="@+id/lyt_main_content"
                        layout="@layout/include_news_content"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentStart="true"
                        android:layout_alignParentTop="true"
                        android:visibility="visible" />

                    <ViewFlipper
                        android:id="@+id/view_flipper2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:background="#F44336">

                    </ViewFlipper>

                </RelativeLayout>

            </androidx.core.widget.NestedScrollView>

        </androidx.cardview.widget.CardView>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Tried almost everything I could without success.

EDIT:

Java class (import):

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.core.widget.NestedScrollView;


来源: stackexchange

问:
Cannot find module 'express' on cpanel
I tried to setup nodejs on a cpanel nodejs app. I put my package.json on my /games folder, and when I do run npm install, the folder node_modules is created but when I launch my app and go to my link (falsegames.com/game), I am getting an error.

I already tried to place my real folder node_modules instead of the one created by cpanel but it still didnt worked. The error is cannot find module express but it is in my package.json file.

My server.js:

```<code>const game = require("./board");

const express = require('express');
const util = require('util');
let app = express();
//var http = require('http').Server(app);
//var io = require('socket.io')(http);
var port = process.env.PORT || 8080;
console.log(window.location)
console.log(window.location.href)
var matched = false;
var rps = {
    checker: 0
}
app.use(express.static('public'));

app.get('/', function (req, res) {
    // nbroom
    res.sendFile("public/index.html");
});
let server = app.listen(port, function () {
    console.log("En écoute sur http://127.0.0.1:"+port);
});
const io = require('socket.io').listen(server).sockets;

// var connections = 0;
var start = 0;
var partialBoards = {}
var boards = {};
var matchmakingboard = null;

let nbroom = 0;

</code>```

The error i am getting on the website is 'Web application could not be started by the Phusion Passenger application server.'
When i go on the terminal then doing node server after entering the virtual environnement im getting error: could not find mondule server.js

答:
You have to save your modules in dependencies.</p>

```<code>npm install --save module_name
</code>```

ContentLicense: CC BY-SA 4.0

Title: Cannot find module 'express' on cpanel

Body:
I tried to setup nodejs on a cpanel nodejs app. I put my package.json on my /games folder, and when I do run npm install, the folder node_modules is created but when I launch my app and go to my link (falsegames.com/game), I am getting an error.

I already tried to place my real folder node_modules instead of the one created by cpanel but it still didnt worked. The error is cannot find module express but it is in my package.json file.

My server.js:

const game = require("./board");

const express = require('express');
const util = require('util');
let app = express();
//var http = require('http').Server(app);
//var io = require('socket.io')(http);
var port = process.env.PORT || 8080;
console.log(window.location)
console.log(window.location.href)
var matched = false;
var rps = {
    checker: 0
}
app.use(express.static('public'));

app.get('/', function (req, res) {
    // nbroom
    res.sendFile("public/index.html");
});
let server = app.listen(port, function () {
    console.log("En écoute sur http://127.0.0.1:"+port);
});
const io = require('socket.io').listen(server).sockets;

// var connections = 0;
var start = 0;
var partialBoards = {}
var boards = {};
var matchmakingboard = null;

let nbroom = 0;

The error i am getting on the website is 'Web application could not be started by the Phusion Passenger application server.'
When i go on the terminal then doing node server after entering the virtual environnement im getting error: could not find mondule server.js

Body:
You have to save your modules in dependencies.

npm install --save module_name


问:
UWP sqlite-net Async database access
On my UWP app, I'm using sqlite-net to access the database. According to their GitHub Page I'm using Source Installation. Now I want to migrate to using the Nuget package (To get the latest updates) and they have mentioned getting the PCL package. When I add the PCL package I don't have Async operations available like it was on Source Installation. Please let me know how to proceed on this matter.

When it comes to UWP and I want to use sqlite-net I see soo many nugets in VS 2015 Nuget Package Manager. Please help me which one to choose. (Selected package should not be deprecated in the near future and should be developed actively by the vendor, providing continues updates)

答:
You need to install both SQLite.Net.Async-PCL and SQLite.Net-PCL to use async operations.

```<code>SQLiteConnectionString connString = new SQLiteConnectionString(file.Path, true);
var asyncConnction = new SQLiteAsyncConnection(
    () => {
        return new SQLiteConnectionWithLock(new SQLitePlatformWinRT(), connString);
    }
);
</code>```

Note that the SQLite.Net-PCL package is different from the one you installed. I'm not sure if the async package is compatible with that one.

Title: UWP sqlite-net Async database access

Body:
You need to install both SQLite.Net.Async-PCL and SQLite.Net-PCL to use async operations.

SQLiteConnectionString connString = new SQLiteConnectionString(file.Path, true);
var asyncConnction = new SQLiteAsyncConnection(
    () => {
        return new SQLiteConnectionWithLock(new SQLitePlatformWinRT(), connString);
    }
);

Note that the SQLite.Net-PCL package is different from the one you installed. I'm not sure if the async package is compatible with that one.


问:
Local Storage remove Item and remove list
I am at the end of my Project. I have problem with add favorites        and to remove item from local storage. It works to delete it from html but when you refresh the page, items are again here. Also remove whole favorites its not working. I hope that someone see my mistake</p>

```<code>   I try to remove whole list with function but its also not working.

    <body>
    <main>
   <h1>Your Favourite Recipes</h1>
<p>These are your favourite recipes that we have saved for you.</p>
  <button id="probam" type="button"
 name="button" onclick="deleteListe()">brisi</button>
  <p id="fav"></p>

  <script>
   let list = localStorage.getItem('favorites');
   list = list ? list.split(',') : [];
   var ll = [];
   ll = list;

   var output = document.createElement('ul');
   output.setAttribute('id', 'list')

   for (let i = 0; i < ll.length; i++) {
       var it = document.createElement('li');
       var bt = document.createElement('button');
       bt.innerHTML = ('Delete');
       bt.setAttribute('class', 'delete')

       it.appendChild(document.createTextNode(ll[i]));
       it.appendChild(bt);
       output.appendChild(it);
   }

   document.getElementById('fav').appendChild(output);

   var del = document.getElementsByClassName('delete');

   for (let j = 0; j < del.length; j++) {
       del[j].addEventListener('click', function() {
           // console.log((del[j].parentNode).parentNode);
           (del[j].parentNode).parentNode.removeChild(del[j].parentNode);
       })
   }
   function deleteListe() {
  localStorage.removeItem("favorites");
   }
    </script>
  <button type="button" name="button"></button>
  <a  href="index.html" class='vido'>Home</a>
  </main>
  </body>
</code>```

答:
I little change your code, and i added for all button required functions</p>

```<code>    <h1>Your Favourite Recipes</h1>
    <p>These are your favourite recipes that we have saved for you.</p>
    <button id="probam" type="button" name="button" onclick="deleteListe()">brisi</button>
    <p id="fav"></p>
    <script>
    function deleteListe() {
        localStorage.removeItem("favorites");
    }

    function deleteElement(element) {
        const newFavorites = (localStorage.getItem('favorites')||"").replace(element,"");
        localStorage.setItem("favorites",newFavorites.split(",").filter(Boolean).join(","));
        setTimeout(()=>{
          localStorage.getItem('favorites')
          location.reload();
        },10);
    }

    let list = (localStorage.getItem('favorites')||"").split(",").filter(Boolean);

   var output = document.createElement('ul');
   output.setAttribute('id', 'list')

   list.forEach((el)=>{
       var it = document.createElement('li');
       var bt = document.createElement('button');
       bt.innerHTML = ('Delete');
       bt.setAttribute('class', 'delete');
       bt.setAttribute('title', el);
       it.appendChild(document.createTextNode(el));
       it.appendChild(bt);
       output.appendChild(it);
   });

   document.getElementById('fav').appendChild(output);

   var del = document.getElementsByClassName('delete');

   for (let j = 0; j < del.length; j++) {
       del[j].addEventListener('click', function() {
            deleteElement(this.getAttribute('title'));
           (this.parentNode).parentNode.removeChild(this.parentNode);
       })
   }

    </script>
    <button type="button" name="button"></button>
    <a href="index.html" class='vido'>Home</a>
</code>```

Body:
I am at the end of my Project. I have problem with add favorites        and to remove item from local storage. It works to delete it from html but when you refresh the page, items are again here. Also remove whole favorites its not working. I hope that someone see my mistake

   I try to remove whole list with function but its also not working.

Your Favourite Recipes

These are your favourite recipes that we have saved for you.

  <button id="probam" type="button"
 name="button" onclick="deleteListe()">brisi</button>

  <button type="button" name="button"></button>
  Home

Body:
I little change your code, and i added for all button required functions

    <h1>Your Favourite Recipes</h1>
    <p>These are your favourite recipes that we have saved for you.</p>
    <button id="probam" type="button" name="button" onclick="deleteListe()">brisi</button>
    <p id="fav"></p>
    <script>
    function deleteListe() {
        localStorage.removeItem("favorites");
    }

    function deleteElement(element) {
        const newFavorites = (localStorage.getItem('favorites')||"").replace(element,"");
        localStorage.setItem("favorites",newFavorites.split(",").filter(Boolean).join(","));
        setTimeout(()=>{
          localStorage.getItem('favorites')
          location.reload();
        },10);
    }

    let list = (localStorage.getItem('favorites')||"").split(",").filter(Boolean);

   var output = document.createElement('ul');
   output.setAttribute('id', 'list')

   list.forEach((el)=>{
       var it = document.createElement('li');
       var bt = document.createElement('button');
       bt.innerHTML = ('Delete');
       bt.setAttribute('class', 'delete');
       bt.setAttribute('title', el);
       it.appendChild(document.createTextNode(el));
       it.appendChild(bt);
       output.appendChild(it);
   });

   document.getElementById('fav').appendChild(output);

   var del = document.getElementsByClassName('delete');

   for (let j = 0; j < del.length; j++) {
       del[j].addEventListener('click', function() {
            deleteElement(this.getAttribute('title'));
           (this.parentNode).parentNode.removeChild(this.parentNode);
       })
   }

    </script>
    <button type="button" name="button"></button>
    <a href="index.html" class='vido'>Home</a>


问:
Checked List Box with data value property for each item?
Does anyone know of a control such as a Checked List Box where each item can have a value against it.

For example you have a list of fruits and in the listbox it displays Apple, Orange & Banana but the values for those items are A, O & B.

答:
What platform?  If it is HTML, then the <select /> tag can have a different value and display string.

If you are working with Winforms, you can set the ListBox to have any type of object. so you could make a class that has a string for display and some kind of object for its value.  Then override the ToString() method and return the display string and there you go!

ContentLicense: CC BY-SA 3.0


问:
Python error "AttributeError: module 'scipy.misc' has no attribute 'logsumexp' "
I'm trying to use the lifetimes header to create the Recency, Frequency and T from a given data but it keeps showing the following error
AttributeError: module 'scipy.misc' has no attribute 'logsumexp'

```<code>from lifetimes.plotting import *
from lifetimes.utils import *
from lifetimes.estimation import *
data = summary_data_from_transaction_data(df, 'CustomerID','InvoiceDate', monetary_value_col='Sales', observation_period_end='2011-12-9')
print(data.head())
</code>```

The following output is received:

```<code>Traceback (most recent call last):
File "prj2.py", line 23, in <module>
from lifetimes.plotting import *
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\lifetimes\__init__.py", line 5, in <module>
from .fitters.beta_geo_fitter import BetaGeoFitter
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\lifetimes\fitters\beta_geo_fitter.py", line 9, in <module>
from autograd.scipy.special import gammaln, beta, gamma
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\autograd\scipy\__init__.py", line 7, in <module>
from . import misc
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\autograd\scipy\misc.py", line 7, in <module>
logsumexp = primitive(scipy.misc.logsumexp)
AttributeError: module 'scipy.misc' has no attribute 'logsumexp'
</code>```

The version of SciPy is 1.3.0
The code should generate a table with Recency, Frequency and T of each Customer

答: Downgrading to scipy==1.1.0 solves the issue</p>

Body:
I'm trying to use the lifetimes header to create the Recency, Frequency and T from a given data but it keeps showing the following error
AttributeError: module 'scipy.misc' has no attribute 'logsumexp'

from lifetimes.plotting import *
from lifetimes.utils import *
from lifetimes.estimation import *
data = summary_data_from_transaction_data(df, 'CustomerID','InvoiceDate', monetary_value_col='Sales', observation_period_end='2011-12-9')
print(data.head())

The following output is received:

Traceback (most recent call last):
File "prj2.py", line 23, in <module>
from lifetimes.plotting import *
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\lifetimes\__init__.py", line 5, in <module>
from .fitters.beta_geo_fitter import BetaGeoFitter
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\lifetimes\fitters\beta_geo_fitter.py", line 9, in <module>
from autograd.scipy.special import gammaln, beta, gamma
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\autograd\scipy\__init__.py", line 7, in <module>
from . import misc
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\autograd\scipy\misc.py", line 7, in <module>
logsumexp = primitive(scipy.misc.logsumexp)
AttributeError: module 'scipy.misc' has no attribute 'logsumexp'

The version of SciPy is 1.3.0
The code should generate a table with Recency, Frequency and T of each Customer


问:
Print array to a file
I would like to print an array to a file.

I would like the file to look exactly similar like how a code like this looks.

print_r ($abc); assuming $abc is an array.

Is there any one lines solution for this rather than regular for each look.

P.S - I currently use serialize but i want to make the files readable as readability is quite hard with serialized arrays.

答:
However op needs to write array as it is on file I have landed this page to find out a solution where I can write a array to file and than can easily read later using php again.

I have found solution my self by using json_encode so anyone else is looking for the same here is the code:

```<code>file_put_contents('array.tmp', json_encode($array));
</code>```

than read

```<code>$array = file_get_contents('array.tmp');
$array = json_decode($array,true);
</code>```

Title: Print array to a file

Body:
However op needs to write array as it is on file I have landed this page to find out a solution where I can write a array to file and than can easily read later using php again.

I have found solution my self by using json_encode so anyone else is looking for the same here is the code:

file_put_contents('array.tmp', json_encode($array));

than read

$array = file_get_contents('array.tmp');
$array = json_decode($array,true);


问:
Get value from an input
How i get the value Flu with input name gejala_id0 in django from my input like this :

```<code><form method="POST" action="/diagnosis/response/" enctype="multipart/form-data" class="AVAST_PAM_nonloginform">
    <input type="hidden" name="csrfmiddlewaretoken" value="B09UeUu83ADaQQkFe2GpIV5TyO5ruEZNA1zwJJ7zgMxCRR7I0Ing4Y7wQRR22NQj">
            <ul id="id_gejala_id0">
                <li>
                    <label for="id_gejala_id0_0">
                        <input type="checkbox" name="gejala_id0" value="Flu" id="id_gejala_id0_0">
                        Flu
                    </label>
                </li>
            </ul>
</code>```

答:
Try this:</p>

```<code>request.POST.getlist('gejala_id0')
</code>```

Title: Get value from an input

Body:
How i get the value Flu with input name gejala_id0 in django from my input like this :

<form method="POST" action="/diagnosis/response/" enctype="multipart/form-data" class="AVAST_PAM_nonloginform">
    <input type="hidden" name="csrfmiddlewaretoken" value="B09UeUu83ADaQQkFe2GpIV5TyO5ruEZNA1zwJJ7zgMxCRR7I0Ing4Y7wQRR22NQj">

                        <input type="checkbox" name="gejala_id0" value="Flu" id="id_gejala_id0_0">
                        Flu

Body:
Try this:

request.POST.getlist('gejala_id0')


问:
Error creating a record XrmServiceToolkit.Rest.Create
I am trying to create an annotation using js: XrmServiceToolkit.Rest.Create.

I get a systax error all the time but I cannot find the problem...

here is my code

```<code>var id = parent.Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');
        var nam = parent.Xrm.Page.data.entity.getEntityName();

        var entity = {};

        entity.subject = "title";
        entity.notetext = "description";
        entity.objectid = {
            id: id,
            logicalname: nam
        };

        XrmServiceToolkit.Rest.Create(
        entity,
        "annotation",
        function (result) {
            alert("OK");
        },
        function (error) {
            //Xrm.Utility.alertDialog(error.message, null);
            alert("KO: " + error.message);
        },
        false
        );
</code>```

I get a "Syntax error"
anyone knows where is the problem??

thanks a lot

答:
why don't you use Webapi, if you are on crm 2016 or higer version better go with Webapi.
Below is code snippet for webapi which creates noted.

```<code>var entity = {};
entity.subject = "Test from webapi";
entity.notetext = "just add some text";

var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/annotations", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 204) {
            var uri = this.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            var newEntityId = matches[1];
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send(JSON.stringify(entity));
</code>```

And now with XrmserviceToolkit

```<code>var entity = {};
entity.Subject = "Test from webapi 1234";
entity.NoteText = "just add some text 1234";

XrmServiceToolkit.Rest.Create(entity, "AnnotationSet", function(result) {
    var newEntityId = result.AnnotationId;
}, function(error) {
    Xrm.Utility.alertDialog(error.message);
}, false);
</code>```

Also what is the issue with your code?
If you look my code above for XrmserviceToolkit, You need to give Entity name as AnnotationSet. Also you do not need Id because CRM will create Id once a record is created.

Body:
I am trying to create an annotation using js: XrmServiceToolkit.Rest.Create.

I get a systax error all the time but I cannot find the problem...

here is my code

var id = parent.Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');
        var nam = parent.Xrm.Page.data.entity.getEntityName();

        var entity = {};

        entity.subject = "title";
        entity.notetext = "description";
        entity.objectid = {
            id: id,
            logicalname: nam
        };

        XrmServiceToolkit.Rest.Create(
        entity,
        "annotation",
        function (result) {
            alert("OK");
        },
        function (error) {
            //Xrm.Utility.alertDialog(error.message, null);
            alert("KO: " + error.message);
        },
        false
        );

I get a "Syntax error"
anyone knows where is the problem??

thanks a lot

Body:
why don't you use Webapi, if you are on crm 2016 or higer version better go with Webapi.
Below is code snippet for webapi which creates noted.

var entity = {};
entity.subject = "Test from webapi";
entity.notetext = "just add some text";

var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/annotations", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 204) {
            var uri = this.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            var newEntityId = matches[1];
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send(JSON.stringify(entity));

And now with XrmserviceToolkit

var entity = {};
entity.Subject = "Test from webapi 1234";
entity.NoteText = "just add some text 1234";

XrmServiceToolkit.Rest.Create(entity, "AnnotationSet", function(result) {
    var newEntityId = result.AnnotationId;
}, function(error) {
    Xrm.Utility.alertDialog(error.message);
}, false);

Also what is the issue with your code?
If you look my code above for XrmserviceToolkit, You need to give Entity name as AnnotationSet. Also you do not need Id because CRM will create Id once a record is created.


问:
Creating 2 numbers from a one #C
I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.

```<code>int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;

        while (checkCount > 0)
        {
            if (checkCount % 2 == 0)
                count2++;
            else
                countRest++;
            checkCount /= 10;
        }

        int[] a = new int[count2];
        int[] b = new int[countRest];

        int k2 = 0, kRest = 0;

        for (int j = 0; j < a.Length + b.Length; j++)
        {
            if (num1 % 2 == 0)
            {
                a[k2] = num1 % 10;
                k2++;
            }
            else
            {
                b[kRest] = num1 % 10;
                kRest++;
            }
            num1 /= 10;
        }
</code>```

I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?

Example:
If I have this number - 12345 so
var = 24, other var = 135

If you have another solution without arrays I think it will be better.
Thank you.

答:
Why not just:

```<code>    int decimalMaskA = 1;
    int decimalMaskB = 1;
    while (checkCount > 0)
    {
        if (checkCount % 2 == 0)
        {
            count2 = count2 + (checkCount % 10)*decimalMaskA;
            decimalMaskA *= 10;
        }
        else
        {
            countRest = countRest + (checkCount % 10)*decimalMaskB;
            decimalMaskB *= 10;
        }
        checkCount /= 10;
    }
</code>```

count2 and countRest will contain those numbers (135 and 24) instead of counts.

Title: Creating 2 numbers from a one #C

Body:
I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.

int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;

        while (checkCount > 0)
        {
            if (checkCount % 2 == 0)
                count2++;
            else
                countRest++;
            checkCount /= 10;
        }

        int[] a = new int[count2];
        int[] b = new int[countRest];

        int k2 = 0, kRest = 0;

        for (int j = 0; j < a.Length + b.Length; j++)
        {
            if (num1 % 2 == 0)
            {
                a[k2] = num1 % 10;
                k2++;
            }
            else
            {
                b[kRest] = num1 % 10;
                kRest++;
            }
            num1 /= 10;
        }

I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?

Example:
If I have this number - 12345 so
var = 24, other var = 135

If you have another solution without arrays I think it will be better.
Thank you.

Body:
Why not just:

    int decimalMaskA = 1;
    int decimalMaskB = 1;
    while (checkCount > 0)
    {
        if (checkCount % 2 == 0)
        {
            count2 = count2 + (checkCount % 10)*decimalMaskA;
            decimalMaskA *= 10;
        }
        else
        {
            countRest = countRest + (checkCount % 10)*decimalMaskB;
            decimalMaskB *= 10;
        }
        checkCount /= 10;
    }

count2 and countRest will contain those numbers (135 and 24) instead of counts.


问:
Rvest getting an specific text from html_node

I want to extract only "Beech Valley Solutions - "

When I run

```<code>html_nodes('li') %>%
  html_nodes(".flexbox.empLoc") %>%
  html_text()
</code>```

All the information comes out. "Beech Valley Solutions - Atlanta, GA Today 24hr"

答:
There is one more way of doing scraping using rvest.
Instead of passing css selector item in html_nodes(), you can pass xpath within html_nodes().Just an example below -

```<code>page %>% html_nodes(xpath = "//*[@id='series-matches']/div[20]/div[3]/div[1]/a[1]/span")
</code>```

Reference:
https://blog.rstudio.com/2014/11/24/rvest-easy-web-scraping-with-r/

x path is easier to fetch -

Right click the section for which you want to fetch xpath.

Select inspect code from the drop down.                                         3. html page will appear to the right side, from which click the right click and press Copy option.

Drop will appear from which select "Copy xpath".

Ctrl V (Paste) the xpath within html_nodes(xpath = "xpath here").        I hope this will help you.

Body:
I want to extract only "Beech Valley Solutions - "

When I run

html_nodes('li') %>%
  html_nodes(".flexbox.empLoc") %>%
  html_text()

All the information comes out. "Beech Valley Solutions - Atlanta, GA Today 24hr"

Body:
There is one more way of doing scraping using rvest.
Instead of passing css selector item in html_nodes(), you can pass xpath within html_nodes().Just an example below -

page %>% html_nodes(xpath = "//*[@id='series-matches']/div[20]/div[3]/div[1]/a[1]/span")

Reference:
https://blog.rstudio.com/2014/11/24/rvest-easy-web-scraping-with-r/

x path is easier to fetch -

Right click the section for which you want to fetch xpath.

Select inspect code from the drop down.                                         3. html page will appear to the right side, from which click the right click and press Copy option.

Drop will appear from which select "Copy xpath".

Ctrl V (Paste) the xpath within html_nodes(xpath = "xpath here").        I hope this will help you.


问:
How to install python dependency inside zalenium containers?
I am using docker-compose file to set up the zalenium environment. Due to an unusual file uploading behavior, I wanted to use robotjs.

Application Behaviour: when click on the navigation button, the file uploading window opening automatically.

It is impossible to use SendKeys here because of that window pop up. I tried with action class. But it didn't work as expected. I can solve this by using robotjs library.

It is impossible to execute(robotjs actions) without python 2.7 dependency inside zalenium containers.

Is there any way to install it?

答: The Zalenium and docker-selenium images are based on Ubuntu 16. You could just extend the one you need and install Python there. Check first because probably it is already installed.</p>


问:
Import Error :cannot import name get_model
```<code>File "C:\Python27\Lib\site-packages\file_picker\forms.py,line 5 in <module>
from django.db.models import Q,get_model
ImportError:cannot import name get_model
</code>```

I am using  django 1.9.7 and file_picker 0.2.2 I don't seem to have any solution  to this problem

答:
Try this,

```<code>from django.apps import apps

model_obj = get_model('app_name', 'model_name')
</code>```

Where "app_name" is your app name and "model_name" is your model name.

Body:
File "C:\Python27\Lib\site-packages\file_picker\forms.py,line 5 in <module>
from django.db.models import Q,get_model
ImportError:cannot import name get_model

I am using  django 1.9.7 and file_picker 0.2.2 I don't seem to have any solution  to this problem

Body:
Try this,

from django.apps import apps

model_obj = get_model('app_name', 'model_name')

Where "app_name" is your app name and "model_name" is your model name.


问:
Oracle Error ORA-29273: HTTP request failed ORA-29259: end-of-input reached When Calling UTL_HTTP.request
I am trying to call a web service using the Oracle UTL_HTTP.request API. The call requires a proxy & wallet/certificate. I believe I have cleared up the certificate issues, since I no longer get a ORA-29024: Certificate validation failure error. Now I am getting ORA-29259: end-of-input reached error. I am using DBMS version 12.1.0.2.0, and should be using TLS 1.2 (not sure how to verify this).

The following call works perfectly & returns a JSON payload:

```<code>SELECT utl_http.request (
  'http://jsonplaceholder.typicode.com/todos/1',
  'proxy.myurl.com')
FROM dual;
</code>```

Response:

```<code>{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
</code>```

The following call throws the ORA-29259 error:

```<code>SELECT utl_http.request (
  'https://service.baseurl.com/ping',
  'proxy.myurl.com',
  'file:/my/wallet/location',
  'mypassword'
 )
FROM DUAL;
</code>```

Runtime exception stack:

```<code>ORA-29273: HTTP request failed
ORA-29259: end-of-input reached
ORA-06512: at "SYS.UTL_HTTP", line 1491
ORA-06512: at line 1
</code>```

I have also tried calling UTL_HTTP.begin_request using an anonymous PL/SQL block, but get essentially the same ORA-29259 error as above.

```<code>DECLARE
  l_http_request utl_http.req;
  l_http_response utl_http.resp;
  l_text VARCHAR2(32767);
BEGIN
  utl_http.set_proxy('proxy.myurl.com');
  utl_http.set_wallet('file:/my/wallet/location'
                      ,'mypassword');
  l_http_request := utl_http.begin_request('https://service.baseurl.com/ping'
                                           ,'POST', 'HTTP/1.1');
  l_http_response := utl_http.get_response(l_http_request);
  BEGIN
    LOOP
      utl_http.read_text(l_http_response, l_text, 32766);
      dbms_output.put_line(l_text);
    END LOOP;
  EXCEPTION WHEN utl_http.end_of_body THEN
    utl_http.end_response(l_http_response);
  END;
END;

ORA-29273: HTTP request failed
ORA-29259: end-of-input reached
ORA-06512: at "SYS.UTL_HTTP", line 1258
ORA-06512: at line 10
</code>```

Any ideas on what could be causing this error?

答:
I think your problem would be the missing cipher suits in 12.1c.
You have to apply a on your database, security patch 24666032 and the minimum DBBP should be 12.1.0.2.160719 (23054246).

After that, the database should add support for cipher.

You can view this information on MOS:UTL_HTTP access to secured website fails with ORA-29259 in 12c database (Doc ID 2402276.1)

Regards

Body:
I am trying to call a web service using the Oracle UTL_HTTP.request API. The call requires a proxy & wallet/certificate. I believe I have cleared up the certificate issues, since I no longer get a ORA-29024: Certificate validation failure error. Now I am getting ORA-29259: end-of-input reached error. I am using DBMS version 12.1.0.2.0, and should be using TLS 1.2 (not sure how to verify this).

The following call works perfectly & returns a JSON payload:

SELECT utl_http.request (
  'http://jsonplaceholder.typicode.com/todos/1',
  'proxy.myurl.com')
FROM dual;

Response:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

The following call throws the ORA-29259 error:

SELECT utl_http.request (
  'https://service.baseurl.com/ping',
  'proxy.myurl.com',
  'file:/my/wallet/location',
  'mypassword'
 )
FROM DUAL;

Runtime exception stack:

ORA-29273: HTTP request failed
ORA-29259: end-of-input reached
ORA-06512: at "SYS.UTL_HTTP", line 1491
ORA-06512: at line 1

I have also tried calling UTL_HTTP.begin_request using an anonymous PL/SQL block, but get essentially the same ORA-29259 error as above.

DECLARE
  l_http_request utl_http.req;
  l_http_response utl_http.resp;
  l_text VARCHAR2(32767);
BEGIN
  utl_http.set_proxy('proxy.myurl.com');
  utl_http.set_wallet('file:/my/wallet/location'
                      ,'mypassword');
  l_http_request := utl_http.begin_request('https://service.baseurl.com/ping'
                                           ,'POST', 'HTTP/1.1');
  l_http_response := utl_http.get_response(l_http_request);
  BEGIN
    LOOP
      utl_http.read_text(l_http_response, l_text, 32766);
      dbms_output.put_line(l_text);
    END LOOP;
  EXCEPTION WHEN utl_http.end_of_body THEN
    utl_http.end_response(l_http_response);
  END;
END;

ORA-29273: HTTP request failed
ORA-29259: end-of-input reached
ORA-06512: at "SYS.UTL_HTTP", line 1258
ORA-06512: at line 10

Any ideas on what could be causing this error?


问:
How to get a specific field of the data to use it in a request?
I am building an app with Polymer and Go at the moment and i just went into this problem.

I have my data stored in a MongoDB, and I am using JWT for the authentication.
The data I will use here is User { email, ...} and the invitation {sender , receiver, event, message , ...}

The problem is : i made a new functionality and I need for my HTTP Request to put the user's Email as an argument but i get the error Can't get 'Email' of Undefined from the google console.

to do so i have 2 polymer components
1 - a component to get the "Invitation" (message, sender, event)
2 - a component that uses the (1) and is just a repeater to show all the invitations a user receives.

I tried to make use another component to get the current user's Email and it didn't work as well, same problem the this.me.Email doesnt work (see in the code below)

(1) the ['collab-service'].me(this.token) returns into the property 'me' the user's data so i have access to me.Email (what i need here)

```<code> static get properties() {
            return {
                invitation: {
                    type: Object,
                    notify: true,
                },
                /**
                 * Current user
                 * @public
                 * @type {Object}
                 **/
                me: {
                    type: Object,
                    notify: true,
                    reflectToAttribute: true,
                },
            };
        }

        /**
         * @inheritdoc
         **/
        connectedCallback() {
            super.connectedCallback();
            this.token = localStorage.getItem('token');

            this.$['collab-service'].me(this.token).then(
                (request) => {
                    this.me = request.response;
                },
                (error) => {
                    console.error('Error.');
                    console.error(error);
                }
            );
</code>```

(2) GetInvitation(User's email) returns all the invitations received by the User

```<code>
<div class="container">
                <template is="dom-repeat" items="{{invitation}}" as="item">
                    <MyComponent1 pub="{{item}}"></MyComponent1>
                </template>
            </div>

{......}
 static get is() {
            return 'myFile2';
        }

        static get properties() {
            return{
            };
        }
        connectedCallback() {
            super.connectedCallback();
            this.$['invitations-service'].getInvitations(this.me.Email).then(
                (request) => {
                    this.invitation = request.response;
                },
                (error) => {
                    console.error('Error.');
                    console.error(error);
                }
            );
        }
</code>```

So what i need is to make this.me.Email work so that i can see every invitation.
I put the an element {{me.Email}} into the HTML code to see if i had something in the "me" property and 'me.Email' exists. It returns the current user's email. It just doesnt work in the method getInvitation and i don't know why.

Thank you for the help !

EDIT :I changed to code, added a  to load the invitations and it has access to the this.me.Email attribute...
It fixes the problem for now but it's really not elegant.
I think it is due to the loading of the me property, i use it when it's not loaded already, so when the page is loaded i have access to the me attributes but not as i load it.

答:
Why do you have reflectToAttribute on the me property? reflectToAttribute just for the DOM so you can add attributes to the element, like hidden or name="MyElement", often used to style the element.

```<code>hidden: {
  type: Boolean,
  value: true,
  reflectToAttribute: true
},
name: {
  type: String,
  value: 'MyElement',
  reflectToAttribute: true
},
</code>```

In the DOM, the element above would look something like <my-element hidden name="MyElement">.

notify: true is used to send variable updates from a child element to a parent element.

```<code><parent-element>
  <child-element child-data={{parentVariable}}></child-element>
</parent-element>
</code>```

Placing the property withing curly brackets {{}} tells parent-element that updated data can come from the child-element.

```<code>static get is() {
            return 'parent-element';
        }

        static get properties() {
            return{
               parentVariable: Object
            };
        }
</code>```

Parent element isn't sending in anything to its child in this example.

```<code>static get is() {
            return 'child-element';
        }

        static get properties() {
            return{
              childData: {
                type: Object,
                notify: true
              }
            };
        }

        ready() {
          super.ready();

          this.set('childData', {'test': 'hello world'});
        }
</code>```

Because child-element has notify: true on childData, setting that property will now update parentVariable in parent-element to the same value.

If you want anything to update in DOM or in your properties, you need to use this.set('myVariable', aValue) and not this.myVariable = aValue.

It seems like you're wanting asynchronous data in connectedCallback, but you can't be sure that it's loaded. Sure, it's loaded afterwards when you try to see if the property is there. It seems like you figured that out by the look of your edited update, but you should probably set up a two-way binding of properties, instead of querySelect elements and then place an observer to see when the element has updated.

If I continue the example above:

```<code>static get is() {
            return 'parentElement';
        }

        static get properties() {
            return{
               parentVariable: {
                 type: Object,
                 observer: 'testObserver'
            };
        }

        testObserver(newChildData) {
          console.log(newChildData); // {'test': 'hello world'}

          // do other stuff, like getInvitations(newChildData.test)
        }
</code>```

Body:
I am building an app with Polymer and Go at the moment and i just went into this problem.

I have my data stored in a MongoDB, and I am using JWT for the authentication.
The data I will use here is User { email, ...} and the invitation {sender , receiver, event, message , ...}

The problem is : i made a new functionality and I need for my HTTP Request to put the user's Email as an argument but i get the error Can't get 'Email' of Undefined from the google console.

to do so i have 2 polymer components
1 - a component to get the "Invitation" (message, sender, event)
2 - a component that uses the (1) and is just a repeater to show all the invitations a user receives.

I tried to make use another component to get the current user's Email and it didn't work as well, same problem the this.me.Email doesnt work (see in the code below)

(1) the ['collab-service'].me(this.token) returns into the property 'me' the user's data so i have access to me.Email (what i need here)

 static get properties() {
            return {
                invitation: {
                    type: Object,
                    notify: true,
                },
                /**
                 * Current user
                 * @public
                 * @type {Object}
                 **/
                me: {
                    type: Object,
                    notify: true,
                    reflectToAttribute: true,
                },
            };
        }

        /**
         * @inheritdoc
         **/
        connectedCallback() {
            super.connectedCallback();
            this.token = localStorage.getItem('token');

            this.$['collab-service'].me(this.token).then(
                (request) => {
                    this.me = request.response;
                },
                (error) => {
                    console.error('Error.');
                    console.error(error);
                }
            );

(2) GetInvitation(User's email) returns all the invitations received by the User

                <template is="dom-repeat" items="{{invitation}}" as="item">
                    <MyComponent1 pub="{{item}}"></MyComponent1>
                </template>

{......}
 static get is() {
            return 'myFile2';
        }

        static get properties() {
            return{
            };
        }
        connectedCallback() {
            super.connectedCallback();
            this.$['invitations-service'].getInvitations(this.me.Email).then(
                (request) => {
                    this.invitation = request.response;
                },
                (error) => {
                    console.error('Error.');
                    console.error(error);
                }
            );
        }

So what i need is to make this.me.Email work so that i can see every invitation.
I put the an element {{me.Email}} into the HTML code to see if i had something in the "me" property and 'me.Email' exists. It returns the current user's email. It just doesnt work in the method getInvitation and i don't know why.

Thank you for the help !

EDIT :I changed to code, added a  to load the invitations and it has access to the this.me.Email attribute...
It fixes the problem for now but it's really not elegant.
I think it is due to the loading of the me property, i use it when it's not loaded already, so when the page is loaded i have access to the me attributes but not as i load it.

Body:
Why do you have reflectToAttribute on the me property? reflectToAttribute just for the DOM so you can add attributes to the element, like hidden or name="MyElement", often used to style the element.

hidden: {
  type: Boolean,
  value: true,
  reflectToAttribute: true
},
name: {
  type: String,
  value: 'MyElement',
  reflectToAttribute: true
},

In the DOM, the element above would look something like <my-element hidden name="MyElement">.

notify: true is used to send variable updates from a child element to a parent element.

<parent-element>
  <child-element child-data={{parentVariable}}></child-element>
</parent-element>

Placing the property withing curly brackets {{}} tells parent-element that updated data can come from the child-element.

static get is() {
            return 'parent-element';
        }

        static get properties() {
            return{
               parentVariable: Object
            };
        }

Parent element isn't sending in anything to its child in this example.

static get is() {
            return 'child-element';
        }

        static get properties() {
            return{
              childData: {
                type: Object,
                notify: true
              }
            };
        }

        ready() {
          super.ready();

          this.set('childData', {'test': 'hello world'});
        }

Because child-element has notify: true on childData, setting that property will now update parentVariable in parent-element to the same value.

If you want anything to update in DOM or in your properties, you need to use this.set('myVariable', aValue) and not this.myVariable = aValue.

It seems like you're wanting asynchronous data in connectedCallback, but you can't be sure that it's loaded. Sure, it's loaded afterwards when you try to see if the property is there. It seems like you figured that out by the look of your edited update, but you should probably set up a two-way binding of properties, instead of querySelect elements and then place an observer to see when the element has updated.

If I continue the example above:

static get is() {
            return 'parentElement';
        }

        static get properties() {
            return{
               parentVariable: {
                 type: Object,
                 observer: 'testObserver'
            };
        }

        testObserver(newChildData) {
          console.log(newChildData); // {'test': 'hello world'}

          // do other stuff, like getInvitations(newChildData.test)
        }


问:
maven gmavenplus-plugin problems with groovy syntax
I am trying to customize maven build process using gmavenplus-plugin.
To be precise, I have a workig script in gmaven-plugin and I am trying to re-implement it in gmavenplus-plugin(which is advertised as a rewrite of GMaven)

My running gmaven code

```<code><plugin>
    <groupId>org.codehaus.gmaven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <version>1.5</version>
    <executions>
        <execution>
            <phase>initialize</phase>
            <goals>
                <goal>execute</goal>
            </goals>
            <configuration>
                <source>
                    println(project.version)
                    println([1, 2, 3])
                </source>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

My attempt to re-write it in gmavenplus:

```<code><plugin>
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.7.0</version>
    <executions>
        <execution>
            <phase>initialize</phase>
            <goals>
                <goal>execute</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <scripts>
            println(project.version)
            println([1, 2, 3])
        </scripts>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.1</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</plugin>
</code>```

Which fails with

```<code>[ERROR] Script1.groovy: 2: unexpected token: 1 @ line 2, column 34.
[ERROR] println([1
[ERROR] ^
[ERROR]
[ERROR] 1 error
</code>```

Any groovy syntax I try to use fails.

Update
CDATA does not help.

```<code><scripts>
<![CDATA[
println(project.version)
println([1, 2, 3])
]]>
</code>```

答:
according to examples https://github.com/groovy/GMavenPlus/wiki/Examples

there should be
        </scripts>
      </configuration>
      <dependencies>
        <dependency>
          <groupId>org.codehaus.groovy</groupId>
          <artifactId>groovy-all</artifactId>
          <version>2.5.7</version>
          <type>pom</type>
          <scope>runtime</scope>
        </dependency>
      </dependencies>
    </plugin>
  </plugins>
  </build>
</project>
```

Body:
I am trying to customize maven build process using gmavenplus-plugin.
To be precise, I have a workig script in gmaven-plugin and I am trying to re-implement it in gmavenplus-plugin(which is advertised as a rewrite of GMaven)

My running gmaven code

<plugin>
    <groupId>org.codehaus.gmaven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <version>1.5</version>
    <executions>
        <execution>
            <phase>initialize</phase>
            <goals>
                <goal>execute</goal>
            </goals>
            <configuration>
                <source>
                    println(project.version)
                    println([1, 2, 3])
                </source>
            </configuration>
        </execution>
    </executions>
</plugin>

My attempt to re-write it in gmavenplus:

<plugin>
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.7.0</version>
    <executions>
        <execution>
            <phase>initialize</phase>
            <goals>
                <goal>execute</goal>
            </goals>
        </execution>
    </executions>
    <configuration>

    </configuration>
    <dependencies>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.1</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</plugin>

Which fails with

[ERROR] Script1.groovy: 2: unexpected token: 1 @ line 2, column 34.
[ERROR] println([1
[ERROR] ^
[ERROR]
[ERROR] 1 error

Any groovy syntax I try to use fails.

Update
CDATA does not help.

Body:
according to examples https://github.com/groovy/GMavenPlus/wiki/Examples

there should be <script> inside <scripts>:

use mvn gplus:execute with the following example pom.xml

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>test-gmavenplus</groupId>
    <artifactId>test-gmavenplus</artifactId>
    <packaging>pom</packaging>
    <version>1.1.0-SNAPSHOT</version>
    <name>test gmavenplus</name>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.gmavenplus</groupId>
        <artifactId>gmavenplus-plugin</artifactId>
        <version>1.7.0</version>
        <executions>
          <execution>
            <goals>
              <goal>execute</goal>
            </goals>
          </execution>
        </executions>
      <configuration>
        <scripts>
          <script><![CDATA[
            println "hello `${project.name}`"
          ]]></script>
        </scripts>
      </configuration>
      <dependencies>
        <dependency>
          <groupId>org.codehaus.groovy</groupId>
          <artifactId>groovy-all</artifactId>
          <version>2.5.7</version>
          <type>pom</type>
          <scope>runtime</scope>
        </dependency>
      </dependencies>
    </plugin>
  </plugins>
  </build>
</project>


问:
How to import excel file from angular to asp.core, than read data and push it in List
I have found package like NPOI, but i dont know how to stream file, or how to convert it to bit before sending to asp.core. Curently i am using Angular 6</p>

答:
html: (Angular ->primeNg)

Ts:

```<code>onFileUpload(event) {
const file = event.files[0];
this.progressBar = true;
const formData: FormData = new FormData();
formData.append('file', file, file.name);
this.Service.importexcel(formData).subscribe(x => console.log(x));
</code>```

}

asp api core controler: You can separete it in arhitecture after with await... And than send it to SQL from ienumerable after checking regex.

```<code>    [HttpPost("import", Name = "ImportExcel")]
    public async Task<IActionResult> ImportExcel([FromForm]IFormFile file)
    {
        string folderName = "Upload";
        string newPath = Path.Combine(Guid.NewGuid().ToString() +'_'+ folderName);

        if (!Directory.Exists(newPath))
        {
            Directory.CreateDirectory(newPath);
        }
            string sFileExtension = Path.GetExtension(file.FileName).ToLower();
            ISheet sheet;
            string fullPath = Path.Combine(newPath, file.FileName);
            var list = new List<ShipmentImportExcel>();

        using (var stream = new FileStream(fullPath, FileMode.Create))
        {
            file.CopyTo(stream);
            stream.Position = 0;
            if (sFileExtension == ".xls")
            {
                HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
                sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
            }
            else
            {
                XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
                sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
            }
            IRow headerRow = sheet.GetRow(0); //Get Header Row
            int cellCount = headerRow.LastCellNum;

            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
            {
                var obj = new ExcelObject..();
                IRow row = sheet.GetRow(i);

                obj.property1 = row.GetCell(0).ToString();
                obj.property2 = row.GetCell(1).ToString();

                list.Add(obj);
            }
        }
        return Ok(list);

    }
</code>```

Body:
html: (Angular ->primeNg)

Ts:

onFileUpload(event) {
const file = event.files[0];
this.progressBar = true;
const formData: FormData = new FormData();
formData.append('file', file, file.name);
this.Service.importexcel(formData).subscribe(x => console.log(x));

}

asp api core controler: You can separete it in arhitecture after with await... And than send it to SQL from ienumerable after checking regex.

    [HttpPost("import", Name = "ImportExcel")]
    public async Task<IActionResult> ImportExcel([FromForm]IFormFile file)
    {
        string folderName = "Upload";
        string newPath = Path.Combine(Guid.NewGuid().ToString() +'_'+ folderName);

        if (!Directory.Exists(newPath))
        {
            Directory.CreateDirectory(newPath);
        }
            string sFileExtension = Path.GetExtension(file.FileName).ToLower();
            ISheet sheet;
            string fullPath = Path.Combine(newPath, file.FileName);
            var list = new List<ShipmentImportExcel>();

        using (var stream = new FileStream(fullPath, FileMode.Create))
        {
            file.CopyTo(stream);
            stream.Position = 0;
            if (sFileExtension == ".xls")
            {
                HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
                sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
            }
            else
            {
                XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
                sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
            }
            IRow headerRow = sheet.GetRow(0); //Get Header Row
            int cellCount = headerRow.LastCellNum;

            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
            {
                var obj = new ExcelObject..();
                IRow row = sheet.GetRow(i);

                obj.property1 = row.GetCell(0).ToString();
                obj.property2 = row.GetCell(1).ToString();

                list.Add(obj);
            }
        }
        return Ok(list);

    }


问:
Image animating sequence
i am new to this platform... I am having 3 png images and i want those images to run in a loop how can i do that...I need know creation of both xml and the java activity codezzz too...plz help on that</p>

答: Probably use an imageswitcher. As far as code examples go, you can pretty much Google that. Here's the doc on imageswitcher.</p>

Title: Image animating sequence


问:
I got a token from AAD using Msal, but can't get the user profile using the token acquired. How to validate the token simply on Node backend?
I used the following configuration for requesting the token from AAD.

The app.module.ts file:

```<code>MsalModule.forRoot({
            clientID: 'CLIENT_ID',
            authority: "https://login.microsoftonline.com/TENANT_ID",
            validateAuthority: true,
            cacheLocation: 'sessionStorage',
            postLogoutRedirectUri: 'http://localhost:4200/authorize/signin',
            navigateToLoginRequestUrl: true,
            popUp: true,
            consentScopes: ['user.read', 'https://graph.microsoft.com']
        }
</code>```

It returns the msal.idtoken, accesstoken, and some more msal key value pairs.
Now following code is used to get the profile of the user by pasting the acquired MSAL_IDTOKEN.

```<code>const request = require('request');
const tok = 'MSAL_IDTOKEN HERE';
request.get({ url: "https://graph.microsoft.com/v1.0/me", headers: { "Authorization": "Bearer " + tok, "Content-type": "application/json" } }, function (err, response, body) {

    if (err) {
        console.log('err', err);
    }
    else
        console.log(response.body);
})
</code>```

Now after running the app on Node, it used to return the profile of the user, as found after decoding the token, but now it does not.

答:
It seems that your are trying to read user profile from your access token.

To do that you need to assign profile dedicated permission on azure portal.

See the screen shot below:

Note:  After assigning permission you can check your token on https://jwt.io/ whether it contains required permission.

Token Claim:

Read User data:

Code Snippet:

Token Class:

 public class AccessTokenClass
        {
            public string token_type { get; set; }
            public string expires_in { get; set; }
            public string resource { get; set; }
            public string scope { get; set; }
            public string access_token { get; set; }
            public string refresh_token { get; set; }

        }
```

<p><strong>Token Method:</strong></p>

<pre class="lang-cs prettyprint-override"><code>private async Task<string> GetTokenByROPCFormat()
        {

            string tokenUrl = $"https://login.microsoftonline.com/YourTenantIdOrName/oauth2/token";

            var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

            tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                ["grant_type"] = "password",
                ["client_id"] = "b603c7be-a866--e6921e61f925",
                ["client_secret"] = "Vxf1SluKbgu4PF0Nf3wE5oG",
                ["resource"] = "https://graph.microsoft.com",
                ["username"] = "kironmemb@MyTenant.onmicrosoft.com",
                ["password"] = "@Mypassword"

            });

            dynamic json;
            dynamic results;
            HttpClient client = new HttpClient();

            var tokenResponse = await client.SendAsync(tokenRequest);

            json = await tokenResponse.Content.ReadAsStringAsync();
            results = JsonConvert.DeserializeObject<AccessTokenClass>(json);
            Console.WriteLine("Your Refresh Token=>{0}", results.refresh_token);

            //  New Block For Accessing Data from API
            HttpClient newClient = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);
            HttpResponseMessage response = await newClient.SendAsync(request);

            string output = await response.Content.ReadAsStringAsync();
            return output;

        }
</code>```

Body:
I used the following configuration for requesting the token from AAD.

The app.module.ts file:

MsalModule.forRoot({
            clientID: 'CLIENT_ID',
            authority: "https://login.microsoftonline.com/TENANT_ID",
            validateAuthority: true,
            cacheLocation: 'sessionStorage',
            postLogoutRedirectUri: 'http://localhost:4200/authorize/signin',
            navigateToLoginRequestUrl: true,
            popUp: true,
            consentScopes: ['user.read', 'https://graph.microsoft.com']
        }

It returns the msal.idtoken, accesstoken, and some more msal key value pairs.
Now following code is used to get the profile of the user by pasting the acquired MSAL_IDTOKEN.

const request = require('request');
const tok = 'MSAL_IDTOKEN HERE';
request.get({ url: "https://graph.microsoft.com/v1.0/me", headers: { "Authorization": "Bearer " + tok, "Content-type": "application/json" } }, function (err, response, body) {

    if (err) {
        console.log('err', err);
    }
    else
        console.log(response.body);
})

Now after running the app on Node, it used to return the profile of the user, as found after decoding the token, but now it does not.

Body:
It seems that your are trying to read user profile from your access token.

To do that you need to assign profile dedicated permission on azure portal.

See the screen shot below:

Note:  After assigning permission you can check your token on https://jwt.io/ whether it contains required permission.

Token Claim:

Read User data:

Code Snippet:

Token Class:

 public class AccessTokenClass
        {
            public string token_type { get; set; }
            public string expires_in { get; set; }
            public string resource { get; set; }
            public string scope { get; set; }
            public string access_token { get; set; }
            public string refresh_token { get; set; }

        }

Token Method:

private async Task<string> GetTokenByROPCFormat()
        {

            string tokenUrl = $"https://login.microsoftonline.com/YourTenantIdOrName/oauth2/token";

            var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

            tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                ["grant_type"] = "password",
                ["client_id"] = "b603c7be-a866--e6921e61f925",
                ["client_secret"] = "Vxf1SluKbgu4PF0Nf3wE5oG",
                ["resource"] = "https://graph.microsoft.com",
                ["username"] = "kironmemb@MyTenant.onmicrosoft.com",
                ["password"] = "@Mypassword"

            });

            dynamic json;
            dynamic results;
            HttpClient client = new HttpClient();

            var tokenResponse = await client.SendAsync(tokenRequest);

            json = await tokenResponse.Content.ReadAsStringAsync();
            results = JsonConvert.DeserializeObject<AccessTokenClass>(json);
            Console.WriteLine("Your Refresh Token=>{0}", results.refresh_token);

            //  New Block For Accessing Data from API
            HttpClient newClient = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);
            HttpResponseMessage response = await newClient.SendAsync(request);

            string output = await response.Content.ReadAsStringAsync();
            return output;

        }