问:
Excel VBA: Save workbook as Word document
I would like to save my workbook (all sheets) as one Word document.
One sheets it's one page in document.

I find only code for save activeSheet.

```<code>Sub ExcelToWord()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim objWd As Object
Set objWd = CreateObject("word.application")
objWd.Visible = True
Dim objDoc As Object
Set objDoc = objWd.Documents.Add
objDoc.PageSetup.Orientation = 1 '  portrait = 0
Application.ScreenUpdating = False
ws.UsedRange.Copy
objDoc.Content.Paste
Application.CutCopyMode = False
Application.DisplayAlerts = False
objDoc.SaveAs (Application.ThisWorkbook.Path & "\dokument.docx")
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
</code>```

Thanks for your reply.

答:
A couple quick things will get you to a solution.

The first is to loop through the worksheets in your workbook, like this:

```<code>Dim ws As Worksheet
For Each ws in ThisWorkbook.Sheets
    Debug.Print "The used range is " & ws.UsedRange.Address
Next ws
</code>```

The next part is to understand how adding content to a Word document is accomplished. The main concept involves where the insertion point for the document is located -- generally this is the current Selection.

When you cut and paste into a Word document, the content just pasted is still "selected". This means that any subsequent paste will effectively replace what you just inserted. So you have to move the selection point to the end of the document.

Putting it all together in an example program:

```<code>Option Explicit

Public Sub ExcelToWord()
    Dim wb As Workbook
    Set wb = ThisWorkbook

    '--- create the Word document
    Dim objWd As Word.Application
    Set objWd = CreateObject("word.application")
    objWd.Visible = True

    Dim objDoc As Word.Document
    Set objDoc = objWd.Documents.Add
    objDoc.PageSetup.Orientation = 1             '  portrait = 0

    Const wdPageBreak As Long = 7

    Dim ws As Worksheet
    For Each ws In wb.Sheets
        ws.UsedRange.Copy
        objWd.Selection.Paste
        '--- advance the selection point to the end of
        '    the document and insert a page break, then
        '    advance the insertion point past the break
        objDoc.Characters.Last.Select
        objWd.Selection.InsertBreak wdPageBreak
        objDoc.Characters.Last.Select
    Next ws
    'objDoc.SaveAs Application.ThisWorkbook.Path & ".\dokument.docx"
End Sub
</code>```

Body:
I would like to save my workbook (all sheets) as one Word document.
One sheets it's one page in document.

I find only code for save activeSheet.

Sub ExcelToWord()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim objWd As Object
Set objWd = CreateObject("word.application")
objWd.Visible = True
Dim objDoc As Object
Set objDoc = objWd.Documents.Add
objDoc.PageSetup.Orientation = 1 '  portrait = 0
Application.ScreenUpdating = False
ws.UsedRange.Copy
objDoc.Content.Paste
Application.CutCopyMode = False
Application.DisplayAlerts = False
objDoc.SaveAs (Application.ThisWorkbook.Path & "\dokument.docx")
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Thanks for your reply.

Body:
A couple quick things will get you to a solution.

The first is to loop through the worksheets in your workbook, like this:

Dim ws As Worksheet
For Each ws in ThisWorkbook.Sheets
    Debug.Print "The used range is " & ws.UsedRange.Address
Next ws

The next part is to understand how adding content to a Word document is accomplished. The main concept involves where the insertion point for the document is located -- generally this is the current Selection.

When you cut and paste into a Word document, the content just pasted is still "selected". This means that any subsequent paste will effectively replace what you just inserted. So you have to move the selection point to the end of the document.

Putting it all together in an example program:

Option Explicit

Public Sub ExcelToWord()
    Dim wb As Workbook
    Set wb = ThisWorkbook

    '--- create the Word document
    Dim objWd As Word.Application
    Set objWd = CreateObject("word.application")
    objWd.Visible = True

    Dim objDoc As Word.Document
    Set objDoc = objWd.Documents.Add
    objDoc.PageSetup.Orientation = 1             '  portrait = 0

    Const wdPageBreak As Long = 7

    Dim ws As Worksheet
    For Each ws In wb.Sheets
        ws.UsedRange.Copy
        objWd.Selection.Paste
        '--- advance the selection point to the end of
        '    the document and insert a page break, then
        '    advance the insertion point past the break
        objDoc.Characters.Last.Select
        objWd.Selection.InsertBreak wdPageBreak
        objDoc.Characters.Last.Select
    Next ws
    'objDoc.SaveAs Application.ThisWorkbook.Path & ".\dokument.docx"
End Sub


来源: stackexchange

问:
Find xpaths and extract text & status of checkbox/radio buttons in a loop
I have a page where I need to extract the text from an xpath and the status of the radio or checkbox that is associated with the text.
Each element is contained in a class called "c-form-group", so i have written a loop to iterate through to extract the "Text" the will be 4 elements found on the page. But it is failing on element 3 & 4, i must have something wrong with my xpath. I have yet to add in the check for the checkbox/radio button,

The first two elements are returning the values i require, then fails on element3.

Here are the 4 text elements i am trying to extract:

Plan B Warranty (Taxi) & Breakdown Recovery

Vehicle Asset Protection - Standard Cover

Negative Equity Cover

You confirm that you have received the VAP key facts leaflet?

Here is the code for the loop.

```<code>WebElement elem = driver.findElement(By.className("c-form-group"));
System.out.println("a");
List<WebElement> elementz =  elem.findElements(By.xpath("//label[contains(@class,'c-option')]"));

for(int i = 0 ; i< elementz.size() ; i++){
    System.out.println("Loop : " + i);
     String vapval1 = elementz.get(i).findElement(By.xpath("//label[@class='c-option c-option--right u-px u-py-sm u-clearfix ng-scope' and not(@class='ng-pristine ng-untouched ng-valid ng-valid-required') and not (@class='c-option__radio')]")).getText();
     System.out.println("0 = " + vapval1);
     String vapval2 = elementz.get(i).findElement(By.xpath("//label[@class='c-option c-option--right u-px u-py-sm u-clearfix' and not(@class='ng-pristine ng-untouched ng-valid ng-valid-required') and not (@class='c-option__radio')]")).getText();
     System.out.println("1 = " + vapval2);
     String vapval3 = elementz.get(i).findElement(By.xpath("//label[@class,'c-option c-option--right u-px u-py-sm u-clearfix ng-scope' and not(@class='ng-pristine ng-untouched ng-valid') and not (@class='c-option__checkbox')]")).getText();
     System.out.println("3 = " + vapval3);
     String vapval4 = elementz.get(i).findElement(By.xpath("//label[@class,'c-option c-option--right u-px u-py-sm u-clearfix' and not(@class='ng-pristine ng-untouched ng-valid ng-valid-required') and not (@class='c-option__checkbox')]")).getText();
     System.out.println("4 = " + vapval4);
    }
</code>```

Here is the full html, which may help.

```<code><!DOCTYPE html>
<html class="ng-scope" ng-app="dan">
<head>
<body class="u-scroll-y ng-scope" ng-controller="CoreController as cc">
<div class="c-animate c-animate--show u-pos-f-t ng-hide" ng-show="global.alerts.length">
<div class="o-grid-fluid u-h-100 u-pl-0">
<div class="o-grid__row u-ml-0 u-h-100">
<div class="c-loader ng-hide" ng-show="loadingHome" style="">
<nav class="o-grid__col-xl-2 o-grid__col-lg-3 o-grid__col-xs-4 u-p-0 c-card__block u-h-100 u-shadowed u-pos-f-t ng-scope" ng-if="global.loggedIn">
<div class="u-p-0 u-h-100 o-grid__col-xl-10 o-grid__col-lg-9 o-grid__col-xs-8 u-pull-right" ng-class="{ 'o-grid__col-xl-10 o-grid__col-lg-9 o-grid__col-xs-8 u-pull-right' : global.loggedIn }">
<header class="o-layout-table__row u-bg-primary u-shadowed u-clearfix u-px ng-scope" ng-if="global.loggedIn">
<main class="o-view-container">
<div class="o-grid-fluid u-py-md">
<div class="o-grid__row">
<div class="c-animate c-animate--view-slide-in-right c-animate--view-slide-out-right ng-scope" ng-view="" style="">
<div class="o-grid__col-md-10 o-grid__col-xl-8 o-grid__col-xl-offset-2 o-grid__col-md-offset-1 ng-scope">
<div class="u-mb-lg u-text-center">
<h1 class="u-text-bold">Recommendations</h1>
</div>
<form class="ng-valid ng-valid-min ng-valid-max ng-valid-required ng-dirty ng-valid-parse" name="recommend" ng-submit="recommend.$valid" style="">
<div class="o-media c-card c-card__block u-shadowed u-mb-lg ng-scope" ng-if="rc.WarrantyEligible && !rc.prevWarranty()">
<label class="c-form-control-label u-px u-py-sm u-w-100">Warranty Options:</label>
<div class="c-form-group u-p-0 u-mb-sm u-clearfix">
<div class="o-grid__col-md-8">
<label class="c-form-control-label u-text-normal">Product Recommendations (Years):</label>
</div>
<div class="o-grid__col-md-4">
<input class="c-form-control ng-pristine ng-untouched ng-valid ng-valid-min ng-valid-max ng-valid-required" required="" placeholder="Years" ng-model="rc.recommend.year" min="1" max="3" type="number">
</div>
</div>
<div class="c-form-group ng-scope" ng-if="data.answer_taxi">
<label class="c-option c-option--right u-px u-py-sm u-clearfix ng-scope" ng-if="!rc.planA && !rc.prestige" ng-click="cc.utils.audit('recommendation_warranty_plan_taxi_b')">
<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.warrantyPlan" value="taxiB" name="warrantyPlan" type="radio">
<i class="c-option__radio"></i>
Plan B Warranty (Taxi) & Breakdown Recovery
</label>
</div>
</div>
<div class="o-media c-card c-card__block u-shadowed u-mb-lg u-text-body u-bg-success" ng-if="!rc.prevVap() && rc.VapEligible ">
<div class="c-form-group">
<label class="c-form-control-label u-px u-py-sm u-w-100">Vehicle Asset Protection Options:</label>
<label class="c-option c-option--right u-px u-py-sm u-clearfix" ng-click="cc.utils.audit('recommend_vap')">
<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapPlan.plan" value="standard" name="vapPlan" type="radio">
<i class="c-option__radio"></i>
Vehicle Asset Protection - Standard Cover
</label>
<label class="c-option c-option--right u-px u-py-sm u-clearfix ng-scope" ng-if="data.answer_equity == true" ng-click="cc.utils.audit('recommend_negative_equity')">
<input class="ng-untouched ng-valid ng-dirty ng-valid-parse" ng-model="rc.recommend.vapPlan.equity" name="vapPlanEquity" type="checkbox" style="">
<i class="c-option__checkbox"></i>
Negative Equity Cover
</label>
<label class="c-option c-option--right u-px u-py-sm u-clearfix" ng-click="cc.utils.audit('vap_key_facts_checked')">
<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapCheck" name="vapCheck" type="checkbox">
<i class="c-option__checkbox"></i>
You confirm that you have received the VAP key facts leaflet?
</label>
</div>
</div>
</form>
<div class="c-form-group">
</div>
</div>
</div>
</div>
</main>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js">
<script src="./build/app.js?v=2.13" defer="">
<script src="/build/standalone/jspdf.js" defer="">
<script src="/build/standalone/sigWebTablet.js" defer="">
</body>
</html>
</code>```

