问:
correct way to call api using react
I have a react code as below which basically creates a treemap:

```<code>class ChartModal extends Component{
   constructor(props){
      super(props)
}
callApi(){

  fetch(someurl)
  .then((result) => {

    return result.json();
  }).then((jsonResult) => {
    console.log(jsonResult);
  })
}
render(){
  return(
    <Modal
            onOk={() => this.props.toggleVisibility()}
            onCancel={() => this.props.toggleVisibility()}
            visible={this.props.isVisible}
            okText={'ok'}
            cancelText={'cancel'}
            confirmLoading={false}
            title="Intent distribution chart"
        >
            <h1>HOWDY</h1>
            <TreeMap
                data =  {this.callApi()}//this is where i want the data returned by apicall
                width={400}
                valueUnit={'count'}
            />
        </Modal>
    )
  }
}
</code>```

Now I want the data returned by api call to be used inside the tree map component, but the way I am doing it now doesn't seem to be working.
When I run this, the data in the tree map comes out to be null though I expect a json returned by api call to be there.

答:
The problem is that callApi isn't returning anything. If it's supposed to assign the data somewhere, it isn't. And if does return something, it will be a promise since it's async.

What you can do is use a state variable and map it to the data prop of your TreeMap. Then use the componentDidMount lifecycle function to fetch the data once the component is rendered. Once it responds, update the mapped state variable with the results. In theory, it should re-render TreeMap automatically.

Title: correct way to call api using react

Body:
I have a react code as below which basically creates a treemap:

class ChartModal extends Component{
   constructor(props){
      super(props)
}
callApi(){

  fetch(someurl)
  .then((result) => {

    return result.json();
  }).then((jsonResult) => {
    console.log(jsonResult);
  })
}
render(){
  return(
    <Modal
            onOk={() => this.props.toggleVisibility()}
            onCancel={() => this.props.toggleVisibility()}
            visible={this.props.isVisible}
            okText={'ok'}
            cancelText={'cancel'}
            confirmLoading={false}
            title="Intent distribution chart"
        >

HOWDY

            <TreeMap
                data =  {this.callApi()}//this is where i want the data returned by apicall
                width={400}
                valueUnit={'count'}
            />
        </Modal>
    )
  }
}

Now I want the data returned by api call to be used inside the tree map component, but the way I am doing it now doesn't seem to be working.
When I run this, the data in the tree map comes out to be null though I expect a json returned by api call to be there.


来源: stackexchange

问:
awk a number, character, then the same number
I have a column of values where the field begins with n/n: and where n is a number between 0 and 20.

Other columns also contain "n/n:" information; I only want to filter based on a single specific column.

"n/n:" can be a combination of any pair of numbers between 0 and 20 (ex. 0/1:, 1/1:, 1/19:, 19/19:)

I would like to filter lines in the file where the first and second n are the same number in the column of interest (0/0, 1/1,... 20/20).

Rather than do this once for each combination of numbers (each iteration would take a long time):

```<code>awk '$col !~ /^n\/n:/' file > filtered.file
</code>```

... I'm hoping there's a more concise, better way.

An example of the file

```<code> 1/1: 0/1: a
 1/2: 1/1: b
 0/1: 2/2: c
 3/3: 0/2: d
 0/2: 0/1: e
</code>```

Desired output, filtered based on col2

```<code> 1/1: 0/1: a
 3/3: 0/2: d
 0/2: 0/1: e
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a column of values where the field begins with n/n: and where n is a number between 0 and 20.

Other columns also contain "n/n:" information; I only want to filter based on a single specific column.

"n/n:" can be a combination of any pair of numbers between 0 and 20 (ex. 0/1:, 1/1:, 1/19:, 19/19:)

I would like to filter lines in the file where the first and second n are the same number in the column of interest (0/0, 1/1,... 20/20).

Rather than do this once for each combination of numbers (each iteration would take a long time):

awk '$col !~ /^n\/n:/' file > filtered.file

... I'm hoping there's a more concise, better way.

An example of the file

 1/1: 0/1: a
 1/2: 1/1: b
 0/1: 2/2: c
 3/3: 0/2: d
 0/2: 0/1: e

Desired output, filtered based on col2

 1/1: 0/1: a
 3/3: 0/2: d
 0/2: 0/1: e

Body:
awk to the rescue!

UPDATED

$ awk -v col=2 '{split($col,a,"[/:]")} a[1]!=a[2]' file

 1/1: 0/1: a
 3/3: 0/2: d
 0/2: 0/1: e


问:
Split string into multiple alpha and numeric segments
I have a string like "ABCD232ERE44RR". How can I split it into separate segments by letters/numbers. I need:
Segment1: ABCD
Segment2: 232
Segment3: ERE
Segment4: 44

There could be any number of segments. I am thinking go Regex but don't understand how to write it properly

答:
I suggest thinking of this as finding matches to a target pattern rather than splitting into the parts you want. Splitting gives significance to the delimiters whereas matching gives significance to the tokens.

You can use Regex.Matches:

Searches the specified input string for all occurrences of a specified regular expression.

```<code>var matches = Regex.Matches("ABCD232ERE44RR", "[A-Z]+|[0-9]+");

foreach (Match match in matches) {
     Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index);
}
</code>```

Body:
I suggest thinking of this as finding matches to a target pattern rather than splitting into the parts you want. Splitting gives significance to the delimiters whereas matching gives significance to the tokens.

You can use Regex.Matches:

Searches the specified input string for all occurrences of a specified regular expression.

var matches = Regex.Matches("ABCD232ERE44RR", "[A-Z]+|[0-9]+");

foreach (Match match in matches) {
     Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index);
}


问:
How to authenticate JavaFX client in JavaEE
I develop three-tier application with JavaFX on client side, JavaEE/Glassfish on server side and MySQL as a database management system. Also I used REST and JSON for transferring the data across network.

Now I try to configure an authentication using JavaEE security means. I use declarative approach with annotations in enterprise beans, I've already configured Glassfish file realm (add user/group) and glassfish-web.xml descriptor (add group-name and role tags). JavaEE tutorial say that If all of needed preparations done then when client attempt to get the protected resource Glassfish should ask client for a login/password pair. I  understand how it work if it would be a web-client, but in my case it is a desktop JavaFX client and I don't understand how Glassfish ask client in desktop application. How to make authentication mechanism with JavaFX-Glassfish?

Update

Authentication window popup if I try to call servlet from browser (Chrome, IE) and authentication mechanism is able to work. But when I open JavaFX window I see nothing (white scene).
Here is the code of class (JavaFX WebView), which I unsuccessfully used to open login window:

```<code>import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

    public class WebViewSample extends Application {
        private Scene scene;

        @Override
        public void start(Stage stage) {
            // create the scene
            stage.setTitle("Web View");
            scene = new Scene(new Browser(), 750, 500, Color.web("#666970"));
            stage.setScene(scene);
            scene.getStylesheets().add("webviewsample/BrowserToolbar.css");
            stage.show();
        }

        public static void main(String[] args) {
            launch(args);
        }
    }

    class Browser extends Region {

        final WebView browser = new WebView();
        final WebEngine webEngine = browser.getEngine();

        public Browser() {

        getStyleClass().add("browser");
    webEngine.load("http://localhost:8080/ForthDynamicWebProject/FirstServlet");
        getChildren().add(browser);
            }
        }
</code>```

答:
You should not use standard Java EE cookie authentication here because your client is desktop application.

You can use Token authentication solution. The below is a guide.

Login servlet: This servlet will verify userName and password. If verification is success, the servlet will return a token contains userId, roles, expires ... etc. You can use JWT (Json Web Token) format. Token will be generated/validated by server using a secret key.

Login scene - JavaFX: When login button pressed, the app will send login request to the login servlet. If login is success, the app will receive a token and save the token in a secret storage for later uses. In memory should be ok.

For subsequent HTTP requests (JavaFX): The app need to resend the token (via header etc). The server will validate the token BEFORE actual resource get invoked. If the validation is success, request is consider as authenticated. You can use JavaEE Filter to validate the token.

ContentLicense: CC BY-SA 4.0

Body:
I develop three-tier application with JavaFX on client side, JavaEE/Glassfish on server side and MySQL as a database management system. Also I used REST and JSON for transferring the data across network.

Now I try to configure an authentication using JavaEE security means. I use declarative approach with annotations in enterprise beans, I've already configured Glassfish file realm (add user/group) and glassfish-web.xml descriptor (add group-name and role tags). JavaEE tutorial say that If all of needed preparations done then when client attempt to get the protected resource Glassfish should ask client for a login/password pair. I  understand how it work if it would be a web-client, but in my case it is a desktop JavaFX client and I don't understand how Glassfish ask client in desktop application. How to make authentication mechanism with JavaFX-Glassfish?

Update

Authentication window popup if I try to call servlet from browser (Chrome, IE) and authentication mechanism is able to work. But when I open JavaFX window I see nothing (white scene).
Here is the code of class (JavaFX WebView), which I unsuccessfully used to open login window:

import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

    public class WebViewSample extends Application {
        private Scene scene;

        @Override
        public void start(Stage stage) {
            // create the scene
            stage.setTitle("Web View");
            scene = new Scene(new Browser(), 750, 500, Color.web("#666970"));
            stage.setScene(scene);
            scene.getStylesheets().add("webviewsample/BrowserToolbar.css");
            stage.show();
        }

        public static void main(String[] args) {
            launch(args);
        }
    }

    class Browser extends Region {

        final WebView browser = new WebView();
        final WebEngine webEngine = browser.getEngine();

        public Browser() {

        getStyleClass().add("browser");
    webEngine.load("http://localhost:8080/ForthDynamicWebProject/FirstServlet");
        getChildren().add(browser);
            }
        }


问:
compute an approximation of pi using cuda in python
I would like to use this simple formula to compute an approximation of pi :
pi approx formula

Here is my code :

```<code>def pi(iteration):
    pi = 0.0
    sign = 1
    b = 1.0

    for i in range(iteration):
        pi += 4.0*sign/b

        b += 2
        sign *= -1

    print pi

pi(100000)
</code>```

How to make this code be computed by the GPU?

答:
You can use Numba.
Here is a good example specifically for CUDA using python for calculating value of pi.
https://github.com/numba/numba/blob/master/examples/pi.py</p>

Body:
I would like to use this simple formula to compute an approximation of pi :
pi approx formula

Here is my code :

def pi(iteration):
    pi = 0.0
    sign = 1
    b = 1.0

    for i in range(iteration):
        pi += 4.0*sign/b

        b += 2
        sign *= -1

    print pi

pi(100000)

How to make this code be computed by the GPU?


问:
How to pass around parameter packs in C++?
Consider the following example:

```<code>template <class T> class method_traits;
template <class T, class Ret, class... Arg> class method_traits<Ret(T::*)(Arg...)> {
public:
    using type = Arg; // this does not work
};

