问:
Trigger compiles without errors, But it does not add data
I'm trying to update the table called 'saturn.szrunsp' after a update or insert happens on the table 'saturn.szraspr'. After kind suggestions i've created a trigger without any errors. however, the main part still doesnt seem to work which is the trigger to add data onto the table saturn.szrunsp after update on table saturn.szraspr. please see all codes of table and trigger below. UPDATED!! </p>

```<code>-- INSERTING table --

        CREATE TABLE SATURN.SZRUNSP
    (
      SZRUNSP_STUDENT_NO       VARCHAR2(9 CHAR)     NOT NULL,
      SZRUNSP_PIDM             NUMBER(8)            NOT NULL,
      SZRUNSP_STUDENT_NAME     VARCHAR2(60 CHAR)    NOT NULL,
      SZRUNSP_SUSPEND_ACCOUNT  VARCHAR2(1 CHAR)     NOT NULL,
      SZRUNSP_UNSUSPEND_DATE   DATE                 NOT NULL,
      SZRUNSP_ACTIVITY_DATE    DATE                 NOT NULL,
      SZRUNSP_USER_ID          VARCHAR2(30 CHAR),
      SZRUNSP_ACTION           VARCHAR2(30 CHAR),
      SZRUNSP_SURROGATE_ID     NUMBER(19)           NOT NULL,
      SZRUNSP_VERSION          NUMBER(19)           NOT NULL,
      SZRUNSP_VPDI_CODE        VARCHAR2(6 CHAR)
    )

-- TRIGGER TABLE --

    CREATE TABLE SATURN.SZRASPR
(
  SZRASPR_STUDENT_NO             VARCHAR2(9 CHAR) NOT NULL,
  SZRASPR_STUDENT_NAME           VARCHAR2(60 CHAR) NOT NULL,
  SZRASPR_DATE_OF_BIRTH          VARCHAR2(8 CHAR) NOT NULL,
  SZRASPR_SUSPEND_ACCOUNT        VARCHAR2(1 CHAR) NOT NULL,
  SZRASPR_EMAIL_ADDRESS          VARCHAR2(100 CHAR) NOT NULL,
  SZRASPR_STUDENT_YEAR           VARCHAR2(2 CHAR) NOT NULL,
  SZRASPR_FACULTY                VARCHAR2(60 CHAR) NOT NULL,
  SZRASPR_SCHOOL_OF_STUDY        VARCHAR2(60 CHAR) NOT NULL,
  SZRASPR_DEGREE_NAME            VARCHAR2(100 CHAR) NOT NULL,
  SZRASPR_MODE_OF_STUDY          VARCHAR2(20 CHAR) NOT NULL,
  SZRASPR_FEE_STATUS             VARCHAR2(20 CHAR) NOT NULL,
  SZRASPR_YEAR_START             VARCHAR2(4 CHAR) NOT NULL,
  SZRASPR_SEMESTER_START         VARCHAR2(5 CHAR) NOT NULL,
  SZRASPR_ENROLMENT_STATUS       VARCHAR2(2 CHAR) NOT NULL,
  SZRASPR_LEAVING_DATE           VARCHAR2(8 CHAR),
  SZRASPR_PENDING_ACTIVITY_DATE  DATE,
  SZRASPR_ACTIVE_ACTIVITY_DATE   DATE,
  SZRASPR_PENDING_STATUS         VARCHAR2(2 CHAR),
  SZRASPR_ACTIVE_STATUS          VARCHAR2(2 CHAR),
  SZRASPR_PIDM                   NUMBER(8)      NOT NULL,
  SZRASPR_TERM_CODE              VARCHAR2(6 CHAR) NOT NULL,
  SZRASPR_ASPIRE_ERROR_REPORTED  VARCHAR2(10 CHAR),
  SZRASPR_ERROR_TEXT             VARCHAR2(100 CHAR),
  SZRASPR_SEQ_NO                 NUMBER,
  SZRASPR_SEND                   INTEGER,
  SZRASPR_SURROGATE_ID           NUMBER(19),
  SZRASPR_VERSION                NUMBER(19),
  SZRASPR_USER_ID                VARCHAR2(30 CHAR),
  SZRASPR_DATA_ORIGIN            VARCHAR2(30 CHAR),
  SZRASPR_ACTIVITY_DATE          DATE,
  SZRASPR_VPDI_CODE              VARCHAR2(6 CHAR)
);

--Trigger--

    CREATE OR REPLACE TRIGGER szrunsp_suspend_trigger
after update or insert on SATURN.SZRASPR
for each row
declare
    SZRUNSP_USER_ID varchar2(30 CHAR);
begin
    select user into SZRUNSP_USER_ID from dual;

    insert into SATURN.SZRUNSP values
        (:new.SZRASPR_STUDENT_NO,
         :new.SZRASPR_PIDM,
         :new.SZRASPR_STUDENT_NAME,
         :new.SZRASPR_SUSPEND_ACCOUNT,
         SYSDATE,
         SYSDATE,
         user,
         :new.SZRASPR_SURROGATE_ID,
         :new.SZRASPR_VERSION,
         :new.SZRASPR_VPDI_CODE);
 end;
/
</code>```

答:
Not sure why you get this error:

```<code>[Error] ORA-00947 (9: 20): PL/SQL: ORA-00947: not enough values
</code>```

The number of values in the INSERT statement matches the table you posted. So, if you are getting that error you need to correct your question.

```<code>[Error] PLS-00049 (10: 2): PLS-00049: bad bind variable 'NEW.SZRUNSP_STUDENT_NO'
</code>```

All the columns referenced in the INSERT statement have the same names as the target table, saturn.szrunsp. However the bind names must match the columns of the triggering table. saturn.szraspr. You say

saturn.szraspr has szraspr_student_no column

so you need to edit the trigger to match:

```<code>CREATE OR REPLACE TRIGGER szrunsp_suspend_trigger
after update or insert on szraspr
for each row
declare
    szrunsp_user_id varchar2(30);
begin
    select user into szrunsp_user_id from dual;

    insert into szrunsp values
        (:new.SZRASPR_STUDENT_NO,
         :new.SZRASPR_PIDM,
         :new.SZRASPR_STUDENT_NAME,
         :new.SZRASPR_SUSPEND_ACCOUNT,
         SYSDATE,
         SYSDATE,
         user,
         :new.SZRASPR_ACTION,
         '',
         '',
         '');
 end;
/
</code>```

In Oracle an empty string is null so you will get NOT NULL violations on  SZRUNSP_SURROGATE_ID and SZRUNSP_VERSION which you need to handle.

Body:
I'm trying to update the table called 'saturn.szrunsp' after a update or insert happens on the table 'saturn.szraspr'. After kind suggestions i've created a trigger without any errors. however, the main part still doesnt seem to work which is the trigger to add data onto the table saturn.szrunsp after update on table saturn.szraspr. please see all codes of table and trigger below. UPDATED!!

-- INSERTING table --

        CREATE TABLE SATURN.SZRUNSP
    (
      SZRUNSP_STUDENT_NO       VARCHAR2(9 CHAR)     NOT NULL,
      SZRUNSP_PIDM             NUMBER(8)            NOT NULL,
      SZRUNSP_STUDENT_NAME     VARCHAR2(60 CHAR)    NOT NULL,
      SZRUNSP_SUSPEND_ACCOUNT  VARCHAR2(1 CHAR)     NOT NULL,
      SZRUNSP_UNSUSPEND_DATE   DATE                 NOT NULL,
      SZRUNSP_ACTIVITY_DATE    DATE                 NOT NULL,
      SZRUNSP_USER_ID          VARCHAR2(30 CHAR),
      SZRUNSP_ACTION           VARCHAR2(30 CHAR),
      SZRUNSP_SURROGATE_ID     NUMBER(19)           NOT NULL,
      SZRUNSP_VERSION          NUMBER(19)           NOT NULL,
      SZRUNSP_VPDI_CODE        VARCHAR2(6 CHAR)
    )

-- TRIGGER TABLE --

    CREATE TABLE SATURN.SZRASPR
(
  SZRASPR_STUDENT_NO             VARCHAR2(9 CHAR) NOT NULL,
  SZRASPR_STUDENT_NAME           VARCHAR2(60 CHAR) NOT NULL,
  SZRASPR_DATE_OF_BIRTH          VARCHAR2(8 CHAR) NOT NULL,
  SZRASPR_SUSPEND_ACCOUNT        VARCHAR2(1 CHAR) NOT NULL,
  SZRASPR_EMAIL_ADDRESS          VARCHAR2(100 CHAR) NOT NULL,
  SZRASPR_STUDENT_YEAR           VARCHAR2(2 CHAR) NOT NULL,
  SZRASPR_FACULTY                VARCHAR2(60 CHAR) NOT NULL,
  SZRASPR_SCHOOL_OF_STUDY        VARCHAR2(60 CHAR) NOT NULL,
  SZRASPR_DEGREE_NAME            VARCHAR2(100 CHAR) NOT NULL,
  SZRASPR_MODE_OF_STUDY          VARCHAR2(20 CHAR) NOT NULL,
  SZRASPR_FEE_STATUS             VARCHAR2(20 CHAR) NOT NULL,
  SZRASPR_YEAR_START             VARCHAR2(4 CHAR) NOT NULL,
  SZRASPR_SEMESTER_START         VARCHAR2(5 CHAR) NOT NULL,
  SZRASPR_ENROLMENT_STATUS       VARCHAR2(2 CHAR) NOT NULL,
  SZRASPR_LEAVING_DATE           VARCHAR2(8 CHAR),
  SZRASPR_PENDING_ACTIVITY_DATE  DATE,
  SZRASPR_ACTIVE_ACTIVITY_DATE   DATE,
  SZRASPR_PENDING_STATUS         VARCHAR2(2 CHAR),
  SZRASPR_ACTIVE_STATUS          VARCHAR2(2 CHAR),
  SZRASPR_PIDM                   NUMBER(8)      NOT NULL,
  SZRASPR_TERM_CODE              VARCHAR2(6 CHAR) NOT NULL,
  SZRASPR_ASPIRE_ERROR_REPORTED  VARCHAR2(10 CHAR),
  SZRASPR_ERROR_TEXT             VARCHAR2(100 CHAR),
  SZRASPR_SEQ_NO                 NUMBER,
  SZRASPR_SEND                   INTEGER,
  SZRASPR_SURROGATE_ID           NUMBER(19),
  SZRASPR_VERSION                NUMBER(19),
  SZRASPR_USER_ID                VARCHAR2(30 CHAR),
  SZRASPR_DATA_ORIGIN            VARCHAR2(30 CHAR),
  SZRASPR_ACTIVITY_DATE          DATE,
  SZRASPR_VPDI_CODE              VARCHAR2(6 CHAR)
);