答:
I'm a little confused as to what you are trying to do. You mention getting the text from the elements and also getting the state of the checkboxes. Your XPaths on the outer and inner loop overlap. Your elementz list is pulled from a LABEL that contains the c-option class but then you start with an element from elementz and the first part of your XPath you repeat the search for a LABEL that contains the c-option class.

There is an much easier way to do this. Each of these checkboxes/radiobuttons are INPUT tags and have a name specific to their value.

Plan B Warranty (Taxi) & Breakdown Recovery: <input ... name="warrantyPlan" type="radio">

Vehicle Asset Protection - Standard Cover: <input ... name="vapPlan" type="radio">

Negative Equity Cover: <input ... name="vapPlanEquity" type="checkbox" style="">

You confirm that you have received the VAP key facts leaflet?: <input ... name="vapCheck" type="checkbox">

So with that info, you can just get each INPUT with CSS selectors like

```<code>By.cssSelector("input[name='warrantyPlan']")
</code>```

Once you have the INPUT element, you can check if it's selected using .isSelected().

If you really do need the text, you can get the label because it's the parent of the INPUT we just got. We can do this with an XPath, By.xpath(".."), which gets the parent of the current element.

We can put this all together like

```<code>// Plan B Warranty (Taxi) & Breakdown Recovery
WebElement e = driver.findElement(By.cssSelector("input[name='warrantyPlan']"));
System.out.println(e.isSelected()); // false
System.out.println(e.findElement(By.xpath("..")).getText()); // Plan B Warranty (Taxi) & Breakdown Recovery

// Vehicle Asset Protection - Standard Cover
e = driver.findElement(By.cssSelector("input[name='vapPlan']"));
System.out.println(e.isSelected()); // false
System.out.println(e.findElement(By.xpath("..")).getText()); // Vehicle Asset Protection - Standard Cover
</code>```

I just did the first two. You can see the pattern and apply it for the last two.

ContentLicense: CC BY-SA 3.0

Body:
I have a page where I need to extract the text from an xpath and the status of the radio or checkbox that is associated with the text.
Each element is contained in a class called "c-form-group", so i have written a loop to iterate through to extract the "Text" the will be 4 elements found on the page. But it is failing on element 3 & 4, i must have something wrong with my xpath. I have yet to add in the check for the checkbox/radio button,

The first two elements are returning the values i require, then fails on element3.

Here are the 4 text elements i am trying to extract:

Plan B Warranty (Taxi) & Breakdown Recovery

Vehicle Asset Protection - Standard Cover

Negative Equity Cover

You confirm that you have received the VAP key facts leaflet?

Here is the code for the loop.

WebElement elem = driver.findElement(By.className("c-form-group"));
System.out.println("a");
List<WebElement> elementz =  elem.findElements(By.xpath("//label[contains(@class,'c-option')]"));

for(int i = 0 ; i< elementz.size() ; i++){
    System.out.println("Loop : " + i);
     String vapval1 = elementz.get(i).findElement(By.xpath("//label[@class='c-option c-option--right u-px u-py-sm u-clearfix ng-scope' and not(@class='ng-pristine ng-untouched ng-valid ng-valid-required') and not (@class='c-option__radio')]")).getText();
     System.out.println("0 = " + vapval1);
     String vapval2 = elementz.get(i).findElement(By.xpath("//label[@class='c-option c-option--right u-px u-py-sm u-clearfix' and not(@class='ng-pristine ng-untouched ng-valid ng-valid-required') and not (@class='c-option__radio')]")).getText();
     System.out.println("1 = " + vapval2);
     String vapval3 = elementz.get(i).findElement(By.xpath("//label[@class,'c-option c-option--right u-px u-py-sm u-clearfix ng-scope' and not(@class='ng-pristine ng-untouched ng-valid') and not (@class='c-option__checkbox')]")).getText();
     System.out.println("3 = " + vapval3);
     String vapval4 = elementz.get(i).findElement(By.xpath("//label[@class,'c-option c-option--right u-px u-py-sm u-clearfix' and not(@class='ng-pristine ng-untouched ng-valid ng-valid-required') and not (@class='c-option__checkbox')]")).getText();
     System.out.println("4 = " + vapval4);
    }

Here is the full html, which may help.

<!DOCTYPE html>

Recommendations

<form class="ng-valid ng-valid-min ng-valid-max ng-valid-required ng-dirty ng-valid-parse" name="recommend" ng-submit="recommend.$valid" style="">

Warranty Options:

Product Recommendations (Years):

<input class="c-form-control ng-pristine ng-untouched ng-valid ng-valid-min ng-valid-max ng-valid-required" required="" placeholder="Years" ng-model="rc.recommend.year" min="1" max="3" type="number">

<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.warrantyPlan" value="taxiB" name="warrantyPlan" type="radio">

Plan B Warranty (Taxi) & Breakdown Recovery

Vehicle Asset Protection Options:

<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapPlan.plan" value="standard" name="vapPlan" type="radio">

Vehicle Asset Protection - Standard Cover

<input class="ng-untouched ng-valid ng-dirty ng-valid-parse" ng-model="rc.recommend.vapPlan.equity" name="vapPlanEquity" type="checkbox" style="">

Negative Equity Cover

<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapCheck" name="vapCheck" type="checkbox">

You confirm that you have received the VAP key facts leaflet?

</form>

Body:
I'm a little confused as to what you are trying to do. You mention getting the text from the elements and also getting the state of the checkboxes. Your XPaths on the outer and inner loop overlap. Your elementz list is pulled from a LABEL that contains the c-option class but then you start with an element from elementz and the first part of your XPath you repeat the search for a LABEL that contains the c-option class.

There is an much easier way to do this. Each of these checkboxes/radiobuttons are INPUT tags and have a name specific to their value.

Plan B Warranty (Taxi) & Breakdown Recovery: <input ... name="warrantyPlan" type="radio">

Vehicle Asset Protection - Standard Cover: <input ... name="vapPlan" type="radio">

Negative Equity Cover: <input ... name="vapPlanEquity" type="checkbox" style="">

You confirm that you have received the VAP key facts leaflet?: <input ... name="vapCheck" type="checkbox">

So with that info, you can just get each INPUT with CSS selectors like

By.cssSelector("input[name='warrantyPlan']")

Once you have the INPUT element, you can check if it's selected using .isSelected().

If you really do need the text, you can get the label because it's the parent of the INPUT we just got. We can do this with an XPath, By.xpath(".."), which gets the parent of the current element.

We can put this all together like

// Plan B Warranty (Taxi) & Breakdown Recovery
WebElement e = driver.findElement(By.cssSelector("input[name='warrantyPlan']"));
System.out.println(e.isSelected()); // false
System.out.println(e.findElement(By.xpath("..")).getText()); // Plan B Warranty (Taxi) & Breakdown Recovery

// Vehicle Asset Protection - Standard Cover
e = driver.findElement(By.cssSelector("input[name='vapPlan']"));
System.out.println(e.isSelected()); // false
System.out.println(e.findElement(By.xpath("..")).getText()); // Vehicle Asset Protection - Standard Cover

I just did the first two. You can see the pattern and apply it for the last two.


问:
Why do the types in `(fmap . fmap) sum Just [1, 2, 3]` work?
I'm having the time of my life reading the wonderful Haskell Programming from first principles and I came by the following example that I'm just not able to take apart (Page 1286 e-reader):

```<code>Prelude> (fmap . fmap) sum Just [1, 2, 3]
Just 6
</code>```

It is obvious to me how the following works:

```<code>Prelude> fmap sum $ Just [1,2,3]
Just 6
</code>```

And I already manually deconstructed (fmap . fmap) to understand how the types work. But when thinking about this as "lifting twice" it doesn't make sense, since I'm lifting over both the Just and List data constructors.

I typed out the following in ghci:

```<code>Prelude> :t (fmap . fmap)
(fmap . fmap)
  :: (Functor f, Functor f1) => (a -> b) -> f1 (f a) -> f1 (f b)

Prelude> :t (fmap . fmap) sum
(fmap . fmap) sum
  :: (Num b, Foldable t, Functor f, Functor f1) =>
     f1 (f (t b)) -> f1 (f b)

Prelude> :t (fmap . fmap) sum Just
(fmap . fmap) sum Just :: (Num b, Foldable t) => t b -> Maybe b
</code>```

I don't understand how to derive the last output. When feeding (fmap . fmap) sum the Just data constructor, How does the compiler know to replace both f1 and f for Maybe? After I'll get a good answer here, how could I have figured it out myself?

答:
That isn't lifting over both Maybe and List (that would be (fmap . fmap) sum (Just [1,2,3]), which has a type problem), but over the function type (->) and Maybe.

```<code>Just :: a -> Maybe a
     -- ((->) a) (Maybe a)
     -- f (g a)   for f ~ ((->) a)  and  g ~ Maybe

(fmap . fmap) :: (a   -> b) -> f (g a  ) -> f (g b)
     -- Num x => ([x] -> x) -> f (g [x]) -> f (g x)
     -- Num x => ([x] -> x) -> ([x] -> Maybe [x]) -> [x] -> Maybe x
     --          ^             ^                     ^
     --          sum           Just                  [1,2,3]
</code>```

Body:
I'm having the time of my life reading the wonderful Haskell Programming from first principles and I came by the following example that I'm just not able to take apart (Page 1286 e-reader):

Prelude> (fmap . fmap) sum Just [1, 2, 3]
Just 6

It is obvious to me how the following works:

Prelude> fmap sum $ Just [1,2,3]
Just 6

And I already manually deconstructed (fmap . fmap) to understand how the types work. But when thinking about this as "lifting twice" it doesn't make sense, since I'm lifting over both the Just and List data constructors.

I typed out the following in ghci:

Prelude> :t (fmap . fmap)
(fmap . fmap)
  :: (Functor f, Functor f1) => (a -> b) -> f1 (f a) -> f1 (f b)

Prelude> :t (fmap . fmap) sum
(fmap . fmap) sum
  :: (Num b, Foldable t, Functor f, Functor f1) =>
     f1 (f (t b)) -> f1 (f b)

Prelude> :t (fmap . fmap) sum Just
(fmap . fmap) sum Just :: (Num b, Foldable t) => t b -> Maybe b