template <class T> using argument_types = typename method_traits<T>::type;

template <class T> class Node {
    T t;
public:
    Node(Input<argument_types<decltype(&T::process)>>... inputs) { // how do I make this work?
        ...
    }
};
</code>```

The arguments of the constructor of Node<T> depend on the arguments of the method T::process. So if a type T has a method process of the signature float process(float a, int b) the signature of the constructor of Node<T> should look like this: Node(Input<float> a, Input<int> b).

How do I extract the parameter pack from T::process to use it on the constructor of Node?

答:
How about using private inheritance and CRTP?

```<code>#include <tuple>
#include <iostream>

template <typename Method> struct method_traits;

template <typename T, typename Ret, typename... Args>
struct method_traits<Ret(T::*)(Args...)> {
public:
    using parameter_pack = std::tuple<Args...>;
};

template <typename Derived, typename Tuple> struct Base;

template <typename Derived, typename... Ts>
struct Base<Derived, std::tuple<Ts...>> {
    void execute_constructor(Ts&&... ts) {
        Derived* d = static_cast<Derived*>(this);
        d->t.process(std::forward<Ts>(ts)...);
        d->num = sizeof...(Ts);
    }
    virtual ~Base() = default;
};

template <typename T, typename... Rest>
class Node : Base<Node<T, Rest...>, typename method_traits<decltype(&T::process)>::parameter_pack> {
    T t;
    int num;
public:
    using Base = Base<Node<T, Rest...>, typename method_traits<decltype(&T::process)>::parameter_pack>;
    friend Base;  // So that Base can do whatever it needs to Node<T, Rest...>'s data members.
    template <typename... Ts>
    Node (Ts&&... ts) {
        Base::execute_constructor(std::forward<Ts>(ts)...);
        std::cout << "num = " << num << '\n';
    }
};

struct foo {
    void process(int a, char c, bool b) {
        std::cout << "foo(" << a << ", " << c << ", " << std::boolalpha << b << ") carried out.\n";
    }
};