--Trigger--

    CREATE OR REPLACE TRIGGER szrunsp_suspend_trigger
after update or insert on SATURN.SZRASPR
for each row
declare
    SZRUNSP_USER_ID varchar2(30 CHAR);
begin
    select user into SZRUNSP_USER_ID from dual;

    insert into SATURN.SZRUNSP values
        (:new.SZRASPR_STUDENT_NO,
         :new.SZRASPR_PIDM,
         :new.SZRASPR_STUDENT_NAME,
         :new.SZRASPR_SUSPEND_ACCOUNT,
         SYSDATE,
         SYSDATE,
         user,
         :new.SZRASPR_SURROGATE_ID,
         :new.SZRASPR_VERSION,
         :new.SZRASPR_VPDI_CODE);
 end;
/

Body:
Not sure why you get this error:

[Error] ORA-00947 (9: 20): PL/SQL: ORA-00947: not enough values

The number of values in the INSERT statement matches the table you posted. So, if you are getting that error you need to correct your question.

[Error] PLS-00049 (10: 2): PLS-00049: bad bind variable 'NEW.SZRUNSP_STUDENT_NO'

All the columns referenced in the INSERT statement have the same names as the target table, saturn.szrunsp. However the bind names must match the columns of the triggering table. saturn.szraspr. You say

saturn.szraspr has szraspr_student_no column

so you need to edit the trigger to match:

CREATE OR REPLACE TRIGGER szrunsp_suspend_trigger
after update or insert on szraspr
for each row
declare
    szrunsp_user_id varchar2(30);
begin
    select user into szrunsp_user_id from dual;

    insert into szrunsp values
        (:new.SZRASPR_STUDENT_NO,
         :new.SZRASPR_PIDM,
         :new.SZRASPR_STUDENT_NAME,
         :new.SZRASPR_SUSPEND_ACCOUNT,
         SYSDATE,
         SYSDATE,
         user,
         :new.SZRASPR_ACTION,
         '',
         '',
         '');
 end;
/

In Oracle an empty string is null so you will get NOT NULL violations on  SZRUNSP_SURROGATE_ID and SZRUNSP_VERSION which you need to handle.


来源: stackexchange

问:
Count as Zero if Row does not exist using group by with LEFT JOIN
I am practicing with mysql and stuck in one scenario as below:

I have two tables as below .

```<code> Table 1 :
    Distinct_dates having DATE as my_date column name:

    Table 2:my_records having following fields

    record_id,
    record_submitter_name,
    record_submit_date as  DATETIME

    I need to get the records submitted by each submitter for each unique month and it should return 0 if no record found for a month.

    For example: the below query gives me distinct months from distinct_dates table.
    select distinct(DATE_FORMAT(my_date,'%m-%Y')) from distinct_dates;
    +--------------------------------+
    | (DATE_FORMAT(my_date,'%m-%Y')) |
    +--------------------------------+
    | 01-2016                        |
    | 01-2017                        |
    | 02-2017                        |
    | 03-2017                        |
    +--------------------------------+
    4 rows in set (0.00 sec)

I am able to get the count of Records in each month by submitter and not getting Zero if No Record found for the particular month?

select distinct(DATE_FORMAT(record_submit_date,'%m-%Y')),count(record_id),record_submitter_name from my_records group by DATE_FORMAT(record_submit_date,'%m-%y'),records_submitter_name;

I have basic understanding of JOINS but not able to get the correct values ,Any help or pointer will be appreciable.
</code>```

I need to get the count of Records by each record_submitter_name for each distinct month and it should give Zero if no record submitted by user in a particular month ?

Further working with LEFT Join I am able to get the NULL value for the distinct dates for which data does not exist for the month , below is what i have queried.

```<code>select distinct(DATE_FORMAT(d.my_date,'%m-%Y')),count(m.record_id), m.record_submitter_name from distinct_dates d left join my_records m on DATE_FORMAT(m.record_submit_date,'%m-%Y') = DATE_FORMAT(d.my_date,'%m-%Y') and record_submitter_name='xyz' group by d.my_date;

+----------------------------------+----------------+-------------------+
| (DATE_FORMAT(d.my_date,'%m-%Y')) | count(m.record_id) | record_submitter_name |
+----------------------------------+----------------+-------------------+
| 01-2016                          |              1 | xyz               |
| 01-2017                          |              1 | xyz               |
| 02-2017                          |              0 | NULL              |
| 03-2017                          |              0 | NULL              |
+----------------------------------+----------------+-------------------+
</code>```

But It is not working when using group by clause :
Using Group By close , I have not received the required result:

```<code>select distinct(DATE_FORMAT(d.my_date,'%m-%Y')),count(m.record_id), m.record_submitter_name from distinct_dates d left join my_records m on DATE_FORMAT(m.record_submit_date,'%m-%Y') = DATE_FORMAT(d.my_date,'%m-%Y') group by d.my_date,record_submitter_name;

Following NULL results was not in the output ....
    .
      +----------------------------------+----------------+-------------------+
        | (DATE_FORMAT(d.my_date,'%m-%Y')) | count(m.record_id) | record_submitter_name |
        +----------------------------------+----------------+-------------------+
        | 01-2016                          |              1 | xyz               |
        | 01-2017                          |              1 | xyz               |
        | 02-2017                          |              0 | NULL              |
        | 03-2017                          |              0 | NULL              |
        +----------------------------------+----------------+-------------------+
</code>```

Is there something wrong with group by clause with LEFT Join ?

Thanks

答:
I created another Employee master table as suggested by Sunjit and the following query is working as required. </p>

```<code>SELECT distinct(DATE_FORMAT(A.my_date,'%m-%Y')),B.EMP_NAME ,COUNT(record_id)AS record_count FROM distinct_dates A JOIN employees B ON 1=1 LEFT JOIN my_records C ON B.emp_name=C.record_submitter_name AND DATE_FORMAT(A.my_date,'%m-%Y')=DATE_FORMAT(C.record_submit_date,'%m-%Y') GROUP BY A.my_date,'%m-%Y',B.emp_name;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am practicing with mysql and stuck in one scenario as below:

I have two tables as below .

 Table 1 :
    Distinct_dates having DATE as my_date column name:

    Table 2:my_records having following fields

    record_id,
    record_submitter_name,
    record_submit_date as  DATETIME

    I need to get the records submitted by each submitter for each unique month and it should return 0 if no record found for a month.

    For example: the below query gives me distinct months from distinct_dates table.
    select distinct(DATE_FORMAT(my_date,'%m-%Y')) from distinct_dates;
    +--------------------------------+
    | (DATE_FORMAT(my_date,'%m-%Y')) |
    +--------------------------------+
    | 01-2016                        |
    | 01-2017                        |
    | 02-2017                        |
    | 03-2017                        |
    +--------------------------------+
    4 rows in set (0.00 sec)

I am able to get the count of Records in each month by submitter and not getting Zero if No Record found for the particular month?

select distinct(DATE_FORMAT(record_submit_date,'%m-%Y')),count(record_id),record_submitter_name from my_records group by DATE_FORMAT(record_submit_date,'%m-%y'),records_submitter_name;

I have basic understanding of JOINS but not able to get the correct values ,Any help or pointer will be appreciable.

I need to get the count of Records by each record_submitter_name for each distinct month and it should give Zero if no record submitted by user in a particular month ?

Further working with LEFT Join I am able to get the NULL value for the distinct dates for which data does not exist for the month , below is what i have queried.

select distinct(DATE_FORMAT(d.my_date,'%m-%Y')),count(m.record_id), m.record_submitter_name from distinct_dates d left join my_records m on DATE_FORMAT(m.record_submit_date,'%m-%Y') = DATE_FORMAT(d.my_date,'%m-%Y') and record_submitter_name='xyz' group by d.my_date;

+----------------------------------+----------------+-------------------+
| (DATE_FORMAT(d.my_date,'%m-%Y')) | count(m.record_id) | record_submitter_name |
+----------------------------------+----------------+-------------------+
| 01-2016                          |              1 | xyz               |
| 01-2017                          |              1 | xyz               |
| 02-2017                          |              0 | NULL              |
| 03-2017                          |              0 | NULL              |
+----------------------------------+----------------+-------------------+

But It is not working when using group by clause :
Using Group By close , I have not received the required result:

select distinct(DATE_FORMAT(d.my_date,'%m-%Y')),count(m.record_id), m.record_submitter_name from distinct_dates d left join my_records m on DATE_FORMAT(m.record_submit_date,'%m-%Y') = DATE_FORMAT(d.my_date,'%m-%Y') group by d.my_date,record_submitter_name;

Following NULL results was not in the output ....
    .
      +----------------------------------+----------------+-------------------+
        | (DATE_FORMAT(d.my_date,'%m-%Y')) | count(m.record_id) | record_submitter_name |
        +----------------------------------+----------------+-------------------+
        | 01-2016                          |              1 | xyz               |
        | 01-2017                          |              1 | xyz               |
        | 02-2017                          |              0 | NULL              |
        | 03-2017                          |              0 | NULL              |
        +----------------------------------+----------------+-------------------+

Is there something wrong with group by clause with LEFT Join ?

Thanks

Body:
I created another Employee master table as suggested by Sunjit and the following query is working as required.

SELECT distinct(DATE_FORMAT(A.my_date,'%m-%Y')),B.EMP_NAME ,COUNT(record_id)AS record_count FROM distinct_dates A JOIN employees B ON 1=1 LEFT JOIN my_records C ON B.emp_name=C.record_submitter_name AND DATE_FORMAT(A.my_date,'%m-%Y')=DATE_FORMAT(C.record_submit_date,'%m-%Y') GROUP BY A.my_date,'%m-%Y',B.emp_name;


问:
What controls where an event can be called?
Say I have a class like this:

```<code>public class FauxIdentityForm
{
    public Guid FormID { get; set; }
    public event EventHandler Closed;
    public void TheObjectWasClosed(EventArgs e)
    {
        Closed(this, e);
    }
}
</code>```

It is fine for me to call the Closed Event inside the TheObjectWasClosed method.  But if, in a different class (even in the same file), I have a method like this:

```<code>public void CallTheEvent()
{
    FauxIdentityForm _formIdentity = new FauxIdentityForm {FormID = Guid.NewGuid()};

    _formIdentity.Closed(_formIdentity, null);  // <-- Does not compile!
}
</code>```

The call to Closed is shot down by the compiler (it wants me to only use += and -=).

So, is actually calling the event only allowed inside the class?  Is that the limitation?

If so, is there anyway around it?  And if not, why did the creators of C# do this?  (It makes working with events very hard sometimes.  I imagine there is a good reason and it is probably saving me from myself, but I would like to know it.)

答:
In fact, Closed(this, e); is nothing but calling invoke on a private delegate. This is why only the class can call it.

C# hides all the complexity from you and it creates a private delegate of type event for you (you can use ILDASM to see all this).

This is private so it is not even protected. This is why it is recommended to use a protected method to raise the event so the subclasses could have access to the event.

ContentLicense: CC BY-SA 2.5

Body:
Say I have a class like this:

public class FauxIdentityForm
{
    public Guid FormID { get; set; }
    public event EventHandler Closed;
    public void TheObjectWasClosed(EventArgs e)
    {
        Closed(this, e);
    }
}

It is fine for me to call the Closed Event inside the TheObjectWasClosed method.  But if, in a different class (even in the same file), I have a method like this:

public void CallTheEvent()
{
    FauxIdentityForm _formIdentity = new FauxIdentityForm {FormID = Guid.NewGuid()};

    _formIdentity.Closed(_formIdentity, null);  // <-- Does not compile!
}

The call to Closed is shot down by the compiler (it wants me to only use += and -=).

So, is actually calling the event only allowed inside the class?  Is that the limitation?

If so, is there anyway around it?  And if not, why did the creators of C# do this?  (It makes working with events very hard sometimes.  I imagine there is a good reason and it is probably saving me from myself, but I would like to know it.)


问:
JavaFX 8 on Button Click show other Scene
Hello I am currently working on a PIN Generator for my work and as I am completely new to Java I am having a few difficulties, especially when using JavaFX.
I want to make the programm show another .fxml file when clicking on one of each buttons.

Here is my code:

```<code>import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class main extends Application {
    public static void main(String[] args) {
        Application.launch(main.class, args);
    }
        @Override
        public void start(Stage stage) throws Exception {
            Parent root = FXMLLoader.load(getClass().getResource("/view/main.fxml"));

            stage.setTitle("PIN-Generator");
            stage.setScene(new Scene(root, 600, 400));
            stage.show();
        }
    }