I don't understand how to derive the last output. When feeding (fmap . fmap) sum the Just data constructor, How does the compiler know to replace both f1 and f for Maybe? After I'll get a good answer here, how could I have figured it out myself?

Body:
That isn't lifting over both Maybe and List (that would be (fmap . fmap) sum (Just [1,2,3]), which has a type problem), but over the function type (->) and Maybe.

Just :: a -> Maybe a
     -- ((->) a) (Maybe a)
     -- f (g a)   for f ~ ((->) a)  and  g ~ Maybe

(fmap . fmap) :: (a   -> b) -> f (g a  ) -> f (g b)
     -- Num x => ([x] -> x) -> f (g [x]) -> f (g x)
     -- Num x => ([x] -> x) -> ([x] -> Maybe [x]) -> [x] -> Maybe x
     --          ^             ^                     ^
     --          sum           Just                  [1,2,3]


问:
Why upload module in repository not found via pip install?
I upload module
example-framework.python.egg
via Jenkins in JFrog Artifactory.
Upload completed good without errors.

I checked in Artifactory, in repository browser saw in properties
pypi.name - example-framework

Tried to install module via artifactory.

```<code>pip install example-framework
</code>```

pip returned error:

```<code>Collecting example-framework
  Could not find a version that satisfies the requirement example-framework (from versions: )
No matching distribution found for example-framework
</code>```

How solve this problem?

答: For the user running pip, make sure you have correctly setup your ~/.pip/pip.conf file to point to Artifactory. You can see an example of this in the Set Me Up box for the pipy repo.</p>

Body:
I upload module
example-framework.python.egg
via Jenkins in JFrog Artifactory.
Upload completed good without errors.

I checked in Artifactory, in repository browser saw in properties
pypi.name - example-framework

Tried to install module via artifactory.

pip install example-framework

pip returned error:

Collecting example-framework
  Could not find a version that satisfies the requirement example-framework (from versions: )
No matching distribution found for example-framework

How solve this problem?


问:
Breaking a column result into further pieces and putting it in another query in postgresql?
One of my result columns brings like 123/234 or 1234/45/567. From another table we can have value of 123 as abc, 234 as cde etc. So how to get the value abc/cde? Please assist.

答:
You're probably going to want a function that converts your id/id field into name/name value.

http://sqlfiddle.com/#!17/2c336/3/0


问:
Getting a list of active sessions in Tomcat using Java
I am developing a project in Java in which I want the count of all active sessions in Tomcat. Based on that I want to see how much of those users are active and actually using the application.</p>

答:
A simple tutorial to demonstrate how to determine active users / sessions in a Java Web Application.

```<code>package com.hubberspot.javaee.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class OnlineUsersCounter implements HttpSessionListener {

private static int numberOfUsersOnline;

 public OnlineUsersCounter() {
  numberOfUsersOnline = 0;
 }

 public static int getNumberOfUsersOnline() {
  return numberOfUsersOnline;
 }

    public void sessionCreated(HttpSessionEvent event) {

     System.out.println("Session created by Id : " + event.getSession().getId());
     synchronized (this) {
   numberOfUsersOnline++;
  }

    }

    public void sessionDestroyed(HttpSessionEvent event) {

     System.out.println("Session destroyed by Id : " + event.getSession().getId());
     synchronized (this) {
   numberOfUsersOnline--;
  }

    }

}
</code>```

Running the below servlet on three different browsers will provide output as : (see fig below)

```<code>package com.hubberspot.javaee;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hubberspot.javaee.listener.OnlineUsersCounter;

// @WebServlet annotation has a initParams field which takes
// in initialization parameters for a servlet.
// @WebInitParam annotation takes in a name and value for the
// initialization parameters for the current Servlet.

@WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }
, initParams = { @WebInitParam(name = "user" , value = "Jonty") })
public class HelloWorldServlet extends HttpServlet {

 protected void doGet(
   HttpServletRequest request,
   HttpServletResponse response
   ) throws ServletException, IOException {

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();

  // sessionCreated method gets executed
  HttpSession session = request.getSession();

  session.setMaxInactiveInterval(60);

  try {
   out.println("<html>");
   out.println("<body>");
   out.println("<h2>Number of Users Online : "
      + OnlineUsersCounter.getNumberOfUsersOnline()
      + "</h2>");
   out.println("</body>");
   out.println("</html>");
  } finally {
   out.close();
  }

 }

}
</code>```

Output of the program :

Eclipse Browser ->

Firefox Browser ->

Internet Explorer Browser ->

Console Output ->

For more: http://www.hubberspot.com/2013/09/how-to-determine-active-users-sessions.html

Body:
A simple tutorial to demonstrate how to determine active users / sessions in a Java Web Application.

package com.hubberspot.javaee.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class OnlineUsersCounter implements HttpSessionListener {

private static int numberOfUsersOnline;

 public OnlineUsersCounter() {
  numberOfUsersOnline = 0;
 }

 public static int getNumberOfUsersOnline() {
  return numberOfUsersOnline;
 }

    public void sessionCreated(HttpSessionEvent event) {

     System.out.println("Session created by Id : " + event.getSession().getId());
     synchronized (this) {
   numberOfUsersOnline++;
  }

    }

    public void sessionDestroyed(HttpSessionEvent event) {

     System.out.println("Session destroyed by Id : " + event.getSession().getId());
     synchronized (this) {
   numberOfUsersOnline--;
  }

    }

}

Running the below servlet on three different browsers will provide output as : (see fig below)

package com.hubberspot.javaee;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hubberspot.javaee.listener.OnlineUsersCounter;

// @WebServlet annotation has a initParams field which takes
// in initialization parameters for a servlet.
// @WebInitParam annotation takes in a name and value for the
// initialization parameters for the current Servlet.

@WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }
, initParams = { @WebInitParam(name = "user" , value = "Jonty") })
public class HelloWorldServlet extends HttpServlet {

 protected void doGet(
   HttpServletRequest request,
   HttpServletResponse response
   ) throws ServletException, IOException {

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();

  // sessionCreated method gets executed
  HttpSession session = request.getSession();

  session.setMaxInactiveInterval(60);

  try {
   out.println("<html>");
   out.println("<body>");
   out.println("<h2>Number of Users Online : "
      + OnlineUsersCounter.getNumberOfUsersOnline()
      + "</h2>");
   out.println("</body>");
   out.println("</html>");
  } finally {
   out.close();
  }

 }

}

Output of the program :

Eclipse Browser ->

Firefox Browser ->

Internet Explorer Browser ->

Console Output ->

For more: http://www.hubberspot.com/2013/09/how-to-determine-active-users-sessions.html


问:
Firebase push notification with data message or notification message
I want to send a push notification to the user which does two things:

inform the user a new file is available

automatically download the file in the background so that it is available when the user opens the app

For the first use case I can use a Notification Message and for the second a Data Message. But what is the best approach to combine both use cases?

Idea 1:
I could send two different messages for each use case?

Idea 2:
I use a Data Message and when the app receives the message the app takes care of showing a notification.

Which one should I prefer or is there a better approach?

答:
According to the documentation:

With FCM, you can send two types of messages to clients:

Notification messages, sometimes thought of as "display messages." These are handled by the FCM SDK automatically.

Data messages, which are handled by the client app.

It sounds like what you're doing is not a "display message".  You're just trying to tell your app to do something.

Also, you should know that notification messages can't be directly handled by the app when it's in the background.  In that case, FCM will simply show the notification in the notification tray.


问:
Python / Pandas: Eliminate for Loop using 2 DataFrames
First time asking a question here so hopefully I will make my issue clear. I am trying to understand how to better apply a list of scenarios (via for loop) to the same dataset and summarize results. *Note that once a scenario is applied, and I pull the relevant statistical data from dataframe and put into the summary table, I do not need to retain the information. Iterrows is painfully slow as I have tens of thousands of scenarios I want to run. Thank you for taking the time to review.

I have two Pandas dataframes: df_analysts and df_results:

1)  df_analysts contains a specific list of factors (e.g. TB,JK,SF,PWR) scenarios of weights (e.g. 50,50,50,50)

```<code>      TB   JK   SF  PWR
0     50   50   50   50
1     50   50   50  100
2     50   50   50  150
3     50   50   50  200
4     50   50   50  250
</code>```

2) df_results holds results by date and group and entrant an then ranking by each factor, finally it has the final finish result.

```<code>      Date       GR  Ent TB-R  JK-R  SF-R  PWR-R Fin   W1  W2  W2  W4  SUM(W)
0     11182017   1   1   2     1     2     1     2
1     11182017   1   2   3     2     3     2     1
2     11182017   1   3   1     3     1     3     3
3     11182017   2   1   1     2     2     1     1
4     11182017   2   2   2     1     1     2     1
</code>```

3) I am using iterrows to

loop through each scenario in the df_analysts dataframe

apply weight scenario to each factor rank  (if rank = 1, then 1.0*weight, rank = 2, then 0.68*weight, rank = 3, then 0.32*weight). Those results go into the W1-W4 columns.

Sum the W1-W4 columns.

Rank the SUM(W) column.

Result sample below for a single scenario (e.g. 50,50,50,50)

```<code>      Date       GR  Ent TB-R  JK-R  SF-R  PWR-R Fin   W1  W2  W2  W4  SUM(W) Rank
0     11182017   1   1   2     1     2     1     1     34  50  34  50  168    1
1     11182017   1   2   3     2     3     2     3     16  34  16  34  100    3
2     11182017   1   3   1     3     1     3     2     50  16  50  16  132    2
3     11182017   2   1   2     2     2     1     1     34  34  34  50  152    2
4     11182017   2   2   1     1     1     2     1     50  50  50  34  184    1
</code>```

4) Finally, for each scenario, I am creating a new dataframe for the summary results (df_summary) which logs the factor / weight scenario used (from df_analysts)  and compares the RANK result to the Finish by date and group and keeps a tally where they land. Sample below (only the 50,50,50,50 scenario is shown above which results in a 1,1).

```<code>      Factors          Weights         Top  Top2
0     (TB,JK,SF,PWR)   (50,50,50,50)   1    1
1     (TB,JK,SF,PWR)   (50,50,50,100)  1    0
2     (TB,JK,SF,PWR)   (50,50,50,150)  1    1
3     (TB,JK,SF,PWR)   (50,50,50,200)  1    0
4     (TB,JK,SF,PWR)   (50,50,50,250)  1    1
</code>```

答:
You could merge your analyst and results dataframe and then perform the calculations.