int main() {
    Node<foo> n(5, 'a', true);
    std::cin.get();
}
</code>```

Output:

```<code>foo(5, a, true) carried out.
num = 3
</code>```

Body:
Consider the following example:

template <class T> class method_traits;
template <class T, class Ret, class... Arg> class method_traits<Ret(T::*)(Arg...)> {
public:
    using type = Arg; // this does not work
};

template <class T> using argument_types = typename method_traits<T>::type;

template <class T> class Node {
    T t;
public:
    Node(Input<argument_types<decltype(&T::process)>>... inputs) { // how do I make this work?
        ...
    }
};

The arguments of the constructor of Node<T> depend on the arguments of the method T::process. So if a type T has a method process of the signature float process(float a, int b) the signature of the constructor of Node<T> should look like this: Node(Input<float> a, Input<int> b).

How do I extract the parameter pack from T::process to use it on the constructor of Node?

Body:
How about using private inheritance and CRTP?

#include <tuple>
#include <iostream>

template <typename Method> struct method_traits;

template <typename T, typename Ret, typename... Args>
struct method_traits<Ret(T::*)(Args...)> {
public:
    using parameter_pack = std::tuple<Args...>;
};

template <typename Derived, typename Tuple> struct Base;

template <typename Derived, typename... Ts>
struct Base<Derived, std::tuple<Ts...>> {
    void execute_constructor(Ts&&... ts) {
        Derived* d = static_cast<Derived*>(this);
        d->t.process(std::forward<Ts>(ts)...);
        d->num = sizeof...(Ts);
    }
    virtual ~Base() = default;
};

template <typename T, typename... Rest>
class Node : Base<Node<T, Rest...>, typename method_traits<decltype(&T::process)>::parameter_pack> {
    T t;
    int num;
public:
    using Base = Base<Node<T, Rest...>, typename method_traits<decltype(&T::process)>::parameter_pack>;
    friend Base;  // So that Base can do whatever it needs to Node<T, Rest...>'s data members.
    template <typename... Ts>
    Node (Ts&&... ts) {
        Base::execute_constructor(std::forward<Ts>(ts)...);
        std::cout << "num = " << num << '\n';
    }
};

struct foo {
    void process(int a, char c, bool b) {
        std::cout << "foo(" << a << ", " << c << ", " << std::boolalpha << b << ") carried out.\n";
    }
};

int main() {
    Node<foo> n(5, 'a', true);
    std::cin.get();
}

Output:

foo(5, a, true) carried out.
num = 3


问:
Looping through SQLDW table with Python
I have a table in a Microsoft Azure SQLDW that has a date field, as well as other columns. There is a row for each day in the past 10 years of business days. Currently the table has not been stored in such a way like "order by date" etc. Below is the code I have so far:

```<code>import pyodbc driver = '{ODBC Driver 13 for SQL Server}'
conn = pyodbc.connect('DRIVER='+driver+';
PORT=1433;SERVER='+server+';
DATABASE='+database+';
UID='+username+';
PWD='+ password)
cursor = conn.cursor() cursor.execute("SELECT * FROM index_att") i = 0 for row in cursor: i += 1 print(i)
</code>```

If I'm using python to loop through every row in this table and I want to go in chronological order (from oldest date to current date) does the table need to be stored in a way that it is ordered by date? And do I need to add an additional incremental ID that starts at 1 with the oldest date and goes up each day?

Or is there a way to do this loop through dates with the data not sorted?

答:
Add an order by to your select statement:</p>

```<code>cursor = conn.cursor()
cursor.execute("SELECT * FROM index_att ORDER BY [MyDate]")
i = 0
for row in cursor:
    i += 1 print(i)
</code>```

Title: Looping through SQLDW table with Python

Body:
I have a table in a Microsoft Azure SQLDW that has a date field, as well as other columns. There is a row for each day in the past 10 years of business days. Currently the table has not been stored in such a way like "order by date" etc. Below is the code I have so far:

import pyodbc driver = '{ODBC Driver 13 for SQL Server}'
conn = pyodbc.connect('DRIVER='+driver+';
PORT=1433;SERVER='+server+';
DATABASE='+database+';
UID='+username+';
PWD='+ password)
cursor = conn.cursor() cursor.execute("SELECT * FROM index_att") i = 0 for row in cursor: i += 1 print(i)

If I'm using python to loop through every row in this table and I want to go in chronological order (from oldest date to current date) does the table need to be stored in a way that it is ordered by date? And do I need to add an additional incremental ID that starts at 1 with the oldest date and goes up each day?

Or is there a way to do this loop through dates with the data not sorted?

Body:
Add an order by to your select statement:

cursor = conn.cursor()
cursor.execute("SELECT * FROM index_att ORDER BY [MyDate]")
i = 0
for row in cursor:
    i += 1 print(i)


问:
How do securely download a file in Appcelerator?
I'm building an iPad app using Appcelerator and I need to securely download an XML file from a web server.  What's the best method for doing this?

I've considered using FTP, but there is no FTP support in Appcelerator, so I would essentially have to start from scratch. Could I use TLS? Am I way off track all together?

Thanks!

答:
this is how I do it.

1] In the Kitchen Sink code check out Platform > XHR > File Download and you can download a remote file.  I would suggest accessing that file over HTTPS for a secure connection.

2] If you want to make sure that not anyone can get to it you'll want to do some authentication.  You can use HTTP auth... here is an example: http://developer.appcelerator.com/question/20951/how-to-do-a-http-put-with-http-basic-authentication  - At your application side of things you'll want to set this up to require some authentication.

Hope that helps... it will get you the file over a secure connection and require a login / password to acquire the file.

ContentLicense: CC BY-SA 2.5


问:
What's the simplest way of horizontally aligning a Font Awesome icon in the center of a div using Bootstrap?
I want to create 3 icons that are sitting at the bottom of my webpage:</p>

```<code><div class="container">
    <h1>contact</h1>
     <div class="row">
        <div class="col-sm-4"><i class="icon-facebook"></i></div>
        <div class="col-sm-4"><i class="icon-envelope"></i></div>
        <div class="col-sm-4"><i class="icon-linkedin"></i></div>
     </div>
 </div>
</div>
</code>```

答: Add text-center  class to your div.

Body:
I want to create 3 icons that are sitting at the bottom of my webpage:

contact

Body: Add text-center  class to your div.


问:
How to check how much char space in 1 string
Lets say I have a string with some text:

```<code>String str="Hello My Name Is Help!"
</code>```

And I want to check how much space chars I have in the following String str. I would like a make a method that takes that following string and returns the number of whitespaces in that string. For example if I name my method getNumberOfWhiteSpaces(String str) and call it a I should get back the number of whitespaces.

```<code>if( getNumberOfWhiteSpaces(String str) > 3)
     System.out.println("There are more then 3 spaces in this string");

public int getNumberOfWhiteSpaces(String str) {
  ....
  return some number
}
</code>```

答:
Java 8 way could be:

```<code>s.chars().filter(Character::isWhitespace).count()
</code>```

which will give you the number of white space in the string s. You can also use isSpaceChar.

Body:
Lets say I have a string with some text:

String str="Hello My Name Is Help!"

And I want to check how much space chars I have in the following String str. I would like a make a method that takes that following string and returns the number of whitespaces in that string. For example if I name my method getNumberOfWhiteSpaces(String str) and call it a I should get back the number of whitespaces.

if( getNumberOfWhiteSpaces(String str) > 3)
     System.out.println("There are more then 3 spaces in this string");

public int getNumberOfWhiteSpaces(String str) {
  ....
  return some number
}

Body:
Java 8 way could be:

s.chars().filter(Character::isWhitespace).count()

which will give you the number of white space in the string s. You can also use isSpaceChar.


问:
Converting strange SQL Server JOIN syntax to MySQL syntax
I have a SQL Server query that I am attempting to port to MySQL, but the JOIN syntax is something that I have never seen used before. The query is from a view designed to measure procedure code usage. What the heck is going on with the JOIN syntax just past T.PatID = P.ID, and the third LEFT OUTER JOIN, and what equivalent syntax can we use in MySQL? It does not like this JOIN syntax at all (disregard the ISNULL and CONVERT SQL Server specific syntax)

```<code>SELECT
                T.Code
              , P.LastName
              , P.FirstName
              , T.TranDate
              , CD.DaysUnits
              , T.TranAmt
              , TD.FullName AS Provider
              , ISNULL(TD.ID, ISNULL(AD.ID, PD.ID))                   AS DoctorID
FROM
                dbo.Doctors AS PD
                INNER JOIN
                                dbo.Transactions AS T
                INNER JOIN
                                dbo.Patients AS P
                                ON
                                                T.PatID = P.ID
                                                ON
                                                                PD.ID = P.DoctorID
                                LEFT OUTER JOIN
                                                dbo.Doctors AS TD
                                                ON
                                                                T.DoctorID = TD.ID
                                LEFT OUTER JOIN
                                                dbo.Doctors AS AD
                                LEFT OUTER JOIN
                                                dbo.Appointments
                                                ON
                                                                AD.ID                                                           = dbo.Appointments.DoctorID
                                                                AND CONVERT(varchar(20), dbo.Appointments.ScheduleDateTime, 8) <> '00:00:00'
                                                                ON
                                                                                T.ApptID = dbo.Appointments.ID
                                                LEFT OUTER JOIN
                                                                dbo.ChargeDetails AS CD
                                                                ON
                                                                                T.ID = CD.ChargeTranID
                                WHERE
                                                (
                                                                T.Code IS NOT NULL
                                                )
</code>```

The SHOW CREATE TABLE are as follows

```<code>CREATE TABLE Doctors
             (

                          ID       int(10) NOT NULL PRIMARY KEY
                        , FullName varchar(50) DEFAULT NULL

             )

CREATE TABLE Patients
             (
                          LName                     varchar(50) DEFAULT NULL
                        , FName                     varchar(50) DEFAULT NULL
                        , ID                        int(10) NOT NULL PRIMARY KEY

             )

CREATE TABLE Transactions
             (
                           TranType           varchar(2) DEFAULT NULL
                        ,  Code               varchar(100) DEFAULT NULL
                        ,  TranSubType        varchar(2) DEFAULT NULL
                        ,  Description         varchar(2000) DEFAULT NULL
                        ,  TranDate           datetime
                        ,  PatID              int(10) DEFAULT NULL
                        ,  ID                 int(10) NOT NULL PRIMARY KEY
                        ,  TranAmt            decimal(19,4) DEFAULT NULL
                        ,  ApptID             int(10) DEFAULT NULL
                        ,  DoctorID          int(10) DEFAULT NULL

             )

CREATE TABLE ChargeDetails
             (

                           DaysUnits          varchar(50) DEFAULT NULL
                        -- DaysUnits is just an int ranging from 1 to 2
                        ,  ChargeTranID       int(10) NOT NULL PRIMARY KEY
             )

CREATE TABLE Appointments
             (

                           DoctorID              int(10) DEFAULT NULL
                        ,  PatientID            int(10) DEFAULT NULL
                        ,  ScheduleDateTime      datetime DEFAULT NULL
                        ,  ID                   int(10) NOT NULL PRIMARY KEY
             )
</code>```

Thank you in advance for your help.

答:
Here is a similar (and simplified) query using the same structure as the first query. The second query moves the joins around to make things easier to read.

```<code>set nocount on;
use tempdb;
go

declare @doc table (id int not null);
declare @tran table (id int not null, patid int not null);
declare @patients table (id int not null, docid int not null);

insert @doc (id) values (1);
insert @patients (id, docid) values (25, 1);
insert @tran (id, patid) values (100, 25)

select *
from @doc as pd
inner join @tran as t
inner join @patients as p
on t.patid = p.id
on pd.id = p.docid;

select *
from @tran as t
inner join @patients as p
on t.patid = p.id
inner join @doc as pd
on pd.id = p.docid;
</code>```

Other things look strange. I don't see a need to join to appointments but I'm not going to spend a lot of time to figure out the logic and the schema. The convert usage seems like a bad way to check for null - unless there is a special "flag" datetime value that is used as the equivalent to null. Again, you need to understand the query, the goal of the query, the schema on which it is based, and how the tables are populated. Quite frankly, this code raises concerns about the quality of the entire system.

.

Body:
I have a SQL Server query that I am attempting to port to MySQL, but the JOIN syntax is something that I have never seen used before. The query is from a view designed to measure procedure code usage. What the heck is going on with the JOIN syntax just past T.PatID = P.ID, and the third LEFT OUTER JOIN, and what equivalent syntax can we use in MySQL? It does not like this JOIN syntax at all (disregard the ISNULL and CONVERT SQL Server specific syntax)

SELECT
                T.Code
              , P.LastName
              , P.FirstName
              , T.TranDate
              , CD.DaysUnits
              , T.TranAmt
              , TD.FullName AS Provider
              , ISNULL(TD.ID, ISNULL(AD.ID, PD.ID))                   AS DoctorID
FROM
                dbo.Doctors AS PD
                INNER JOIN
                                dbo.Transactions AS T
                INNER JOIN
                                dbo.Patients AS P
                                ON
                                                T.PatID = P.ID
                                                ON
                                                                PD.ID = P.DoctorID
                                LEFT OUTER JOIN
                                                dbo.Doctors AS TD
                                                ON
                                                                T.DoctorID = TD.ID
                                LEFT OUTER JOIN
                                                dbo.Doctors AS AD
                                LEFT OUTER JOIN
                                                dbo.Appointments
                                                ON
                                                                AD.ID                                                           = dbo.Appointments.DoctorID
                                                                AND CONVERT(varchar(20), dbo.Appointments.ScheduleDateTime, 8) <> '00:00:00'
                                                                ON
                                                                                T.ApptID = dbo.Appointments.ID
                                                LEFT OUTER JOIN
                                                                dbo.ChargeDetails AS CD
                                                                ON
                                                                                T.ID = CD.ChargeTranID
                                WHERE
                                                (
                                                                T.Code IS NOT NULL
                                                )

The SHOW CREATE TABLE are as follows

CREATE TABLE Doctors
             (

                          ID       int(10) NOT NULL PRIMARY KEY
                        , FullName varchar(50) DEFAULT NULL

             )

CREATE TABLE Patients
             (
                          LName                     varchar(50) DEFAULT NULL
                        , FName                     varchar(50) DEFAULT NULL
                        , ID                        int(10) NOT NULL PRIMARY KEY

             )

CREATE TABLE Transactions
             (
                           TranType           varchar(2) DEFAULT NULL
                        ,  Code               varchar(100) DEFAULT NULL
                        ,  TranSubType        varchar(2) DEFAULT NULL
                        ,  Description         varchar(2000) DEFAULT NULL
                        ,  TranDate           datetime
                        ,  PatID              int(10) DEFAULT NULL
                        ,  ID                 int(10) NOT NULL PRIMARY KEY
                        ,  TranAmt            decimal(19,4) DEFAULT NULL
                        ,  ApptID             int(10) DEFAULT NULL
                        ,  DoctorID          int(10) DEFAULT NULL

             )

CREATE TABLE ChargeDetails
             (

                           DaysUnits          varchar(50) DEFAULT NULL
                        -- DaysUnits is just an int ranging from 1 to 2
                        ,  ChargeTranID       int(10) NOT NULL PRIMARY KEY
             )

CREATE TABLE Appointments
             (

                           DoctorID              int(10) DEFAULT NULL
                        ,  PatientID            int(10) DEFAULT NULL
                        ,  ScheduleDateTime      datetime DEFAULT NULL
                        ,  ID                   int(10) NOT NULL PRIMARY KEY
             )

Thank you in advance for your help.

Body:
Here is a similar (and simplified) query using the same structure as the first query. The second query moves the joins around to make things easier to read.

set nocount on;
use tempdb;
go

declare @doc table (id int not null);
declare @tran table (id int not null, patid int not null);
declare @patients table (id int not null, docid int not null);

insert @doc (id) values (1);
insert @patients (id, docid) values (25, 1);
insert @tran (id, patid) values (100, 25)

select *
from @doc as pd
inner join @tran as t
inner join @patients as p
on t.patid = p.id
on pd.id = p.docid;

select *
from @tran as t
inner join @patients as p
on t.patid = p.id
inner join @doc as pd
on pd.id = p.docid;

Other things look strange. I don't see a need to join to appointments but I'm not going to spend a lot of time to figure out the logic and the schema. The convert usage seems like a bad way to check for null - unless there is a special "flag" datetime value that is used as the equivalent to null. Again, you need to understand the query, the goal of the query, the schema on which it is based, and how the tables are populated. Quite frankly, this code raises concerns about the quality of the entire system.

.


问:
loop through string to find substring
I have this string:

```<code>text = "book//title//page/section/para";
</code>```

I want to go through it to find all // and / and their index.

I tried doing this with:

```<code>if (text.Contains("//"))
{
    Console.WriteLine(" // index:  {0}  ", text.IndexOf("//"));
}
if (text.Contains("/"))
{
    Console.WriteLine("/ index:  {0}  :", text.IndexOf("/"));
}
</code>```

I was also thinking about using:

```<code>Foreach(char c in text)
</code>```

but it will not work since // is not a single char.

How can I achieve what I want?

I tried this one also but did not display result

```<code>string input = "book//title//page/section/para";
string pattern = @"\/\//";

Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
 if (matches.Count > 0)
  {
      Console.WriteLine("{0} ({1} matches):", input, matches.Count);
      foreach (Match match in matches)
         Console.WriteLine("   " + input.IndexOf(match.Value));
 }
</code>```

Thank you in advance.

答:
Sometin like:

```<code>bool lastCharASlash = false;
foreach(char c in text)
{
    if(c == @'/')
    {
      if(lastCharASlash)
      {

          // my code...
      }
      lastCharASlash = true;
    }
    else lastCharASlash = false;
}
</code>```

You can also do text.Split(@"//")

Title: loop through string to find substring

Body:
I have this string:

text = "book//title//page/section/para";

I want to go through it to find all // and / and their index.

I tried doing this with:

if (text.Contains("//"))
{
    Console.WriteLine(" // index:  {0}  ", text.IndexOf("//"));
}
if (text.Contains("/"))
{
    Console.WriteLine("/ index:  {0}  :", text.IndexOf("/"));
}

I was also thinking about using:

Foreach(char c in text)

but it will not work since // is not a single char.

How can I achieve what I want?

I tried this one also but did not display result

string input = "book//title//page/section/para";
string pattern = @"\/\//";

Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
 if (matches.Count > 0)
  {
      Console.WriteLine("{0} ({1} matches):", input, matches.Count);
      foreach (Match match in matches)
         Console.WriteLine("   " + input.IndexOf(match.Value));
 }

Thank you in advance.

Body:
Sometin like:

bool lastCharASlash = false;
foreach(char c in text)
{
    if(c == @'/')
    {
      if(lastCharASlash)
      {

          // my code...
      }
      lastCharASlash = true;
    }
    else lastCharASlash = false;
}

You can also do text.Split(@"//")


问:
Bootstrap-table: Server Side pagination + nextPage method
I'm using Django and the app Bootstrap-table to correctly format my tables.

I've got a lot of data so I'm using a server-side pagination. It's working great.

Now I'd like to implement some method like a nextPage method.

By combining the example jsfiddle of server-side pagination + method nextPage, it doesn't work : Clicking on the button nextPage does nothing  even if it's bound to nextPage method:

http://jsfiddle.net/ThePhi/msj2apLb/1/

```<code><button id="button2" class="btn btn-default">nextPage</button>

<table data-toggle="table"
       data-url="http://issues.wenzhixin.net.cn/examples/bootstrap_table/data"
       data-pagination="true"
       data-side-pagination="server"
       data-page-list="[5, 10, 20, 50, 100, 200]"
       data-search="true"
       data-height="300">
    <thead>
    <tr>
        <th data-field="state" data-checkbox="true"></th>
        <th data-field="id" data-align="right" data-sortable="true">Item ID</th>
        <th data-field="name" data-align="center" data-sortable="true">Item Name</th>
        <th data-field="price" data-sortable="true">Item Price</th>
    </tr>
    </thead>
</table>
<script>
    var $table = $('#table'),

        $button2 = $('#button2');
    $(function () {

        $button2.click(function () {
            $table.bootstrapTable('nextPage');
        });

    });
</script>
</code>```

答:
I forgot to put id="table" ...

working jsFiddle: http://jsfiddle.net/ThePhi/msj2apLb/1/

Body:
I'm using Django and the app Bootstrap-table to correctly format my tables.

I've got a lot of data so I'm using a server-side pagination. It's working great.

Now I'd like to implement some method like a nextPage method.

By combining the example jsfiddle of server-side pagination + method nextPage, it doesn't work : Clicking on the button nextPage does nothing  even if it's bound to nextPage method:

http://jsfiddle.net/ThePhi/msj2apLb/1/

<button id="button2" class="btn btn-default">nextPage</button>

        Item ID
        Item Name
        Item Price


问:
Plot type for illustrating before and after scores
Given a basic dataset like so:

```<code>import pandas as pd

df = pd.DataFrame([
  {'sid': 'SID0', 'before': .5, 'after': .8},
  {'sid': 'SID1', 'before': .6, 'after': .4},
  {'sid': 'SID2', 'before': .2, 'after': .2}
]);
# `before `has max value of 1.0; same for `after`, as these are percentages
</code>```

What's a way of charting the difference between before & after scores?

Thinking to exclude the SID, and showing the distribution properly (# of students matters; not just scatter-plotting the scores). With the SID I played around with slope graphs, but that's just not good to show aggregate reflections.

答:
IIUC, something just like this (Chainsmokers / Coldplay):

```<code>ax = df.set_index('sid').eval('diff = after - before')\
       .plot(kind='bar', alpha =1, edgecolor='black', zorder=10)
ax.grid(axis='y', color='k', alpha=.5)
</code>```

Body:
Given a basic dataset like so:

import pandas as pd

df = pd.DataFrame([
  {'sid': 'SID0', 'before': .5, 'after': .8},
  {'sid': 'SID1', 'before': .6, 'after': .4},
  {'sid': 'SID2', 'before': .2, 'after': .2}
]);
# `before `has max value of 1.0; same for `after`, as these are percentages

What's a way of charting the difference between before & after scores?

Thinking to exclude the SID, and showing the distribution properly (# of students matters; not just scatter-plotting the scores). With the SID I played around with slope graphs, but that's just not good to show aggregate reflections.

Body:
IIUC, something just like this (Chainsmokers / Coldplay):

ax = df.set_index('sid').eval('diff = after - before')\
       .plot(kind='bar', alpha =1, edgecolor='black', zorder=10)
ax.grid(axis='y', color='k', alpha=.5)


问:
Alternatives to long polling?
I have an application in JAVA which checks from the ftp server, whether a given file is updated or not. If the file is updated, I download the file again.

I am using long polling to check, whether the file has  been modified. So I ping the FTP server every 5 seconds and check whether the modified date of the file is changed or not. If the date is modified, I re-download the file again.

Is there a better way to perform this operation, other than long polling?

答:
In general, there are two approaches for checking for updates.

The first is the one that you mentioned, and that is polling for changes periodically.

The second solution, is to register a "hook" which will be invoked once a  specific action is occurs. For example, when pushing to a git repository, you can create a hook to automatically start a build of the source code.

In your case, option two is not applicable. There isn't an obvious way to make the FTP server ping you once the files change.

Title: Alternatives to long polling?


问:
How to get field names from a tbl_dbi?
Is there a  way to directly get the field names from a tbl_dbi object (db_mtcars below)?

```<code> library(RSQLite)
 library(dbplyr)
 library(dplyr)
 con <- dbConnect(RSQLite::SQLite(), ":memory:")
 dbWriteTable(con, "mtcars", mtcars)

 db_mtcars <- tbl(con, "mtcars")
</code>```

答:
colnames(db_mtcars) is the easy solution, DBI::dbListFields(con, "mtcars") is the fancy solution.
Both work even when names(db_mtcars) fail.

Title: How to get field names from a tbl_dbi?

Body:
Is there a  way to directly get the field names from a tbl_dbi object (db_mtcars below)?

 library(RSQLite)
 library(dbplyr)
 library(dplyr)
 con <- dbConnect(RSQLite::SQLite(), ":memory:")
 dbWriteTable(con, "mtcars", mtcars)

 db_mtcars <- tbl(con, "mtcars")


问:
Virtuoso crash "search.c:326 box_serial_length not supported for data type"
I am connecting to a Virtuoso 7.20.3216 compiled and installed inside a VirtualBox CentOS 7.3 64bit, using the RDF4J Virtuoso adapter.

I try to load a Turtle file in Virtuoso using this code :

```<code>Repository r = new virtuoso.rdf4j.driver.VirtuosoRepository(url, login, password);
RepositoryConnection connection = r.openConnection();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Turtle data written inside baos

String graphUri = ... ;
connection.add(new ByteArrayInputStream(baos.toByteArray()), RDF.NAMESPACE, RDFFormat.TURTLE, SimpleValueFactory.getInstance().createIRI(graphUri));
</code>```

Virtuoso crashes (stops) with the following logs :

```<code>12:10:01 box_serial_len called with dtp 225
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x8c6d3a]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x8c6d98]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x4fba85]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x629664]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x629997]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x622485]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x65233d]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x6524dd]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x592328]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x59a807]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x59760a]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x5c0e30]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x5ca63b]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x59370c]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x597d13]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x5c0e30]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x5cbeee]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x5d3d36]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t(sf_sql_execute_w+0x7b) [0x5d3edb]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x8cb297]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x8d1683]
12:10:01 /lib64/libpthread.so.0(+0x7e25) [0x7fe04db7ee25]
12:10:01 /lib64/libc.so.6(clone+0x6d) [0x7fe04d3a634d]
12:10:01 GPF: search.c:326 box_serial_length not supported for data type
</code>```

The same Turtle string, when uploaded to the conductor back-office, works properly. The file is pretty large so I can't paste it here.

We have narrowed down the problem to a character encoding issue. The turtle file contains literals with accented characters such as "Disque à gravure directe"@fr.

We haven't set any character encoding parameters, neither on the Virtuoso config side, nor in the JDBC connection side. We tried by adding charset=UTF-8 in the JDBC connection string, with no luck.

It seems also that the problem only arises when the database is empty. When the database already contains some data, Virtuoso does not crash.

Any idea on

what the error message means?

what could be the cause of the problem?

how to fix or work around this?

Thanks!

答:
This issue has been verified and logged as issue #697 on the github project. Resolution work is in progress.

Further updates will be posted to the issue on github.

Body:
I am connecting to a Virtuoso 7.20.3216 compiled and installed inside a VirtualBox CentOS 7.3 64bit, using the RDF4J Virtuoso adapter.

I try to load a Turtle file in Virtuoso using this code :

Repository r = new virtuoso.rdf4j.driver.VirtuosoRepository(url, login, password);
RepositoryConnection connection = r.openConnection();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Turtle data written inside baos

String graphUri = ... ;
connection.add(new ByteArrayInputStream(baos.toByteArray()), RDF.NAMESPACE, RDFFormat.TURTLE, SimpleValueFactory.getInstance().createIRI(graphUri));

Virtuoso crashes (stops) with the following logs :

12:10:01 box_serial_len called with dtp 225
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x8c6d3a]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x8c6d98]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x4fba85]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x629664]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x629997]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x622485]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x65233d]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x6524dd]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x592328]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x59a807]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x59760a]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x5c0e30]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x5ca63b]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x59370c]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x597d13]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x5c0e30]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x5cbeee]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x5d3d36]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t(sf_sql_execute_w+0x7b) [0x5d3edb]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x8cb297]
12:10:01 /usr/local/virtuoso-opensource/bin/virtuoso-t() [0x8d1683]
12:10:01 /lib64/libpthread.so.0(+0x7e25) [0x7fe04db7ee25]
12:10:01 /lib64/libc.so.6(clone+0x6d) [0x7fe04d3a634d]
12:10:01 GPF: search.c:326 box_serial_length not supported for data type

The same Turtle string, when uploaded to the conductor back-office, works properly. The file is pretty large so I can't paste it here.

We have narrowed down the problem to a character encoding issue. The turtle file contains literals with accented characters such as "Disque à gravure directe"@fr.

We haven't set any character encoding parameters, neither on the Virtuoso config side, nor in the JDBC connection side. We tried by adding charset=UTF-8 in the JDBC connection string, with no luck.

It seems also that the problem only arises when the database is empty. When the database already contains some data, Virtuoso does not crash.

Any idea on

what the error message means?

what could be the cause of the problem?

how to fix or work around this?

Thanks!


问:
Getting lines one by one to the dynamically allocated char array
Is this possible to get lines from file one by one and save them to the char array which size is determined by the number of characters in each line?</p>

答:
Your question:

Is this possible to get lines from file one by one and save them to the char array which size is determined by the number of characters in each line?

The answer:

Yes

To actually accomplish this, suggest looking at the functions: fgets()  and getline().  Both are found in the header file: stdio.h.   Read their associated MAN pages for details.


问:
How to use Context.Request.Body and retain it?
I am trying to write a middleware where I will be doing a json schema validation against the request body. After the validation, I need to use the request body again. But I am not able to figure out how this can be done. I referred this post
and found a way to access the body. But once the request body is used, I need that available to my next function.

Here is the sample code:

```<code>package main
import (
        "fmt"
        "io/ioutil"
        "net/http"
        "github.com/gin-gonic/gin"
        //"github.com/xeipuuv/gojsonschema"
)