</code>```

I have created a controller Class for each button on the scene.

Controller Class Code:

```<code>    package view;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;

public class MainController {

    @FXML
    private Label dpmadirektpropingenerator;
    @FXML
    private Button unlockPinButton;
    @FXML
    private Button confirmationPinButton;
}
</code>```

答:
This code should works.

Modify your main class like this:

```<code>import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class main extends Application {
public static void main(String[] args) {
    Application.launch(main.class, args);
}
    static Stage stg;
    @Override
    public void start(Stage stage) throws Exception {
    this.stg = stage;
        Parent root = FXMLLoader.load(getClass().getResource("/view/main.fxml"));
        stage.setTitle("PIN-Generator");
        stage.setScene(new Scene(root, 600, 400));
        stage.show();
    }
}
</code>```

and here is your pressButton function:

```<code> public void pressButton(ActionEvent event){
    try {
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("sedondFXML.fxml"));
            Parent root = (Parent) fxmlLoader.load();
            Stage stage = new Stage();
            stage.setScene(new Scene(root));
            stage.show();
            main.stg.close();
    } catch(Exception e) {
       e.printStackTrace();
      }
 }
</code>```

Body:
Hello I am currently working on a PIN Generator for my work and as I am completely new to Java I am having a few difficulties, especially when using JavaFX.
I want to make the programm show another .fxml file when clicking on one of each buttons.

Here is my code:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class main extends Application {
    public static void main(String[] args) {
        Application.launch(main.class, args);
    }
        @Override
        public void start(Stage stage) throws Exception {
            Parent root = FXMLLoader.load(getClass().getResource("/view/main.fxml"));

            stage.setTitle("PIN-Generator");
            stage.setScene(new Scene(root, 600, 400));
            stage.show();
        }
    }

I have created a controller Class for each button on the scene.

Controller Class Code:

    package view;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;

public class MainController {

    @FXML
    private Label dpmadirektpropingenerator;
    @FXML
    private Button unlockPinButton;
    @FXML
    private Button confirmationPinButton;
}

Body:
This code should works.

Modify your main class like this:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class main extends Application {
public static void main(String[] args) {
    Application.launch(main.class, args);
}
    static Stage stg;
    @Override
    public void start(Stage stage) throws Exception {
    this.stg = stage;
        Parent root = FXMLLoader.load(getClass().getResource("/view/main.fxml"));
        stage.setTitle("PIN-Generator");
        stage.setScene(new Scene(root, 600, 400));
        stage.show();
    }
}

and here is your pressButton function:

 public void pressButton(ActionEvent event){
    try {
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("sedondFXML.fxml"));
            Parent root = (Parent) fxmlLoader.load();
            Stage stage = new Stage();
            stage.setScene(new Scene(root));
            stage.show();
            main.stg.close();
    } catch(Exception e) {
       e.printStackTrace();
      }
 }


问:
Finding image type from NSData or UIImage
I am loading an image from a URL provided by a third-party. There is no file extension (or filename for that matter) on the URL (as it is an obscured URL). I can take the data from this (in the form of NSData) and load it into a UIImage and display it fine.

I want to persist this data to a file. However, I don't know what format the data is in (PNG, JPG, BMP)? I assume it is JPG (since it's an image from the web) but is there a programmatic way of finding out for sure? I've looked around StackOverflow and at the documentation and haven't been able to find anything.

TIA.

Edit: Do I really need the file extension? I'm persisting it to an external storage (Amazon S3) but considering that it will always be used in the context of iOS or a browser (both of whom seem fine in interpreting the data without an extension) perhaps this is a non-issue.

答:
An alternative of accepted answer is checking image's UTI with image I/O frameWork. You can achieve image type form UTI.
try this:

```<code>CGImageSourceRef imgSrc = CGImageSourceCreateWithData((CFDataRef)data, NULL);
NSString *uti = (NSString*)CGImageSourceGetType(imgSrc);
NSLog(@"%@",uti);
</code>```

For example, a GIF image's UTI is "com.compuserve.gif" and PNG image's UTI is "public.png".BUT you can't achieve UTI from image which image I/O frameWork doesn't recognized.

Body:
An alternative of accepted answer is checking image's UTI with image I/O frameWork. You can achieve image type form UTI.
try this:

CGImageSourceRef imgSrc = CGImageSourceCreateWithData((CFDataRef)data, NULL);
NSString *uti = (NSString*)CGImageSourceGetType(imgSrc);
NSLog(@"%@",uti);

For example, a GIF image's UTI is "com.compuserve.gif" and PNG image's UTI is "public.png".BUT you can't achieve UTI from image which image I/O frameWork doesn't recognized.


问:
Update when pulling down the screen | ANDROID
Does anyone know how to code it to update the information from the Internet in my app with pulling down the screen?
Like this

Thanks for answering!

答:
Use SwipeRefreshLayout like as

step1: make xml file

```<code><android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="@string/hello_world"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"/>
</ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
</code>```

step2: in your activity do this

```<code>  @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
        android.R.color.holo_green_light,
        android.R.color.holo_orange_light,
        android.R.color.holo_red_light);
}
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
    @Override public void run() {
        swipeLayout.setRefreshing(false);
    }
}, 5000);
}
</code>```

Body:
Use SwipeRefreshLayout like as

step1: make xml file

<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="@string/hello_world"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"/>
</ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>

step2: in your activity do this

  @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
        android.R.color.holo_green_light,
        android.R.color.holo_orange_light,
        android.R.color.holo_red_light);
}
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
    @Override public void run() {
        swipeLayout.setRefreshing(false);
    }
}, 5000);
}


问:
Web Service in Nodejs
I want to print out all number from 1 to 1,000,000 with 1,000 numbers per line. and return the response without having a long delay.

Thanks in advance for any type of help!!!

答:
Well, first you can create a function to print numbers from 1 to 1000.

```<code>function getThousand(index) {
  var result = '';
  for (var i = index; i < index + 1000; i++) {
    result += i + ' ';
  }
  return result;
}
</code>```

Then, you need a function to call this for 1 to 1000000.

```<code>function getAll() {
  var result = '';
  for (var i = 0; i < 1000; i++) {
    result = getThousand((i * 1000) + 1) + " \n";
    fs.appendFileSync('foo.txt', result);
  }
}
</code>```

Then call it all:

```<code>getAll();
</code>```

This will save your lines into a file. At the end of getAll() you can print what you need.

Title: Web Service in Nodejs

Body:
Well, first you can create a function to print numbers from 1 to 1000.

function getThousand(index) {
  var result = '';
  for (var i = index; i < index + 1000; i++) {
    result += i + ' ';
  }
  return result;
}

Then, you need a function to call this for 1 to 1000000.

function getAll() {
  var result = '';
  for (var i = 0; i < 1000; i++) {
    result = getThousand((i * 1000) + 1) + " \n";
    fs.appendFileSync('foo.txt', result);
  }
}

Then call it all:

getAll();

This will save your lines into a file. At the end of getAll() you can print what you need.


问:
How to get started with WCF Performance profiling
I'm trying to figure out how to profile a WCF service so I can identify any bottlenecks.

I have found a bit of information on line, but nothing that assumes no prior knowlege which is where I'm at.

What are recomended FREE tools?

```<code>- visual studio tools
- clrprofiler
</code>```

Here is information I found using vsperfcmd.exe to profile wcf service and according to this it is very simple, but I need to fill in the gaps on where to start. My assumptions are to copy VsPerfCLREnv and VsPerfCmd to the server that hosts my wcf service and perform some configuraiton steps that I'm not quite sure on. I'm also not quite sure how I would be able to see the call stack to evaluate the performance of each call.

clrprofiler seems a bit simpler. I assume I would copy clrprofiler.exe to the server, File->Profile Service and add the name and start/stop commands. (is this a friendly name or filename or the service display name?) I assume I would then run my tests against the service and I could see the call stack in clrprofiler. Does that sound correct?

[edit]

I'm not so interested in testing the network since this is on a test server, and this is a large wcf project with multiple devs on it and I am unable to make changes to the project for the sole purpose of monitoring the performance. I want to focus on the performance of the actual methods within it.

Any assistance on getting started is greatly appreciated.

答:
some things I've learned that someone might find helpful:

you cannot remote profile a service, even over your local network. The profiler must be running on the same machine as the service. (This actually took me quite a while to figure out. Maybe obvious to you, but it was never spelled out so I kept trying to do it)

Visual Studio didn't work for me to profile my WCF service. I was able to get a bit of help from the VS profiler team, but never came out of it with a working solution.

VS was slow to connect and disconnect the profiler and often instrumented my binaries and left them in a corrupted state.

.net binaries do not need to be instrumented since they contain the metadata of the methods which is odd that visual studio kept hosing my binaries trying to instrument them.

I also tried the VS standalone profiler but this is very complex to use and requires reboots of my server.

I ended up getting an internal profiler to work (after getting a private build from the team) so I'm not sure how many profilers out there are designed to work with a WCF service.

I actually set the profiler to watch the WAS service and then added my additional binaries to the profiler.

process explorer is useful when troubleshooting if the profiler is connected or not. Use it to look at inetinfo.exe environment

Body:
I'm trying to figure out how to profile a WCF service so I can identify any bottlenecks.

I have found a bit of information on line, but nothing that assumes no prior knowlege which is where I'm at.

What are recomended FREE tools?

- visual studio tools
- clrprofiler

Here is information I found using vsperfcmd.exe to profile wcf service and according to this it is very simple, but I need to fill in the gaps on where to start. My assumptions are to copy VsPerfCLREnv and VsPerfCmd to the server that hosts my wcf service and perform some configuraiton steps that I'm not quite sure on. I'm also not quite sure how I would be able to see the call stack to evaluate the performance of each call.

clrprofiler seems a bit simpler. I assume I would copy clrprofiler.exe to the server, File->Profile Service and add the name and start/stop commands. (is this a friendly name or filename or the service display name?) I assume I would then run my tests against the service and I could see the call stack in clrprofiler. Does that sound correct?

[edit]

I'm not so interested in testing the network since this is on a test server, and this is a large wcf project with multiple devs on it and I am unable to make changes to the project for the sole purpose of monitoring the performance. I want to focus on the performance of the actual methods within it.

Any assistance on getting started is greatly appreciated.


问:
Multiple concurrent rides for Guests not working
When attempting multiple ride request, "request_id" of first ride is returned in the second request which means new ride is not booked for the second ride request. Please see the request/response below,

Ride Request 1 :

```<code>https://sandbox-api.uber.com/v1.2/requests
{
  "start_latitude": "37.713706",
  "start_longitude": "-122.403708",
  "end_latitude": "37.744186",
  "end_longitude": "-122.466388",
  "fare_id" :"48ba6200227450d3965081024657275f9d1ff5cbb719aaa0bf30be234325f300",
  "guest_id" : "5b357e78-c495-4614-afa1-e2a0b0f3dffc",
  "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
}

