问:
Template not reactive in meteor on adding new data?
This are the event listeners for my two templates,specified in events.js

```<code>// event listeners on the addSiteForm template
Template.addCommentForm.events({
    // this runs when they click the add button... you need to compete it
 'click .js-add-comment':function(event){
     var comment_text = $('#comment_input').val();// get the form value using jquery...
     var user = 'anonymous person';
     // the 'this' variable contains
     // the data that this template is displaying
     // which is the Website item
     var site = this;
     if (Meteor.user()){
         user = Meteor.user().emails[0].address
     }
     var comment = {"text":comment_text,
                    "siteId":site._id,
                 "createdOn":new Date(),
                 "createdBy":user};// create a simple object to insert to the collectoin
    Comments.insert(comment);
     console.log("events start");
     console.log("totla coomets are "+Comments.find({}).count()+"\n");
     console.log("commenst in site "+Comments.find({siteId:site._id}).count()+"\n");
     console.log("site id is "+site._id);
     console.log("events end");

     return false;
 }
});

// event listeners on the addSiteForm template
Template.addSiteForm.events({
    // this runs when they click the add button... you need to compete it
 'click .js-add-site':function(event){
     var url = $('#url_input').val();// get the form value using jquery...
     var user = 'anonymous person';
     if (Meteor.user()){
         user = Meteor.user().emails[0].address
     }
     var site = {"url":url,
                 "createdOn":new Date(),
                 "createdBy":user};// create a simple object to insert to the collectoin
     Websites.insert(site);
     return false;
 }
});
</code>```

The router function is specified in router.js

```<code>Router.configure({
  layoutTemplate: 'ApplicationLayout'
});

// the main route. showing the list of sites.
Router.route('/', function () {
  this.render('siteList');
});

// this route is for the discussion page for a site
Router.route('/discussSite/:_id', function () {
    var siteId = this.params._id;
    site = Websites.findOne({_id:siteId});
    this.render('discussSite', {data:site});
});
</code>```

the main.js contain the collections
// shared code

```<code>Websites = new Mongo.Collection("websites");
Comments = new Mongo.Collection("comments");
</code>```

helpers is

```<code>// this helper gets the data from the collection for the site-list Template
Template.siteList.helpers({
    'all_websites':function(){
        return Websites.find({});
    },
    'safer_email':function(email){
        if (email.indexOf('@')!=-1){// we have an email
            return email.split('@')[0];
        }
        else{// probably anonymouse.
            return email;
        }
    }
});

Template.discussSite.helpers({

'comments':function(siteId){
//console.log("helper comments "+this.site);
// complete the code here so that it reruns

    console.log(this.params.site._id);
return Comments.find({siteId:siteId});

// all the comments with a siteId equal to siteId.

}

});
</code>```

the html file is in main.html.here it first displays the websites available in the webpage.On clicking this the user is routed to a new page.Here the user can add comments for the website

```<code><head>
  <title>week_4_peer_assessment</title>
</head>

<body>
</body>

<!-- this is the template that iron:router renders every time -->
<template name="ApplicationLayout">
    <div class="container">
        <a href="/">Home</a>
        {{>loginButtons}}
        <h1>SiteAce - discuss your favourite websites</h1>
        <!-- iron router will select what to render in place of yield-->
        {{> yield }}
    </div>
</template>

<template name="discussSite">
    <h3>Discussing: {{url}} </h3>
    {{> addCommentForm}}

    <!-- write some code here that iterates through the comments and displays
    the comment text and the author -->
    <!-- clue - you have already written the 'comments' helper function -->

    <ul>
    {{#each comments}}
    <li>{{text}} (added by {{safer_email createdBy}})

    </li>
    {{/each}}
    </ul>

</template>

<template name="addCommentForm">
<div class="row">
  <div class="col-lg-6">
    <div class="input-group">
      <input type="text" id="comment_input" class="form-control" placeholder="Enter your comment">
      <input type="hidden" id="site_id" class="form-control" placeholder="Enter your comment">

      <span class="input-group-btn">
        <button class="btn btn-default js-add-comment" type="submit">Add!</button>
      </span>
    </div><!-- /input-group -->
  </div><!-- /.col-lg-6 -->
</div>
</template>

<template name="siteList">
    Fill in the form and click submit to add a site:

    {{>addSiteForm}}

    <h3>Sites you have added:</h3>
    <ul>
    {{#each all_websites}}
    <li>{{url}} (added by {{safer_email createdBy}})
        <br/><a href="/discussSite/{{_id}}">discuss</a>
        <br/><a href="{{url}}">visit site</a>
    </li>
    {{/each}}
    </ul>
</template>

<template name="addSiteForm">
<div class="row">
  <div class="col-lg-6">
    <div class="input-group">
      <input type="text" id="url_input" class="form-control" placeholder="Enter website URL...">
      <span class="input-group-btn">
        <button class="btn btn-default js-add-site" type="submit">Add!</button>
      </span>
    </div><!-- /input-group -->
  </div><!-- /.col-lg-6 -->
</div>
</template>
</code>```

The starup.js contains the start up code run by the server

```<code>  Meteor.startup(function(){
    if (!Websites.findOne()){// nothing in the database yet
        var site = {"url":"http://www.google.com",
                    "createdOn":new Date(),
                    "createdBy":"Michael"};// create a simple object to insert to the collectoin
        Websites.insert(site);
        site = {"url":"http://www.yeeking.net",
                    "createdOn":new Date(),
                    "createdBy":"Janet"};// create a simple object to insert to the collectoin
        Websites.insert(site);
        site = {"url":"http://www.coursera.org",
                    "createdOn":new Date(),
                    "createdBy":"Jose"};// create a simple object to insert to the collectoin
        Websites.insert(site);
    }

});
</code>```

答:
This is what your template should be: (I removed safer_email. It was erroring. Not sure if it was something else you were working on.)

```<code><template name="discussSite">
    <h3>Discussing: {{url}} </h3>
    {{> addCommentForm}}

    <!-- write some code here that iterates through the comments and displays
    the comment text and the author -->
    <!-- clue - you have already written the 'comments' helper function -->
    <ul>
    {{#each comments}}

    <li>{{text}} (added by {{createdBy}})</li>
    {{/each}}
    </ul>

</template>
</code>```

helper:

your helper function is designed to take in siteId as an input, yet you are not passing one to it.

this._id or Router.current().params._id will get you the siteId that you are looking for. You'd used this.site._id which used to error out as this.site was not valid.You can further see what the this object contains by doing a console.log(this). That would have helped you sort this out faster.

```<code>'comments':function(){

    console.log("site id in helper is ",this._id); // or Router.current().params._id;
    console.log(Comments.find({siteId:this._id}).fetch());
    return Comments.find({siteId:this._id});
}
</code>```

Body:
This are the event listeners for my two templates,specified in events.js

// event listeners on the addSiteForm template
Template.addCommentForm.events({
    // this runs when they click the add button... you need to compete it
 'click .js-add-comment':function(event){
     var comment_text = $('#comment_input').val();// get the form value using jquery...
     var user = 'anonymous person';
     // the 'this' variable contains
     // the data that this template is displaying
     // which is the Website item
     var site = this;
     if (Meteor.user()){
         user = Meteor.user().emails[0].address
     }
     var comment = {"text":comment_text,
                    "siteId":site._id,
                 "createdOn":new Date(),
                 "createdBy":user};// create a simple object to insert to the collectoin
    Comments.insert(comment);
     console.log("events start");
     console.log("totla coomets are "+Comments.find({}).count()+"\n");
     console.log("commenst in site "+Comments.find({siteId:site._id}).count()+"\n");
     console.log("site id is "+site._id);
     console.log("events end");

     return false;
 }
});

// event listeners on the addSiteForm template
Template.addSiteForm.events({
    // this runs when they click the add button... you need to compete it
 'click .js-add-site':function(event){
     var url = $('#url_input').val();// get the form value using jquery...
     var user = 'anonymous person';
     if (Meteor.user()){
         user = Meteor.user().emails[0].address
     }
     var site = {"url":url,
                 "createdOn":new Date(),
                 "createdBy":user};// create a simple object to insert to the collectoin
     Websites.insert(site);
     return false;
 }
});

The router function is specified in router.js

Router.configure({
  layoutTemplate: 'ApplicationLayout'
});

// the main route. showing the list of sites.
Router.route('/', function () {
  this.render('siteList');
});

// this route is for the discussion page for a site
Router.route('/discussSite/:_id', function () {
    var siteId = this.params._id;
    site = Websites.findOne({_id:siteId});
    this.render('discussSite', {data:site});
});

the main.js contain the collections
// shared code

Websites = new Mongo.Collection("websites");
Comments = new Mongo.Collection("comments");

helpers is

// this helper gets the data from the collection for the site-list Template
Template.siteList.helpers({
    'all_websites':function(){
        return Websites.find({});
    },
    'safer_email':function(email){
        if (email.indexOf('@')!=-1){// we have an email
            return email.split('@')[0];
        }
        else{// probably anonymouse.
            return email;
        }
    }
});

Template.discussSite.helpers({

'comments':function(siteId){
//console.log("helper comments "+this.site);
// complete the code here so that it reruns

    console.log(this.params.site._id);
return Comments.find({siteId:siteId});

// all the comments with a siteId equal to siteId.

}

});

the html file is in main.html.here it first displays the websites available in the webpage.On clicking this the user is routed to a new page.Here the user can add comments for the website

  <title>week_4_peer_assessment</title>

<template name="ApplicationLayout">

        Home
        {{>loginButtons}}

SiteAce - discuss your favourite websites

        {{> yield }}

</template>

<template name="discussSite">