func middleware() gin.HandlerFunc {
 return func(c *gin.Context) {
    //Will be doing json schema validation here

    body := c.Request.Body
    x, _ := ioutil.ReadAll(body)

    fmt.Printf("%s \n", string(x))

    fmt.Println("I am a middleware for json schema validation")

    c.Next()
    return
 }
}

type E struct {
 Email    string
 Password string
}

func test(c *gin.Context) {
 //data := &E{}
 //c.Bind(data)
 //fmt.Println(data)   //prints empty as json body is already used

 body := c.Request.Body
 x, _ := ioutil.ReadAll(body)

 fmt.Printf("body is: %s \n", string(x))
 c.JSON(http.StatusOK, c)
}

func main() {
 router := gin.Default()

 router.Use(middleware())

 router.POST("/test", test)

 //Listen and serve
 router.Run("127.0.0.1:8080")
}
</code>```

Current output:

```<code>{
    "email": "test@test.com",
    "password": "123"
}

I am a middleware for json schema validation
body is:
</code>```

Expected output:

```<code>{
    "email": "test@test.com",
    "password": "123"
}
I am a middleware for json schema validation
body is: {
    "email": "test@test.com",
    "password": "123"
}
</code>```

答:
What Thellimist said, but in more words.

You need to "catch and restore" the Body.
The Body is a buffer, that means that once you read it, its gone. So, if you catch it and "put it back", you can access it again.

Check this answer, I think this is what you are looking for:
https://stackoverflow.com/a/47295689/3521313

Body:
I am trying to write a middleware where I will be doing a json schema validation against the request body. After the validation, I need to use the request body again. But I am not able to figure out how this can be done. I referred this post
and found a way to access the body. But once the request body is used, I need that available to my next function.

Here is the sample code:

package main
import (
        "fmt"
        "io/ioutil"
        "net/http"
        "github.com/gin-gonic/gin"
        //"github.com/xeipuuv/gojsonschema"
)

func middleware() gin.HandlerFunc {
 return func(c *gin.Context) {
    //Will be doing json schema validation here

    body := c.Request.Body
    x, _ := ioutil.ReadAll(body)

    fmt.Printf("%s \n", string(x))

    fmt.Println("I am a middleware for json schema validation")

    c.Next()
    return
 }
}

type E struct {
 Email    string
 Password string
}

func test(c *gin.Context) {
 //data := &E{}
 //c.Bind(data)
 //fmt.Println(data)   //prints empty as json body is already used

 body := c.Request.Body
 x, _ := ioutil.ReadAll(body)

 fmt.Printf("body is: %s \n", string(x))
 c.JSON(http.StatusOK, c)
}

func main() {
 router := gin.Default()

 router.Use(middleware())

 router.POST("/test", test)

 //Listen and serve
 router.Run("127.0.0.1:8080")
}

Current output:

{
    "email": "test@test.com",
    "password": "123"
}

I am a middleware for json schema validation
body is:

Expected output:

{
    "email": "test@test.com",
    "password": "123"
}
I am a middleware for json schema validation
body is: {
    "email": "test@test.com",
    "password": "123"
}


问:
setup multiple cameras for capturing images
I am trying to collect images from up to 6 different cameras.  The code I have works, but it does not seem very object oriented since I have to do a switch on the index of the cameras to set the NewFrame event handler to individually named handlers to put the image in the picturebox for each camera.  Is there a better way to do this (see code below).

```<code>    private void ImageCollector_Load(object sender, EventArgs e)
    {
        webcams = new FilterInfoCollection(FilterCategory.VideoInputDevice);

        Cameras = new VideoCaptureDevice[webcams.Count];
        int index = 0;
        foreach (FilterInfo CaptureDevice in webcams)
        {
            // Enable the cameras display
            ViewLabelflowLayoutPanel.Controls[index].Visible = true;
            ImageLabelflowLayoutPanel.Controls[index].Visible = true;
            ViewflowLayoutPanel.Controls[index].Visible = true;
            ImageflowLayoutPanel.Controls[index].Visible = true;
            CameracomboBox.Items.Add(CaptureDevice.Name);
            try
            {
                Cameras[index] = new VideoCaptureDevice(webcams[index].MonikerString);
                switch (index)
                {
                    case 0:
                        Cameras[index].NewFrame += new NewFrameEventHandler(cam1_NewFrame);
                        break;

                    case 1:
                        Cameras[index].NewFrame += new NewFrameEventHandler(cam2_NewFrame);
                        break;

                    case 2:
                        Cameras[index].NewFrame += new NewFrameEventHandler(cam3_NewFrame);
                        break;

                    case 3:
                        Cameras[index].NewFrame += new NewFrameEventHandler(cam4_NewFrame);
                        break;

                    case 4:
                        Cameras[index].NewFrame += new NewFrameEventHandler(cam5_NewFrame);
                        break;

                    case 5:
                        Cameras[index].NewFrame += new NewFrameEventHandler(cam6_NewFrame);
                        break;
                }//endswitch

                Cameras[index].Start();
            }//endtry
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }//endcatch
        }//endforeach
        CameracomboBox.SelectedIndex = 0;
        index++;
    }//endImageCollector_Load