**Response :**

{
"status": "processing",
"product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
"destination": {
"latitude": 37.744186,
"longitude": -122.466388
},
"driver": null,
"pickup": {
"latitude": 37.713706,
"longitude": -122.403708
},
"request_id": "2be01f1e-6687-4393-9fcf-e3b840803849",
"eta": null,
"location": null,
"vehicle": null,
"shared": false,
"guest": {
"guest_id": "5b357e78-c495-4614-afa1-e2a0b0f3dffc",
"phone_number": "+14150001234",
"first_name": "Jane",
"last_name": "Smith",
"email": "jane.smith@email.com"
}
}
</code>```

Ride Request 2 :

```<code>https://sandbox-api.uber.com/v1.2/requests
{
  "start_latitude": "37.743033",
  "start_longitude": "-122.389675",
  "end_latitude": "37.7759073",
  "end_longitude": "-122.4245247",
  "fare_id" :"502eed0ccbb906363df23cf9e81ecb6ceb35b8af46a25194775ac9560871da12",
  "guest_id" : "ecc5adeb-fa20-4580-ac24-1ae184bffce9",
  "product_id" : "26546650-e557-4a7b-86e7-6a3942445247"
}

Response:
{
"status": "processing",
"product_id": "26546650-e557-4a7b-86e7-6a3942445247",
"destination": {
"latitude": 37.744186,
"longitude": -122.466388
},
"driver": null,
"pickup": {
"latitude": 37.713706,
"longitude": -122.403708
},
"request_id": "2be01f1e-6687-4393-9fcf-e3b840803849",
"eta": null,
"location": null,
"vehicle": null,
"shared": false,
"guest": {
"guest_id": "ecc5adeb-fa20-4580-ac24-1ae184bffce9",
"phone_number": "+14150001234",
"first_name": "Jane",
"last_name": "Smith",
"email": "jane.smith@email.com"
}
}
</code>```

答: You can only have one concurrent ride per user/token so it is expected. In your case you just made a ride request in the sandbox and did not progress the state to completed or cancel the ride. </p>

Body:
When attempting multiple ride request, "request_id" of first ride is returned in the second request which means new ride is not booked for the second ride request. Please see the request/response below,

Ride Request 1 :

https://sandbox-api.uber.com/v1.2/requests
{
  "start_latitude": "37.713706",
  "start_longitude": "-122.403708",
  "end_latitude": "37.744186",
  "end_longitude": "-122.466388",
  "fare_id" :"48ba6200227450d3965081024657275f9d1ff5cbb719aaa0bf30be234325f300",
  "guest_id" : "5b357e78-c495-4614-afa1-e2a0b0f3dffc",
  "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
}

**Response :**

{
"status": "processing",
"product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
"destination": {
"latitude": 37.744186,
"longitude": -122.466388
},
"driver": null,
"pickup": {
"latitude": 37.713706,
"longitude": -122.403708
},
"request_id": "2be01f1e-6687-4393-9fcf-e3b840803849",
"eta": null,
"location": null,
"vehicle": null,
"shared": false,
"guest": {
"guest_id": "5b357e78-c495-4614-afa1-e2a0b0f3dffc",
"phone_number": "+14150001234",
"first_name": "Jane",
"last_name": "Smith",
"email": "jane.smith@email.com"
}
}

Ride Request 2 :

https://sandbox-api.uber.com/v1.2/requests
{
  "start_latitude": "37.743033",
  "start_longitude": "-122.389675",
  "end_latitude": "37.7759073",
  "end_longitude": "-122.4245247",
  "fare_id" :"502eed0ccbb906363df23cf9e81ecb6ceb35b8af46a25194775ac9560871da12",
  "guest_id" : "ecc5adeb-fa20-4580-ac24-1ae184bffce9",
  "product_id" : "26546650-e557-4a7b-86e7-6a3942445247"
}

Response:
{
"status": "processing",
"product_id": "26546650-e557-4a7b-86e7-6a3942445247",
"destination": {
"latitude": 37.744186,
"longitude": -122.466388
},
"driver": null,
"pickup": {
"latitude": 37.713706,
"longitude": -122.403708
},
"request_id": "2be01f1e-6687-4393-9fcf-e3b840803849",
"eta": null,
"location": null,
"vehicle": null,
"shared": false,
"guest": {
"guest_id": "ecc5adeb-fa20-4580-ac24-1ae184bffce9",
"phone_number": "+14150001234",
"first_name": "Jane",
"last_name": "Smith",
"email": "jane.smith@email.com"
}
}


问:
How to create and deploy a contract with ether attached?
How to create and deploy a contract with ether attached in web3.js?
In solidity, I know it can be writted like this:

D newD = (new D).value(amount)(arg);```

But how to write it in web3.js for testing contract.
Thanks sincerely

答:
Just attach the attribute of "value: amount" when create contract like this:
.new(
{
from: web3.eth.accounts[0],
value: 5 wei
}</p>

Body:
How to create and deploy a contract with ether attached in web3.js?
In solidity, I know it can be writted like this:

D newD = (new D).value(amount)(arg);

But how to write it in web3.js for testing contract.
Thanks sincerely


问:
How do I merge two time series to result in an object with only the dates from the smaller one (R)?
I have two daily time series ranging from 1st of Jan 2016 to 1st of Aug 2016, however one my my series only includes data from business days (i.e weekends and bank holidays omitted), the other has data for everyday. My question is, how do I merge the two series so that for both time series I have only the business day data left over (deleting those extra days from the second time series)</p>

答:
The question was tagged also with data.table so I guess that the two time series are stored as data.frames or data.tables.

By default, joins in data.table are right joins. So, if you know in advance which one the "shorter" time series is you can write:

```<code>library(data.table)
dt_long[dt_short, on = "date"]
#         date weekday i.weekday
#1: 2017-03-30       4         4
#2: 2017-03-31       5         5
#3: 2017-04-03       1         1
#4: 2017-04-04       2         2
#5: 2017-04-05       3         3
#6: 2017-04-06       4         4
</code>```

If you are not sure which the "shorter" time series is you can use an inner join:

```<code>dt_short[dt_long, on = "date", nomatch = 0]
</code>```

nomatch = 0 specifies the inner join.

If your time series are not already data.tables as the sample data here but are stored as data.frames, you need to coerce them to data.table class beforehand by:

```<code>setDT(dt_long)
setDT(dt_short)
</code>```

Data

As the OP hasn't provided any reproducible data, we need to prepare sample data on our own (similar to this answer but as data.table):

```<code>library(data.table)
dt_long <- data.table(date = as.Date("2017-03-30") + 0:7)
# add payload: integer weekday according ISO (week starts on Monday == 1L)
dt_long[, weekday := as.integer(format(date, "%u"))]
# remove weekends
dt_short <- dt_long[weekday < 6L]
</code>```

Body:
The question was tagged also with data.table so I guess that the two time series are stored as data.frames or data.tables.

By default, joins in data.table are right joins. So, if you know in advance which one the "shorter" time series is you can write:

library(data.table)
dt_long[dt_short, on = "date"]
#         date weekday i.weekday
#1: 2017-03-30       4         4
#2: 2017-03-31       5         5
#3: 2017-04-03       1         1
#4: 2017-04-04       2         2
#5: 2017-04-05       3         3
#6: 2017-04-06       4         4

If you are not sure which the "shorter" time series is you can use an inner join:

dt_short[dt_long, on = "date", nomatch = 0]

nomatch = 0 specifies the inner join.

If your time series are not already data.tables as the sample data here but are stored as data.frames, you need to coerce them to data.table class beforehand by:

setDT(dt_long)
setDT(dt_short)

Data

As the OP hasn't provided any reproducible data, we need to prepare sample data on our own (similar to this answer but as data.table):

library(data.table)
dt_long <- data.table(date = as.Date("2017-03-30") + 0:7)
# add payload: integer weekday according ISO (week starts on Monday == 1L)
dt_long[, weekday := as.integer(format(date, "%u"))]
# remove weekends
dt_short <- dt_long[weekday < 6L]


问:
Debugging 'CALayer position contains NaN: [nan nan]'
Right after updating Xcode to 8.3, I started receiving this error at launch: Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan nan]'

The main view for my app has a couple of container views, one of which holds a mapView. It appears the error has to do with the map, but I can't quite make out from the message what that might be. Any thoughts would be greatly appreciated!