```<code>def factor_rank(x,y):
    if (x==1): return y
    elif (x==2): return y*0.68
    elif (x==3): return y*0.32

df_analysts.index.name='SCENARIO'
df_analysts.reset_index(inplace=True)

df_analysts['key'] = 1
df_results['key'] = 1

df = pd.merge(df_analysts, df_results, on='key')
df.drop(['key'],axis=1,inplace=True)

df['W1'] = df.apply(lambda r: factor_rank(r['TB-R'], r['TB']), axis=1)
df['W2'] = df.apply(lambda r: factor_rank(r['JK-R'], r['JK']), axis=1)
df['W3'] = df.apply(lambda r: factor_rank(r['SF-R'], r['SF']), axis=1)
df['W4'] = df.apply(lambda r: factor_rank(r['PWR-R'], r['PWR']), axis=1)
df['SUM(W)'] = df.W1 + df.W1 + df.W3 + df.W4

df["rank"] = df.groupby(['GR','SCENARIO'])['SUM(W)'].rank(ascending=False)
</code>```

You may also want to check out this question which deals with improving processing times on row based calculations:

How to apply a function to mulitple columns of a pandas DataFrame in parallel

Body:
First time asking a question here so hopefully I will make my issue clear. I am trying to understand how to better apply a list of scenarios (via for loop) to the same dataset and summarize results. *Note that once a scenario is applied, and I pull the relevant statistical data from dataframe and put into the summary table, I do not need to retain the information. Iterrows is painfully slow as I have tens of thousands of scenarios I want to run. Thank you for taking the time to review.

I have two Pandas dataframes: df_analysts and df_results:

1)  df_analysts contains a specific list of factors (e.g. TB,JK,SF,PWR) scenarios of weights (e.g. 50,50,50,50)

      TB   JK   SF  PWR
0     50   50   50   50
1     50   50   50  100
2     50   50   50  150
3     50   50   50  200
4     50   50   50  250

2) df_results holds results by date and group and entrant an then ranking by each factor, finally it has the final finish result.

      Date       GR  Ent TB-R  JK-R  SF-R  PWR-R Fin   W1  W2  W2  W4  SUM(W)
0     11182017   1   1   2     1     2     1     2
1     11182017   1   2   3     2     3     2     1
2     11182017   1   3   1     3     1     3     3
3     11182017   2   1   1     2     2     1     1
4     11182017   2   2   2     1     1     2     1

3) I am using iterrows to

loop through each scenario in the df_analysts dataframe

apply weight scenario to each factor rank  (if rank = 1, then 1.0*weight, rank = 2, then 0.68*weight, rank = 3, then 0.32*weight). Those results go into the W1-W4 columns.

Sum the W1-W4 columns.

Rank the SUM(W) column.

Result sample below for a single scenario (e.g. 50,50,50,50)

      Date       GR  Ent TB-R  JK-R  SF-R  PWR-R Fin   W1  W2  W2  W4  SUM(W) Rank
0     11182017   1   1   2     1     2     1     1     34  50  34  50  168    1
1     11182017   1   2   3     2     3     2     3     16  34  16  34  100    3
2     11182017   1   3   1     3     1     3     2     50  16  50  16  132    2
3     11182017   2   1   2     2     2     1     1     34  34  34  50  152    2
4     11182017   2   2   1     1     1     2     1     50  50  50  34  184    1

4) Finally, for each scenario, I am creating a new dataframe for the summary results (df_summary) which logs the factor / weight scenario used (from df_analysts)  and compares the RANK result to the Finish by date and group and keeps a tally where they land. Sample below (only the 50,50,50,50 scenario is shown above which results in a 1,1).

      Factors          Weights         Top  Top2
0     (TB,JK,SF,PWR)   (50,50,50,50)   1    1
1     (TB,JK,SF,PWR)   (50,50,50,100)  1    0
2     (TB,JK,SF,PWR)   (50,50,50,150)  1    1
3     (TB,JK,SF,PWR)   (50,50,50,200)  1    0
4     (TB,JK,SF,PWR)   (50,50,50,250)  1    1

Body:
You could merge your analyst and results dataframe and then perform the calculations.

def factor_rank(x,y):
    if (x==1): return y
    elif (x==2): return y*0.68
    elif (x==3): return y*0.32

df_analysts.index.name='SCENARIO'
df_analysts.reset_index(inplace=True)

df_analysts['key'] = 1
df_results['key'] = 1

df = pd.merge(df_analysts, df_results, on='key')
df.drop(['key'],axis=1,inplace=True)

df['W1'] = df.apply(lambda r: factor_rank(r['TB-R'], r['TB']), axis=1)
df['W2'] = df.apply(lambda r: factor_rank(r['JK-R'], r['JK']), axis=1)
df['W3'] = df.apply(lambda r: factor_rank(r['SF-R'], r['SF']), axis=1)
df['W4'] = df.apply(lambda r: factor_rank(r['PWR-R'], r['PWR']), axis=1)
df['SUM(W)'] = df.W1 + df.W1 + df.W3 + df.W4

df["rank"] = df.groupby(['GR','SCENARIO'])['SUM(W)'].rank(ascending=False)

You may also want to check out this question which deals with improving processing times on row based calculations:

How to apply a function to mulitple columns of a pandas DataFrame in parallel


问:
Compressing a JPG image to a given size in KB?
I have a byte array returned by the camera in input.

I need to scale down my image to make its size equal to 500KB. I am trying to achieve this using a Bitmap, but I cannot find how to get the proper compression value.

```<code>public static byte[] compressCapture(byte[] capture) {

    // How to get the right compression value ?
    int compression = 50;

    Bitmap bitmap  = BitmapFactory.decodeByteArray(capture, 0, capture.length);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, compression, outputStream);
    return outputStream.toByteArray();
}
</code>```

The problem is that the compression is not proportional to the image size, meaning that compression equals to 50 will not divide the image size by 2.

Is there a way to get a fixed image size in output that does not depend on the focus, or the smartphone model ?

EDIT :

I do not want to use a File (I work with confidential data).

答:
It's hard to compress to a given size, I suggest using ImageMagick and tweaking the options until you get to a size you feel comfortable using.

I use always ImageMagick. Consider this command

```<code>convert -strip -interlace Plane -gaussian-blur 0.05 -quality 85% source.jpg result.jpg
</code>```

The command uses these options:

quality in 85

progressive (comprobed compression)

a very tiny gausssian blur to optimize the size (0.05 or 0.5 of radius) depends on the quality and size of the picture, this notably
  optimizes the size of the jpeg.

Strip any comment or exif tag

Source

Try tweaking the quality parameter. If you decrease it, it increases compression and reduces file size.

Body:
I have a byte array returned by the camera in input.

I need to scale down my image to make its size equal to 500KB. I am trying to achieve this using a Bitmap, but I cannot find how to get the proper compression value.

public static byte[] compressCapture(byte[] capture) {

    // How to get the right compression value ?
    int compression = 50;

    Bitmap bitmap  = BitmapFactory.decodeByteArray(capture, 0, capture.length);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, compression, outputStream);
    return outputStream.toByteArray();
}

The problem is that the compression is not proportional to the image size, meaning that compression equals to 50 will not divide the image size by 2.

Is there a way to get a fixed image size in output that does not depend on the focus, or the smartphone model ?

EDIT :

I do not want to use a File (I work with confidential data).

Body:
It's hard to compress to a given size, I suggest using ImageMagick and tweaking the options until you get to a size you feel comfortable using.

I use always ImageMagick. Consider this command

convert -strip -interlace Plane -gaussian-blur 0.05 -quality 85% source.jpg result.jpg

The command uses these options:

quality in 85

progressive (comprobed compression)

a very tiny gausssian blur to optimize the size (0.05 or 0.5 of radius) depends on the quality and size of the picture, this notably
  optimizes the size of the jpeg.

Strip any comment or exif tag

Source

Try tweaking the quality parameter. If you decrease it, it increases compression and reduces file size.