</code>```

Thanks

答:
Good for you, you can identify code smell!

I don't know how NewFrame works, but it probably has a sender which is the Camera that triggered the event, so you can do this.

```<code>    foreach (FilterInfo CaptureDevice in webcams)
    {
        // Enable the cameras display
        ViewLabelflowLayoutPanel.Controls[index].Visible = true;
        ImageLabelflowLayoutPanel.Controls[index].Visible = true;
        ViewflowLayoutPanel.Controls[index].Visible = true;
        ImageflowLayoutPanel.Controls[index].Visible = true;
        CameracomboBox.Items.Add(CaptureDevice.Name);
        try
        {
            Cameras[index] = new VideoCaptureDevice(webcams[index].MonikerString);
            Cameras[index].NewFrame += new NewFrameEventHandler(cam_NewFrame);

            Cameras[index].Start();
        }//endtry
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error");
        }//endcatch
    }//endforeach
    CameracomboBox.SelectedIndex = 0;
    index++;

 public void cam_NewFrame(object sender, EventArgs e){

     VideoCaptureDevice cam = sender as VideoCaptureDevice;
     //do what you need to do with cam here.

 }
</code>```

This works assuming that the sender is set to the camera object.

Body:
I am trying to collect images from up to 6 different cameras.  The code I have works, but it does not seem very object oriented since I have to do a switch on the index of the cameras to set the NewFrame event handler to individually named handlers to put the image in the picturebox for each camera.  Is there a better way to do this (see code below).

    private void ImageCollector_Load(object sender, EventArgs e)
    {
        webcams = new FilterInfoCollection(FilterCategory.VideoInputDevice);

        Cameras = new VideoCaptureDevice[webcams.Count];
        int index = 0;
        foreach (FilterInfo CaptureDevice in webcams)
        {
            // Enable the cameras display
            ViewLabelflowLayoutPanel.Controls[index].Visible = true;
            ImageLabelflowLayoutPanel.Controls[index].Visible = true;
            ViewflowLayoutPanel.Controls[index].Visible = true;
            ImageflowLayoutPanel.Controls[index].Visible = true;
            CameracomboBox.Items.Add(CaptureDevice.Name);
            try
            {
                Cameras[index] = new VideoCaptureDevice(webcams[index].MonikerString);
                switch (index)
                {
                    case 0:
                        Cameras[index].NewFrame += new NewFrameEventHandler(cam1_NewFrame);
                        break;

                    case 1:
                        Cameras[index].NewFrame += new NewFrameEventHandler(cam2_NewFrame);
                        break;

                    case 2:
                        Cameras[index].NewFrame += new NewFrameEventHandler(cam3_NewFrame);
                        break;

                    case 3:
                        Cameras[index].NewFrame += new NewFrameEventHandler(cam4_NewFrame);
                        break;

                    case 4:
                        Cameras[index].NewFrame += new NewFrameEventHandler(cam5_NewFrame);
                        break;

                    case 5:
                        Cameras[index].NewFrame += new NewFrameEventHandler(cam6_NewFrame);
                        break;
                }//endswitch

                Cameras[index].Start();
            }//endtry
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }//endcatch
        }//endforeach
        CameracomboBox.SelectedIndex = 0;
        index++;
    }//endImageCollector_Load

Thanks

Body:
Good for you, you can identify code smell!

I don't know how NewFrame works, but it probably has a sender which is the Camera that triggered the event, so you can do this.

    foreach (FilterInfo CaptureDevice in webcams)
    {
        // Enable the cameras display
        ViewLabelflowLayoutPanel.Controls[index].Visible = true;
        ImageLabelflowLayoutPanel.Controls[index].Visible = true;
        ViewflowLayoutPanel.Controls[index].Visible = true;
        ImageflowLayoutPanel.Controls[index].Visible = true;
        CameracomboBox.Items.Add(CaptureDevice.Name);
        try
        {
            Cameras[index] = new VideoCaptureDevice(webcams[index].MonikerString);
            Cameras[index].NewFrame += new NewFrameEventHandler(cam_NewFrame);

            Cameras[index].Start();
        }//endtry
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error");
        }//endcatch
    }//endforeach
    CameracomboBox.SelectedIndex = 0;
    index++;

 public void cam_NewFrame(object sender, EventArgs e){

     VideoCaptureDevice cam = sender as VideoCaptureDevice;
     //do what you need to do with cam here.

 }

This works assuming that the sender is set to the camera object.


问:
Having case multiple conditions in SQL Server 2014
I have a table 'FinancialTrans' where only 3 of those fields are needed.

```<code>AcctID  TransTypeCode   DateOfTrans  Field 4  Field 5  Field 6....
123     TOLL            2016-06-06
123     TOLL            2016-06-02
123     TOLL            2016-04-28
123     PYMT            2016-03-11
123     TOLL            2015-12-22
123     TOLL            2015-12-22
</code>```

What I need:

I only need account numbers where there are No Tolls AND No Pymt in the last 2 years.

My attempt at the code:

I know I need a Having clause but not quite sure how to write it.

Perhaps, a NOT Exist?

```<code>SELECT [AcctID]
      ,[TransTypeCode]
      ,[TransDate]

 FROM [FinancialTrans]

 WHERE (
        (TransTypeCode = 'TOLL' AND Max(TransDate) <= DATEADD(year, -2, GETDATE()))
     OR (TransTypeCode = 'PYMT' AND Max(TransDate) <= DATEADD(year, -2, GETDATE()))
       )

 GROUP BY AcctID, TransTypeCode, TransDate