```<code>*** Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan nan]'
*** First throw call stack:
(
0   CoreFoundation                      0x00000001029b1b0b __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x0000000102416141 objc_exception_throw + 48
2   CoreFoundation                      0x0000000102a1a625 +[NSException raise:format:] + 197
3   QuartzCore                          0x00000001039d90be _ZN2CA5Layer12set_positionERKNS_4Vec2IdEEb + 152
4   QuartzCore                          0x00000001039d9231 -[CALayer setPosition:] + 43
5   MapKit                              0x000000010354a97b -[MKMapView _updateScrollContainerView:] + 1214
6   MapKit                              0x000000010354bbeb -[MKMapView _sizeDidChangeWithCenterCoordinate:] + 55
7   MapKit                              0x000000010354606e -[MKMapView setBounds:] + 271
8   UIKit                               0x0000000103c14b23 -[UIView(Geometry) _applyISEngineLayoutValuesToBoundsOnly:] + 598
9   UIKit                               0x0000000103c14e0e -[UIView(Geometry) _resizeWithOldSuperviewSize:] + 125
10  CoreFoundation                      0x0000000102942652 __53-[__NSArrayM enumerateObjectsWithOptions:usingBlock:]_block_invoke + 114
11  CoreFoundation                      0x000000010294256f -[__NSArrayM enumerateObjectsWithOptions:usingBlock:] + 335
12  UIKit                               0x0000000103c1387c -[UIView(Geometry) resizeSubviewsWithOldSize:] + 183
13  UIKit                               0x000000010452f1f9 -[UIView(AdditionalLayoutSupport) _is_layout] + 168
14  UIKit                               0x0000000103c1fd56 -[UIView(Hierarchy) _updateConstraintsAsNecessaryAndApplyLayoutFromEngine] + 994
15  UIKit                               0x0000000103c3120b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1268
16  QuartzCore                          0x00000001039e2904 -[CALayer layoutSublayers] + 146
17  QuartzCore                          0x00000001039d6526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370
18  QuartzCore                          0x00000001039d63a0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
19  QuartzCore                          0x0000000103965e92 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
20  QuartzCore                          0x0000000103992130 _ZN2CA11Transaction6commitEv + 468
21  QuartzCore                          0x0000000103992b37 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 115
22  CoreFoundation                      0x0000000102957717 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
23  CoreFoundation                      0x0000000102957687 __CFRunLoopDoObservers + 391
24  CoreFoundation                      0x000000010293c038 CFRunLoopRunSpecific + 440
25  UIKit                               0x0000000103b6802f -[UIApplication _run] + 468
26  UIKit                               0x0000000103b6e0d4 UIApplicationMain + 159
27  Pulley                              0x0000000101bd95b7 main + 55
28  libdyld.dylib                       0x0000000109eaa65d start + 1
29  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
</code>```

答:
It seems that you are doing setPosition: using CALayer object and that CALayer object is nil. Thats why your app is crashed.

please check that CALayer is nil or not by if statement.

Body:
Right after updating Xcode to 8.3, I started receiving this error at launch: Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan nan]'

The main view for my app has a couple of container views, one of which holds a mapView. It appears the error has to do with the map, but I can't quite make out from the message what that might be. Any thoughts would be greatly appreciated!

*** Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan nan]'
*** First throw call stack:
(
0   CoreFoundation                      0x00000001029b1b0b __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x0000000102416141 objc_exception_throw + 48
2   CoreFoundation                      0x0000000102a1a625 +[NSException raise:format:] + 197
3   QuartzCore                          0x00000001039d90be _ZN2CA5Layer12set_positionERKNS_4Vec2IdEEb + 152
4   QuartzCore                          0x00000001039d9231 -[CALayer setPosition:] + 43
5   MapKit                              0x000000010354a97b -[MKMapView _updateScrollContainerView:] + 1214
6   MapKit                              0x000000010354bbeb -[MKMapView _sizeDidChangeWithCenterCoordinate:] + 55
7   MapKit                              0x000000010354606e -[MKMapView setBounds:] + 271
8   UIKit                               0x0000000103c14b23 -[UIView(Geometry) _applyISEngineLayoutValuesToBoundsOnly:] + 598
9   UIKit                               0x0000000103c14e0e -[UIView(Geometry) _resizeWithOldSuperviewSize:] + 125
10  CoreFoundation                      0x0000000102942652 __53-[__NSArrayM enumerateObjectsWithOptions:usingBlock:]_block_invoke + 114
11  CoreFoundation                      0x000000010294256f -[__NSArrayM enumerateObjectsWithOptions:usingBlock:] + 335
12  UIKit                               0x0000000103c1387c -[UIView(Geometry) resizeSubviewsWithOldSize:] + 183
13  UIKit                               0x000000010452f1f9 -[UIView(AdditionalLayoutSupport) _is_layout] + 168
14  UIKit                               0x0000000103c1fd56 -[UIView(Hierarchy) _updateConstraintsAsNecessaryAndApplyLayoutFromEngine] + 994
15  UIKit                               0x0000000103c3120b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1268
16  QuartzCore                          0x00000001039e2904 -[CALayer layoutSublayers] + 146
17  QuartzCore                          0x00000001039d6526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370
18  QuartzCore                          0x00000001039d63a0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
19  QuartzCore                          0x0000000103965e92 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
20  QuartzCore                          0x0000000103992130 _ZN2CA11Transaction6commitEv + 468
21  QuartzCore                          0x0000000103992b37 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 115
22  CoreFoundation                      0x0000000102957717 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
23  CoreFoundation                      0x0000000102957687 __CFRunLoopDoObservers + 391
24  CoreFoundation                      0x000000010293c038 CFRunLoopRunSpecific + 440
25  UIKit                               0x0000000103b6802f -[UIApplication _run] + 468
26  UIKit                               0x0000000103b6e0d4 UIApplicationMain + 159
27  Pulley                              0x0000000101bd95b7 main + 55
28  libdyld.dylib                       0x0000000109eaa65d start + 1
29  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)


问:
How to toggle a class within a form element using onClick?
I'm looking for some JS or jQuery (either plugin or otherwise) to help me with manipulating the class="required" that jQuery's validation plugin uses for form validation in the form fields.  I need to be able to toggle that class to equal nothing when a Delete button is clicked.

Here's more context on why I need to be able to toggle that class "required on or off:

1) This is a registration form for more than one attendee for an event

2) there is a control in the form allowing the registrant to "Delete" an attendee (if s/he decides to bring 2 instead of 4 people).  This toggles the visibility of that DIV where that attendee's form elements live.  I can see what attendee the form elements belong to since my PHP loop created them with first_name_1 (for the first attendee) and then the second attendee would have first_name_2.  Then each div_attendee_1 or 2 or 3 has their form fields with this counter appended to the end of each field.

3) When a div is rendered visibility="hidden" I also reset the form elements in that div.  BUT I think I need to also access the class="required" to render it class="".

What's the best way to do that?  Here's the jQuery I have so far to toggle the visibility and reset the field values:

Validation:

```<code> <script>
  $(document).ready(function(){
    $("#the_form").validate();
  });
  </script>
</code>```

And then:

```<code><script language="JavaScript">
  function showhidefield(hideablearea){
   document.getElementById(hideablearea).style.visibility = "hidden";
   var el = document.getElementById(hideablearea);
    if ( el.style.display != 'none' ) {
        el.style.display = 'none';
    }
    else {
        el.style.display = '';
    }
    $('#' + hideablearea).hide().find("input").val("");
    $('#' + hideablearea).attr('disabled', true);
  }
</script>
</code>```

Should I just try and rewrite the elements using inner.html?

Thanks!

答: You can use addClass and removeClass.  You can also use .css and set the value to something, or set it to nothing, and that will add and remove a style rather than a class... just looks like you need class level.</p>

Body:
I'm looking for some JS or jQuery (either plugin or otherwise) to help me with manipulating the class="required" that jQuery's validation plugin uses for form validation in the form fields.  I need to be able to toggle that class to equal nothing when a Delete button is clicked.

Here's more context on why I need to be able to toggle that class "required on or off:

1) This is a registration form for more than one attendee for an event

2) there is a control in the form allowing the registrant to "Delete" an attendee (if s/he decides to bring 2 instead of 4 people).  This toggles the visibility of that DIV where that attendee's form elements live.  I can see what attendee the form elements belong to since my PHP loop created them with first_name_1 (for the first attendee) and then the second attendee would have first_name_2.  Then each div_attendee_1 or 2 or 3 has their form fields with this counter appended to the end of each field.

3) When a div is rendered visibility="hidden" I also reset the form elements in that div.  BUT I think I need to also access the class="required" to render it class="".

What's the best way to do that?  Here's the jQuery I have so far to toggle the visibility and reset the field values:

Validation:

And then:

Should I just try and rewrite the elements using inner.html?

Thanks!


问:
How to convert an IO String to a algebraic Type of data "Products" of a txt file?
I have to ask the user to enter the code, the name, and the price of a product in Products.txt.

```<code>produtoPath::FilePath
produtoPath = "Products.txt"

 adicionaProd::IO()
 adicionaProd = do
    putStr "Product's Code:"
    cod<-getLine
    putStr "Product's Name:"
    nom<-getLine
    putStr "Product's Price:"
    pre<-getLine
--  appendFile produtoPath
    putStr "Do you want to add some other product?"
    resp <- getLine
    if ((resp == "y")) then adicionaProd else return()
</code>```

So, after the products have been added, I have to create another function that will read the contents of Products.txt, and return Products ... type Products = [(Code, Name, Price)], and I do not know how to do this ...
I've tried, but I could not.

```<code> generateList:: [[String]]-> Produtos
 generateList [] = []
 --generateList [[cod,nom,pre]:[]] = [(read:cod)::]
</code>```

After that, I have to load the products with the function loadProducts ... That reads the files of the previous function, and returns the type IO Products, in order that the user can visualize what is in the file in the format of the type Products .

```<code>loadTable:: IO Produtos
loadTable = do
         s<-readFile produtoPath
    --   return generateList (map words)
</code>```

In summary: I do not know the way I should be saving the data in the "addProd" function, to read the file and generate Products cpm the generateList function, and load them to the user with the loadTable function.Can you help me?
Complete code of what I did: https://ideone.com/Al9ZLf

答:
You probably need to return the input data from adicionaProd. So, its type must become

```<code>type Products   = [(Code, Name, Price)]
adicionaProd :: IO Products
</code>```

Then, you adjust the code itself

```<code> adicionaProd = do
    putStr "Product's Code:"
    cod<-getLine
    putStr "Product's Name:"
    nom<-getLine
    putStr "Product's Price:"
    pre<-getLine
    let prod :: (Code, Name, Price)
        prod = (read cod, nom, read pre)
    putStr "Do you want to add some other product?"
    resp <- getLine
    if resp == "y" then do
       rest <- adicionaProd
       return (prod : rest)
    else
       return [prod]
</code>```

The idea is: if the response is "yes", then you recursively ask for a list of products, and bind it to rest. Then, you return a list comprising your product and following with the rest. If the response is "no", you return a list containing the first product, only.