问:
How to re-render part of the component upon state change?
I have a component the includes progress.circle from the library react-native-progress (see link: https://github.com/oblador/react-native-progress).

Initially I set the progress prop of the progress circle to a state variable that is set to 0 at idle state as shown in the code below:

```<code><Progress.Circle
        showsText={true}
        progress={this.state.progress} // this.state.progress = 0
        size={width * 0.1388888888888}
        color={"#EF5D6C"}
/>
</code>```

Number of user interactions take place to set the state variable (this.state.progress) to a certain percentage then the component re-render to show the progress animation as intended.

Problem is the component flashes for part of a second as result of the re-rendering process.
So is there a way to only re-render the progress circle and leave the rest of the component in its current rendering form.

答:
You could try separating out the Progress.Circle element into a different file so its in its own renderer.

```<code>render() {
  return (
    <Progress.Circle
      showsText={true}
      progress={this.state.progress} // this.state.progress = 0
      size={width * 0.1388888888888}
      color={"#EF5D6C"}
    />
  )
}
</code>```

That way when you change the element in state only the progress.circle should re-render. Then you would import this into your main file and call it there:

```<code>render(){
  ....
  <ProgressCircle />
  ....
}
</code>```

Basically whatever is inside the render function will re-render. If the progress.circle element is on its own where the state is changed, only it should re-render as far as i know.

Hope this helps in some way!

ContentLicense: CC BY-SA 4.0

Body:
I have a component the includes progress.circle from the library react-native-progress (see link: https://github.com/oblador/react-native-progress).

Initially I set the progress prop of the progress circle to a state variable that is set to 0 at idle state as shown in the code below:

<Progress.Circle
        showsText={true}
        progress={this.state.progress} // this.state.progress = 0
        size={width * 0.1388888888888}
        color={"#EF5D6C"}
/>

Number of user interactions take place to set the state variable (this.state.progress) to a certain percentage then the component re-render to show the progress animation as intended.

Problem is the component flashes for part of a second as result of the re-rendering process.
So is there a way to only re-render the progress circle and leave the rest of the component in its current rendering form.

Body:
You could try separating out the Progress.Circle element into a different file so its in its own renderer.

render() {
  return (
    <Progress.Circle
      showsText={true}
      progress={this.state.progress} // this.state.progress = 0
      size={width * 0.1388888888888}
      color={"#EF5D6C"}
    />
  )
}

That way when you change the element in state only the progress.circle should re-render. Then you would import this into your main file and call it there:

render(){
  ....
  <ProgressCircle />
  ....
}

Basically whatever is inside the render function will re-render. If the progress.circle element is on its own where the state is changed, only it should re-render as far as i know.

Hope this helps in some way!


问:
Local scope object sometimes works within a javascript promise with .then
Hoping someone out there can offer an incline of insight/advice on how to overcome my coding issue?

I am trying to update a global scope object var, locally within a Promise.then() function. The data comes from an element in the DOM which has been manipulated inside another function as part of the $.when procedure.

Inside the .then() I can console.log the element and verify that the element has been updated and is such within the local scope, but when I try to pass that data to "placeIDs" object and console.log that it sometimes works and sometimes shows as undefined.

It, to me seems to have defied normal logic unless my brain is cooked and I am not seeing the obvious.

My code is below (it is all part of a Google maps API script), please ask if you need any answers in order to help, good luck and thank you.

```<code>  var target   = null,
      placeIDs = {

          originPlaceId:      null,
          destinationPlaceId: null

      }
  ;

  // Render the direction route for the map
  $.when(calculateAndDisplayRoute(map, me, directionsService, directionsDisplay)).then(function(response) {

    const target = $('.site-content');

    const placeIDs = {

      originPlaceId:      target.attr('data-orig'),
      destinationPlaceId: target.attr('data-dest')

    }

    // Add the autocomplete function for the map
    new AutocompleteDirectionsHandler(map, directionsService, directionsDisplay, placeIDs.originPlaceId, placeIDs.destinationPlaceId);

  }).catch(

    (reason) => {

      // Log the rejection reason
      console.log('Handle rejected ' + reason + ' promise.');

  });
</code>```

As requested the promise function below:

```<code>function calculateAndDisplayRoute(map, me, directionsService, directionsDisplay) {

    if (me == null) {

        var travelModeChosen = 'DRIVING';

    } else {

        var travelModeChosen = me.travelMode;

    }

    placeIDs = directionsService.route({

        origin:       document.getElementById('origin-input').value,
        destination:  document.getElementById('destination-input').value,
        travelMode:   travelModeChosen

    }, function(response, status) {

        if (status === 'OK') {

            // Clear the direction text panel
            $('#right-panel').empty();

            // Insert place IDs into the DOM
            $('.site-content')
                .attr('data-orig', response.geocoded_waypoints[0]['place_id'])
                .attr('data-dest', response.geocoded_waypoints[1]['place_id'])
            ;

            directionsDisplay.setPanel(document.getElementById('right-panel'));
            directionsDisplay.setDirections(response);

            if (travelModeChosen == 'DRIVING') {

                var trafficLayer = new google.maps.TrafficLayer();
                trafficLayer.setMap(map);

            } else if (travelModeChosen == 'TRANSIT') {

                var transitLayer = new google.maps.TransitLayer();
                transitLayer.setMap(map);

            } else if (travelModeChosen == 'BYCYCLE') {

                var bikeLayer = new google.maps.BicyclingLayer();
                bikeLayer.setMap(map);

            }

            // Set up the map for the direction route and pins
            directionsDisplay.setMap(null);
            directionsDisplay.setMap(map);

        } else {

            window.alert('Directions request failed due to ' + status);

        }

    });

}
</code>```

答:
As requested in comments, please let me know if you need help. I'd advice you to read into promises or at least watch the video to understand why, the how gets easier when you understand why JS uses promises:</p>

```<code>function calculateAndDisplayRoute(map, me, directionsService, directionsDisplay) {
  const travelModeChosen = (me||{}).travelMode || "DRIVING";

  return new Promise(
    (resolve,reject)=>
      directionsService.route(
        {
          origin: document.getElementById('origin-input').value,
          destination: document.getElementById('destination-input').value,
          travelMode: travelModeChosen
        }
        ,(response,status)=>
          status==="OK"
            ? resolve(response)
            : reject(status)
      )

  )
  .then(
    response => {
      $('#right-panel').empty();

      // Insert place IDs into the DOM
      $('.site-content')
        .attr('data-orig', response.geocoded_waypoints[0]['place_id'])
        .attr('data-dest', response.geocoded_waypoints[1]['place_id'])
        ;

      directionsDisplay.setPanel(document.getElementById('right-panel'));
      directionsDisplay.setDirections(response);

      if (travelModeChosen == 'DRIVING') {

        var trafficLayer = new google.maps.TrafficLayer();
        trafficLayer.setMap(map);

      } else if (travelModeChosen == 'TRANSIT') {

        var transitLayer = new google.maps.TransitLayer();
        transitLayer.setMap(map);

      } else if (travelModeChosen == 'BYCYCLE') {

        var bikeLayer = new google.maps.BicyclingLayer();
        bikeLayer.setMap(map);

      }

      // Set up the map for the direction route and pins
      directionsDisplay.setMap(null);
      directionsDisplay.setMap(map);
    }
    ,reject =>
      window.alert('Directions request failed due to ' + reject)
  )

}
</code>```

Body:
Hoping someone out there can offer an incline of insight/advice on how to overcome my coding issue?

I am trying to update a global scope object var, locally within a Promise.then() function. The data comes from an element in the DOM which has been manipulated inside another function as part of the $.when procedure.

Inside the .then() I can console.log the element and verify that the element has been updated and is such within the local scope, but when I try to pass that data to "placeIDs" object and console.log that it sometimes works and sometimes shows as undefined.

It, to me seems to have defied normal logic unless my brain is cooked and I am not seeing the obvious.

My code is below (it is all part of a Google maps API script), please ask if you need any answers in order to help, good luck and thank you.

  var target   = null,
      placeIDs = {

          originPlaceId:      null,
          destinationPlaceId: null

      }
  ;

  // Render the direction route for the map
  $.when(calculateAndDisplayRoute(map, me, directionsService, directionsDisplay)).then(function(response) {

    const target = $('.site-content');

    const placeIDs = {

      originPlaceId:      target.attr('data-orig'),
      destinationPlaceId: target.attr('data-dest')

    }

    // Add the autocomplete function for the map
    new AutocompleteDirectionsHandler(map, directionsService, directionsDisplay, placeIDs.originPlaceId, placeIDs.destinationPlaceId);

  }).catch(

    (reason) => {

      // Log the rejection reason
      console.log('Handle rejected ' + reason + ' promise.');

  });

As requested the promise function below:

function calculateAndDisplayRoute(map, me, directionsService, directionsDisplay) {

    if (me == null) {

        var travelModeChosen = 'DRIVING';

    } else {

        var travelModeChosen = me.travelMode;

    }

    placeIDs = directionsService.route({

        origin:       document.getElementById('origin-input').value,
        destination:  document.getElementById('destination-input').value,
        travelMode:   travelModeChosen

    }, function(response, status) {

        if (status === 'OK') {

            // Clear the direction text panel
            $('#right-panel').empty();

            // Insert place IDs into the DOM
            $('.site-content')
                .attr('data-orig', response.geocoded_waypoints[0]['place_id'])
                .attr('data-dest', response.geocoded_waypoints[1]['place_id'])
            ;

            directionsDisplay.setPanel(document.getElementById('right-panel'));
            directionsDisplay.setDirections(response);

            if (travelModeChosen == 'DRIVING') {

                var trafficLayer = new google.maps.TrafficLayer();
                trafficLayer.setMap(map);

            } else if (travelModeChosen == 'TRANSIT') {

                var transitLayer = new google.maps.TransitLayer();
                transitLayer.setMap(map);

            } else if (travelModeChosen == 'BYCYCLE') {

                var bikeLayer = new google.maps.BicyclingLayer();
                bikeLayer.setMap(map);

            }

            // Set up the map for the direction route and pins
            directionsDisplay.setMap(null);
            directionsDisplay.setMap(map);

        } else {

            window.alert('Directions request failed due to ' + status);

        }

    });

}

Body:
As requested in comments, please let me know if you need help. I'd advice you to read into promises or at least watch the video to understand why, the how gets easier when you understand why JS uses promises:

function calculateAndDisplayRoute(map, me, directionsService, directionsDisplay) {
  const travelModeChosen = (me||{}).travelMode || "DRIVING";

  return new Promise(
    (resolve,reject)=>
      directionsService.route(
        {
          origin: document.getElementById('origin-input').value,
          destination: document.getElementById('destination-input').value,
          travelMode: travelModeChosen
        }
        ,(response,status)=>
          status==="OK"
            ? resolve(response)
            : reject(status)
      )

  )
  .then(
    response => {
      $('#right-panel').empty();

      // Insert place IDs into the DOM
      $('.site-content')
        .attr('data-orig', response.geocoded_waypoints[0]['place_id'])
        .attr('data-dest', response.geocoded_waypoints[1]['place_id'])
        ;

      directionsDisplay.setPanel(document.getElementById('right-panel'));
      directionsDisplay.setDirections(response);

      if (travelModeChosen == 'DRIVING') {

        var trafficLayer = new google.maps.TrafficLayer();
        trafficLayer.setMap(map);

      } else if (travelModeChosen == 'TRANSIT') {

        var transitLayer = new google.maps.TransitLayer();
        transitLayer.setMap(map);

      } else if (travelModeChosen == 'BYCYCLE') {

        var bikeLayer = new google.maps.BicyclingLayer();
        bikeLayer.setMap(map);

      }

      // Set up the map for the direction route and pins
      directionsDisplay.setMap(null);
      directionsDisplay.setMap(map);
    }
    ,reject =>
      window.alert('Directions request failed due to ' + reject)
  )

}


问:
How do I kill the process currently using a port on localhost in Windows?
How can I remove the current process/application which is already assigned to a port?

For example: localhost:8080

答:
In Windows PowerShell version 1 or later to stop a process on port 3000 type:

Stop-Process (,(netstat -ano | findstr :3000).split() | foreach {$[$.length-1]}) -Force

As suggested by @morganpdx here`s a more PowerShell-ish, better version:

Stop-Process -Id (Get-NetTCPConnection -LocalPort 3000).OwningProcess -Force


问:
Image layers cufon jquery php saving the resulting composite?
This question is a bit open at the moment as I'm not sure the idea is even possible.

So far I've loaded an image from a url, and then used jQuery UI draggable feature to allow the user to drag html text (which has been replaced using cufon font replacement) over the top of the image.

The major step (which is what my question relates to) is being able to take the image and text layered over the top of the image, and save the result, either to the server, or potentially offer the option to save the altered image to the user's HD, or what would also be useful is to upload to facebook using the facebook API, but this is something I know is possible.

It all hangs on whether it's even possible to achieve the first step, which is to save the image and layered text as a combined image?

I wonder if there is a PHP/jQuery solution that would allow me to do this?

答: My suggestion would be to have an internal URL that outputs the final image using jQuery and PHP, then take a screenshot using webkit2png of that page. You should know the dimensions etc., so you'll be able to crop down the resulting screenshot to just the region you're looking for.</p>

ContentLicense: CC BY-SA 2.5


问:
Method to determine if caching was used for a particular HttpClient request
The new .NET 4.5 HttpClient class is handy for sending off web requests so I'm trying to use it instead of the old HttpWebRequest and related classes.

I can get it to do just about everything I used to do, including decompression, caching...

But how do I know if a completed request was satisfied by the cache or not?

This was possible before:

```<code>using (var resp = request.GetResponse())
using (var rs = resp.GetResponseStream())
{
    if (!resp.IsFromCache)
    {
        //do something
    }
}
</code>```

Where can I add that check here?

```<code>HttpClient client = new HttpClient(
            new WebRequestHandler
            {
                AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
                CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable),
                UseDefaultCredentials = true,
                PreAuthenticate = true
            });
var data = await client.GetByteArrayAsync(uri);
//did that come from the cache?
return data;
</code>```

Anticipating "why do you need to know if it was from the cache?" ... well I happen to want to know if I just communicated with the server, because if I did then I'll extend a session keep-alive timer... but if I just got that from the cache and didn't even go to the server, I may need to send a session keep alive request sooner... session creation for this server takes at least a couple of seconds and I want to avoid it.

If I use the more piece-meal methods on HttpClient, there is more room to investigate the response and look for status codes and headers:

```<code>var resp = await client.GetAsync(uri);
resp.EnsureSuccessStatusCode();
//can look at status codes, headers etc here
return await resp.Content.ReadAsByteArrayAsync();
</code>```

The status code appears to be 200 whether it is cached or not ... there are some interesting things in the header, but I'm not sure how to interpret all of them.

For instance resp.Headers.Date looks like its the date response was cached, so if its sufficiently far in the past (more than a couple of seconds?) that might tell me if its cached or not.  But I just don't know how reliable that kind of thinking is ...

答: The Age header shows that it's from the cache.  On the left is the 1st (uncached) request, and on the right, the 2nd (cached) request:

Body:
The new .NET 4.5 HttpClient class is handy for sending off web requests so I'm trying to use it instead of the old HttpWebRequest and related classes.

I can get it to do just about everything I used to do, including decompression, caching...

But how do I know if a completed request was satisfied by the cache or not?

This was possible before:

using (var resp = request.GetResponse())
using (var rs = resp.GetResponseStream())
{
    if (!resp.IsFromCache)
    {
        //do something
    }
}

Where can I add that check here?

HttpClient client = new HttpClient(
            new WebRequestHandler
            {
                AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
                CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable),
                UseDefaultCredentials = true,
                PreAuthenticate = true
            });
var data = await client.GetByteArrayAsync(uri);
//did that come from the cache?
return data;

Anticipating "why do you need to know if it was from the cache?" ... well I happen to want to know if I just communicated with the server, because if I did then I'll extend a session keep-alive timer... but if I just got that from the cache and didn't even go to the server, I may need to send a session keep alive request sooner... session creation for this server takes at least a couple of seconds and I want to avoid it.

If I use the more piece-meal methods on HttpClient, there is more room to investigate the response and look for status codes and headers:

var resp = await client.GetAsync(uri);
resp.EnsureSuccessStatusCode();
//can look at status codes, headers etc here
return await resp.Content.ReadAsByteArrayAsync();

The status code appears to be 200 whether it is cached or not ... there are some interesting things in the header, but I'm not sure how to interpret all of them.

For instance resp.Headers.Date looks like its the date response was cached, so if its sufficiently far in the past (more than a couple of seconds?) that might tell me if its cached or not.  But I just don't know how reliable that kind of thinking is ...


问:
Sending JSON using the django test client
I'm working on a django a project that will serve as the endpoint for a webhook. The webhook will POST some JSON data to my endpoint, which will then parse that data. I'm trying to write unit tests for it, but I'm not sure if I'm sending the JSON properly.

I keep getting "TypeError: string indices must be integers" in pipeline_endpoint

Here's the code:

```<code># tests.py
from django.test import TestCase
from django.test.client import Client
import simplejson

class TestPipeline(TestCase):

    def setUp(self):
        """initialize the Django test client"""
        self.c = Client()

    def test_200(self):
        json_string = u'{"1": {"guid": "8a40135230f21bdb0130f21c255c0007", "portalId": 999, "email": "fake@email"}}'
        json_data = simplejson.loads(json_string)
        self.response = self.c.post('/pipeline-endpoint', json_data, content_type="application/json")
        self.assertEqual(self.response.status_code, "200")
</code>```

and

```<code># views.py
from pipeline.prospect import Prospect
import simplejson

def pipeline_endpoint(request):

    #get the data from the json object that came in
    prospects_json = simplejson.loads(request.raw_post_data)
    for p in prospects_json:
        prospect = {
            'email'          : p['email'],
            'hs_id'          : p['guid'],
            'portal'         : p['portalId'],
        }
</code>```

Edit: whole traceback.

```<code>======================================================================
ERROR: test_200 (pipeline.tests.TestPipeline)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "F:\......\pipeline\tests.py", line 31, in test_200
    self.response = self.c.post('/pipeline-endpoint', json_string, content_type="application/json")
  File "C:\Python27\lib\site-packages\django\test\client.py", line 455, in post
    response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
  File "C:\Python27\lib\site-packages\django\test\client.py", line 256, in post
    return self.request(**r)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 111, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "F:\......\pipeline\views.py", line 18, in pipeline_endpoint
    'email'          : p['email'],
TypeError: string indices must be integers

----------------------------------------------------------------------
Ran 1 test in 0.095s

FAILED (errors=1)
Destroying test database for alias 'default'...
</code>```

答:
rest_framework's APIClient (which is the the default client_class in APITestCase) takes care of dumping dict to JSON and it sets proper content type by passing format='json'.

```<code>from rest_framework import status
from rest_framework.test import APIClient, APITestCase

class MyTestCase(APITestCase):
    url = '/url'

    def post(self, payload, url=None):
        """
        Helper to send an HTTP post.

        @param (dict) payload: request body

        @returns: response
        """
        if url is None:
            url = self.url

        return self.client.post(url, payload, format='json')

    def test_my_function(self):
        payload = {
            'key': 'value'
        }
        response = self.post(payload)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
</code>```

Body:
I'm working on a django a project that will serve as the endpoint for a webhook. The webhook will POST some JSON data to my endpoint, which will then parse that data. I'm trying to write unit tests for it, but I'm not sure if I'm sending the JSON properly.

I keep getting "TypeError: string indices must be integers" in pipeline_endpoint

Here's the code:

# tests.py
from django.test import TestCase
from django.test.client import Client
import simplejson

class TestPipeline(TestCase):

    def setUp(self):
        """initialize the Django test client"""
        self.c = Client()

    def test_200(self):
        json_string = u'{"1": {"guid": "8a40135230f21bdb0130f21c255c0007", "portalId": 999, "email": "fake@email"}}'
        json_data = simplejson.loads(json_string)
        self.response = self.c.post('/pipeline-endpoint', json_data, content_type="application/json")
        self.assertEqual(self.response.status_code, "200")

and

# views.py
from pipeline.prospect import Prospect
import simplejson

def pipeline_endpoint(request):

    #get the data from the json object that came in
    prospects_json = simplejson.loads(request.raw_post_data)
    for p in prospects_json:
        prospect = {
            'email'          : p['email'],
            'hs_id'          : p['guid'],
            'portal'         : p['portalId'],
        }

Edit: whole traceback.

======================================================================
ERROR: test_200 (pipeline.tests.TestPipeline)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "F:\......\pipeline\tests.py", line 31, in test_200
    self.response = self.c.post('/pipeline-endpoint', json_string, content_type="application/json")
  File "C:\Python27\lib\site-packages\django\test\client.py", line 455, in post
    response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
  File "C:\Python27\lib\site-packages\django\test\client.py", line 256, in post
    return self.request(**r)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 111, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "F:\......\pipeline\views.py", line 18, in pipeline_endpoint
    'email'          : p['email'],
TypeError: string indices must be integers

----------------------------------------------------------------------
Ran 1 test in 0.095s

FAILED (errors=1)
Destroying test database for alias 'default'...

Body:
rest_framework's APIClient (which is the the default client_class in APITestCase) takes care of dumping dict to JSON and it sets proper content type by passing format='json'.

from rest_framework import status
from rest_framework.test import APIClient, APITestCase

class MyTestCase(APITestCase):
    url = '/url'

    def post(self, payload, url=None):
        """
        Helper to send an HTTP post.

        @param (dict) payload: request body

        @returns: response
        """
        if url is None:
            url = self.url

        return self.client.post(url, payload, format='json')

    def test_my_function(self):
        payload = {
            'key': 'value'
        }
        response = self.post(payload)
        self.assertEqual(response.status_code, status.HTTP_200_OK)


答:
What about simply adding a NOT EXISTS:</p>

```<code>SELECT *
 FROM student st
 WHERE EXISTS (SELECT NULL
                 FROM grade g
                WHERE st.student_id = g.student_id
                  AND g.grade IN ('A','B'))
AND NOT EXISTS (SELECT NULL
                  FROM grade g
                WHERE st.student_id = g.student_id
                  AND g.grade IN ('C', 'D', 'F'))
</code>```

Title: how to select records with specific value/condition in another table

Body:
I have 3 tables STUDENT, SUBJECT and GRADE.

STUDENT

+------------+------------+------------+
| student_id | first_name |  last_name |
+------------+------------+------------+
|          0 | Arthur     | Pain       |
|          1 | Richard    | Gordon     |
|          2 | Jennifer   | Adelaide   |
+------------+------------+------------+

SUBJECT

+------------+--------------+
| subject_id | subject_name |
+------------+--------------+
|        001 | Math         |
|        002 | Science      |
|        003 | English      |
+------------+--------------+

GRADE

+-------------+-------------+--------+
| student_id  | subject_id  |  grade |
+-------------+-------------+--------+
| 0           | 001         | A      |
| 0           | 002         | B      |
| 0           | 003         | A      |
| 1           | 001         | B      |
| 1           | 002         | A      |
| 1           | 003         | F      |
| 2           | 001         | A      |
| 2           | 002         | B      |
| 2           | 003         | B      |
+-------------+-------------+--------+

I have tried the query below.

SELECT * FROM student st WHERE EXISTS
       (SELECT 1 FROM grade g WHERE st.student_id = g.student_id AND g.grade IN ('A','B');

I want to select the students with grades only 'A' OR 'B'.

Body:
What about simply adding a NOT EXISTS:

SELECT *
 FROM student st
 WHERE EXISTS (SELECT NULL
                 FROM grade g
                WHERE st.student_id = g.student_id
                  AND g.grade IN ('A','B'))
AND NOT EXISTS (SELECT NULL
                  FROM grade g
                WHERE st.student_id = g.student_id
                  AND g.grade IN ('C', 'D', 'F'))


问:
WPF Why are my Line objects not changing position?
I want to show two horizontal lines within a graphic. The Position of the Lines is depending on some data.
Therefor I created a ValueConverter (basically double to int). The Problems is, the lines are always shown in the same position.

I have to following XAML:

```<code>    <Window
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:CGM_Auswertung"
            xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit" x:Class="CGM_Auswertung.MainWindow"
            mc:Ignorable="d"
            Title="MainWindow" Height="780" Width="1300" Loaded="Window_Loaded">
        <Window.Resources>
            <local:DoubleToPositionConverter x:Key="DtPConverter"/>
        </Window.Resources>
        <Grid Name="MainGrid">
            <StackPanel Margin="10" Orientation="Vertical">
                <Button Name="OpenFile" Content="Öffnen" Height="30" Margin="550,0" Click="OpenFile_Click"/>
                <Grid x:Name="drawGrid" >
                    <TextBox Height="30" Width="40" HorizontalAlignment="Left" VerticalAlignment="Top" Text="{Binding OptMinimum}"/>
                    <Frame x:Name="drawFrame" HorizontalAlignment="Left" Height="420" Margin="40,10,10,50" VerticalAlignment="Top" Width="1210" BorderBrush="Black" BorderThickness="3">
                        <Frame.Content>
                            <Grid Name="contentGrid" Background="Transparent" >
                                <Line x:Name="MinLine" Stroke="Red" StrokeThickness="2" StrokeDashArray="2,2" X1="0" X2="1200" Y1="{Binding OptMinimum, Converter={StaticResource DtPConverter}}" Y2="{Binding OptMinimum, Converter={StaticResource DtPConverter}}"/>
                                <Line x:Name="MaxLine" Stroke="Red" StrokeThickness="2" StrokeDashArray="2,2" X1="0" X2="1200" Y1="{Binding OptMaximum, Converter={StaticResource DtPConverter}}" Y2="{Binding OptMaximum, Converter={StaticResource DtPConverter}}"/>
                                <Grid Name="vertLineGrid" MouseMove="tempLineGrid_MouseMove" Background="Transparent" HorizontalAlignment="Center" VerticalAlignment="Center" Height="394" Width="1183" MouseUp="ReleaseSelectedItem"/>
                            </Grid>
                        </Frame.Content>
...
</code>```

this is the converter:

```<code>namespace CGM_Auswertung
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            PropertyChanged?.Invoke(this, e);
        }
    }

    public class ViewModel : ViewModelBase
    {
        ...

        private double _optMinimum;
        public double OptMinimum
        {
            get { return _optMinimum; }
            set
            {
                _optMinimum = value;
                OnPropertyChanged(new PropertyChangedEventArgs("OptMinimum"));
            }
        }

        private double _optMaximum;
        public double OptMaximum
        {
            get { return _optMaximum; }
            set
            {
                _optMaximum = value;
                OnPropertyChanged(new PropertyChangedEventArgs("OptMaximum"));
            }
        }

    }

    public class DoubleToPositionConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (int)(Math.Abs(400 - (double)value * 20));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (double)(Math.Abs((double)value / 20 - 400 / 20));
        }
    }
}
</code>```

I also tried this before the converter:

```<code>[ValueConversion(typeof(double),typeof(int))]
</code>```

but it didn't change anything
And here is the start of my program:

```<code>namespace CGM_Auswertung
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private List<CGM_Measurement> completeMeasures = new List<CGM_Measurement>();
        private ViewModel mvm = new ViewModel() { MinimalValue = 0, MaximalValue=0, ActualValue=0};
        private UIElement selectedItem = null;

        public MainWindow()
        {
            mvm.FirstDay = mvm.LastDay = DateTime.Today;
            mvm.OverviewText = "Switch to day view";
            mvm.Visual = Visibility.Visible;
            mvm.VisualInverse = Visibility.Collapsed;
            mvm.OptMinimum = 2.0;
            mvm.OptMaximum = 3.0;

            InitializeComponent();

            MainGrid.DataContext = mvm;

        }