</code>```

The challenge I'm facing is that I want account numbers where there is NEITHER a toll NOR a payment in the past two years.
I'm getting account numbers that have no tolls in the past two years but has a payment in the past two years.

Question: How do I ensure I get account numbers that doesn't have BOTH in the past two years?
This question is different from an earlier question asked because the requirements have now changed.

答:
Not exists would work also.</p>

```<code>Select  AcctID,
        TransTypeCode,
        TransDate
From    FinancialTrans ft1
Where   Not Exists (Select  1
                    From    FinancialTrans ft2
                    Where   ft1.AcctID = ft2.AcctID
                    and     ft2.TransTypeCode IN ('TOLL','PYMT')
                    and     ft2.DateOfTrans > DATEADD(year, -2, getdate()))
</code>```

Body:
I have a table 'FinancialTrans' where only 3 of those fields are needed.

AcctID  TransTypeCode   DateOfTrans  Field 4  Field 5  Field 6....
123     TOLL            2016-06-06
123     TOLL            2016-06-02
123     TOLL            2016-04-28
123     PYMT            2016-03-11
123     TOLL            2015-12-22
123     TOLL            2015-12-22

What I need:

I only need account numbers where there are No Tolls AND No Pymt in the last 2 years.

My attempt at the code:

I know I need a Having clause but not quite sure how to write it.

Perhaps, a NOT Exist?

SELECT [AcctID]
      ,[TransTypeCode]
      ,[TransDate]

 FROM [FinancialTrans]

 WHERE (
        (TransTypeCode = 'TOLL' AND Max(TransDate) <= DATEADD(year, -2, GETDATE()))
     OR (TransTypeCode = 'PYMT' AND Max(TransDate) <= DATEADD(year, -2, GETDATE()))
       )

 GROUP BY AcctID, TransTypeCode, TransDate

The challenge I'm facing is that I want account numbers where there is NEITHER a toll NOR a payment in the past two years.
I'm getting account numbers that have no tolls in the past two years but has a payment in the past two years.

Question: How do I ensure I get account numbers that doesn't have BOTH in the past two years?
This question is different from an earlier question asked because the requirements have now changed.

Body:
Not exists would work also.

Select  AcctID,
        TransTypeCode,
        TransDate
From    FinancialTrans ft1
Where   Not Exists (Select  1
                    From    FinancialTrans ft2
                    Where   ft1.AcctID = ft2.AcctID
                    and     ft2.TransTypeCode IN ('TOLL','PYMT')
                    and     ft2.DateOfTrans > DATEADD(year, -2, getdate()))


问:
SSRS - calculations from different datasets
I am new to SSRS and need help in completing this.
I have a SSRS report which has 2 different datasets Dataset 1 & Dataset 2. In Dataset 2 I have to use a calculation in one of the rows, which requires values from Dataset 2 and Dataset 1. Please see the image attached for the layout of the report and for other details. I would request your help in achieving the orange highlighted fields.

答: in SSRS each tablix object can only have one dataset. what you want to do is not possible using two different datasets. i'll suggest to do all calculations at query level in your dataset2. </p>


问:
Where to put Hunspell dictionary for Elasticsearch
The Elasticsearch Hunspell docs say to put the dictionaries
in config/hunspell

Is it

```<code>/usr/share/elasticsearch/config/hunspell/
</code>```

or

```<code>/etc/elasticsearch/config/hunspell/
</code>```

or

```<code>/etc/elasticsearch/hunspell/
</code>```

or something else?

So far, I've tried all of those with no success.

There is some talk about a similar issue in this bug report, but I don't see an answer.

答:
Here is an example of the directory structure for Elasticsearch 5 installed using the .deb installer:

```<code># Elasticsearch home directory
#ES_HOME=/usr/share/elasticsearch

# Elasticsearch configuration directory
#CONF_DIR=/etc/elasticsearch

# Elasticsearch data directory
#DATA_DIR=/var/lib/elasticsearch

# Elasticsearch logs directory
#LOG_DIR=/var/log/elasticsearch

# Elasticsearch PID directory
#PID_DIR=/var/run/elasticsearch
</code>```

In this case, the Hunspell dictionaries should be in a folder called /hunspell in the config directory, which in this particular case would be:
/etc/elasticsearch/hunspell

Body:
The Elasticsearch Hunspell docs say to put the dictionaries
in config/hunspell

Is it

/usr/share/elasticsearch/config/hunspell/

or

/etc/elasticsearch/config/hunspell/

or

/etc/elasticsearch/hunspell/

or something else?

So far, I've tried all of those with no success.

There is some talk about a similar issue in this bug report, but I don't see an answer.

Body:
Here is an example of the directory structure for Elasticsearch 5 installed using the .deb installer:

# Elasticsearch home directory
#ES_HOME=/usr/share/elasticsearch

# Elasticsearch configuration directory
#CONF_DIR=/etc/elasticsearch

# Elasticsearch data directory
#DATA_DIR=/var/lib/elasticsearch

# Elasticsearch logs directory
#LOG_DIR=/var/log/elasticsearch

# Elasticsearch PID directory
#PID_DIR=/var/run/elasticsearch

In this case, the Hunspell dictionaries should be in a folder called /hunspell in the config directory, which in this particular case would be:
/etc/elasticsearch/hunspell


问:
How can I change the color of the value base on the amount of the value?
I have this HTML table and JS

var example = document.getElementid('*Numerical Value*');
var exampledbref = firebase.database().ref().child('example').child('value');
exampledbref.on('value'
  snap => expample.innerText = snap.val());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Untitled Document</title>
</head>

<body>
  <table width="200" border="1">
    <tbody>
      <tr>
        <td>String</td>
        <td>String</td>
      </tr>
      <tr>
        <td>*Numerical Value*</td>
        <td>*Numerical Value*</td>
      </tr>
      <tr> </tr>
    </tbody>
  </table>
</body>

</html></code>```

This model works and does it needs to do which is fetch and display data on the table from firebase.

My question,
How can I change the color of value based on the amount of the value being fetched from firebase?

For example, I am thinking of a parameter where if the value is less than 5 the color of the value itself changes to the color red. Now if it is more than 5 the color of the value is green.

If the data being fetched has the value of 4, how can it change so that the value is being displayed in red and furthermore if its more than 5 the color of the value becomes green? How can I make this work?

答:
A jQuery solution to check values would be

jQuery

```<code>// for each <td>
$('td').each(function(){
   // get the text value in each <td>
   var val = $(this).text();
   // convert to int
   var int = parseInt(val);
   // if more than 5
   if(int > 5) {
      $(this).css({'background': 'green'});
   }else {
       $(this).css({'background': 'red'});
   }
});
</code>```

A simple fiddle - https://fiddle.jshell.net/Jim_Miraidev/akcgabug/

Body:
I have this HTML table and JS

var example = document.getElementid('*Numerical Value*');
var exampledbref = firebase.database().ref().child('example').child('value');
exampledbref.on('value'
  snap => expample.innerText = snap.val());

<!doctype html>

  <meta charset="UTF-8">
  <title>Untitled Document</title>

        String
        String

        *Numerical Value*
        *Numerical Value*

This model works and does it needs to do which is fetch and display data on the table from firebase.

My question,
How can I change the color of value based on the amount of the value being fetched from firebase?

For example, I am thinking of a parameter where if the value is less than 5 the color of the value itself changes to the color red. Now if it is more than 5 the color of the value is green.

If the data being fetched has the value of 4, how can it change so that the value is being displayed in red and furthermore if its more than 5 the color of the value becomes green? How can I make this work?

Body:
A jQuery solution to check values would be

jQuery

// for each <td>
$('td').each(function(){
   // get the text value in each <td>
   var val = $(this).text();
   // convert to int
   var int = parseInt(val);
   // if more than 5
   if(int > 5) {
      $(this).css({'background': 'green'});
   }else {
       $(this).css({'background': 'red'});
   }
});

A simple fiddle - https://fiddle.jshell.net/Jim_Miraidev/akcgabug/


答:
If what you want is a list "book","title","page","section","para"
you can use split.</p>

```<code>    string text = "book//title//page/section/para";
    string[] delimiters = { "//", "/" };

    string[] result = text.Split(delimiters,StringSplitOptions.RemoveEmptyEntries);
    System.Diagnostics.Debug.WriteLine(result);
    Assert.IsTrue(result[0].isEqual("book"));
    Assert.IsTrue(result[1].isEqual("title"));
    Assert.IsTrue(result[2].isEqual("page"));
    Assert.IsTrue(result[3].isEqual("section"));
    Assert.IsTrue(result[4].isEqual("para"));
</code>```

Title: loop through string to find substring

Body:
If what you want is a list "book","title","page","section","para"
you can use split.

    string text = "book//title//page/section/para";
    string[] delimiters = { "//", "/" };

    string[] result = text.Split(delimiters,StringSplitOptions.RemoveEmptyEntries);
    System.Diagnostics.Debug.WriteLine(result);
    Assert.IsTrue(result[0].isEqual("book"));
    Assert.IsTrue(result[1].isEqual("title"));
    Assert.IsTrue(result[2].isEqual("page"));
    Assert.IsTrue(result[3].isEqual("section"));
    Assert.IsTrue(result[4].isEqual("para"));


问:
How can I connect a dataset with the average of the values between two dates of another dataset in R?
I want to connect two datasets with each other by adding a new column called  Average. This column is the average of the durations between Date and Date - diff. I got two datasets, the first one is called data and looks like this:

```<code>       Date   Weight   diff   Loc.nr
2013-01-24     1040       7        2
2013-01-31     1000       7        2
2013-01-19      500       4        9
2013-01-23     1040       4        9
2013-01-28      415       5        9
2013-01-31      650       3        9
</code>```

The other one is called Rain.duration, in the column Duration are the hours of rain on that day. This dataset looks like this:

```<code>      Date  Duration
2013-01-14       4.5
2013-01-15       0.0
2013-01-16       6.9
2013-01-17       0.0
2013-01-18       1.8
2013-01-19       2.1
2013-01-20       0.0
2013-01-21       0.0
2013-01-22       4.3
2013-01-23       0.0
2013-01-24       7.5
2013-01-25       4.7
2013-01-26       0.0
2013-01-27       0.7
2013-01-28       5.0
2013-01-29       0.0
2013-01-30       3.1
2013-01-31       2.8
</code>```

I made a code to do this:

```<code>for(i in 1:nrow(data)) {
  for(j in 1:nrow(Rain.duration)) {
    if(data$Date[i] == Rain.duration$Date[j]) {
      average <- as.array(Rain.duration$Duration[(j-(data$diff[i])):j])

      j <- nrow(Rain.duration)
    }
  }
  data$Average[i] <- mean(average)
}
</code>```

The problem of this code is that, because of the size of my datasets, it takes like 3 days to run. Is there a faster way to do this?

My expected outcome is:

```<code>       Date   Weight   diff   Loc.nr   Average
2013-01-24     1040       7        2      1.96
2013-01-31     1000       7        2      2.98
2013-01-19      500       4        9      2.16
2013-01-23     1040       4        9      1.28
2013-01-28      415       5        9      2.98
2013-01-31      650       3        9      2.73
</code>```

答:
Here's a dplyr solution:</p>

```<code>library(dplyr)

# add row number as a new column just to make it easier to read
weather_with_rows  <- Weather %>%
    mutate(Rownum = row_number())

# write function to filter by row number, then return the average duration
getavgduration  <- function(mydate, mydiff) {

    myrow = weather_with_rows %>%
         filter(Date == mydate) %>%
         pluck("Rownum")

    mystartrow = myrow -mydiff

    myduration = weather_with_rows %>%
        filter(
              Rownum <= myrow
            , Rownum >= mystartrow
        )

    mean(myduration$Duration)

}

# get the average duration for each Date/diff pair
averages  <- data %>%
    group_by(Date, Diff) %>%
    summarize(Average = getavgduration(Date, Diff)) %>%
    ungroup()

# join this back into the original data frame
#    this step might not be necessary
#    and might be a big drag on performance,
#    depending on the size of your real data
data_with_avg_duration  <- data %>%
    left_join(averages, by = c('Date','Diff')
</code>```

Body:
I want to connect two datasets with each other by adding a new column called  Average. This column is the average of the durations between Date and Date - diff. I got two datasets, the first one is called data and looks like this:

       Date   Weight   diff   Loc.nr
2013-01-24     1040       7        2
2013-01-31     1000       7        2
2013-01-19      500       4        9
2013-01-23     1040       4        9
2013-01-28      415       5        9
2013-01-31      650       3        9

The other one is called Rain.duration, in the column Duration are the hours of rain on that day. This dataset looks like this:

      Date  Duration
2013-01-14       4.5
2013-01-15       0.0
2013-01-16       6.9
2013-01-17       0.0
2013-01-18       1.8
2013-01-19       2.1
2013-01-20       0.0
2013-01-21       0.0
2013-01-22       4.3
2013-01-23       0.0
2013-01-24       7.5
2013-01-25       4.7
2013-01-26       0.0
2013-01-27       0.7
2013-01-28       5.0
2013-01-29       0.0
2013-01-30       3.1
2013-01-31       2.8

I made a code to do this:

for(i in 1:nrow(data)) {
  for(j in 1:nrow(Rain.duration)) {
    if(data$Date[i] == Rain.duration$Date[j]) {
      average <- as.array(Rain.duration$Duration[(j-(data$diff[i])):j])

      j <- nrow(Rain.duration)
    }
  }
  data$Average[i] <- mean(average)
}

The problem of this code is that, because of the size of my datasets, it takes like 3 days to run. Is there a faster way to do this?

My expected outcome is:

       Date   Weight   diff   Loc.nr   Average
2013-01-24     1040       7        2      1.96
2013-01-31     1000       7        2      2.98
2013-01-19      500       4        9      2.16
2013-01-23     1040       4        9      1.28
2013-01-28      415       5        9      2.98
2013-01-31      650       3        9      2.73

Body:
Here's a dplyr solution:

library(dplyr)

# add row number as a new column just to make it easier to read
weather_with_rows  <- Weather %>%
    mutate(Rownum = row_number())

# write function to filter by row number, then return the average duration
getavgduration  <- function(mydate, mydiff) {

    myrow = weather_with_rows %>%
         filter(Date == mydate) %>%
         pluck("Rownum")

    mystartrow = myrow -mydiff

    myduration = weather_with_rows %>%
        filter(
              Rownum <= myrow
            , Rownum >= mystartrow
        )

    mean(myduration$Duration)

}

# get the average duration for each Date/diff pair
averages  <- data %>%
    group_by(Date, Diff) %>%
    summarize(Average = getavgduration(Date, Diff)) %>%
    ungroup()