Body:
I have to ask the user to enter the code, the name, and the price of a product in Products.txt.

produtoPath::FilePath
produtoPath = "Products.txt"

 adicionaProd::IO()
 adicionaProd = do
    putStr "Product's Code:"
    cod<-getLine
    putStr "Product's Name:"
    nom<-getLine
    putStr "Product's Price:"
    pre<-getLine
--  appendFile produtoPath
    putStr "Do you want to add some other product?"
    resp <- getLine
    if ((resp == "y")) then adicionaProd else return()

So, after the products have been added, I have to create another function that will read the contents of Products.txt, and return Products ... type Products = [(Code, Name, Price)], and I do not know how to do this ...
I've tried, but I could not.

 generateList:: [[String]]-> Produtos
 generateList [] = []
 --generateList [[cod,nom,pre]:[]] = [(read:cod)::]

After that, I have to load the products with the function loadProducts ... That reads the files of the previous function, and returns the type IO Products, in order that the user can visualize what is in the file in the format of the type Products .

loadTable:: IO Produtos
loadTable = do
         s<-readFile produtoPath
    --   return generateList (map words)

In summary: I do not know the way I should be saving the data in the "addProd" function, to read the file and generate Products cpm the generateList function, and load them to the user with the loadTable function.Can you help me?
Complete code of what I did: https://ideone.com/Al9ZLf

Body:
You probably need to return the input data from adicionaProd. So, its type must become

type Products   = [(Code, Name, Price)]
adicionaProd :: IO Products

Then, you adjust the code itself

 adicionaProd = do
    putStr "Product's Code:"
    cod<-getLine
    putStr "Product's Name:"
    nom<-getLine
    putStr "Product's Price:"
    pre<-getLine
    let prod :: (Code, Name, Price)
        prod = (read cod, nom, read pre)
    putStr "Do you want to add some other product?"
    resp <- getLine
    if resp == "y" then do
       rest <- adicionaProd
       return (prod : rest)
    else
       return [prod]

The idea is: if the response is "yes", then you recursively ask for a list of products, and bind it to rest. Then, you return a list comprising your product and following with the rest. If the response is "no", you return a list containing the first product, only.


问:
Hadoop MapReduce Jobs for Highest Frequency
I'm trying to use the basic word count as defined here. Is it possible that when the IntSumReducer does context.write, that context.write could be passed to a second reducer or output class that would reduce/change the final list given by the IntSumReducer down to a single largest frequency?

I am quite new to Hadoop/MapReduce and the concept of jobs in Java so I'm uncertain how exactly I would need to modify the default WordCount to comply to make that possible. Could I write a second Reducer function and place it inside of the same job? How would I do that? How would I signal that there is another reducer to be run after IntSumReducer?

Base WordCount:

```<code>import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class WordCount {

   public static class TokenizerMapper
   extends Mapper<Object, Text, Text, IntWritable>{

private final static IntWritable one = new IntWritable(1);
private Text word = new Text();

public void map(Object key, Text value, Context context
                ) throws IOException, InterruptedException {
  StringTokenizer itr = new StringTokenizer(value.toString());
  while (itr.hasMoreTokens()) {
    word.set(itr.nextToken());
    context.write(word, one);
  }
}
}

public static class IntSumReducer
   extends Reducer<Text,IntWritable,Text,IntWritable> {
private IntWritable result = new IntWritable();

public void reduce(Text key, Iterable<IntWritable> values,
                   Context context
                   ) throws IOException, InterruptedException {
  int sum = 0;
  for (IntWritable val : values) {
    sum += val.get();
  }
  result.set(sum);
  context.write(key, result);
     }
}

  public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}`
</code>```

答: What you're looking for is called a Combiner in hadoop, which does some semi-reduction before emitting the output to a final reducer class. For more info on it click here.

Body:
I'm trying to use the basic word count as defined here. Is it possible that when the IntSumReducer does context.write, that context.write could be passed to a second reducer or output class that would reduce/change the final list given by the IntSumReducer down to a single largest frequency?

I am quite new to Hadoop/MapReduce and the concept of jobs in Java so I'm uncertain how exactly I would need to modify the default WordCount to comply to make that possible. Could I write a second Reducer function and place it inside of the same job? How would I do that? How would I signal that there is another reducer to be run after IntSumReducer?

Base WordCount:

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class WordCount {

   public static class TokenizerMapper
   extends Mapper<Object, Text, Text, IntWritable>{

private final static IntWritable one = new IntWritable(1);
private Text word = new Text();

public void map(Object key, Text value, Context context
                ) throws IOException, InterruptedException {
  StringTokenizer itr = new StringTokenizer(value.toString());
  while (itr.hasMoreTokens()) {
    word.set(itr.nextToken());
    context.write(word, one);
  }
}
}

public static class IntSumReducer
   extends Reducer<Text,IntWritable,Text,IntWritable> {
private IntWritable result = new IntWritable();

public void reduce(Text key, Iterable<IntWritable> values,
                   Context context
                   ) throws IOException, InterruptedException {
  int sum = 0;
  for (IntWritable val : values) {
    sum += val.get();
  }
  result.set(sum);
  context.write(key, result);
     }
}

  public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}`


问:
when calling lapply or for loop , Plots not getting displayed iteratively in the html generated by knitting code in R markdown
My data frame 'df'  looks like this

```<code>C1 C2 C3 C4
AA 10 ab 9
AA 11 ac 10
AA 12 ae 11
BB 10 ab 20
BB 11 ab 30
BB 12 ab 2
CC 10 ax 20
CC 12 ad 20
DD 17 ae 23
</code>```

and so on.. 13000 rows.

In R Studio I am able to iteratively display/generate individual bar charts using plotly for each unique value in C1 in the following way :

```<code>abcd<-c('AA','BB','CC', 'DD')
        ## when using all of the data frame I plan to do : abcd<-df$C1

        myfun<- function(j)
        {

          main<-paste("Printing  ", abcd[j],"  <br> (Hover for values) " )

          df %>%
            filter(C1==abcd[j])%>%
            select(C1,C2,C3,C4) %>%
            group_by(C1,C2,C3) %>%
            summarise(value=sum(C4))-> new_df

          p<-(plot_ly(new_df, x= ~C2, y = ~value, color = ~C3, type = "bar", alpha = 0.9) %>%
                layout(title = main, xaxis = list(title ="", yaxis = list(title = "Test Title")))%>% layout(barmode = "stack"))

          p
        }
        lapply(1:4, myfun)
</code>```

I was also able to do the same thing using a for loop over 'abcd'

Here is my Rmarkdown code:

```<code>    ---
    title: 'Apple bees'
    author: "Krazzy R"
    date: "28 March 2017"
    output:
      html_document:
        highlight: pygments
        pdf_document: default
        theme: spacelab
      pdf_document: default
      word_document: default
    ---

    ```{r setup, include=FALSE}
    library(knitr)

    knitr::opts_chunk$set(tidy.opts=list(width.cutoff=120),tidy=TRUE,echo = TRUE)
    ```

    ```{r, include=TRUE,results='hide', message=FALSE, warning=FALSE, echo=TRUE}
    library(plyr)
    library(dplyr)
    library(ggplot2)
    library(readr)
    require(knitr)
    require(plotly)
    ```
    ```{r, echo= TRUE)
    df<- read.csv("my_csv.csv")

    abcd<-c('AA','BB','CC', 'DD')
        ## when using all of the data frame I plan to do : abcd<-df$C1

        myfun<- function(j)
        {
          main<-paste("Printing  ", abcd[j],"
 (Hover for values) " )

          df %>%
            filter(C1==abcd[j])%>%
            select(C1,C2,C3,C4) %>%
            group_by(C1,C2,C3) %>%
            summarise(value=sum(C4))-> new_df

          p<-(plot_ly(new_df, x= ~C2, y = ~value, color = ~C3, type = "bar", alpha = 0.9) %>%
                layout(title = main, xaxis = list(title ="", yaxis = list(title = "Test Title")))%>% layout(barmode = "stack"))

          p
        }

    ```

    ```{r, echo=TRUE}
    myfun(1)
    myfun(2)
    myfun(3)

    ```
</code>```

When I explicitly call

  myfun(1)

      myfun(2)   etc.

    the plots are displayed in the knitted html.

    However I have 200 unique values in C1 and I want to display all of them iteratively.

So I tried

1.

```<code>      ```{r, echo=TRUE}
        lapply(1:4,myfun)

        ```
</code>```

But this doesn't display any plots.

Then I tried:

 2.

```<code>    ```{r, echo =TRUE}
    print(lapply(1:4, myfun))
    ```
</code>```

Still no outputs

So

3.

```<code>    ```{r, echo =TRUE}
    for(i in 1:4){
    (myfun(i))
    }
    ```
</code>```

Again no plots.

4.
So yried using for loop

```<code>        ```{r, echo= TRUE}
        abcd<-c('AA','BB','CC', 'DD')
                ## when using all of the data frame I plan to do : abcd<-df$C1

                for(j in 1:4){

       main<-paste("Printing  ", abcd[j],"
 (Hover for values) " )

              df %>%
                filter(C1==abcd[j])%>%
                select(C1,C2,C3,C4) %>%
                group_by(C1,C2,C3) %>%
                summarise(value=sum(C4))-> new_df

              p<-(plot_ly(new_df, x= ~C2, y = ~value, color = ~C3, type = "bar", alpha = 0.9) %>%
                    layout(title = main, xaxis = list(title ="", yaxis = list(title = "Test Title")))%>% layout(barmode = "stack"))

              p
    # no change when using print(p)

            }

    ```
</code>```

No plots.

However if I move the p to outside the for loop it prints only one plot corresponding to the last value of the loop.
What am I missing? How do I fix this?
Thanks in advance.

答:
lapply() returns a list that has to be rendered as HTML when the document is knitted.

To do that you should use htmltools::tagList()

```<code>```{r, echo=TRUE}
htmltools::tagList(lapply(1:4,myfun))
```
</code>```

Note that this returns a white space if rendered 'inline'

Body:
My data frame 'df'  looks like this

C1 C2 C3 C4
AA 10 ab 9
AA 11 ac 10
AA 12 ae 11
BB 10 ab 20
BB 11 ab 30
BB 12 ab 2
CC 10 ax 20
CC 12 ad 20
DD 17 ae 23

and so on.. 13000 rows.

In R Studio I am able to iteratively display/generate individual bar charts using plotly for each unique value in C1 in the following way :

abcd<-c('AA','BB','CC', 'DD')
        ## when using all of the data frame I plan to do : abcd<-df$C1

        myfun<- function(j)
        {

          main<-paste("Printing  ", abcd[j],"
 (Hover for values) " )

          df %>%
            filter(C1==abcd[j])%>%
            select(C1,C2,C3,C4) %>%
            group_by(C1,C2,C3) %>%
            summarise(value=sum(C4))-> new_df

          p<-(plot_ly(new_df, x= ~C2, y = ~value, color = ~C3, type = "bar", alpha = 0.9) %>%
                layout(title = main, xaxis = list(title ="", yaxis = list(title = "Test Title")))%>% layout(barmode = "stack"))

          p
        }
        lapply(1:4, myfun)

I was also able to do the same thing using a for loop over 'abcd'

Here is my Rmarkdown code:

    ---
    title: 'Apple bees'
    author: "Krazzy R"
    date: "28 March 2017"
    output:
      html_document:
        highlight: pygments
        pdf_document: default
        theme: spacelab
      pdf_document: default
      word_document: default
    ---

    ```{r setup, include=FALSE}
    library(knitr)

    knitr::opts_chunk$set(tidy.opts=list(width.cutoff=120),tidy=TRUE,echo = TRUE)
    ```

    ```{r, include=TRUE,results='hide', message=FALSE, warning=FALSE, echo=TRUE}
    library(plyr)
    library(dplyr)
    library(ggplot2)
    library(readr)
    require(knitr)
    require(plotly)
    ```
    ```{r, echo= TRUE)
    df<- read.csv("my_csv.csv")

    abcd<-c('AA','BB','CC', 'DD')
        ## when using all of the data frame I plan to do : abcd<-df$C1

        myfun<- function(j)
        {
          main<-paste("Printing  ", abcd[j],"  <br> (Hover for values) " )

          df %>%
            filter(C1==abcd[j])%>%
            select(C1,C2,C3,C4) %>%
            group_by(C1,C2,C3) %>%
            summarise(value=sum(C4))-> new_df

          p<-(plot_ly(new_df, x= ~C2, y = ~value, color = ~C3, type = "bar", alpha = 0.9) %>%
                layout(title = main, xaxis = list(title ="", yaxis = list(title = "Test Title")))%>% layout(barmode = "stack"))

          p
        }

    ```

    ```{r, echo=TRUE}
    myfun(1)
    myfun(2)
    myfun(3)

    ```

When I explicitly call

  myfun(1)

      myfun(2)   etc.

    the plots are displayed in the knitted html.

    However I have 200 unique values in C1 and I want to display all of them iteratively.

So I tried

1.

      ```{r, echo=TRUE}
        lapply(1:4,myfun)

        ```

But this doesn't display any plots.

Then I tried:

 2.

    ```{r, echo =TRUE}
    print(lapply(1:4, myfun))
    ```

Still no outputs

So

3.

    ```{r, echo =TRUE}
    for(i in 1:4){
    (myfun(i))
    }
    ```

Again no plots.

4.
So yried using for loop

        ```{r, echo= TRUE}
        abcd<-c('AA','BB','CC', 'DD')
                ## when using all of the data frame I plan to do : abcd<-df$C1

                for(j in 1:4){

       main<-paste("Printing  ", abcd[j],"  <br> (Hover for values) " )

              df %>%
                filter(C1==abcd[j])%>%
                select(C1,C2,C3,C4) %>%
                group_by(C1,C2,C3) %>%
                summarise(value=sum(C4))-> new_df

              p<-(plot_ly(new_df, x= ~C2, y = ~value, color = ~C3, type = "bar", alpha = 0.9) %>%
                    layout(title = main, xaxis = list(title ="", yaxis = list(title = "Test Title")))%>% layout(barmode = "stack"))

              p
    # no change when using print(p)

            }

    ```

No plots.

However if I move the p to outside the for loop it prints only one plot corresponding to the last value of the loop.
What am I missing? How do I fix this?
Thanks in advance.

Body:
lapply() returns a list that has to be rendered as HTML when the document is knitted.

To do that you should use htmltools::tagList()

```{r, echo=TRUE}
htmltools::tagList(lapply(1:4,myfun))
```

Note that this returns a white space if rendered 'inline'


问:
Destination array is not long enough to copy all the items in the collection. Check array index and length
I have this code. It gives me an error :

Destination array is not long enough to copy all the items in the
  collection. Check array index and length.

I thought that it was because of using a dictionary, so I switched it to ConcurrentDictionary, but the error is still here.

```<code>private void SaverCallback()
{
    AddThread("Main Thread");
    const string path = "milestone";
    while (!stop)
    {
        ConcurrentDictionary<string, object> milestone = new ConcurrentDictionary<string, object>();
        milestone.TryAdd("Jobs", JobQueue.Queue.MainQueue);
        milestone.TryAdd("Locked Jobs", JobQueue.Queue.LockedQueue);

    again: try {
            using (FileStream writingStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
            {
                BinaryFormatter formater = new BinaryFormatter();
                formater.Serialize(writingStream, milestone);
                writingStream.Flush();
                Logger.Debug("Status saved");
            }
        }
        catch(Exception e)
        {
            Logger.Error($"Milestone exception: {e.Message}");
            goto again;
        }
        this.WaitTime(60000);
    }
    RemoveThread();
}
</code>```

UPD:

Destination array is not long enough to copy all the items in the
  collection. Check array index and length. and    at
  System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
  at System.Collections.Generic.Dictionary2.CopyTo(KeyValuePair2[]
  array, Int32 index)    at
  System.Collections.Generic.Dictionary`2.GetObjectData(SerializationInfo
  info, StreamingContext context)    at
  System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object
  obj, ISurrogateSelector surrogateSelector, StreamingContext context,
  SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter,
  ObjectWriter objectWriter, SerializationBinder binder)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo
  objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteArrayMember(WriteObjectInfo
  objectInfo, NameInfo arrayElemTypeNameInfo, Object data)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteArray(WriteObjectInfo
  objectInfo, NameInfo memberNameInfo, WriteObjectInfo memberObjectInfo)
  at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo
  objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object
  graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)

  at
  System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream
  serializationStream, Object graph, Header[] headers, Boolean fCheck)

  at AggregateRunner.Enteties.Saver.SaverCallback()

答:
To avoid this error I use lock before a try to serialize a file.
Now it works correctly. </p>

Body:
I have this code. It gives me an error :

Destination array is not long enough to copy all the items in the
  collection. Check array index and length.

I thought that it was because of using a dictionary, so I switched it to ConcurrentDictionary, but the error is still here.

private void SaverCallback()
{
    AddThread("Main Thread");
    const string path = "milestone";
    while (!stop)
    {
        ConcurrentDictionary<string, object> milestone = new ConcurrentDictionary<string, object>();
        milestone.TryAdd("Jobs", JobQueue.Queue.MainQueue);
        milestone.TryAdd("Locked Jobs", JobQueue.Queue.LockedQueue);

    again: try {
            using (FileStream writingStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
            {
                BinaryFormatter formater = new BinaryFormatter();
                formater.Serialize(writingStream, milestone);
                writingStream.Flush();
                Logger.Debug("Status saved");
            }
        }
        catch(Exception e)
        {
            Logger.Error($"Milestone exception: {e.Message}");
            goto again;
        }
        this.WaitTime(60000);
    }
    RemoveThread();
}

UPD:

Destination array is not long enough to copy all the items in the
  collection. Check array index and length. and    at
  System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
  at System.Collections.Generic.Dictionary2.CopyTo(KeyValuePair2[]
  array, Int32 index)    at
  System.Collections.Generic.Dictionary`2.GetObjectData(SerializationInfo
  info, StreamingContext context)    at
  System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object
  obj, ISurrogateSelector surrogateSelector, StreamingContext context,
  SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter,
  ObjectWriter objectWriter, SerializationBinder binder)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo
  objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteArrayMember(WriteObjectInfo
  objectInfo, NameInfo arrayElemTypeNameInfo, Object data)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteArray(WriteObjectInfo
  objectInfo, NameInfo memberNameInfo, WriteObjectInfo memberObjectInfo)
  at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo
  objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object
  graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)

  at
  System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream
  serializationStream, Object graph, Header[] headers, Boolean fCheck)

  at AggregateRunner.Enteties.Saver.SaverCallback()


问:
Insert data on Xampp using jquery on phonegap
I am developing a simple application to save records on mysql database (xampp) using phonegap. However i am getting stucked somewhere.
My code keeps writing "connecting..." for ever without saving the records on database. I researched all through but I cant seem to get the problem Please can somewhere show me my mistakes from my code? Thanks
Maybe its the url, i am not sure,
NOTE: My url is from the phonegap server.</p>

```<code> index.html
          <link rel="stylesheet" type="text/css" href="css/index.css" />
         <title>Hello World</title>
       </head>

  <body>
   <script src="jquery-3.1.1.min.js"></script>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script type="text/javascript" src="cordova.js"></script>
  <script type="text/javascript" src="js/index.js"></script>
  <script type="text/javascript">
    app.initialize();
    $(document).ready(function()
        {
    $("#insert").click(function(){
        var firstname=$("#firstname").val();
        var lastname=$("#lastname").val();
        var phone=$("#phone").val();
        var dataString="firstname="+firstname+"&lastname="+lastname+"&phone="+phone+"&insert=";
        if($.trim(firstname).length>0 & $.trim(lastname).length>0 & $.trim(phone).length>0)
            {

        $.ajax({
        type: "POST",
        url: "http://10.250.216.195:3000/insert.php",
        data: dataString,

        crossDomain: true,
        cache: false,
        beforeSend: function(){ $("#insert").val('Connecting...');},
        success: function(data){
            if(data=="success"){
                console.log(data);
                alert("inserted");
                $("insert").val('submit');
            }
            else if (data=="error"){
                console.log(data);
                alert("error");
            }
        }

    });

    }   return false;
    });
      }

      );

       </script>
     <div data-role ="page" id ="page1">
     <div data-role ="header">
        <h1>Hello World</h1>
        <center><h3>Register</h3>
        <input type="hidden" id="id" value=""/>
        <label for ="Firstname" class="ui-hidden-accessible"></label> <input type = "text" id="firstname" placeholder ="firstname" required="required"><br>
         <label for ="Lastname" class="ui-hidden-accessible"></label> <input type = "text" id="lastname" placeholder ="lastname" required="required"><br>
        <label for ="Phone" class="ui-hidden-accessible"></label>       <input type = "text" id="phone" placeholder ="Phone" required="required"><br>
        <input type="button" value="insert" id = "insert"></center>

    </div>

 insert.php
   <?php
     include "dbconfig.php";
     if(isset($_POST['insert']))
   {
     $first=$_POST['firstname'];
     $last=$_POST['lastname'];
     $phone=$_POST['phone'];

     $first = mysqli_real_escape_string($con,$_POST['firstname']);
     $last = mysqli_real_escape_string($con,$_POST['lastname']);
     $phone = mysqli_real_escape_string($con,$_POST['phone']);

    $q=mysqli_query($con,"INSERT INTO phone (firstname,lastname,phone) VALUES ('$first','$last','$phone')");
  if($q)
 echo "success";
   else
    echo "error";
  }
  ?>
</code>```