</code>```

I guess the problem is somewhere in the xaml, because when i set a breakpoint within my converter the convert is never called.

I guess because the conversion is so simple I could use another property within my viewmodel. But since im still learning about WPF I would like to do it with a value converter.

Thanks for your help.

答: Frame doesn't inherit DataContext of parent container (explained in this SO post). So contentGrid is missing source for its bindings. As a result bindings are not resolved and converter is not called. Try replace Frame with ContentControl or just remove it completely

Body:
I want to show two horizontal lines within a graphic. The Position of the Lines is depending on some data.
Therefor I created a ValueConverter (basically double to int). The Problems is, the lines are always shown in the same position.

I have to following XAML:

    <Window
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:CGM_Auswertung"
            xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit" x:Class="CGM_Auswertung.MainWindow"
            mc:Ignorable="d"
            Title="MainWindow" Height="780" Width="1300" Loaded="Window_Loaded">
        <Window.Resources>
            <local:DoubleToPositionConverter x:Key="DtPConverter"/>
        </Window.Resources>
        <Grid Name="MainGrid">
            <StackPanel Margin="10" Orientation="Vertical">
                <Button Name="OpenFile" Content="Öffnen" Height="30" Margin="550,0" Click="OpenFile_Click"/>
                <Grid x:Name="drawGrid" >
                    <TextBox Height="30" Width="40" HorizontalAlignment="Left" VerticalAlignment="Top" Text="{Binding OptMinimum}"/>
                    <Frame x:Name="drawFrame" HorizontalAlignment="Left" Height="420" Margin="40,10,10,50" VerticalAlignment="Top" Width="1210" BorderBrush="Black" BorderThickness="3">
                        <Frame.Content>
                            <Grid Name="contentGrid" Background="Transparent" >
                                <Line x:Name="MinLine" Stroke="Red" StrokeThickness="2" StrokeDashArray="2,2" X1="0" X2="1200" Y1="{Binding OptMinimum, Converter={StaticResource DtPConverter}}" Y2="{Binding OptMinimum, Converter={StaticResource DtPConverter}}"/>
                                <Line x:Name="MaxLine" Stroke="Red" StrokeThickness="2" StrokeDashArray="2,2" X1="0" X2="1200" Y1="{Binding OptMaximum, Converter={StaticResource DtPConverter}}" Y2="{Binding OptMaximum, Converter={StaticResource DtPConverter}}"/>
                                <Grid Name="vertLineGrid" MouseMove="tempLineGrid_MouseMove" Background="Transparent" HorizontalAlignment="Center" VerticalAlignment="Center" Height="394" Width="1183" MouseUp="ReleaseSelectedItem"/>
                            </Grid>
                        </Frame.Content>
...

this is the converter:

namespace CGM_Auswertung
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            PropertyChanged?.Invoke(this, e);
        }
    }

    public class ViewModel : ViewModelBase
    {
        ...

        private double _optMinimum;
        public double OptMinimum
        {
            get { return _optMinimum; }
            set
            {
                _optMinimum = value;
                OnPropertyChanged(new PropertyChangedEventArgs("OptMinimum"));
            }
        }

        private double _optMaximum;
        public double OptMaximum
        {
            get { return _optMaximum; }
            set
            {
                _optMaximum = value;
                OnPropertyChanged(new PropertyChangedEventArgs("OptMaximum"));
            }
        }

    }

    public class DoubleToPositionConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (int)(Math.Abs(400 - (double)value * 20));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (double)(Math.Abs((double)value / 20 - 400 / 20));
        }
    }
}

I also tried this before the converter:

[ValueConversion(typeof(double),typeof(int))]

but it didn't change anything
And here is the start of my program:

namespace CGM_Auswertung
{
    ///
    /// Interaktionslogik für MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {

        private List<CGM_Measurement> completeMeasures = new List<CGM_Measurement>();
        private ViewModel mvm = new ViewModel() { MinimalValue = 0, MaximalValue=0, ActualValue=0};
        private UIElement selectedItem = null;

        public MainWindow()
        {
            mvm.FirstDay = mvm.LastDay = DateTime.Today;
            mvm.OverviewText = "Switch to day view";
            mvm.Visual = Visibility.Visible;
            mvm.VisualInverse = Visibility.Collapsed;
            mvm.OptMinimum = 2.0;
            mvm.OptMaximum = 3.0;

            InitializeComponent();

            MainGrid.DataContext = mvm;

        }

I guess the problem is somewhere in the xaml, because when i set a breakpoint within my converter the convert is never called.

I guess because the conversion is so simple I could use another property within my viewmodel. But since im still learning about WPF I would like to do it with a value converter.

Thanks for your help.


问:
error C2280: 'QQmlPrivate::QQmlElement<T>::QQmlElement(void)': attempting to reference a deleted function
I tried to operate a part of a qt project in Qt\Examples\Qt-5.9\quick\views, I am new to qml and I am trying to open each time a different QDialog window depending on qml pathview component that has been clicked. First of all, I started with creating a class (interfacageQML) which will serve to interface the qml Mainform and the QDialog (qtinterface), the necessary files are included among which interfacageqml.h.

here is the main.cpp :

```<code>#include "interfacageqml.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    qmlRegisterType<interfacageQML>("Interfacage", 1, 0,"Component:MouseArea");

   QQmlApplicationEngine engine;
   engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

   return app.exec();
}
</code>```

And here's interfacageqml.h :

```<code>#ifndef INTERFACAGEQML_H
#define INTERFACAGEQML_H