# join this back into the original data frame
#    this step might not be necessary
#    and might be a big drag on performance,
#    depending on the size of your real data
data_with_avg_duration  <- data %>%
    left_join(averages, by = c('Date','Diff')


问:
Encryption with AES-256-GCM using (LibreSSL) libcrypto
Given an appropriate key and iv, this C program should encrypt stdin, outputting to stdout.

```<code>EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit(ctx, EVP_aes_256_gcm(), key, iv);

const size_t block_size = 128;
unsigned char inbuf[block_size];
unsigned char outbuf[block_size + EVP_MAX_BLOCK_LENGTH];
int inlen, outlen;
for (;;)
{
        inlen = fread(inbuf, 1, block_size, stdin);
        if (inlen <= 0)
                break;

        EVP_EncryptUpdate(ctx, outbuf, &outlen, inbuf, inlen)
        fwrite(outbuf, 1, outlen, stdout);
}
EVP_EncryptFinal_ex(ctx, outbuf, &outlen)
fwrite(outbuf, 1, outlen, stdout);
</code>```

(Error checking removed for brevity.)

I am verifying the output of this code by running

openssl aes-256-gcm -in ciphertext.txt -K <key> -iv <iv> -d

This successfully and reliably decrypts the ciphertext, but writes bad decrypt afterwards, for instance

```<code>$ openssl aes-256-gcm ...
Hello World.
bad decrypt
</code>```

What could be going wrong to cause it to say this?

答:
The issue here is, that you do not implement proper padding as PKCS#7 requires. openssl expects correct padding to be present in the decoded message. Rules are:

There has to be always at least 1 byte of padding

It has to be padded to block size of the cipher

Now with AES-256 you have a block size of 128 bit (16 byte). This means, you have to add 1-16 padding bytes. The padding bytes to add are always the size of the padding, so if you have to add 9 bytes of padding, you would add 9 0x09 bytes.

If you properly add this padding to your original plaintext, then openssl should stop complaining on decrypt.

Body:
Given an appropriate key and iv, this C program should encrypt stdin, outputting to stdout.

EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit(ctx, EVP_aes_256_gcm(), key, iv);

const size_t block_size = 128;
unsigned char inbuf[block_size];
unsigned char outbuf[block_size + EVP_MAX_BLOCK_LENGTH];
int inlen, outlen;
for (;;)
{
        inlen = fread(inbuf, 1, block_size, stdin);
        if (inlen <= 0)
                break;

        EVP_EncryptUpdate(ctx, outbuf, &outlen, inbuf, inlen)
        fwrite(outbuf, 1, outlen, stdout);
}
EVP_EncryptFinal_ex(ctx, outbuf, &outlen)
fwrite(outbuf, 1, outlen, stdout);

(Error checking removed for brevity.)

I am verifying the output of this code by running

openssl aes-256-gcm -in ciphertext.txt -K <key> -iv <iv> -d

This successfully and reliably decrypts the ciphertext, but writes bad decrypt afterwards, for instance

$ openssl aes-256-gcm ...
Hello World.
bad decrypt

What could be going wrong to cause it to say this?


问:
asterisk events in codeigniter
I'm developing a contact management system with Codeigniter framework (php-jquery) and I'm using Asterisk (11 or higher) to manage calls.

In this system, there are both incoming and outgoing calls. In case of outgoing calls, I want to call someone by clicking a button and in case of incoming calls, I want to show them as notification popup whenever that happens. For this purpose, I'm writing a library class as follows which only manages outgoing calls.

```<code>class Asterisk {
public $server;
public $port;
public $socket;
public $error;
const NOSOCKET      = 'No Socket Defined';
const CONNECTFAILED = 'Connection Failed';
const AUTHFAIL      = 'Authentication Failed';
const NORESP        = 'Server Didn\'t Respond';

public function __construct($params = array()) {

    $this->server = $_SERVER['HTTP_HOST'];
    $this->port = 5038;

    if (isset($params['server']))
        $this->server = $params['server'];
    if (isset($params['port'])) {
        $this->port = $params['port'];
    }
}

private function _check() {
    if ($this->socket)
        return true;

    $this->error = Asterisk::NOSOCKET;
    redirect('');
}

private function _command($query, $expect = null, $error = null) {
    $this->_check();

    fputs($this->socket, $query."\r\n");
    $response = fgets($this->socket);

    if (!$response) {
        $this->error = Asterisk::NORESP;
        return false;
    }

    if ($expect == null)
        return true;

    if (strpos($response, $expect) != false)
        return true;

    $this->error = $error;
    return false;
}

/* ************************************************************************************************************** */

public function connect($server = null, $port = null) {
    if ($this->socket)
        $this->close();

    if ($server != null && $port != null) {
        $this->server = $server;
        $this->port = $port;
    }

    $this->socket = fsockopen($this->server, $this->port, $errno, $errstr, 1);
    if (!$this->socket) {
        $this->error =  Asterisk::CONNECTFAILED . " - $errstr ($errno)";
        return false;
    }

    stream_set_timeout($this->socket, 3);
    return true;
}

public function close() {
    $this->_check();

    fclose($this->socket);
    return true;
}

public function login($username, $password) {
    return $this->_command(
        "Action: Login\r\n".
        "UserName: $username\r\n".
        "Secret: $password\r\n".
        "Events: off\r\n",
        "Message: Authentication accepted",
        Asterisk::AUTHFAIL
    );
}

public function logout() {
    return $this->_command(
        "Action: Logoff\r\n"
    );
}

/* ************************************************************************************************************** */

public function call($channel, $context, $extension, $callerId, $priority = 1, $async = true, $timeout = 30000) {
    return $this->_command(
        "Action: Originate\r\n".
        "Channel: $channel\r\n".
        "Context: $context\r\n".
        "Exten: $extension\r\n".
        "Priority: $priority\r\n".
        "Async: $async\r\n".
        "CallerId: $callerId\r\n".
        "TimeOut: $timeout\r\n"
    );
}
}
</code>```

How can I update this class to handle incoming calls and their events?

I know there are some existing libraries like PAMI but it does not work with codeigniter and mvc model properly.

how can i manage these incoming calls? Can someone post some example code?

thanks.

答:
I've done this in a few implementations, using PHP and Laravel as well as PAMI (and PAGI for booting customized AGI interactions).

In short: The stream of AMI events requires active listening to a series of events and parsing data from the stream. To get a handle on the stream, I've always created a small separate program (in PHP with PAGI), which handles the stream of events and sends events back to the host application via WebSocket (using HOA Websocket on both ends).

The reasons for this approach is:

Allows a small and lightweight program to do the job of listening for all AMI events.

Decouple a 'real-time' system from a web application, and talk to the web application in a manner commensurate to the way a web application is used to being talked

Unblock the consumption of events streaming from AMI, since you onloy have to see the event, and send a message across a socket connection without acknowledging response.

Use a great library, like PAMI, to deal with AMI and share a lib of custom DTOs so that mapping AMI raw info to application-specific DTOs only happens on the AMI consumer program, and my other applications don't have to have knowledge of AMI.

Most importantly: the run time configurations for PHP as a web application will most likely be very different from the configuration of a program meant to consume live streams of events. If you miss an event, you will not get it again!

Once set up with a AMI gateway program, which takes events and passes them to the main application, you can then use the AMI gateway program to send instructions to Asterisk (Actions) and you will already have a means of handling the response from the action.

Title: asterisk events in codeigniter

Body:
I'm developing a contact management system with Codeigniter framework (php-jquery) and I'm using Asterisk (11 or higher) to manage calls.

In this system, there are both incoming and outgoing calls. In case of outgoing calls, I want to call someone by clicking a button and in case of incoming calls, I want to show them as notification popup whenever that happens. For this purpose, I'm writing a library class as follows which only manages outgoing calls.

class Asterisk {
public $server;
public $port;
public $socket;
public $error;
const NOSOCKET      = 'No Socket Defined';
const CONNECTFAILED = 'Connection Failed';
const AUTHFAIL      = 'Authentication Failed';
const NORESP        = 'Server Didn\'t Respond';

public function __construct($params = array()) {

    $this->server = $_SERVER['HTTP_HOST'];
    $this->port = 5038;

    if (isset($params['server']))
        $this->server = $params['server'];
    if (isset($params['port'])) {
        $this->port = $params['port'];
    }
}

private function _check() {
    if ($this->socket)
        return true;

    $this->error = Asterisk::NOSOCKET;
    redirect('');
}

private function _command($query, $expect = null, $error = null) {
    $this->_check();

    fputs($this->socket, $query."\r\n");
    $response = fgets($this->socket);

    if (!$response) {
        $this->error = Asterisk::NORESP;
        return false;
    }

    if ($expect == null)
        return true;

    if (strpos($response, $expect) != false)
        return true;

    $this->error = $error;
    return false;
}

/* ************************************************************************************************************** */

public function connect($server = null, $port = null) {
    if ($this->socket)
        $this->close();

    if ($server != null && $port != null) {
        $this->server = $server;
        $this->port = $port;
    }

    $this->socket = fsockopen($this->server, $this->port, $errno, $errstr, 1);
    if (!$this->socket) {
        $this->error =  Asterisk::CONNECTFAILED . " - $errstr ($errno)";
        return false;
    }

    stream_set_timeout($this->socket, 3);
    return true;
}

public function close() {
    $this->_check();

    fclose($this->socket);
    return true;
}

public function login($username, $password) {
    return $this->_command(
        "Action: Login\r\n".
        "UserName: $username\r\n".
        "Secret: $password\r\n".
        "Events: off\r\n",
        "Message: Authentication accepted",
        Asterisk::AUTHFAIL
    );
}

public function logout() {
    return $this->_command(
        "Action: Logoff\r\n"
    );
}

/* ************************************************************************************************************** */

public function call($channel, $context, $extension, $callerId, $priority = 1, $async = true, $timeout = 30000) {
    return $this->_command(
        "Action: Originate\r\n".
        "Channel: $channel\r\n".
        "Context: $context\r\n".
        "Exten: $extension\r\n".
        "Priority: $priority\r\n".
        "Async: $async\r\n".
        "CallerId: $callerId\r\n".
        "TimeOut: $timeout\r\n"
    );
}
}

How can I update this class to handle incoming calls and their events?

I know there are some existing libraries like PAMI but it does not work with codeigniter and mvc model properly.

how can i manage these incoming calls? Can someone post some example code?

thanks.


问:
Adding dll's to the project and making functions work
I have to do one project and I was given dll and a header file with implemented functions needed for the project. I was told just to add the header file to the project but this way i get unresolve externals error if i try to use functions referenced in header. So what needs to be done to make everything work? Visual Studio 2010.
Here are the files i have: http://www.ipix.lt/images/33871682.png
And this is header file:

```<code>#ifndef __BIM482_RADAR__
#define __BIM482_RADAR__

int BIM482OpenRadar();
int BIM482AddPlane(double x, double y);
int BIM482SetPlaneColor(int planeidx, int coloridx);
int BIM482SetPlanePos(int planeidx, double x, double y);
void BIM482UpdateRadar();

#endif // __BIM482_RADAR__
</code>```

I need to initiate gui with OpenRadar and pass information with those functions. How to start this thing?

答:
You may use windows API LoadLibrary to load the dll during runtime, followed by GetProcAddress to retrieve function address.  With the function address is retrieved, you need to declare the method signature so that compiler know how to call given function.

Below is a sample code for how to "link" to function in Dll:

```<code>HINSTANCE m_hExtDll = LoadLibrary( "SDL.dll" )
if (m_hExtDll)
{
    FARPROC m_pfnOpenRadar = GetProcAddress(m_hExtDll, "BIM482OpenRadar")
    if (m_pfnOpenRadar)
    {
        typedef int (*OPENRADARFUNC)();
        OPENRADARFUNC fnOpenRadar = (OPENRADARFUNC)m_pfnOpenRadar;

        int iRetCode = fnOpenRadar();
    }
}
</code>```

Do note that functions exported are subject to name mangling and you can verify the function name using third-party utility like Dependency Walker.

Body:
I have to do one project and I was given dll and a header file with implemented functions needed for the project. I was told just to add the header file to the project but this way i get unresolve externals error if i try to use functions referenced in header. So what needs to be done to make everything work? Visual Studio 2010.
Here are the files i have: http://www.ipix.lt/images/33871682.png
And this is header file:

#ifndef __BIM482_RADAR__
#define __BIM482_RADAR__

int BIM482OpenRadar();
int BIM482AddPlane(double x, double y);
int BIM482SetPlaneColor(int planeidx, int coloridx);
int BIM482SetPlanePos(int planeidx, double x, double y);
void BIM482UpdateRadar();

#endif // __BIM482_RADAR__

I need to initiate gui with OpenRadar and pass information with those functions. How to start this thing?

Body:
You may use windows API LoadLibrary to load the dll during runtime, followed by GetProcAddress to retrieve function address.  With the function address is retrieved, you need to declare the method signature so that compiler know how to call given function.

Below is a sample code for how to "link" to function in Dll:

HINSTANCE m_hExtDll = LoadLibrary( "SDL.dll" )
if (m_hExtDll)
{
    FARPROC m_pfnOpenRadar = GetProcAddress(m_hExtDll, "BIM482OpenRadar")
    if (m_pfnOpenRadar)
    {
        typedef int (*OPENRADARFUNC)();
        OPENRADARFUNC fnOpenRadar = (OPENRADARFUNC)m_pfnOpenRadar;

        int iRetCode = fnOpenRadar();
    }
}

Do note that functions exported are subject to name mangling and you can verify the function name using third-party utility like Dependency Walker.


问:
How sort two arrays?
Please help me get my 2 arrays asc sorted and desc sorted. My solution has not worked

```<code>function solve(arr){
  var descArr = [];
  var ascArr = [];

  ascArr = arr.sort(function(a, b) {
    return a - b;
  });

  descArr = arr.sort(function(a, b) {
    return b - a;
  });

  console.log(descArr);
  console.log(ascArr);

};

solve([15,11,10,7,12])
</code>```

Console.log displays similar sorted arrays.

JSFIDDLE

答:
To get descArr, slice to get a shallow copy of the array, and sort. Slice descArr and Array#reverse to get ascArr.

You need to use Array#slice to get a shallow clone because both Array#sort, and Array#reverse are in place, which means that they mutate the original array.

function solve(arr){
  var descArr = arr.slice().sort(function(a, b) {
    return a - b;
  });

  var ascArr = descArr.slice().reverse();

  console.log(descArr);
  console.log(ascArr);

};

solve([15,11,10,7,12])```

Title: How sort two arrays?

Body:
Please help me get my 2 arrays asc sorted and desc sorted. My solution has not worked

function solve(arr){
  var descArr = [];
  var ascArr = [];

  ascArr = arr.sort(function(a, b) {
    return a - b;
  });

  descArr = arr.sort(function(a, b) {
    return b - a;
  });

  console.log(descArr);
  console.log(ascArr);

};

solve([15,11,10,7,12])

Console.log displays similar sorted arrays.

JSFIDDLE


问:
JCalendar get the current date clicked
So I have this

```<code>    @Override
        public void propertyChange(PropertyChangeEvent evt) {
            Date current = new Date(System.currentTimeMillis());

            if (calendar.getDate().after(current) || (calendar.getDate().getDate() == current.getDate()
                    && calendar.getDate().getMonth() == current.getMonth()
                    && calendar.getDate().getYear() == current.getYear())) {

                int month = calendar.getMonthChooser().getMonth() + 1;
                int day = (int) evt.getNewValue();

                String date = day + "/" + month;
                txtNothing.setText("Event:" + date);
                dispose();
            }
        }
    });
</code>```

I know it can be better but this works for listening for a change in dates..

What can I use to get the current date selected when it is pressed again? currently that date is still highlighted but the propertychange event wont trigger when clicked the same date.

答:
found a way to trigger it by using this</p>

```<code>calendar.getDayChooser().setAlwaysFireDayProperty(true);
</code>```

Title: JCalendar get the current date clicked

Body:
So I have this

    @Override
        public void propertyChange(PropertyChangeEvent evt) {
            Date current = new Date(System.currentTimeMillis());

            if (calendar.getDate().after(current) || (calendar.getDate().getDate() == current.getDate()
                    && calendar.getDate().getMonth() == current.getMonth()
                    && calendar.getDate().getYear() == current.getYear())) {

                int month = calendar.getMonthChooser().getMonth() + 1;
                int day = (int) evt.getNewValue();

                String date = day + "/" + month;
                txtNothing.setText("Event:" + date);
                dispose();
            }
        }
    });

I know it can be better but this works for listening for a change in dates..

What can I use to get the current date selected when it is pressed again? currently that date is still highlighted but the propertychange event wont trigger when clicked the same date.

Body:
found a way to trigger it by using this

calendar.getDayChooser().setAlwaysFireDayProperty(true);