答:
If you are using an XAMPP server I am presuming the server is on the same computer you are developing on.

If this is the case test the phonegap app in your browser using google chrome and change your URL to:

```<code>http://10.250.216.195/insert.php
</code>```

Port 3000 is for phonegap build testing. the above URL should work fine.

Body:
I am developing a simple application to save records on mysql database (xampp) using phonegap. However i am getting stucked somewhere.
My code keeps writing "connecting..." for ever without saving the records on database. I researched all through but I cant seem to get the problem Please can somewhere show me my mistakes from my code? Thanks
Maybe its the url, i am not sure,
NOTE: My url is from the phonegap server.

 index.html
          <link rel="stylesheet" type="text/css" href="css/index.css" />
         <title>Hello World</title>

Hello World

Register

        <input type="hidden" id="id" value=""/>
         <input type = "text" id="firstname" placeholder ="firstname" required="required">

          <input type = "text" id="lastname" placeholder ="lastname" required="required">

               <input type = "text" id="phone" placeholder ="Phone" required="required">

        <input type="button" value="insert" id = "insert">

 insert.php
   <?php
     include "dbconfig.php";
     if(isset($_POST['insert']))
   {
     $first=$_POST['firstname'];
     $last=$_POST['lastname'];
     $phone=$_POST['phone'];

     $first = mysqli_real_escape_string($con,$_POST['firstname']);
     $last = mysqli_real_escape_string($con,$_POST['lastname']);
     $phone = mysqli_real_escape_string($con,$_POST['phone']);

    $q=mysqli_query($con,"INSERT INTO phone (firstname,lastname,phone) VALUES ('$first','$last','$phone')");
  if($q)
 echo "success";
   else
    echo "error";
  }
  ?>

Body:
If you are using an XAMPP server I am presuming the server is on the same computer you are developing on.

If this is the case test the phonegap app in your browser using google chrome and change your URL to:

http://10.250.216.195/insert.php

Port 3000 is for phonegap build testing. the above URL should work fine.


问:
Use body stream parameter in WebApi controller's action
I currently read input stream from body like this:

```<code>public async Task<IActionResult> Post()
{
    byte[] array = new byte[Request.ContentLength.Value];

    using (MemoryStream memoryStream = new MemoryStream(array))
    {
        await Request.Body.CopyToAsync(memoryStream);
    }

    return Ok();
}
</code>```

I would like to specify the input parameter in the methods signature, due to testing and swagger generation.

Is it possible to specify the input parameter as stream somehow?

```<code>public async Task<IActionResult> Post([FromBody]Stream body) ...
</code>```

答:
AS Web Api don't Bind stream in model binding this won't work. Instead if you need parameter stream you can use custom Model binding </p>

```<code>public class MyModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        // Extract the posted data from the request
        // Convert the base64string to Stream
        // Extract the model from the bindingcontext
        // Assign the model's property with their values accordingly
    }
}
</code>```

<p>Controller </p>

```<code>public ApiActionResult SaveDocument([ModelBinder(typeof(MyModelBinder))]DocumentVM contentDTO)
</code>```

Body:
I currently read input stream from body like this:

public async Task<IActionResult> Post()
{
    byte[] array = new byte[Request.ContentLength.Value];

    using (MemoryStream memoryStream = new MemoryStream(array))
    {
        await Request.Body.CopyToAsync(memoryStream);
    }

    return Ok();
}

I would like to specify the input parameter in the methods signature, due to testing and swagger generation.

Is it possible to specify the input parameter as stream somehow?

public async Task<IActionResult> Post([FromBody]Stream body) ...

Body:
AS Web Api don't Bind stream in model binding this won't work. Instead if you need parameter stream you can use custom Model binding

public class MyModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        // Extract the posted data from the request
        // Convert the base64string to Stream
        // Extract the model from the bindingcontext
        // Assign the model's property with their values accordingly
    }
}

Controller

public ApiActionResult SaveDocument([ModelBinder(typeof(MyModelBinder))]DocumentVM contentDTO)


问:
Sorting two arrays (values,keys), then sorting the keys
I have what seems to be a simple problem but I can't figure it out so far.

Say I have two arrays:

```<code>int[] values = {10,20,20,10,30};
int[] keys = {1,2,3,4,5};

Array.Sort(values,keys);
</code>```

Then the arrays would look like this:

```<code>values = {10,10,20,20,30};
keys = {4,1,2,3,5};
</code>```

Now, what I want to do is make it so that the keys are also sorted in second priority so the key array to look like this:

```<code>keys = {1,4,2,3,5};
</code>```

Notice the 1 and 4 values are switched and the order of the value array has not changed.

答:
Generally, parallel arrays are frowned upon.  It is very easy for the data to become out of sync.  What I would suggest is either using a map/Dictionary data type, or storing the keys and values in a single object, and then having an array of said objects.

Edit: after re-reading your question, I dont' think the Dictionary is the data type you want, based on your need to sort the values.  I would still suggest having an object that contains the keys and values, however.  You can then sort by the values, and rest assured that they keys aren't out of sync.

Body:
I have what seems to be a simple problem but I can't figure it out so far.

Say I have two arrays:

int[] values = {10,20,20,10,30};
int[] keys = {1,2,3,4,5};

Array.Sort(values,keys);

Then the arrays would look like this:

values = {10,10,20,20,30};
keys = {4,1,2,3,5};

Now, what I want to do is make it so that the keys are also sorted in second priority so the key array to look like this:

keys = {1,4,2,3,5};

Notice the 1 and 4 values are switched and the order of the value array has not changed.


问:
How to Call a slot of another class without creating its object?
I have two classes A and B.  I want to call a slot of class A in B without Creating the object of class A. Is this possible?
I've tried this in class B
connect (PButton, SIGNAL(triggered()) , A , SLOT(slotofA));
but I'm getting an error "expected primary expression befor ',' "</p>

答:
There are two approaches to accomplish this task.

You can make slot a static function that way you can call it with class name dot function name.

Make class A singleton and than you can access all of its public functions without creating a object.

Hope it will help !


问:
Sql query using count(*) , groupby and fetching a column value simultaneously
I am been developing application in java and not much insight into sql.
Meanwhile , I have got to fetch count and username in the same query. My query goes like this :

```<code>SELECT count(*),c_user_name
FROM tra_shipment_status
WHERE i_tra_shipment_status_id IN
  (SELECT MAX(i_tra_shipment_status_id)
  FROM tra_shipment_status
  WHERE i_status_code = '4072'
  AND c_reference    IN ('FILEIO0023','MIASTOFIL003')
  Group By C_Reference
  );
</code>```

This throws me an exception "not a single-group group function"
I want the count and C_user_name of the top most row (latest one).
Can somebody please help.

答:
When you try to include an aggregate function like count, sum, max,.. you should use group by with other unaggregated columns like c_user_name in your case. There is another thing; you say that you need the top most row but your sub query will return the top most row for each C_Reference, and to get the top most row regardless of C_Reference you should do something like the following:

```<code>SELECT count(*),c_user_name
FROM tra_shipment_status
WHERE i_tra_shipment_status_id IN
  (SELECT MAX(i_tra_shipment_status_id)
  FROM tra_shipment_status
  WHERE i_status_code = '4072'
  AND c_reference    IN ('FILEIO0023','MIASTOFIL003')
  );
 Group By c_user_name
</code>```

Body:
I am been developing application in java and not much insight into sql.
Meanwhile , I have got to fetch count and username in the same query. My query goes like this :

SELECT count(*),c_user_name
FROM tra_shipment_status
WHERE i_tra_shipment_status_id IN
  (SELECT MAX(i_tra_shipment_status_id)
  FROM tra_shipment_status
  WHERE i_status_code = '4072'
  AND c_reference    IN ('FILEIO0023','MIASTOFIL003')
  Group By C_Reference
  );

This throws me an exception "not a single-group group function"
I want the count and C_user_name of the top most row (latest one).
Can somebody please help.

Body:
When you try to include an aggregate function like count, sum, max,.. you should use group by with other unaggregated columns like c_user_name in your case. There is another thing; you say that you need the top most row but your sub query will return the top most row for each C_Reference, and to get the top most row regardless of C_Reference you should do something like the following:

SELECT count(*),c_user_name
FROM tra_shipment_status
WHERE i_tra_shipment_status_id IN
  (SELECT MAX(i_tra_shipment_status_id)
  FROM tra_shipment_status
  WHERE i_status_code = '4072'
  AND c_reference    IN ('FILEIO0023','MIASTOFIL003')
  );
 Group By c_user_name


问:
Can we call the function written in one JavaScript in another JS file?
Can we call the function written in one JS file in another JS file? Can anyone help me how to call the function from another JS file? </p>

答:
You can call the function created in another js file from the file you are working in. So for this firstly you need to add the external js file into the html document as-

```<code><html>
<head>
    <script type="text/javascript" src='path/to/external/js'></script>
</head>
<body>
........
</code>```

The function defined in the external javascript file -

```<code>$.fn.yourFunctionName = function(){
    alert('function called succesfully for - ' + $(this).html() );
}
</code>```

To call this function in your current file, just call the function as -

```<code>......
<script type="text/javascript">
    $(function(){
        $('#element').yourFunctionName();
    });
</script>
</code>```

If you want to pass the parameters to the function, then define the function as-

```<code>$.fn.functionWithParameters = function(parameter1, parameter2){
        alert('Parameters passed are - ' + parameter1 + ' , ' + parameter2);
}
</code>```

And call this function in your current file as -

```<code>$('#element').functionWithParameters('some parameter', 'another parameter');
</code>```

Body:
You can call the function created in another js file from the file you are working in. So for this firstly you need to add the external js file into the html document as-

<html>
<head>
    <script type="text/javascript" src='path/to/external/js'></script>
</head>
<body>
........

The function defined in the external javascript file -

$.fn.yourFunctionName = function(){
    alert('function called succesfully for - ' + $(this).html() );
}

To call this function in your current file, just call the function as -

......
<script type="text/javascript">
    $(function(){
        $('#element').yourFunctionName();
    });
</script>

If you want to pass the parameters to the function, then define the function as-

$.fn.functionWithParameters = function(parameter1, parameter2){
        alert('Parameters passed are - ' + parameter1 + ' , ' + parameter2);
}

And call this function in your current file as -

$('#element').functionWithParameters('some parameter', 'another parameter');