#include <QObject>
#include "qtinterface.h"

class interfacageQML : public QObject
{
Q_OBJECT

public:
interfacageQML(QObject *parent);
~interfacageQML();

Q_INVOKABLE void mouseClick();

signals:
    void clicked();

};

#endif // INTERFACAGEQML_H
</code>```

interfacageqml.cpp :

```<code>#include "interfacageqml.h"
#include <QDebug>
#include <QApplication>

interfacageQML::interfacageQML(QObject *parent)
    : QObject(parent)
{

}

interfacageQML::~interfacageQML()
{

}

void interfacageQML::mouseClick()
{
    qDebug() << "qmlinterface::mouseClick()";
    emit clicked();
}
</code>```

My project is organised this way :

the qmlinterface.qrc file contains these paths:

main.qml :

```<code>import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MainForm{
        anchors.fill: parent
    }
}
</code>```

MainForm.qml :

```<code>import QtQuick 2.6
import QtQuick.Controls 2.0 as QQC2
import Interfacage 1.0

Rectangle {
    width: 800
    height: 800
    color: "white"

    ListModel {
        id: appModel
        ListElement {
            name: "Contacts"
            icon: "pics/Resources/AddressBook_48.png"
        }
        ListElement {
            name: "Music"
            icon: "pics/Resources/AudioPlayer_48.png"
        }
        ListElement {
            name: "Movies"
            icon: "pics/Resources/VideoPlayer_48.png"
        }
        ListElement {
            name: "Camera"
            icon: "pics/Resources/Camera_48.png"
        }
        ListElement {
            name: "Calendar"
            icon: "pics/Resources/DateBook_48.png"
        }
        ListElement {
            name: "Todo List"
            icon: "pics/Resources/TodoList_48.png"
        }
    }

    Component {
        id: appDelegate
        Item {
            width: 100
            height: 100
            scale: PathView.iconScale

            Image {
                id: myIcon
                y: 20
                anchors.horizontalCenter: parent.horizontalCenter
                source: icon
            }
            Text {
                anchors {
                    top: myIcon.bottom
                    horizontalCenter: parent.horizontalCenter
                }
                text: name
            }

            MouseArea {
                anchors.fill: parent
                onClicked: {
                    view.currentIndex = index
                    Interfacage.mouseClick
                }
            }
        }
    }

    Component {
        id: appHighlight
        Rectangle {
            width: 100
            height: 80
            color: "lightsteelblue"
        }
    }

    PathView {
        id: view
        anchors.fill: parent
        highlight: appHighlight
        preferredHighlightBegin: 0.5
        preferredHighlightEnd: 0.5
        focus: true
        model: appModel
        delegate: appDelegate
        path: Path {
            startX: 50
            startY: 80
            PathAttribute {
                name: "iconScale"
                value: 2.0
            }
            PathQuad {
                x: 250
                y: 200
                controlX: 50
                controlY: 200
            }
            PathAttribute {
                name: "iconScale"
                value: 2.0
            }
            PathQuad {
                x: 600
                y: 50
                controlX: 400
                controlY: 200
            }
            PathAttribute {
                name: "iconScale"
                value: 2.0
            }
        }
    }
}
</code>```

When I run this project, i got an error :

error:C2280

However, when I comment this line : qmlRegisterType<interfacageQML>("Interfacage", 1, 0, "Component:MouseArea"); the project runs and I can navigate between the pathview components in the MainForm.

答:
When you use qmlRegisterType you are registering a new data type in QML, it is not an object, in that case the name "Component: MouseArea" is not suitable.

```<code>qmlRegisterType<interfacageQML>("Interfacage", 1, 0, "InterfacageQML");
</code>```

Another error is that you must pass a parent by default, in this case 0 or nullptr since the items may not have parents.

```<code>class interfacageQML : public QObject
{
    Q_OBJECT
public:
    explicit interfacageQML(QObject *parent = nullptr);
    [...]
</code>```

As I said in the first lines, this is a new type, it is not an object so you must create it.

```<code>import QtQuick 2.6
import QtQuick.Controls 2.0 as QQC2
import Interfacage 1.0

Rectangle {
    width: 800
    height: 800
    color: "white"

    InterfacageQML{
        id: myitem
    }
    [...]
</code>```

And in the end if you want to use it you must call the function through the item.

```<code>MouseArea {
    anchors.fill: parent
    onClicked: {
        view.currentIndex = index
        myitem.mouseClick()
    }
}
</code>```

Since you want to connect your QDialog with the QML through that class, you can not do it since they will be different objects, one solution for this is to use a singleton, for this you must do the following:

interfacageqml.h

```<code>#ifndef INTERFACAGEQML_H
#define INTERFACAGEQML_H

#include <QObject>
#include <QQmlEngine>

class interfacageQML : public QObject
{
    Q_OBJECT
    static interfacageQML* instance;
    explicit interfacageQML(QObject *parent = nullptr);
public:
    static interfacageQML *getInstance();
    ~interfacageQML();
    Q_INVOKABLE void mouseClick();

signals:
    void clicked();
};
#endif // INTERFACAGEQML_H
</code>```

interfacageqml.cpp

```<code>#include "interfacageqml.h"
#include <QDebug>

interfacageQML* interfacageQML::instance = 0;

interfacageQML *interfacageQML::getInstance()
{
    if (instance == 0)
        instance = new interfacageQML;
    return instance;
}

interfacageQML::interfacageQML(QObject *parent) : QObject(parent)
{
}

interfacageQML::~interfacageQML()
{
}

void interfacageQML::mouseClick()
{
    qDebug() << "qmlinterface::mouseClick()";
    emit clicked();
}
</code>```

main.cpp

```<code>#include "interfacageqml.h"

#include <QGuiApplication>
#include <QQmlApplicationEngine>

static QObject *singletonTypeProvider(QQmlEngine *, QJSEngine *)
{

    return interfacageQML::getInstance();
}

int main(int argc, char *argv[])
{
    qmlRegisterSingletonType<interfacageQML>("Interfacage", 1, 0, "InterfacageQML", singletonTypeProvider);

    // test
    interfacageQML *obj = qobject_cast<interfacageQML*>(interfacageQML::getInstance());
    QObject::connect(obj, &interfacageQML::clicked,[]{
        qDebug()<<"clicked";
    });

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}
</code>```

As it is a singleton it is not necessary to create an item, you can do it directly:

```<code>import Interfacage 1.0
[...]
MouseArea {
    anchors.fill: parent
    onClicked: {
        view.currentIndex = index
        InterfacageQML.mouseClick()
    }
}
</code>```

This last example can be found in the following link.

Body:
I tried to operate a part of a qt project in Qt\Examples\Qt-5.9\quick\views, I am new to qml and I am trying to open each time a different QDialog window depending on qml pathview component that has been clicked. First of all, I started with creating a class (interfacageQML) which will serve to interface the qml Mainform and the QDialog (qtinterface), the necessary files are included among which interfacageqml.h.

here is the main.cpp :

#include "interfacageqml.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    qmlRegisterType<interfacageQML>("Interfacage", 1, 0,"Component:MouseArea");

   QQmlApplicationEngine engine;
   engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

   return app.exec();
}

And here's interfacageqml.h :

#ifndef INTERFACAGEQML_H
#define INTERFACAGEQML_H

#include <QObject>
#include "qtinterface.h"

class interfacageQML : public QObject
{
Q_OBJECT

public:
interfacageQML(QObject *parent);
~interfacageQML();

Q_INVOKABLE void mouseClick();

signals:
    void clicked();

};

#endif // INTERFACAGEQML_H

interfacageqml.cpp :

#include "interfacageqml.h"
#include <QDebug>
#include <QApplication>

interfacageQML::interfacageQML(QObject *parent)
    : QObject(parent)
{

}

interfacageQML::~interfacageQML()
{

}

void interfacageQML::mouseClick()
{
    qDebug() << "qmlinterface::mouseClick()";
    emit clicked();
}

My project is organised this way :

the qmlinterface.qrc file contains these paths:

main.qml :

import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MainForm{
        anchors.fill: parent
    }
}

MainForm.qml :

import QtQuick 2.6
import QtQuick.Controls 2.0 as QQC2
import Interfacage 1.0

Rectangle {
    width: 800
    height: 800
    color: "white"

    ListModel {
        id: appModel
        ListElement {
            name: "Contacts"
            icon: "pics/Resources/AddressBook_48.png"
        }
        ListElement {
            name: "Music"
            icon: "pics/Resources/AudioPlayer_48.png"
        }
        ListElement {
            name: "Movies"
            icon: "pics/Resources/VideoPlayer_48.png"
        }
        ListElement {
            name: "Camera"
            icon: "pics/Resources/Camera_48.png"
        }
        ListElement {
            name: "Calendar"
            icon: "pics/Resources/DateBook_48.png"
        }
        ListElement {
            name: "Todo List"
            icon: "pics/Resources/TodoList_48.png"
        }
    }

    Component {
        id: appDelegate
        Item {
            width: 100
            height: 100
            scale: PathView.iconScale

            Image {
                id: myIcon
                y: 20
                anchors.horizontalCenter: parent.horizontalCenter
                source: icon
            }
            Text {
                anchors {
                    top: myIcon.bottom
                    horizontalCenter: parent.horizontalCenter
                }
                text: name
            }

            MouseArea {
                anchors.fill: parent
                onClicked: {
                    view.currentIndex = index
                    Interfacage.mouseClick
                }
            }
        }
    }

    Component {
        id: appHighlight
        Rectangle {
            width: 100
            height: 80
            color: "lightsteelblue"
        }
    }

    PathView {
        id: view
        anchors.fill: parent
        highlight: appHighlight
        preferredHighlightBegin: 0.5
        preferredHighlightEnd: 0.5
        focus: true
        model: appModel
        delegate: appDelegate
        path: Path {
            startX: 50
            startY: 80
            PathAttribute {
                name: "iconScale"
                value: 2.0
            }
            PathQuad {
                x: 250
                y: 200
                controlX: 50
                controlY: 200
            }
            PathAttribute {
                name: "iconScale"
                value: 2.0
            }
            PathQuad {
                x: 600
                y: 50
                controlX: 400
                controlY: 200
            }
            PathAttribute {
                name: "iconScale"
                value: 2.0
            }
        }
    }
}

When I run this project, i got an error :

error:C2280

However, when I comment this line : qmlRegisterType<interfacageQML>("Interfacage", 1, 0, "Component:MouseArea"); the project runs and I can navigate between the pathview components in the MainForm.

Body:
When you use qmlRegisterType you are registering a new data type in QML, it is not an object, in that case the name "Component: MouseArea" is not suitable.

qmlRegisterType<interfacageQML>("Interfacage", 1, 0, "InterfacageQML");

Another error is that you must pass a parent by default, in this case 0 or nullptr since the items may not have parents.

class interfacageQML : public QObject
{
    Q_OBJECT
public:
    explicit interfacageQML(QObject *parent = nullptr);
    [...]

As I said in the first lines, this is a new type, it is not an object so you must create it.

import QtQuick 2.6
import QtQuick.Controls 2.0 as QQC2
import Interfacage 1.0

Rectangle {
    width: 800
    height: 800
    color: "white"

    InterfacageQML{
        id: myitem
    }
    [...]

And in the end if you want to use it you must call the function through the item.

MouseArea {
    anchors.fill: parent
    onClicked: {
        view.currentIndex = index
        myitem.mouseClick()
    }
}

Since you want to connect your QDialog with the QML through that class, you can not do it since they will be different objects, one solution for this is to use a singleton, for this you must do the following:

interfacageqml.h

#ifndef INTERFACAGEQML_H
#define INTERFACAGEQML_H

#include <QObject>
#include <QQmlEngine>

class interfacageQML : public QObject
{
    Q_OBJECT
    static interfacageQML* instance;
    explicit interfacageQML(QObject *parent = nullptr);
public:
    static interfacageQML *getInstance();
    ~interfacageQML();
    Q_INVOKABLE void mouseClick();

signals:
    void clicked();
};
#endif // INTERFACAGEQML_H

interfacageqml.cpp

#include "interfacageqml.h"
#include <QDebug>

interfacageQML* interfacageQML::instance = 0;

interfacageQML *interfacageQML::getInstance()
{
    if (instance == 0)
        instance = new interfacageQML;
    return instance;
}

interfacageQML::interfacageQML(QObject *parent) : QObject(parent)
{
}

interfacageQML::~interfacageQML()
{
}

void interfacageQML::mouseClick()
{
    qDebug() << "qmlinterface::mouseClick()";
    emit clicked();
}

main.cpp

#include "interfacageqml.h"

#include <QGuiApplication>
#include <QQmlApplicationEngine>

static QObject *singletonTypeProvider(QQmlEngine *, QJSEngine *)
{

    return interfacageQML::getInstance();
}

int main(int argc, char *argv[])
{
    qmlRegisterSingletonType<interfacageQML>("Interfacage", 1, 0, "InterfacageQML", singletonTypeProvider);

    // test
    interfacageQML *obj = qobject_cast<interfacageQML*>(interfacageQML::getInstance());
    QObject::connect(obj, &interfacageQML::clicked,[]{
        qDebug()<<"clicked";
    });

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

As it is a singleton it is not necessary to create an item, you can do it directly:

import Interfacage 1.0
[...]
MouseArea {
    anchors.fill: parent
    onClicked: {
        view.currentIndex = index
        InterfacageQML.mouseClick()
    }
}

This last example can be found in the following link.