Discussing: {{url}}

    {{> addCommentForm}}

    {{#each comments}}

{{text}} (added by {{safer_email createdBy}})

    {{/each}}

</template>

<template name="addCommentForm">

      <input type="text" id="comment_input" class="form-control" placeholder="Enter your comment">
      <input type="hidden" id="site_id" class="form-control" placeholder="Enter your comment">

        <button class="btn btn-default js-add-comment" type="submit">Add!</button>

</template>

<template name="siteList">
    Fill in the form and click submit to add a site:

    {{>addSiteForm}}

Sites you have added:

    {{#each all_websites}}

{{url}} (added by {{safer_email createdBy}})

discuss

visit site

    {{/each}}

</template>

<template name="addSiteForm">

      <input type="text" id="url_input" class="form-control" placeholder="Enter website URL...">

        <button class="btn btn-default js-add-site" type="submit">Add!</button>

</template>

The starup.js contains the start up code run by the server

  Meteor.startup(function(){
    if (!Websites.findOne()){// nothing in the database yet
        var site = {"url":"http://www.google.com",
                    "createdOn":new Date(),
                    "createdBy":"Michael"};// create a simple object to insert to the collectoin
        Websites.insert(site);
        site = {"url":"http://www.yeeking.net",
                    "createdOn":new Date(),
                    "createdBy":"Janet"};// create a simple object to insert to the collectoin
        Websites.insert(site);
        site = {"url":"http://www.coursera.org",
                    "createdOn":new Date(),
                    "createdBy":"Jose"};// create a simple object to insert to the collectoin
        Websites.insert(site);
    }

});

Body:
This is what your template should be: (I removed safer_email. It was erroring. Not sure if it was something else you were working on.)

<template name="discussSite">
    <h3>Discussing: {{url}} </h3>
    {{> addCommentForm}}

    <!-- write some code here that iterates through the comments and displays
    the comment text and the author -->
    <!-- clue - you have already written the 'comments' helper function -->
    <ul>
    {{#each comments}}

    <li>{{text}} (added by {{createdBy}})</li>
    {{/each}}
    </ul>

</template>

helper:

your helper function is designed to take in siteId as an input, yet you are not passing one to it.

this._id or Router.current().params._id will get you the siteId that you are looking for. You'd used this.site._id which used to error out as this.site was not valid.You can further see what the this object contains by doing a console.log(this). That would have helped you sort this out faster.

'comments':function(){

    console.log("site id in helper is ",this._id); // or Router.current().params._id;
    console.log(Comments.find({siteId:this._id}).fetch());
    return Comments.find({siteId:this._id});
}


来源: stackexchange

问:
Batch script: local variable from function1 to function2
Okay guys, let my try to explain my problem:

I start with a line from where I start 2 different functions

```<code>setlocal EnableDelayedExpansion
for %%i in ("C:\*.*") do (
call :function1 "%%~i"
call :function2 "%%~i"
)
goto :eof
</code>```

In function1, at a certain point I DO a SET in a local environment:

```<code>setlocal EnableDelayedExpansion
...
...
set name1=blabla
endlocal  & SET name=%name1%
echo %name%
goto :eof
</code>```

The echo does return my variable. Now onto my problem.
I quit function one and i go to function 2 (see first code-segment)
I can't call the variable form here. I tried in the function2, I tried before function2 is called, but both didn't resolve the issue.

My guess is a have set only a local variable for function1. I search the nets but i read that the line "endlocal  & SET name=%name1%" should have solved my issue.

I hope I have explained it well, all help appreciated!

答:
First a small working sample

```<code>@echo off
setlocal EnableDelayedExpansion

call :myAdd returnVar 1 2
echo 1. Percent %returnVar%
echo 1. Exlcam  !returnVar!

(
call :myAdd returnVar 4 5
echo 2. Percent %returnVar%
echo 2. Exlcam  !returnVar!
)
goto :eof

:myAdd
setlocal
set /a result=%2 + %3

(
  endlocal
  set %1=%result%
  goto :eof
)

---- Output ----
1. Percent 3
1. Exlcam  3
2. Percent 3
2. Exlcam  9
</code>```

The cause for the wrong result in "2. Percent" is a result of the expanding of %var%.

They are expanded at the time of parsing, before executing any line of the parenthesis block, so there is the old value in returnVar.

But that is also the cause why the returning of variables from a function works.

the endlocal removes all local variables, but the block (an ampersand works the same way)
is expanded before the "endlocal" is executed.

It's a good idea to test this issues with "echo on".

ContentLicense: CC BY-SA 2.5

Body:
Okay guys, let my try to explain my problem:

I start with a line from where I start 2 different functions

setlocal EnableDelayedExpansion
for %%i in ("C:\*.*") do (
call :function1 "%%~i"
call :function2 "%%~i"
)
goto :eof

In function1, at a certain point I DO a SET in a local environment:

setlocal EnableDelayedExpansion
...
...
set name1=blabla
endlocal  & SET name=%name1%
echo %name%
goto :eof

The echo does return my variable. Now onto my problem.
I quit function one and i go to function 2 (see first code-segment)
I can't call the variable form here. I tried in the function2, I tried before function2 is called, but both didn't resolve the issue.

My guess is a have set only a local variable for function1. I search the nets but i read that the line "endlocal  & SET name=%name1%" should have solved my issue.

I hope I have explained it well, all help appreciated!

Body:
First a small working sample

@echo off
setlocal EnableDelayedExpansion

call :myAdd returnVar 1 2
echo 1. Percent %returnVar%
echo 1. Exlcam  !returnVar!

(
call :myAdd returnVar 4 5
echo 2. Percent %returnVar%
echo 2. Exlcam  !returnVar!
)
goto :eof

:myAdd
setlocal
set /a result=%2 + %3

(
  endlocal
  set %1=%result%
  goto :eof
)

---- Output ----
1. Percent 3
1. Exlcam  3
2. Percent 3
2. Exlcam  9

The cause for the wrong result in "2. Percent" is a result of the expanding of %var%.

They are expanded at the time of parsing, before executing any line of the parenthesis block, so there is the old value in returnVar.

But that is also the cause why the returning of variables from a function works.

the endlocal removes all local variables, but the block (an ampersand works the same way)
is expanded before the "endlocal" is executed.

It's a good idea to test this issues with "echo on".


问:
CompileDebugJavawithJavac
I am trying to develop an app which has a fingerprint security before getting to the actual webview.
I keep getting the error compileDebugjavawithjavac

Link

答:
In line 22 you have unnecessary public declaration.
Delete line 22: public to {. The package statement is needed.

I recommend reading https://docs.oracle.com/javase/tutorial/java/javaOO/index.html

ContentLicense: CC BY-SA 3.0

Title: CompileDebugJavawithJavac


问:
How to get current Workflow XML for active Instance by the Rest API
In my AngularApp i will show the User the current Workflow, by using the REST API.
No Problem so far, usnig:

GET /process-definition/{id}/xml

and the

bpmn.io Viewer.

But it's possible to highlight the current Task or get the special Instance of the Workflow, with highlight the current Task?

Thank you for your help.

答:
1. Get actual the task

The call http://localhost:8080/engine-rest/task/?processInstanceId=<processInstanceId> return a json with the taskDefinitionKey.

https://docs.camunda.org/manual/latest/reference/rest/task/get-query/

2. Style the task

You can add a style class and so highlight a task.

```<code>viewer.importXML(diagramXML, function() {
    var canvas = viewer.get('canvas');
    canvas.addMarker('<<TaskId>>', 'highlight');
});
</code>```

CSS for the color:

```<code>.highlight:not(.djs-connection) .djs-visual > :nth-child(1) {
    fill: green !important; /* color elements as green */
}
</code>```

The example is from https://github.com/bpmn-io/bpmn-js-examples/tree/master/colors#adding-colors

Body:
1. Get actual the task

The call http://localhost:8080/engine-rest/task/?processInstanceId=<processInstanceId> return a json with the taskDefinitionKey.

https://docs.camunda.org/manual/latest/reference/rest/task/get-query/

2. Style the task

You can add a style class and so highlight a task.

viewer.importXML(diagramXML, function() {
    var canvas = viewer.get('canvas');
    canvas.addMarker('<<TaskId>>', 'highlight');
});

CSS for the color:

.highlight:not(.djs-connection) .djs-visual > :nth-child(1) {
    fill: green !important; /* color elements as green */
}

The example is from https://github.com/bpmn-io/bpmn-js-examples/tree/master/colors#adding-colors


问:
How to monitor memory usage and build scalable java web server?
We are writing a web application with Java, which is served as chat room server powered by WebSocket. We design the server structure properly so that we can run multiple identical server instance to support massive connection and communication. The problem is that we can't scale the servers cluster dynamically. Ideally, any slave node should monitor its memory usage and notify the dedicated master node when it can't accept more connection. Now the web application simply crashes when too much connections come in rapidly. Are there any solution (or idea) to improve the situation?</p>

答:
Try utilizing a tool like JProfiler or IntelliJ for noticing how your application behaves in overloaded situations, also it can help you in noticing if you ave some threads which aren't garbage collected and so much more.
A tool like the ones mentioned above can check the load on your webserver or jvm, however your application is deployed to identify if there's any need to expand hardware or just an application correction would suffice.

A tool to overload the application would be Jmeter that'd help you do the stress testing for long periods of times.


问:
returning result of a function multiple times within the same function
I am trying to return a list of numbers that add up to 100 .. 11 times.

There are 3 numbers which are generated from a numpy random uniform distribution.

I want to add an if statement to see if the 1st, 2nd and 3rd numbers of each list (11 in total).. if plotted would have a Pearson correlation coefficient of >0.99.

At the moment, I am only able to generate 1 list of numbers which have a sum equal to 100.

I have following code:

```<code>import math
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

c1_high = 98
c1_low = 75
c2_high = 15
c2_low = 6
c3_high = 8
c3_low = 2

def mix_gen():
    while True:
        c1 = np.random.uniform(c1_low, c1_high)
        c2 = np.random.uniform(c2_low, c2_high)
        c3 = np.random.uniform(c3_low, c3_high)
        tot = c1+c2+c3

        if 99.99<= tot <=100.01:
            comp_list = [c1,c2,c3]
            return comp_list

my_list = mix_gen()
print(my_list)
</code>```

so if i was to plot each component.. for example c1... i would get an R^2 value of >0.99.

I'm stuck at generating multiple lists inside the same function. I know this can be done outside the function.. using [mix_gen() for _ in range(11)].. but this will not work because I require this additional check of the peasron corr coeff before returning the 11 lists.

OBJECTIVE:

to return a dataframe with the following values:

```<code>   C1    C2    C3    sum
1   70    20    10    100
2   ..
3   ..
4   ..
5   ..
6   ..
7   ..
8   ..
9   ..
10  ..
11  90
R^2  1     1     1
</code>```

答:
This can be an option using a list of lists for the return

```<code>def mix_gen(number):
    flag = 0
    container = []
    while flag < number:
        c1 = np.random.uniform(c1_low, c1_high)
        c2 = np.random.uniform(c2_low, c2_high)
        c3 = np.random.uniform(c3_low, c3_high)
        tot = c1+c2+c3

        if 99.99 <= tot <= 100.01:
            flag += 1
            container.append([c1,c2,c3])

    return container
</code>```

You call it with

```<code>my_list_of_lists = mix_gen(11)
</code>```

Body:
I am trying to return a list of numbers that add up to 100 .. 11 times.

There are 3 numbers which are generated from a numpy random uniform distribution.

I want to add an if statement to see if the 1st, 2nd and 3rd numbers of each list (11 in total).. if plotted would have a Pearson correlation coefficient of >0.99.

At the moment, I am only able to generate 1 list of numbers which have a sum equal to 100.

I have following code:

import math
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

c1_high = 98
c1_low = 75
c2_high = 15
c2_low = 6
c3_high = 8
c3_low = 2

def mix_gen():
    while True:
        c1 = np.random.uniform(c1_low, c1_high)
        c2 = np.random.uniform(c2_low, c2_high)
        c3 = np.random.uniform(c3_low, c3_high)
        tot = c1+c2+c3

        if 99.99<= tot <=100.01:
            comp_list = [c1,c2,c3]
            return comp_list

my_list = mix_gen()
print(my_list)

so if i was to plot each component.. for example c1... i would get an R^2 value of >0.99.

I'm stuck at generating multiple lists inside the same function. I know this can be done outside the function.. using [mix_gen() for _ in range(11)].. but this will not work because I require this additional check of the peasron corr coeff before returning the 11 lists.

OBJECTIVE:

to return a dataframe with the following values:

   C1    C2    C3    sum
1   70    20    10    100
2   ..
3   ..
4   ..
5   ..
6   ..
7   ..
8   ..
9   ..
10  ..
11  90
R^2  1     1     1

Body:
This can be an option using a list of lists for the return

def mix_gen(number):
    flag = 0
    container = []
    while flag < number:
        c1 = np.random.uniform(c1_low, c1_high)
        c2 = np.random.uniform(c2_low, c2_high)
        c3 = np.random.uniform(c3_low, c3_high)
        tot = c1+c2+c3

        if 99.99 <= tot <= 100.01:
            flag += 1
            container.append([c1,c2,c3])

    return container

You call it with

my_list_of_lists = mix_gen(11)


问:
Get all numbers starting with 104* including the next line associated with some texts or spaces
I am trying to get all the possible order numbers for example on a given chunk of text. Order number usually starts with 104* and character limit 0f 10. However I was not able to get my desired outcome.

Here is the sample chunk of text.

05.12.17 PRZELEW PRZYCHODZACY 05.12.17 1,408.10
 Referencje : PL0INE117339IZFN
 Nr Ref: 4339429172
 Tytuł Płatnosci: 400481
  1048432317, 400470 104843231
 6
 Kontr. : GDANSKDIS SP. Z O.O.
  UL. OBRONCÓW
 WYBRZEZA 1 80-398 GDANSK POLAND
 Nr Banku:
  18400007 SG Centrala
 Nr Rachunku: 31184000072413423008101119

  Data Stempla 171205
 Kwota Przekazu: 1,408.10 PLN Info Code;
  0002794237

Some input are like these:

05.12.17 PRZELEW PRZYCHODZACY 05.12.17 316,082.18
 Referencje : PL0INE117339BHBU
 Nr Ref: 4339079115
 Tytuł Płatnosci: ID
  0001817374 ZA1048418311 1
 0484240771048423894 10484238
 95AWIZO
  Z DNIA 05.12.17
 Kontr. : ZABKA POLSKA SPÓŁKA AKCYJNA
 PL
  ANDERSA 7
 61-894 POZNAN
 Nr Banku: 12402076 PEKAO Centrum
  Rozliczeniow
 Nr Rachunku: 94124017471111001003042253
 Data
  Stempla 171205
 Kwota Przekazu: 316,082.18 PLN

Also like this:

05.12.17 PRZELEW PRZYCHODZACY 05.12.17 999,429.47
 Referencje : PL0INE117339LJBU
 Nr Ref: 4339548267
 Tytuł Płatnosci:
  PY01832649 1048432358 1048432351 10
 48432466 1048432560 1048432594
  1048
 432267 1048432353 1048432450 104843
 2360 1048432577
  1048432391/KOR
 Kontr. : EUROCASH S.A.
 UL. WISNIOWA 11

  62-052 KOMORNIKI
 Nr Banku: 10500028 ING Bank Slaski S.A.
 Nr
  Rachunku: 73105000861000002334209315
 Data Stempla 171205
 Kwota
  Przekazu: 999,429.47 PLN
 Info Code; 0000193176

The code I used is simple as this: \b104\d*

My result from the first input was:

1048432317

and

104843231

The last result was lacking in number as you can see, the last digit was in the next line.

My expected result is a regex that will able to extract all those order numbers without getting cut because the next digit was on the next line or sometimes order number getting cut.

答:
You don't need regex, you can do that with simple string methods and readable LINQ:

```<code>List<string> orderNumberList = text.Replace(Environment.NewLine, "")
  .Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries)
  .Where(word => word.StartsWith("104") && word.Length <= 10)
  .ToList();
</code>```

Your sample text blocks contain these 10 numbers:

```<code>    [0] "1048432358"
    [1] "1048432351"
    [2] "1048432466"
    [3] "1048432560"
    [4] "1048432594"
    [5] "1048432267"
    [6] "1048432353"
    [7] "1048432450"
    [8] "1048432360"
    [9] "1048432577"
</code>```

Edit:

Sorry not using a code, I just need help with the regular expression
  itself.

Saw this too late. Maybe better provide such informations in the question itself

Body:
You don't need regex, you can do that with simple string methods and readable LINQ:

List<string> orderNumberList = text.Replace(Environment.NewLine, "")
  .Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries)
  .Where(word => word.StartsWith("104") && word.Length <= 10)
  .ToList();

Your sample text blocks contain these 10 numbers:

    [0] "1048432358"
    [1] "1048432351"
    [2] "1048432466"
    [3] "1048432560"
    [4] "1048432594"
    [5] "1048432267"
    [6] "1048432353"
    [7] "1048432450"
    [8] "1048432360"
    [9] "1048432577"

Edit:

Sorry not using a code, I just need help with the regular expression
  itself.

Saw this too late. Maybe better provide such informations in the question itself


问:
How do you rotate PNG files using ffmpeg
I have tried ffmpeg.exe -loglevel error -i \"$Image_Folder$file\" -filter:v \"transpose=1\" \"$Output_Folder$file\

but this crashes ffmpeg.exe

so maybe it only works for videos?

答:
The problem is with the version of ffmpeg. The latest version ffmpeg-20171114-91a565e-win64-static causes it to crash.

Using an older version of ffmpeg, there is no problem. For example:
ffmpeg-20170312-58f0bbc-win64-static
is OK

ffmpeg can definitely rotate PNG images by 90 degrees clockwise.


问:
Async implementation of ICommand reasonable?
I've got an async implementation of the ICommand interface that of course has to implement the method void Execute(object parameter)

The actual implementation is then async like the following:

```<code>public async void Execute(object parameter)
{
    await ExecuteAsync((T)parameter);
}
</code>```

The ExecuteAsync method is then defined as follows:

```<code>private readonly Func<T, Task> execute;
private bool isExecuting;

public async Task ExecuteAsync(T parameter)
{
    try
    {
        isExecuting = true;
        InvokeCanExecuteChanged();
        await execute(parameter);
    }
    finally
    {
        isExecuting = false;
        InvokeCanExecuteChanged();
    }
}
</code>```

Now I do know that except for EventHandlers void should be avoided as return type for async methods. However ICommand is more or less a wrapper to clearly separate the view model from the actual event handlers. So am I fine with this implementation or will I run into problems?

Especially I'd like to know if I can safely use the execute command and rely on the Task to finish before the handler or will the handler complete regardless of the Task's status?

答:
The biggest issue around async + void is that unlike an ordinary void any following code on the call site will be executed, before the code within the async void method has actually finished. You have to be 100% aware of this.

This behavior is why async void is uncommon on an API level compared to async Task. In fact it's why i wrote a compiler error for any usage of async void within our company - Not all developers are aware of this and it can introduce potential bugs if you expect the content of that void method to finish before the call site code continues.

Therefore your command will be fine if it provides a public async Task ExecuteAsync version of your command.

See for yourself with this sample:

```<code>public class SampleCommand<T> : ICommand where T : class
{
    /// <inheritdoc />
    public SampleCommand(Func<T, Task> execute)
    {
        this.execute = execute;
    }

    /// <inheritdoc />
    public bool CanExecute(object parameter)
    {
        return !isExecuting;
    }

    /// <inheritdoc />
    public async void Execute(object parameter)
    {
        await ExecuteAsync(parameter as T);
    }

    /// <inheritdoc />
    public event EventHandler CanExecuteChanged;

    private readonly Func<T, Task> execute;
    private bool isExecuting;

    public async Task ExecuteAsync(T parameter)
    {
        try
        {
            isExecuting = true;
            InvokeCanExecuteChanged();
            await execute(parameter);
        }
        finally
        {
            isExecuting = false;
            InvokeCanExecuteChanged();
        }
    }

    private void InvokeCanExecuteChanged()
    {
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    }
}

public class SampleViewModel
{
    public SampleCommand<object> TaskedCommand { get; set; }

    public SampleViewModel()
    {
        TaskedCommand = new SampleCommand<object>(TaskExecutionAsync);

        RunSomeMoreInitialization();
        RunSomeMoreInitialization2();
    }

    private async void RunSomeMoreInitialization()
    {
        /*
         * wpf usually calls it this way
         * if a user calls this he might not be aware of the different behavior of this void method
         */
        TaskedCommand.Execute(null);
        await Task.Delay(250);
        Debug.WriteLine("more code executed");

        /*
         * this will print
         *
         * more code executed
         * command invoked
         */
    }

    private async void RunSomeMoreInitialization2()
    {
        // user might manually call it this way.
        await TaskedCommand.ExecuteAsync(null);
        await Task.Delay(250);
        Debug.WriteLine("more code executed");
        /*
         * this will print
         *
         * command invoked
         * more code executed
         */
    }

    private Task TaskExecutionAsync(object o)
    {
        Task.Delay(500);
        Debug.WriteLine("command invoked");

        return Task.CompletedTask;
    }
}
</code>```

Body:
I've got an async implementation of the ICommand interface that of course has to implement the method void Execute(object parameter)

The actual implementation is then async like the following:

public async void Execute(object parameter)
{
    await ExecuteAsync((T)parameter);
}

The ExecuteAsync method is then defined as follows:

private readonly Func<T, Task> execute;
private bool isExecuting;

public async Task ExecuteAsync(T parameter)
{
    try
    {
        isExecuting = true;
        InvokeCanExecuteChanged();
        await execute(parameter);
    }
    finally
    {
        isExecuting = false;
        InvokeCanExecuteChanged();
    }
}

Now I do know that except for EventHandlers void should be avoided as return type for async methods. However ICommand is more or less a wrapper to clearly separate the view model from the actual event handlers. So am I fine with this implementation or will I run into problems?

Especially I'd like to know if I can safely use the execute command and rely on the Task to finish before the handler or will the handler complete regardless of the Task's status?

Body:
The biggest issue around async + void is that unlike an ordinary void any following code on the call site will be executed, before the code within the async void method has actually finished. You have to be 100% aware of this.

This behavior is why async void is uncommon on an API level compared to async Task. In fact it's why i wrote a compiler error for any usage of async void within our company - Not all developers are aware of this and it can introduce potential bugs if you expect the content of that void method to finish before the call site code continues.

Therefore your command will be fine if it provides a public async Task ExecuteAsync version of your command.

See for yourself with this sample:

public class SampleCommand<T> : ICommand where T : class
{
    /// <inheritdoc />
    public SampleCommand(Func<T, Task> execute)
    {
        this.execute = execute;
    }

    /// <inheritdoc />
    public bool CanExecute(object parameter)
    {
        return !isExecuting;
    }

    /// <inheritdoc />
    public async void Execute(object parameter)
    {
        await ExecuteAsync(parameter as T);
    }

    /// <inheritdoc />
    public event EventHandler CanExecuteChanged;

    private readonly Func<T, Task> execute;
    private bool isExecuting;

    public async Task ExecuteAsync(T parameter)
    {
        try
        {
            isExecuting = true;
            InvokeCanExecuteChanged();
            await execute(parameter);
        }
        finally
        {
            isExecuting = false;
            InvokeCanExecuteChanged();
        }
    }

    private void InvokeCanExecuteChanged()
    {
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    }
}

public class SampleViewModel
{
    public SampleCommand<object> TaskedCommand { get; set; }

    public SampleViewModel()
    {
        TaskedCommand = new SampleCommand<object>(TaskExecutionAsync);

        RunSomeMoreInitialization();
        RunSomeMoreInitialization2();
    }

    private async void RunSomeMoreInitialization()
    {
        /*
         * wpf usually calls it this way
         * if a user calls this he might not be aware of the different behavior of this void method
         */
        TaskedCommand.Execute(null);
        await Task.Delay(250);
        Debug.WriteLine("more code executed");

        /*
         * this will print
         *
         * more code executed
         * command invoked
         */
    }

    private async void RunSomeMoreInitialization2()
    {
        // user might manually call it this way.
        await TaskedCommand.ExecuteAsync(null);
        await Task.Delay(250);
        Debug.WriteLine("more code executed");
        /*
         * this will print
         *
         * command invoked
         * more code executed
         */
    }

    private Task TaskExecutionAsync(object o)
    {
        Task.Delay(500);
        Debug.WriteLine("command invoked");

        return Task.CompletedTask;
    }
}


问:
getCropAndSetWallpaperIntent() Content Uri Error
I am getting this error when using getCropAndSetWallpaperIntent() in android

```<code>D/Exception: java.lang.IllegalArgumentException: Cannot use passed URI to set wallpaper; check that the type returned by ContentProvider matches image/*
</code>```

But when I check for the type of Content using ContentResolver I am getting

D/CONTENT TYPE:: IS: image/jpeg

then why is Wallpaper Manager is giving me content error ?

Here is the code I am using to get Image URI

```<code>    public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    tempPath = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    Log.d("URI OF SET IMAGE", tempPath);
    ContentResolver cr = this.getContentResolver();
    Log.d("CONTENT TYPE: ", "IS: " + cr.getType(Uri.parse(tempPath)));
    return Uri.parse(tempPath);
}
</code>```

Any ideas ?

答:
I'm getting the same error...

IllegalArgumentException: Cannot use passed URI to set wallpaper;
  check that the type returned by ContentProvider matches image/*

I've checked the uri type (getActivity().getContentResolver().getType(uri);)...  says the type is image/jpeg so kinda stumped!!

This is what I've done... will at least give it a chance on Oreo

```<code>try {
    Intent intent = WallpaperManager.getInstance(getActivity()).getCropAndSetWallpaperIntent(contentUri);
    //startActivityForResult to stop the progress bar
    startActivityForResult(intent, ACTIVITY_CROP);
} catch (IllegalArgumentException e) {
    // Seems to be an Oreo bug - fall back to using the bitmap instead
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), contentUri);
    WallpaperManager.getInstance(getActivity()).setBitmap(bitmap);
    imageLoadProgress.setVisibility(View.GONE);
}
</code>```

Body:
I am getting this error when using getCropAndSetWallpaperIntent() in android

D/Exception: java.lang.IllegalArgumentException: Cannot use passed URI to set wallpaper; check that the type returned by ContentProvider matches image/*

But when I check for the type of Content using ContentResolver I am getting

D/CONTENT TYPE:: IS: image/jpeg

then why is Wallpaper Manager is giving me content error ?

Here is the code I am using to get Image URI

    public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    tempPath = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    Log.d("URI OF SET IMAGE", tempPath);
    ContentResolver cr = this.getContentResolver();
    Log.d("CONTENT TYPE: ", "IS: " + cr.getType(Uri.parse(tempPath)));
    return Uri.parse(tempPath);
}

Any ideas ?

Body:
I'm getting the same error...

IllegalArgumentException: Cannot use passed URI to set wallpaper;
  check that the type returned by ContentProvider matches image/*

I've checked the uri type (getActivity().getContentResolver().getType(uri);)...  says the type is image/jpeg so kinda stumped!!

This is what I've done... will at least give it a chance on Oreo

try {
    Intent intent = WallpaperManager.getInstance(getActivity()).getCropAndSetWallpaperIntent(contentUri);
    //startActivityForResult to stop the progress bar
    startActivityForResult(intent, ACTIVITY_CROP);
} catch (IllegalArgumentException e) {
    // Seems to be an Oreo bug - fall back to using the bitmap instead
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), contentUri);
    WallpaperManager.getInstance(getActivity()).setBitmap(bitmap);
    imageLoadProgress.setVisibility(View.GONE);
}


问:
How to select a specific id value not the last one mysql php
Hi I am trying to update a specific value from a row, but it only gets the last id no matter what and changes active to 0 just for the last row.

Any idea?
Thanks!

```<code> <?php
  include 'db.php';

  $selectquery="SELECT pid from tblpes WHERE active=1";
  $result = mysqli_query($conn, $selectquery) or die("Error");
   while ($row = mysqli_fetch_array($result)) {
      $pid= $row['pid'];
   }

   $sqlupdate="UPDATE tblpes SET active=0 WHERE pid=$pid";

    $result1=mysqli_query($conn,$sqlupdate);

   $conn->close();
 ?>
</code>```

答:
The last id is updated because the $pid value is replaced in the loop.

Move your update query in the loop like this :

```<code>include 'db.php';
$selectquery="SELECT pid from tblpes WHERE active=1";
$result = mysqli_query($conn, $selectquery) or die("Error");
while ($row = mysqli_fetch_array($result)) {
  $pid= $row['pid'];
  $sqlupdate="UPDATE tblpes SET active=0 WHERE pid=$pid";
  $result1=mysqli_query($conn,$sqlupdate);
}
</code>```

But if I understand what do you want to do, you can just do it :

```<code> $sqlupdate="UPDATE tblpes SET active=0 WHERE active=1";
 $result1=mysqli_query($conn,$sqlupdate);
</code>```

Body:
Hi I am trying to update a specific value from a row, but it only gets the last id no matter what and changes active to 0 just for the last row.

Any idea?
Thanks!

 <?php
  include 'db.php';

  $selectquery="SELECT pid from tblpes WHERE active=1";
  $result = mysqli_query($conn, $selectquery) or die("Error");
   while ($row = mysqli_fetch_array($result)) {
      $pid= $row['pid'];
   }

   $sqlupdate="UPDATE tblpes SET active=0 WHERE pid=$pid";

    $result1=mysqli_query($conn,$sqlupdate);

   $conn->close();
 ?>

Body:
The last id is updated because the $pid value is replaced in the loop.

Move your update query in the loop like this :

include 'db.php';
$selectquery="SELECT pid from tblpes WHERE active=1";
$result = mysqli_query($conn, $selectquery) or die("Error");
while ($row = mysqli_fetch_array($result)) {
  $pid= $row['pid'];
  $sqlupdate="UPDATE tblpes SET active=0 WHERE pid=$pid";
  $result1=mysqli_query($conn,$sqlupdate);
}

But if I understand what do you want to do, you can just do it :

 $sqlupdate="UPDATE tblpes SET active=0 WHERE active=1";
 $result1=mysqli_query($conn,$sqlupdate);


问:
Pandas rolling mean and selective indexing by time
I've a dataset where I've reindexed it with respect to dates (datetime.datetime). A small sample of the dataframe looks like this, df2:

```<code>                                lat          lon        Press   NetLW
rounded_dt 1997-11-30 17:00:00  76.15387    -147.62606  998.8   -51.0
           1997-11-30 18:00:00  76.15280    -147.60379  1000.0  -50.9
           1997-11-30 19:00:00  76.15164    -147.58055  1001.1  -54.4
           1997-11-30 20:00:00  76.15037    -147.56047  1002.6  -52.2
           1997-11-30 21:00:00  76.14948    -147.54034  1004.2  -51.9
           1997-11-30 22:00:00  76.14834    -147.52181  1005.5  -51.3
           1997-11-30 23:00:00  76.14777    -147.50568  1006.5  -50.7
           1997-12-01 06:00:00  76.14152    -147.42073  1013.3  -44.6
           1997-12-01 07:00:00  76.14105    -147.41370  1013.8  -45.4
           1997-12-01 08:00:00  76.14072    -147.40661  1014.5  -46.1
           1997-12-01 09:00:00  76.14059    -147.40093  1015.0  -43.0
</code>```

So the time series is daily per hourly continuing for an year.

What my aim is?

I would like to extract the data based on NetLW for a specific range of days and only for 11 hour and 23 hour for those days. But the NetLW at that hour let's say, 11 hour should be averaged wrt NetLW(10 hour) , NetLW(11 hour) and  NetLW(12 hour).

What I've done so far?

```<code>df3 = df2.rolling(window=3, center=True).mean() # to get the rolling mean
# I want to extract the dates of interest from df3
dates_list =[]
for idx in df2.index:
    # Winter dates (Dec-March)
    if idx > datetime.datetime(1997, 11, 30, 23) and idx < datetime.datetime(1998, 3, 1, 0):
       if idx.hour ==11 or idx.hour == 23:
          dates_list.append(df3[df3.loc[idx, 'NetLW'] < -30.0])
</code>```

And then I could concatenate the dates_list in one series/dataframe and get the dates

Error message
KeyError: True

During handling of the above exception, another exception occurred

And it points to this line:

--->        dates_list.append(df3[df3.loc[idx, 'NetLW'] < -30.0])

I'm expecting to use a boolean dtype to use it as an index for df3 and extract the data.

Also, if it is possible to groupby the hour I'm interested in instead of writing multiple loops then please let me know as I'm new to Pandas.

答:
Boolean indexing in a dataframe will generally require you to use the .loc indexer. But what is happening here is that there is only a single index as you are looping. Freely translated: df3_clear = df3[True or False]. I am afraid you do not have a row in your index called True. Neither False.

What you are looking for seems to be along the lines of (can probably be a oneliner, but I'm a bit lazy):

```<code>df3_clear = df3['1997-11-30 23:00':'1998-03-01'].query('NetLW < -30')
df3_clear = df3_clear.iloc[np.where((df3_clear.index.hour == 23) | (df3_clear.index.hour == 11))]
</code>```

Body:
I've a dataset where I've reindexed it with respect to dates (datetime.datetime). A small sample of the dataframe looks like this, df2:

                                lat          lon        Press   NetLW
rounded_dt 1997-11-30 17:00:00  76.15387    -147.62606  998.8   -51.0
           1997-11-30 18:00:00  76.15280    -147.60379  1000.0  -50.9
           1997-11-30 19:00:00  76.15164    -147.58055  1001.1  -54.4
           1997-11-30 20:00:00  76.15037    -147.56047  1002.6  -52.2
           1997-11-30 21:00:00  76.14948    -147.54034  1004.2  -51.9
           1997-11-30 22:00:00  76.14834    -147.52181  1005.5  -51.3
           1997-11-30 23:00:00  76.14777    -147.50568  1006.5  -50.7
           1997-12-01 06:00:00  76.14152    -147.42073  1013.3  -44.6
           1997-12-01 07:00:00  76.14105    -147.41370  1013.8  -45.4
           1997-12-01 08:00:00  76.14072    -147.40661  1014.5  -46.1
           1997-12-01 09:00:00  76.14059    -147.40093  1015.0  -43.0

So the time series is daily per hourly continuing for an year.

What my aim is?

I would like to extract the data based on NetLW for a specific range of days and only for 11 hour and 23 hour for those days. But the NetLW at that hour let's say, 11 hour should be averaged wrt NetLW(10 hour) , NetLW(11 hour) and  NetLW(12 hour).

What I've done so far?

df3 = df2.rolling(window=3, center=True).mean() # to get the rolling mean
# I want to extract the dates of interest from df3
dates_list =[]
for idx in df2.index:
    # Winter dates (Dec-March)
    if idx > datetime.datetime(1997, 11, 30, 23) and idx < datetime.datetime(1998, 3, 1, 0):
       if idx.hour ==11 or idx.hour == 23:
          dates_list.append(df3[df3.loc[idx, 'NetLW'] < -30.0])

And then I could concatenate the dates_list in one series/dataframe and get the dates

Error message
KeyError: True

During handling of the above exception, another exception occurred

And it points to this line:

--->        dates_list.append(df3[df3.loc[idx, 'NetLW'] < -30.0])

I'm expecting to use a boolean dtype to use it as an index for df3 and extract the data.

Also, if it is possible to groupby the hour I'm interested in instead of writing multiple loops then please let me know as I'm new to Pandas.

Body:
Boolean indexing in a dataframe will generally require you to use the .loc indexer. But what is happening here is that there is only a single index as you are looping. Freely translated: df3_clear = df3[True or False]. I am afraid you do not have a row in your index called True. Neither False.

What you are looking for seems to be along the lines of (can probably be a oneliner, but I'm a bit lazy):

df3_clear = df3['1997-11-30 23:00':'1998-03-01'].query('NetLW < -30')
df3_clear = df3_clear.iloc[np.where((df3_clear.index.hour == 23) | (df3_clear.index.hour == 11))]


问:
Highcharts bar format datalabels to percent and add text
I have highcharts bar.

How I can format my datalabel to percent and add text datalabels (how i can reposition this text? It's need me for create vertical version of this bar) ?

In the end, it should turn out like this in a horizontal or vertical solution.

Highcharts.chart('container', {
    chart: {
        type: 'bar'
    },
    title: {
        text: 'Activity'
    },
    xAxis: {
        categories: ['Activity']
    },
    yAxis: {
        min: 0,
        title: {
            text: ''
        }
    },
    legend: {
        reversed: true
    },
    plotOptions: {
        series: {
         borderWidth: 0,
            stacking: 'normal',
            pointWidth: 3,
            dataLabels: {
                enabled: true,
                y: 2,
                verticalAlign: 'top',
                align: 'left',
                color: '#000000',
             style: {
                    textOutline: false
                }
            }
        }
    },
    series: [{
        name: 'One',
        data: [10],
        color: '#f45b69'
    }, {
        name: 'Two',
        data: [20],
        color: '#44bba4'

    }, {
        name: 'Three',
        data: [30],
        color: '#ff9f1c'
    }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div></code>```

答:
To just show the number with a percentage sign behind as well as the series name you can set the dataLabels format like this:

```<code>plotOptions: {
  series: {
    format: '{y} % <br/> {series.name}',
    ...
  }
}
</code>```

If you want to change how it looks or have more customize-ability you can use formatter instead of format.

Working example: https://jsfiddle.net/ewolden/y5ygdx2a/1/

API on dataLabels.format: https://api.highcharts.com/highcharts/plotOptions.series.dataLabels.format

Body:
To just show the number with a percentage sign behind as well as the series name you can set the dataLabels format like this:

plotOptions: {
  series: {
    format: '{y} % <br/> {series.name}',
    ...
  }
}

If you want to change how it looks or have more customize-ability you can use formatter instead of format.

Working example: https://jsfiddle.net/ewolden/y5ygdx2a/1/

API on dataLabels.format: https://api.highcharts.com/highcharts/plotOptions.series.dataLabels.format


问:
How to optimize SQL query with two where clauses?
My query is something like this

```<code>SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND (tbl2.date = '$date' OR ('$date' BETWEEN tbl1.planA AND tbl1.planB ))
</code>```

When I run this query, it is considerably slower than for example this query

```<code>SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND ('$date' BETWEEN tbl1.planA AND tbl1.planB )
</code>```

or

```<code>SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND tbl2.date = '$date'
</code>```

In localhost, the first query takes about 0.7 second, the second query about 0.012 second and the third one 0.008 second.

My question is how do you optimize this? If currently I have 1000 rows in my tables and it takes 0.7 second to display the first query, it will take 7 seconds if I have 10.000 rows right? That's a massive slow down compared to second query (0.12 second) and third (0.08).

I've tried adding indexes, but the result is no different.

Thanks

Edit : This application will only work locally, so no need to worry about the speed over the web.

Sorry, I didn't include the EXPLAIN because my real query are much more complicated (about 5 joins). But the joins (I think) don't really matter, cos I've tried omitting them and still get approximately the same result as above.

The date belongs to tbl1, planA and planB belongs to tbl2. I've tried adding indexes to tbl1.date, tbl2.planA and tbl2.planB but the result is insignificant.

By schema do you mean MyISAM or InnoDB? It's MyISAM.

Okay, I'll just post my query straight away. Hopefully it's not that confusing.

```<code>SELECT *
FROM tb_joborder jo
LEFT JOIN tb_project p ON jo.project_id = p.project_id
LEFT JOIN tb_customer c ON p.customer_id = c.customer_id
LEFT JOIN tb_dispatch d ON jo.joborder_id = d.joborder_id
LEFT JOIN tb_joborderitem ji ON jo.joborder_id = ji.joborder_id
LEFT JOIN tb_mix m ON ji.mix_id = m.mix_id
WHERE dispatch_date = '2011-01-11'
OR '2011-01-11'
BETWEEN planA
AND planB
GROUP BY jo.joborder_id
ORDER BY customer_name ASC
</code>```

And the describe output

```<code>id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  jo  ALL     NULL    NULL    NULL    NULL    453     Using temporary; Using filesort
1   SIMPLE  p   eq_ref  PRIMARY     PRIMARY     4   db_dexada.jo.project_id     1
1   SIMPLE  c   eq_ref  PRIMARY     PRIMARY     4   db_dexada.p.customer_id     1
1   SIMPLE  d   ALL     NULL    NULL    NULL    NULL    2048    Using where
1   SIMPLE  ji  ALL     NULL    NULL    NULL    NULL    455
1   SIMPLE  m   eq_ref  PRIMARY     PRIMARY     4   db_dexada.ji.mix_id     1
</code>```

答:
First thing that comes to mind is to union the two:

```<code>SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND ('$date' BETWEEN planA AND planB )

UNION ALL

SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND date = '$date'
</code>```

You have provided too little to make optimizations. We don't know anything about your data structures.

Body:
My query is something like this

SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND (tbl2.date = '$date' OR ('$date' BETWEEN tbl1.planA AND tbl1.planB ))

When I run this query, it is considerably slower than for example this query

SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND ('$date' BETWEEN tbl1.planA AND tbl1.planB )

or

SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND tbl2.date = '$date'

In localhost, the first query takes about 0.7 second, the second query about 0.012 second and the third one 0.008 second.

My question is how do you optimize this? If currently I have 1000 rows in my tables and it takes 0.7 second to display the first query, it will take 7 seconds if I have 10.000 rows right? That's a massive slow down compared to second query (0.12 second) and third (0.08).

I've tried adding indexes, but the result is no different.

Thanks

Edit : This application will only work locally, so no need to worry about the speed over the web.

Sorry, I didn't include the EXPLAIN because my real query are much more complicated (about 5 joins). But the joins (I think) don't really matter, cos I've tried omitting them and still get approximately the same result as above.

The date belongs to tbl1, planA and planB belongs to tbl2. I've tried adding indexes to tbl1.date, tbl2.planA and tbl2.planB but the result is insignificant.

By schema do you mean MyISAM or InnoDB? It's MyISAM.

Okay, I'll just post my query straight away. Hopefully it's not that confusing.

SELECT *
FROM tb_joborder jo
LEFT JOIN tb_project p ON jo.project_id = p.project_id
LEFT JOIN tb_customer c ON p.customer_id = c.customer_id
LEFT JOIN tb_dispatch d ON jo.joborder_id = d.joborder_id
LEFT JOIN tb_joborderitem ji ON jo.joborder_id = ji.joborder_id
LEFT JOIN tb_mix m ON ji.mix_id = m.mix_id
WHERE dispatch_date = '2011-01-11'
OR '2011-01-11'
BETWEEN planA
AND planB
GROUP BY jo.joborder_id
ORDER BY customer_name ASC

And the describe output

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  jo  ALL     NULL    NULL    NULL    NULL    453     Using temporary; Using filesort
1   SIMPLE  p   eq_ref  PRIMARY     PRIMARY     4   db_dexada.jo.project_id     1
1   SIMPLE  c   eq_ref  PRIMARY     PRIMARY     4   db_dexada.p.customer_id     1
1   SIMPLE  d   ALL     NULL    NULL    NULL    NULL    2048    Using where
1   SIMPLE  ji  ALL     NULL    NULL    NULL    NULL    455
1   SIMPLE  m   eq_ref  PRIMARY     PRIMARY     4   db_dexada.ji.mix_id     1

Body:
First thing that comes to mind is to union the two:

SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND ('$date' BETWEEN planA AND planB )

UNION ALL

SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND date = '$date'

You have provided too little to make optimizations. We don't know anything about your data structures.


问:
Writing to a local file on hdfs in Spark from a non-Spark datastructure
I have the following code:

```<code>def writeCSV(indexing: ListBuffer[Array[Int]], outputpath: String): Unit = {
    new PrintWriter(outputpath + "out.csv") {
      write("col1,col2,col3\n")

      for (entry <- indexing) {
        for (num <- entry) {
          write(num + "");
          if (num != entry(2)) write(",");
        }
        write("\n")
      }
      close
    }
</code>```

Which does not work, because my Spark complains that the output path cannot be found. How would I be able to print this out from a regular datastructure (ListBuffer[Array[Int]]) to just a regular file in my Spark program? Do I need to map the ListBuffer to some Spark datastructure?

I understand this is not what you want to do normally, but this is more for use for debugging and will not be used in production code.

I am new to Spark and I am using Spark 1.6.0.

答:
If you want to write a file on HDFS, you would pass InputStream via FileSystem in org.apache.hadoop.fs package to PrintWriter constructor.

Example code

```<code>import org.apache.hadoop.fs.{FileSystem,Path}
val fs = FileSystem.get(spark.sparkContext.hadoopConfiguration)
new PrintWriter(fs.create(new Path(""))){
    write(...)
  }
</code>```

Body:
I have the following code:

def writeCSV(indexing: ListBuffer[Array[Int]], outputpath: String): Unit = {
    new PrintWriter(outputpath + "out.csv") {
      write("col1,col2,col3\n")

      for (entry <- indexing) {
        for (num <- entry) {
          write(num + "");
          if (num != entry(2)) write(",");
        }
        write("\n")
      }
      close
    }

Which does not work, because my Spark complains that the output path cannot be found. How would I be able to print this out from a regular datastructure (ListBuffer[Array[Int]]) to just a regular file in my Spark program? Do I need to map the ListBuffer to some Spark datastructure?

I understand this is not what you want to do normally, but this is more for use for debugging and will not be used in production code.

I am new to Spark and I am using Spark 1.6.0.

Body:
If you want to write a file on HDFS, you would pass InputStream via FileSystem in org.apache.hadoop.fs package to PrintWriter constructor.

Example code

import org.apache.hadoop.fs.{FileSystem,Path}
val fs = FileSystem.get(spark.sparkContext.hadoopConfiguration)
new PrintWriter(fs.create(new Path(""))){
    write(...)
  }


问:
How to add hanging indent to the labels of a checkbox customized with custom icons in CSS?
I am trying to customize the look of my checkboxes using font-awesome and to have all the text of the labels correctly indented. I have customized the look of the checkboxes which makes the usual approaches to indent the text not working as I am hiding the actual checkbox (see the CSS below).

Currently, I obtain the following (left) while I would like the one on the right:

I used the following code (see the JSFiddle):

CSS

Inspired by this simple CSS checkboxes, I use the following to format my checkboxes with font-awesome:

```<code>input[type=checkbox] {
    display:none;
}

input[type=checkbox] + label:before {
    font-family: FontAwesome;
    display: inline-block;
    content: "\f096";
    letter-spacing: 10px;
    cursor: pointer;
}

input[type=checkbox]:checked + label:before {
    content: "\f046";
}

input[type=checkbox]:checked + label:before {
    letter-spacing: 8px;
}
</code>```

HTML

```<code><input type="checkbox" id="box1" checked="">
<label for="box1">Item 1: some long text...</label>
<br>
<input type="checkbox" id="box2" checked="">
<label for="box2">Item 2: some long text...</label>
<br>
<input type="checkbox" id="box3">
<label for="box3">Item 3: some long text...</label>
</code>```

I have tried to modify the margin-left and text-indent attributes of the label and label:before selectors but without any success.

Any idea how I could have the correct indent while using the nice font-awesome icons?

Thank you very much for your help!

答:
After trying fcalderan's suggestion and not being able to get the values for padding-left and text-indent right for different browsers, I switched to a flex box. It is pretty green nowadays.

If you put the input/label pairs in divs as it is recommended by Mozilla, you can style them this way.

fieldset {
  width: 13ch;
}

fieldset > div {
  display: flex;
}

fieldset > div > * {
  align-self: baseline;
}

fieldset > div > input[type=checkbox] {
  margin: 0 0.5ch 0 0;
  width: 1em;
  height: 1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><fieldset>
  <legend>Sichtbarkeit</legend>
  <div>
    <input id="c1" checked="" type="checkbox">
    <label for="c1">Minuten</label>
  </div>
  <div>
    <input id="c2" checked="" type="checkbox">
    <label for="c2">Nur Minuten, die Vielfache von 5 sind</label>
  </div>
  <div>
    <input id="c3" checked="" type="checkbox">
    <label for="c3">Stunden</label>
  </div>
  <div>
    <input id="c4" checked="" type="checkbox">
    <label for="c4">Nur 12 Stunden</label>
  </div>
</fieldset></code>```

Body:
I am trying to customize the look of my checkboxes using font-awesome and to have all the text of the labels correctly indented. I have customized the look of the checkboxes which makes the usual approaches to indent the text not working as I am hiding the actual checkbox (see the CSS below).

Currently, I obtain the following (left) while I would like the one on the right:

I used the following code (see the JSFiddle):

CSS

Inspired by this simple CSS checkboxes, I use the following to format my checkboxes with font-awesome:

input[type=checkbox] {
    display:none;
}

input[type=checkbox] + label:before {
    font-family: FontAwesome;
    display: inline-block;
    content: "\f096";
    letter-spacing: 10px;
    cursor: pointer;
}

input[type=checkbox]:checked + label:before {
    content: "\f046";
}

input[type=checkbox]:checked + label:before {
    letter-spacing: 8px;
}

HTML

<input type="checkbox" id="box1" checked="">
Item 1: some long text...

<input type="checkbox" id="box2" checked="">
Item 2: some long text...

<input type="checkbox" id="box3">
Item 3: some long text...

I have tried to modify the margin-left and text-indent attributes of the label and label:before selectors but without any success.

Any idea how I could have the correct indent while using the nice font-awesome icons?

Thank you very much for your help!

Body:
After trying fcalderan's suggestion and not being able to get the values for padding-left and text-indent right for different browsers, I switched to a flex box. It is pretty green nowadays.

If you put the input/label pairs in divs as it is recommended by Mozilla, you can style them this way.

fieldset {
  width: 13ch;
}

fieldset > div {
  display: flex;
}

fieldset > div > * {
  align-self: baseline;
}

fieldset > div > input[type=checkbox] {
  margin: 0 0.5ch 0 0;
  width: 1em;
  height: 1em;
}

<fieldset>
  <legend>Sichtbarkeit</legend>
  <div>
    <input id="c1" checked="" type="checkbox">
    <label for="c1">Minuten</label>
  </div>
  <div>
    <input id="c2" checked="" type="checkbox">
    <label for="c2">Nur Minuten, die Vielfache von 5 sind</label>
  </div>
  <div>
    <input id="c3" checked="" type="checkbox">
    <label for="c3">Stunden</label>
  </div>
  <div>
    <input id="c4" checked="" type="checkbox">
    <label for="c4">Nur 12 Stunden</label>
  </div>
</fieldset>


问:
How can I loop over a 2d array in PostgreSQL
I am trying to loop over a 2D array getting the first and second value from each row to update a table

```<code>CREATE OR REPLACE FUNCTION fc_update_arrangement(input_arrangementid int, input_NAME text, input_price money, input_expirationdate date, products int[][])
RETURNS void AS
$BODY$
BEGIN
update arrangement set "NAME" = $2, price = $3, expirationdate = $4 where arrangementid = $1;
-- loop through array getting the first and second value
-- update productinarrangement set amount = arrayinputnumber2 where productid = arrayinputnumber1 and arrangementid = $1
END;
$BODY$ LANGUAGE plpgsql STRICT;
</code>```

With help I got the function call right, which doesn't return errors anymore. I don't understand how I can loop through the array getting the values within? I've commented out the lines and I don't know what to do. I call the function within this line:

```<code>select fc_update_arrangement(1::int, 'tom'::text, 15::money, now()::date, array[ array[1,2], array[3,4] ]);
</code>```

答:
There is an example in the documentation:

```<code>CREATE FUNCTION scan_rows(int[]) RETURNS void AS $$
DECLARE
  x int[];
BEGIN
  FOREACH x SLICE 1 IN ARRAY $1
  LOOP
    RAISE NOTICE 'row = %', x;
  END LOOP;
END;
$$ LANGUAGE plpgsql;

SELECT scan_rows(ARRAY[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]);

NOTICE:  row = {1,2,3}
NOTICE:  row = {4,5,6}
NOTICE:  row = {7,8,9}
NOTICE:  row = {10,11,12}
</code>```

To try a verbal description: If the array of of type whatever[] and you loop with SLICE 1, the array gets cut into slices of one element each. The loop variable then will contain arrays of the same type whatever[], each containing a single element of the original array. If you choose SLICE 2, the loop variable will contain arrays of size 2.

Body:
I am trying to loop over a 2D array getting the first and second value from each row to update a table

CREATE OR REPLACE FUNCTION fc_update_arrangement(input_arrangementid int, input_NAME text, input_price money, input_expirationdate date, products int[][])
RETURNS void AS
$BODY$
BEGIN
update arrangement set "NAME" = $2, price = $3, expirationdate = $4 where arrangementid = $1;
-- loop through array getting the first and second value
-- update productinarrangement set amount = arrayinputnumber2 where productid = arrayinputnumber1 and arrangementid = $1
END;
$BODY$ LANGUAGE plpgsql STRICT;

With help I got the function call right, which doesn't return errors anymore. I don't understand how I can loop through the array getting the values within? I've commented out the lines and I don't know what to do. I call the function within this line:

select fc_update_arrangement(1::int, 'tom'::text, 15::money, now()::date, array[ array[1,2], array[3,4] ]);

Body:
There is an example in the documentation:

CREATE FUNCTION scan_rows(int[]) RETURNS void AS $$
DECLARE
  x int[];
BEGIN
  FOREACH x SLICE 1 IN ARRAY $1
  LOOP
    RAISE NOTICE 'row = %', x;
  END LOOP;
END;
$$ LANGUAGE plpgsql;

SELECT scan_rows(ARRAY[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]);

NOTICE:  row = {1,2,3}
NOTICE:  row = {4,5,6}
NOTICE:  row = {7,8,9}
NOTICE:  row = {10,11,12}

To try a verbal description: If the array of of type whatever[] and you loop with SLICE 1, the array gets cut into slices of one element each. The loop variable then will contain arrays of the same type whatever[], each containing a single element of the original array. If you choose SLICE 2, the loop variable will contain arrays of size 2.

ContentLicense: CC BY-SA 4.0


问:
AAPT2 gradle issue in android studio 3.0 beta4
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

We have already added android.enableAapt2=false in gradle.properties file

答:
Add to your gradle.properties file this line

android.enableAapt2=false

EDIT:

You should use stable verison of Android Studio 3


问:
How to send model data from view to api controller using ajax
I am trying to send the value from my this view to given API controller.It is working when i hard-code the json data.I am unable to send the data of id and brandname when i press the button since it is in table. How do I make it work?Please help

```<code>  <table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Brand.BrandName)
        </th>
                <th>
            @Html.DisplayNameFor(model => model.ProductName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>

        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Brand.BrandName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ProductName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
      <td><input type="button" id="Save" /></td>

    </tr>
}

</table>
@section scripts {
<script>
    $(document).ready(function () {
        $("#Save").click(function () {

            var brand = { 'id':1, 'brandname': 'abc' }

            $.ajax({
                url: 'http://localhost:51429/api/brands',
                type: 'POST',
                dataType: 'json',
                data: brand,
                success: function (data, textStatus, xhr) {
                    console.log(data);
                },
                error: function (xhr, textStatus, errorThrown) {
                    console.log('Error in Operation');
                }
            });

        });
    });

   </script>
    }
</code>```

I have a brand API. And it post API controller is

```<code>    [HttpPost]
    public IHttpActionResult Post([FromBody]Brands brand)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        db.Brands.Add(brand);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = brand.Id }, brand);

    }
</code>```

答:
You are using DisplayFor, which is used to display the lable, or name of the text field. you need to replace DisplayFor with EditorFor where you are populating data in foreach loop.
Also you should use razor HTML helper form or AJAX helper form</p>

Body:
I am trying to send the value from my this view to given API controller.It is working when i hard-code the json data.I am unable to send the data of id and brandname when i press the button since it is in table. How do I make it work?Please help

            @Html.DisplayNameFor(model => model.Brand.BrandName)

            @Html.DisplayNameFor(model => model.ProductName)

            @Html.DisplayNameFor(model => model.Price)

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.Brand.BrandName)

            @Html.DisplayFor(modelItem => item.ProductName)

            @Html.DisplayFor(modelItem => item.Price)

      <input type="button" id="Save" />

}

@section scripts {

    }

I have a brand API. And it post API controller is

    [HttpPost]
    public IHttpActionResult Post([FromBody]Brands brand)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        db.Brands.Add(brand);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = brand.Id }, brand);

    }


问:
Find device information from IP address
I have a list of IP addresses and they are probably of the IOT devices. How can I figure out the OS of the device(I only have its IP address) using any script/tool/service ? Any help would be immensely appreciated. I am new to this. Thanks.</p>

答:
Look at this (for an example):

automating telnet session using bash scripts

you can try to write your own telnet script (open session, send some command and retrieve information that you need).

Title: Find device information from IP address


问:
Div won't close
```<code><div style="margin: 8px auto;text-align: center; clear: both;">
<img src="https://storage.googleapis.com/support-kms-
prod/SNP_3094702_en_v0" style="max-width: 100%; />
</div>

^ // THIS IS THE DIV THAT WON'T CLOSE //
  // IT INSTEAD INCLUDES THE CONTENT BELOW //

<article class=">
<div class="category">
</div>
</code>```

Hello! I own a wordpress blog and I'm trying to implement ads between posts, but I've run into a weird problem. This div won't close, no matter how many
's I put after the img tag ends. It instead includes the whole rest of the page.

Is there something I am missing here?

答:
There is an error in your given code of missing " in img tag style attribute

Error in code

```<code><img src="https://storage.googleapis.com/support-kms-
prod/SNP_3094702_en_v0" style="max-width: 100%;></div>
</code>```

Correct code

```<code><img src="https://storage.googleapis.com/support-kms-
prod/SNP_3094702_en_v0" style="max-width: 100%;"></div>
</code>```

Title: Div won't close

Body:
^ // THIS IS THE DIV THAT WON'T CLOSE //
  // IT INSTEAD INCLUDES THE CONTENT BELOW //

Hello! I own a wordpress blog and I'm trying to implement ads between posts, but I've run into a weird problem. This div won't close, no matter how many
's I put after the img tag ends. It instead includes the whole rest of the page.

Is there something I am missing here?

Body:
There is an error in your given code of missing " in img tag style attribute

Error in code

<img src="https://storage.googleapis.com/support-kms-
prod/SNP_3094702_en_v0" style="max-width: 100%;></div>

Correct code

<img src="https://storage.googleapis.com/support-kms-
prod/SNP_3094702_en_v0" style="max-width: 100%;"></div>


问:
Why is this exception happening?
 See EDIT 2

Hello, I'm stumped of why this exception is happening

```<code>
exception

javax.servlet.ServletException: Error instantiating servlet class controllers.Dashboard
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    java.lang.Thread.run(Thread.java:662)
root cause

java.lang.RuntimeException: Uncompilable source code - missing method body, or declare abstract
    DAO.OrderDAO.(OrderDAO.java:68)
    BO.OrderForm.(OrderForm.java:33)
    controllers.Dashboard.(Dashboard.java:23)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    java.lang.Class.newInstance0(Class.java:355)
    java.lang.Class.newInstance(Class.java:308)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    java.lang.Thread.run(Thread.java:662)
</code>```

At first I was getting this in NetBeans 6.9.1 and continued to search and found this
weird bug  after trying th solution posted to no success I decided to switch IDE, so I downloaded the Intellij IDE 9 (loving it so far) and still got the same exception!! I mean come on.., the only three classes that do not belong to common libs are the DAO,BO and controllers packages and they a

Now I'm lost as the code exists and there no colon typo or anything.

EDIT 1:

removed the source code of DAO.OrderDAO.java, BO.OrderForm.java and controllers.OrderSearch.java as it was concluded that the problem was caused by one of the below classes (which one is yet to be determined.) So I configured IntelliJ debugger to stop whenever a Exception is thrown and I have a ClassNotFoundException being thrown in looking for the class org.apache.catalina.startup.bootstrap I'm unsure if this has to do with PATH variables because I have downloaded the apache-tomcat-6.0.30 and I verified that the troublesome class is there., Any suggestions?

Edit 2:

Switched back to NetBeans 6.9.1  added a bunch of libraries, the Runtime exception stopped, however I'm stuck again with the above exception and stack trace and I reiterate the method body is there!!.
A link to the complete trace, the password is 1234

答:
```<code>java.io.NotSerializableException: DTO.ColorDTO
</code>```

It seems ColorDTO doesn't implement Serializable

AND / OR

```<code>java.lang.RuntimeException: Uncompilable source code - missing method body, or declare abstract
at DAO.OrderDAO.<init>(OrderDAO.java:68)
at BO.OrderForm.<init>(OrderForm.java:33)
</code>```

OrderDAO doesn't implement all the methods that it should implement or make it abstract and provide its implementation in subclass at last everything should be concrete.

Title: Why is this exception happening?

Body:
 See EDIT 2

Hello, I'm stumped of why this exception is happening

exception

javax.servlet.ServletException: Error instantiating servlet class controllers.Dashboard
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    java.lang.Thread.run(Thread.java:662)
root cause

java.lang.RuntimeException: Uncompilable source code - missing method body, or declare abstract
    DAO.OrderDAO.(OrderDAO.java:68)
    BO.OrderForm.(OrderForm.java:33)
    controllers.Dashboard.(Dashboard.java:23)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    java.lang.Class.newInstance0(Class.java:355)
    java.lang.Class.newInstance(Class.java:308)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    java.lang.Thread.run(Thread.java:662)

At first I was getting this in NetBeans 6.9.1 and continued to search and found this
weird bug  after trying th solution posted to no success I decided to switch IDE, so I downloaded the Intellij IDE 9 (loving it so far) and still got the same exception!! I mean come on.., the only three classes that do not belong to common libs are the DAO,BO and controllers packages and they a

Now I'm lost as the code exists and there no colon typo or anything.

EDIT 1:

removed the source code of DAO.OrderDAO.java, BO.OrderForm.java and controllers.OrderSearch.java as it was concluded that the problem was caused by one of the below classes (which one is yet to be determined.) So I configured IntelliJ debugger to stop whenever a Exception is thrown and I have a ClassNotFoundException being thrown in looking for the class org.apache.catalina.startup.bootstrap I'm unsure if this has to do with PATH variables because I have downloaded the apache-tomcat-6.0.30 and I verified that the troublesome class is there., Any suggestions?

Edit 2:

Switched back to NetBeans 6.9.1  added a bunch of libraries, the Runtime exception stopped, however I'm stuck again with the above exception and stack trace and I reiterate the method body is there!!.
A link to the complete trace, the password is 1234

Body:
java.io.NotSerializableException: DTO.ColorDTO

It seems ColorDTO doesn't implement Serializable

AND / OR

java.lang.RuntimeException: Uncompilable source code - missing method body, or declare abstract
at DAO.OrderDAO.<init>(OrderDAO.java:68)
at BO.OrderForm.<init>(OrderForm.java:33)

OrderDAO doesn't implement all the methods that it should implement or make it abstract and provide its implementation in subclass at last everything should be concrete.


问:
How to resolve this error (t: Identifier cannot extend from super type) on Hyperledger Composer playground?
Im following the Hyperledger tutorial Youtube Link and the instructor modifies a sample contract. However with the current version of Hyperledger fabric playground which can be accessed online, there is no mention of state after entering the accountTransfer function. This leads to an error as shown below:

How to solve the same? I have tried searching for answers but I couldnt find any which addresses this specific issue.

答:
t: stands for transaction.

you have two problems in your model

transactionId is already reserved (you don't need to model/define it - a transaction Id is returned when a transaction is submitted - Or call the field something else if you are using it for your own transaction purposes) - the Docs do mention this about transactionId https://hyperledger.github.io/composer/reference/cto_language.html

you do not use 'identified by' in your definition of the transaction - unlike Participants and Assets

see -> https://hyperledger.github.io/composer/reference/js_scripts.html and our sample networks (which you can browse) show examples of modeled transactions -> https://github.com/hyperledger/composer-sample-networks

I would add that more info about modeling transactions should be included in the  page ref in 1. above.

Finally for this out-of-context 't:' error (ie item 1 above) - we have an outstanding Github issue (a different kind of problem producing the error, but the same error results nonetheless). https://github.com/hyperledger/composer/issues/1497


问:
curved div with transparent top
I'm trying to create transparent div full width and height around 500px using borders but i have trouble with creating this kind of curved shape.
It should look like on the example image, the yellow shape.

.transparent_bg {
    width: 100%;
    height: 485px;
    background: transparent;
    border:solid 5px #000;
    border-color:#000 transparent transparent transparent;
    border-radius: 50%/200px 200px 0 0;
    transform: rotate(180deg);
    position: relative;
    overflow:hidden;
}

.transparent_bg:after {
    content: "";
    width: 100%;
    height: 485px;
    position: absolute;
    top: 0;
    background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="transparent_bg"></div></code>```

I have included a link to my work until this moment but without success.

答:
You can use clip path in both ways (on the top element or the bottom one) and simply make top and bottom to overlay like this :

.first,
.second {
  display: inline-block;
  margin: 5px;
}

.first .top {
  clip-path: circle(72.9% at 50% 27%);
  height: 200px;
  width: 200px;
  background: url(https://picsum.photos/id/10/800/800) center/cover;
  position: relative;
}

.first .bottom {
  margin-top: -70px;
  background: yellow;
  height: 100px;
  width: 200px;
}

.second .top {
  height: 200px;
  width: 200px;
  background:url(https://picsum.photos/id/10/800/800) center/cover;
  position: relative;
}

.second .bottom {
clip-path: polygon(0 25%, 14% 41%, 28% 51%, 49% 54%, 66% 53%, 79% 48%, 89% 39%, 100% 27%, 100% 100%, 47% 100%, 0% 100%);
  margin-top: -70px;
  background: yellow;
  height: 100px;
  width: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="first">
  <div class="top">
  </div>
  <div class="bottom">
  </div>
</div>

<div class="second">
  <div class="top">
  </div>
  <div class="bottom">
  </div>
</div></code>```

Here is a useful link to generate path :

https://bennettfeely.com/clippy/

Here is another idea using radial-gradient

.first  {
  height: 200px;
  width: 400px;
  background:
    radial-gradient(100% 100% at top, #0000 60%, yellow 61%),
    url(https://picsum.photos/id/10/800/800) center/cover;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="first">

</div></code>```

Using mask if you want transparency:

.first  {
  height: 200px;
  width: 400px;
  background: url(https://picsum.photos/id/10/800/800) center/cover;
  -webkit-mask:radial-gradient(100% 100% at top, #fff 60%, #0000 61%);
          mask:radial-gradient(100% 100% at top, #fff 60%, #0000 61%);
}
.bottom {
  -webkit-mask:radial-gradient(100% 100% at top, #0000 60%, #fff 61%);
          mask:radial-gradient(100% 100% at top, #0000 60%, #fff 61%);

}
body {
  background:yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="first">

</div>

<div class="first bottom">

</div></code>```

Title: curved div with transparent top

Body:
I'm trying to create transparent div full width and height around 500px using borders but i have trouble with creating this kind of curved shape.
It should look like on the example image, the yellow shape.

.transparent_bg {
    width: 100%;
    height: 485px;
    background: transparent;
    border:solid 5px #000;
    border-color:#000 transparent transparent transparent;
    border-radius: 50%/200px 200px 0 0;
    transform: rotate(180deg);
    position: relative;
    overflow:hidden;
}

.transparent_bg:after {
    content: "";
    width: 100%;
    height: 485px;
    position: absolute;
    top: 0;
    background: red;
}

I have included a link to my work until this moment but without success.

Body:
You can use clip path in both ways (on the top element or the bottom one) and simply make top and bottom to overlay like this :

.first,
.second {
  display: inline-block;
  margin: 5px;
}

.first .top {
  clip-path: circle(72.9% at 50% 27%);
  height: 200px;
  width: 200px;
  background: url(https://picsum.photos/id/10/800/800) center/cover;
  position: relative;
}

.first .bottom {
  margin-top: -70px;
  background: yellow;
  height: 100px;
  width: 200px;
}

.second .top {
  height: 200px;
  width: 200px;
  background:url(https://picsum.photos/id/10/800/800) center/cover;
  position: relative;
}

.second .bottom {
clip-path: polygon(0 25%, 14% 41%, 28% 51%, 49% 54%, 66% 53%, 79% 48%, 89% 39%, 100% 27%, 100% 100%, 47% 100%, 0% 100%);
  margin-top: -70px;
  background: yellow;
  height: 100px;
  width: 200px;
}

<div class="first">
  <div class="top">
  </div>
  <div class="bottom">
  </div>
</div>

<div class="second">
  <div class="top">
  </div>
  <div class="bottom">
  </div>
</div>

Here is a useful link to generate path :

https://bennettfeely.com/clippy/

Here is another idea using radial-gradient

.first  {
  height: 200px;
  width: 400px;
  background:
    radial-gradient(100% 100% at top, #0000 60%, yellow 61%),
    url(https://picsum.photos/id/10/800/800) center/cover;

}

<div class="first">

</div>

Using mask if you want transparency:

.first  {
  height: 200px;
  width: 400px;
  background: url(https://picsum.photos/id/10/800/800) center/cover;
  -webkit-mask:radial-gradient(100% 100% at top, #fff 60%, #0000 61%);
          mask:radial-gradient(100% 100% at top, #fff 60%, #0000 61%);
}
.bottom {
  -webkit-mask:radial-gradient(100% 100% at top, #0000 60%, #fff 61%);
          mask:radial-gradient(100% 100% at top, #0000 60%, #fff 61%);

}
body {
  background:yellow;
}

<div class="first">

</div>

<div class="first bottom">

</div>


问:
How could I limit the range of a variable in tensorflow
I want to train a model using tensorflow.

I have the following variable which I want the model to learn it

```<code>Mj=tf.get_variable('Mj_',dtype=tf.float32, shape=[500,4],initializer=tf.random_uniform_initializer(maxval=1, minval=0))
</code>```

I want the resulted value of Mj to be between 0 and 1. How can I add this constraint?

答:
The proper way to do this would be to pass the clipping function tf.clip_by_value as the constraint argument to the tf.Variable constructor:

```<code>Mj=tf.get_variable('Mj_',
                   dtype=tf.float32,
                   shape=[500,4],
                   initializer=tf.random_uniform_initializer(maxval=1, minval=0),
                   constraint=lambda t: tf.clip_by_value(t, 0, 1))
</code>```

From the docs of tf.Variable:

constraint: An optional projection function to be applied to the
  variable after being updated by an Optimizer (e.g. used to implement
  norm constraints or value constraints for layer weights). The function
  must take as input the unprojected Tensor representing the value of
  the variable and return the Tensor for the projected value (which must
  have the same shape). Constraints are not safe to use when doing
  asynchronous distributed training.

Or you might want to consider simply adding a nonlinearity tf.sigmoid on top of your variable.

```<code>Mj=tf.get_variable('Mj_',dtype=tf.float32, shape=[500,4])
Mj_out=tf.sigmoid(Mj)
</code>```

This will transform your variable to range between 0 and 1. Read more about activation functions here.

Body:
I want to train a model using tensorflow.

I have the following variable which I want the model to learn it

Mj=tf.get_variable('Mj_',dtype=tf.float32, shape=[500,4],initializer=tf.random_uniform_initializer(maxval=1, minval=0))

I want the resulted value of Mj to be between 0 and 1. How can I add this constraint?

Body:
The proper way to do this would be to pass the clipping function tf.clip_by_value as the constraint argument to the tf.Variable constructor:

Mj=tf.get_variable('Mj_',
                   dtype=tf.float32,
                   shape=[500,4],
                   initializer=tf.random_uniform_initializer(maxval=1, minval=0),
                   constraint=lambda t: tf.clip_by_value(t, 0, 1))

From the docs of tf.Variable:

constraint: An optional projection function to be applied to the
  variable after being updated by an Optimizer (e.g. used to implement
  norm constraints or value constraints for layer weights). The function
  must take as input the unprojected Tensor representing the value of
  the variable and return the Tensor for the projected value (which must
  have the same shape). Constraints are not safe to use when doing
  asynchronous distributed training.

Or you might want to consider simply adding a nonlinearity tf.sigmoid on top of your variable.

Mj=tf.get_variable('Mj_',dtype=tf.float32, shape=[500,4])
Mj_out=tf.sigmoid(Mj)

This will transform your variable to range between 0 and 1. Read more about activation functions here.


问:
Push confirmation notification before vocal action
I would like to push notification from google home app before do an vocal action

example: I dev an banking application, i want to ask by vocal command " transfer 10000$ to John Doe"

at this moment, i want a notification on my phone for confirm the transaction

someone knows about which function use ?

Thanks

答:
There is nothing in the Actions on Google platform that will do this directly, although you have a few potential ways to approach this.

As part of the conversation, you can confirm if they are talking to you through a mobile device. If they aren't, you can prompt them to continue the conversation there. Once they are on a mobile device, you can send a card that links to a URL which will let them authorize the transaction.

You can also use something like FCM to send the notification to their mobile platform when they reach that stage in the conversation. The notification would take them to your app or website to authorize the transaction.


问:
Does Python have an ordered set?
Python has an ordered dictionary. What about an ordered set?</p>

答:
There's no OrderedSet in official library.
I make an exhaustive cheatsheet of all the data structure for your reference.

```<code>DataStructure = {
    'Collections': {
        'Map': [
            ('dict', 'OrderDict', 'defaultdict'),
            ('chainmap', 'types.MappingProxyType')
        ],
        'Set': [('set', 'frozenset'), {'multiset': 'collection.Counter'}]
    },
    'Sequence': {
        'Basic': ['list', 'tuple', 'iterator']
    },
    'Algorithm': {
        'Priority': ['heapq', 'queue.PriorityQueue'],
        'Queue': ['queue.Queue', 'multiprocessing.Queue'],
        'Stack': ['collection.deque', 'queue.LifeQueue']
        },
    'text_sequence': ['str', 'byte', 'bytearray']
}
</code>```

Title: Does Python have an ordered set?

Body:
There's no OrderedSet in official library.
I make an exhaustive cheatsheet of all the data structure for your reference.

DataStructure = {
    'Collections': {
        'Map': [
            ('dict', 'OrderDict', 'defaultdict'),
            ('chainmap', 'types.MappingProxyType')
        ],
        'Set': [('set', 'frozenset'), {'multiset': 'collection.Counter'}]
    },
    'Sequence': {
        'Basic': ['list', 'tuple', 'iterator']
    },
    'Algorithm': {
        'Priority': ['heapq', 'queue.PriorityQueue'],
        'Queue': ['queue.Queue', 'multiprocessing.Queue'],
        'Stack': ['collection.deque', 'queue.LifeQueue']
        },
    'text_sequence': ['str', 'byte', 'bytearray']
}


问:
Windows rmdir batch to delete FOLDERS but skip files
So i have a dir called c:\user\jdoe\desktop\Folder1\

Inside folder1 i have many folders with subfolder and files.

I have a 7-Zip batch that zips all the folders in place.
So now i have subfolders and subfolders.zip inside folder1.

I need a batch that will detele all the non zipped folders but skip the zip files and the .bat file that lives in c:\user\jdoe\desktop\Folder1\

Any ideas?

If i can get a 7-zip batch that will zip fodlers (example subfolder1.zip subfolder2.zip) and then afterwards delete all non zipped folders that would be great.

Been all over the internet and after deleting half my data by testing my own scripts i have now decided to come here.

答:
So after a long collaboration with a friend we came up with this.
Tested this and it is working 100% </p>

```<code>REM create list of directories
SET cwd="C:\Users\user\Desktop\New folder"
SET date=date /T
CD %cwd%
DIR /AD /B >dirlist.txt

REM Zip contents of each directory
for /f "tokens=*" %%a in (dirlist.txt) do (
  "c:\program files\7-zip\7z.exe" a "%%a.zip" "%%a"

  del /s /q "%%a"
  rmdir /s /q "%%a"

)

del dirlist.txt

pause
</code>```

Body:
So after a long collaboration with a friend we came up with this.
Tested this and it is working 100%

REM create list of directories
SET cwd="C:\Users\user\Desktop\New folder"
SET date=date /T
CD %cwd%
DIR /AD /B >dirlist.txt

REM Zip contents of each directory
for /f "tokens=*" %%a in (dirlist.txt) do (
  "c:\program files\7-zip\7z.exe" a "%%a.zip" "%%a"

  del /s /q "%%a"
  rmdir /s /q "%%a"

)

del dirlist.txt

pause


问:
Check if a number is int or float
Here's how I did it:

```<code>inNumber = somenumber
inNumberint = int(inNumber)
if inNumber == inNumberint:
    print "this number is an int"
else:
    print "this number is a float"
</code>```

Something like that.

Are there any nicer looking ways to do this?

答:
how about this solution? </p>

```<code>if type(x) in (float, int):
    # do whatever
else:
    # do whatever
</code>```

Title: Check if a number is int or float

Body:
Here's how I did it:

inNumber = somenumber
inNumberint = int(inNumber)
if inNumber == inNumberint:
    print "this number is an int"
else:
    print "this number is a float"

Something like that.

Are there any nicer looking ways to do this?

Body:
how about this solution?

if type(x) in (float, int):
    # do whatever
else:
    # do whatever


问:
Socket.io listening on multiple ports?
I've did some searching and couldn't find any updated answers about this topic, seeing as the answers found applied only to older versions of Socket.io.

Here is my code:

```<code>let http = require('http').Server(app);
let io = require('socket.io')(http);

http.listen(7000, '::1', function () {
    // Now listening
});

io.on('connect', function (socket) {

}
</code>```

Am I able to add in additional code? such as:

```<code>http.listen(8000, '::1', function () {
    // Now listening
});

io2.on('connect', function (socket) {

}
</code>```

I want this single node.js instance to be listening on two different ports at once. This is so that I can handle two different types of clients appropriately, by having them connect to their appropriate socket, and then handling the two groups differently.

How would one do this?

答:
```<code>    var express =   require("express");

    var app =   express();

    app.get('/',function(req,res){
     console.log("Inside app get  method");

    });

    app.listen(2000,function(){
        console.log("Server is running on port 2000");
    });

    app.listen(2001,function(){
        console.log("Server is running on port 2001");
    });
</code>```

Title: Socket.io listening on multiple ports?

Body:
I've did some searching and couldn't find any updated answers about this topic, seeing as the answers found applied only to older versions of Socket.io.

Here is my code:

let http = require('http').Server(app);
let io = require('socket.io')(http);

http.listen(7000, '::1', function () {
    // Now listening
});

io.on('connect', function (socket) {

}

Am I able to add in additional code? such as:

http.listen(8000, '::1', function () {
    // Now listening
});

io2.on('connect', function (socket) {

}

I want this single node.js instance to be listening on two different ports at once. This is so that I can handle two different types of clients appropriately, by having them connect to their appropriate socket, and then handling the two groups differently.

How would one do this?