问:
How to add a font awesome icon into input text ::after with j query?
I have a sign up form like this image:

After I use jQuery code to check valid email, and that code:

```<code>function isEmail(email) {
            var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            return regex.test(email);
        }
</code>```

I want to insert a font awesome icon in after my email input form (check icon if true and cross icon if false), like this image:

So how can I do that with jQuery and I want to set color for this icon?

答:
It looks like :before and :after does not work for input, you have to set this for the input container.

Try this approach to see if it can help:

HTLM:

```<code><div class="container">
<h3>Enter valid email</h3>
<div class="input-container" id="email-container">
  <input type="text" required placeholder="you@example.com" id="email" />
</div>
</div>
</code>```

CSS:

```<code>.input-container{
  position:relative;
  height:32px;
}
.input-container input{
  width:100%;
  padding:8px;
}
#email-container:before,
#email-container:after{
  position:absolute;
  right:10px;
  top:10px;
  font-family: FontAwesome;
  z-index:1;
  display:none;
}
#email-container:before{
   content:'\f00c';
   color: green;
 }
#email-container:after{
   content:'\f00d';
   color: red
}
.valid-email:before{
  display:block !important;
}
.invalid-email:after{
  display:block !important;
}
.valid{
  border:1px solid green;
}
.invalid{
  border:1px solid red;
}
</code>```

JS:

```<code>$(function(){
    $('#email').bind({
    blur: function(){
        if($(this).val() != ''){
        if(isEmail($(this).val())){
            $('#email-container').removeClass('invalid-email').addClass('valid-email');
          $(this).removeClass('invalid');
          $(this).addClass('valid');
        }else{
            $('#email-container').removeClass('valid-email').addClass('invalid-email');
          $(this).removeClass('valid');
          $(this).addClass('invalid');
        }
      }
    }
  });
});

function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}
</code>```

See this solution in action here: https://jsfiddle.net/pkm05tax/

Body:
I have a sign up form like this image:

After I use jQuery code to check valid email, and that code:

function isEmail(email) {
            var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            return regex.test(email);
        }

I want to insert a font awesome icon in after my email input form (check icon if true and cross icon if false), like this image:

So how can I do that with jQuery and I want to set color for this icon?

Body:
It looks like :before and :after does not work for input, you have to set this for the input container.

Try this approach to see if it can help:

HTLM:

<div class="container">
<h3>Enter valid email</h3>
<div class="input-container" id="email-container">
  <input type="text" required placeholder="you@example.com" id="email" />
</div>
</div>

CSS:

.input-container{
  position:relative;
  height:32px;
}
.input-container input{
  width:100%;
  padding:8px;
}
#email-container:before,
#email-container:after{
  position:absolute;
  right:10px;
  top:10px;
  font-family: FontAwesome;
  z-index:1;
  display:none;
}
#email-container:before{
   content:'\f00c';
   color: green;
 }
#email-container:after{
   content:'\f00d';
   color: red
}
.valid-email:before{
  display:block !important;
}
.invalid-email:after{
  display:block !important;
}
.valid{
  border:1px solid green;
}
.invalid{
  border:1px solid red;
}

JS:

$(function(){
    $('#email').bind({
    blur: function(){
        if($(this).val() != ''){
        if(isEmail($(this).val())){
            $('#email-container').removeClass('invalid-email').addClass('valid-email');
          $(this).removeClass('invalid');
          $(this).addClass('valid');
        }else{
            $('#email-container').removeClass('valid-email').addClass('invalid-email');
          $(this).removeClass('valid');
          $(this).addClass('invalid');
        }
      }
    }
  });
});

function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

See this solution in action here: https://jsfiddle.net/pkm05tax/


来源: stackexchange

问:
Grouped data in dplyr
In Foundations of Linear and Generalized Linear Models by Alan Agresti, the author points out that there is a difference between grouped and ungrouped data for binary date modeling. The format does not matter for inference, but it does matter for goodness-of-fit. I am having difficulty getting grouped data from ungrouped data in an efficient way in dplyr.

```<code>#ungrouped data
x = c(rep(0,4),rep(1,4),rep(2,4))
y = c(c(1,0,0,0,1,1,0,0,1,1,1,1))
data = as_tibble(list(x=x,y=y))
> data
# A tibble: 12 × 2
       x     y
   <dbl> <dbl>
1      0     1
2      0     0
3      0     0
4      0     0
5      1     1
6      1     1
7      1     0
8      1     0
9      2     1
10     2     1
11     2     1
12     2     1
</code>```

Now to get grouped data the form should look like the following

```<code>x    ntrials   nsuccesses
0      4           1
1      4           2
2      4           4
</code>```

I have tried the following

```<code>data %>%
group_by(x,y) %>%
  tally()
      x     y     n
  <dbl> <dbl> <int>
1     0     0     3
2     0     1     1
3     1     0     2
4     1     1     2
5     2     1     4
</code>```

The problem is that y is being separated into successes and failures.

答:
You can just group by column x and then summarize based on column y:

```<code>data %>% group_by(x) %>% summarise(ntrials = n(), nsuccesses = sum(y))
# the number of successes is the sum of y if y is binary

# A tibble: 3 x 3
#      x ntrials nsuccesses
#  <dbl>   <int>      <dbl>
#1     0       4          1
#2     1       4          2
#3     2       4          4
</code>```

ContentLicense: CC BY-SA 3.0

Title: Grouped data in dplyr

Body:
In Foundations of Linear and Generalized Linear Models by Alan Agresti, the author points out that there is a difference between grouped and ungrouped data for binary date modeling. The format does not matter for inference, but it does matter for goodness-of-fit. I am having difficulty getting grouped data from ungrouped data in an efficient way in dplyr.

#ungrouped data
x = c(rep(0,4),rep(1,4),rep(2,4))
y = c(c(1,0,0,0,1,1,0,0,1,1,1,1))
data = as_tibble(list(x=x,y=y))
> data
# A tibble: 12 × 2
       x     y
   <dbl> <dbl>
1      0     1
2      0     0
3      0     0
4      0     0
5      1     1
6      1     1
7      1     0
8      1     0
9      2     1
10     2     1
11     2     1
12     2     1

Now to get grouped data the form should look like the following

x    ntrials   nsuccesses
0      4           1
1      4           2
2      4           4

I have tried the following

data %>%
group_by(x,y) %>%
  tally()
      x     y     n
  <dbl> <dbl> <int>
1     0     0     3
2     0     1     1
3     1     0     2
4     1     1     2
5     2     1     4

The problem is that y is being separated into successes and failures.

Body:
You can just group by column x and then summarize based on column y:

data %>% group_by(x) %>% summarise(ntrials = n(), nsuccesses = sum(y))
# the number of successes is the sum of y if y is binary

# A tibble: 3 x 3
#      x ntrials nsuccesses
#  <dbl>   <int>      <dbl>
#1     0       4          1
#2     1       4          2
#3     2       4          4


问:
Buyers structure by registration date query optimisation
I would like to show buyers structure by their registration date e.g.:

```<code>H12016 10.000 buyers
</code>```

from which

```<code>2.000 registered in H12014

4.000 registered in H22014
</code>```

etc.

I have two queries for that:

Number 1 (buyers from H12016 (about 50k records)):

```<code>SELECT DISTINCT
r.idUsera as id_usera

FROM
rezerwacje r

WHERE
r.dataZalozenia between '2016-01-01' and '2016-07-01'
and r.`status` = 'zabookowana'

ORDER BY
id_usera
</code>```

Number 2 (users_ids and their registration (insert) date (about 3,8M users)):

```<code>SELECT
m.user_id,
date(m.action_date) as data_insert

FROM
mwids m

WHERE
m.`type` = 'insert'
</code>```

Both queries separately run fine, but when I try to combine them like so:

```<code>SELECT DISTINCT
r.idUsera as id_usera,
t1.data_insert

FROM
rezerwacje r

LEFT JOIN
    (
    SELECT
    m.user_id,
    date(m.action_date) as data_insert

    FROM
    mwids m

    WHERE
    m.`type` = 'insert'
    ) t1 ON t1.user_id = r.idUsera

WHERE
r.dataZalozenia between '2016-01-01' and '2016-07-01'
and r.`status` = 'zabookowana'

ORDER BY
id_usera
</code>```

this query runs "indefinetely" and I have to kill it after some time.

I do not belive it should run that long. If the query Number 2 was smaller i.e. about 1M users I could combine results in Excel in matter of seconds. So why is it not possible inside the database? What am I doing wrong?

答:
Query 1 needs

```<code>INDEX(status, dataZalozenia, id_usera)
</code>```

Query 3: Rewrite thus:

If there is only one row in mwids for 'insert' per user:

```<code>SELECT  r.idUsera as id_usera, DATE(m.action_date) AS data_insert
    FROM  rezerwacje r
    LEFT JOIN  mwids m  ON m.user_id = r.idUsera
      AND  m.`type` = 'insert'
    WHERE  r.dataZalozenia >= '2016-01-01'
      AND  r.dataZalozenia  < '2016-01-01' + 12 MONTH
      and  r.`status` = 'zabookowana'
    ORDER BY  r.idUsera
</code>```

with

```<code>INDEX(status, dataZalozenia, isUsera)   --  on r
INDEX(type, user_id, action_date)       --  on m
</code>```

If there can be multiple rows, do this:

```<code>SELECT  r.idUsera as id_usera,
        ( SELECT  DATE(m.action_date)
            FROM  mwids m
            WHERE  m.user_id = r.idUsera
              AND  m.`type` = 'insert'
            LIMIT  1
        ) AS data_insert
    FROM  rezerwacje r
    LEFT JOIN  mwids m  ON m.user_id = r.idUsera
      AND  m.`type` = 'insert'
    WHERE  r.dataZalozenia >= '2016-01-01'
      AND  r.dataZalozenia <  '2016-01-01' + 12 MONTH
      and  r.`status` = 'zabookowana'
    ORDER BY  r.idUsera
</code>```

But you will be getting a random action_date.  So maybe you want MIN() or MAX()?

Body:
I would like to show buyers structure by their registration date e.g.:

H12016 10.000 buyers

from which

2.000 registered in H12014

4.000 registered in H22014

etc.

I have two queries for that:

Number 1 (buyers from H12016 (about 50k records)):

SELECT DISTINCT
r.idUsera as id_usera

FROM
rezerwacje r

WHERE
r.dataZalozenia between '2016-01-01' and '2016-07-01'
and r.`status` = 'zabookowana'

ORDER BY
id_usera

Number 2 (users_ids and their registration (insert) date (about 3,8M users)):

SELECT
m.user_id,
date(m.action_date) as data_insert

FROM
mwids m

WHERE
m.`type` = 'insert'

Both queries separately run fine, but when I try to combine them like so:

SELECT DISTINCT
r.idUsera as id_usera,
t1.data_insert

FROM
rezerwacje r

LEFT JOIN
    (
    SELECT
    m.user_id,
    date(m.action_date) as data_insert

    FROM
    mwids m

    WHERE
    m.`type` = 'insert'
    ) t1 ON t1.user_id = r.idUsera

WHERE
r.dataZalozenia between '2016-01-01' and '2016-07-01'
and r.`status` = 'zabookowana'

ORDER BY
id_usera

this query runs "indefinetely" and I have to kill it after some time.

I do not belive it should run that long. If the query Number 2 was smaller i.e. about 1M users I could combine results in Excel in matter of seconds. So why is it not possible inside the database? What am I doing wrong?

Body:
Query 1 needs

INDEX(status, dataZalozenia, id_usera)

Query 3: Rewrite thus:

If there is only one row in mwids for 'insert' per user:

SELECT  r.idUsera as id_usera, DATE(m.action_date) AS data_insert
    FROM  rezerwacje r
    LEFT JOIN  mwids m  ON m.user_id = r.idUsera
      AND  m.`type` = 'insert'
    WHERE  r.dataZalozenia >= '2016-01-01'
      AND  r.dataZalozenia  < '2016-01-01' + 12 MONTH
      and  r.`status` = 'zabookowana'
    ORDER BY  r.idUsera

with

INDEX(status, dataZalozenia, isUsera)   --  on r
INDEX(type, user_id, action_date)       --  on m

If there can be multiple rows, do this:

SELECT  r.idUsera as id_usera,
        ( SELECT  DATE(m.action_date)
            FROM  mwids m
            WHERE  m.user_id = r.idUsera
              AND  m.`type` = 'insert'
            LIMIT  1
        ) AS data_insert
    FROM  rezerwacje r
    LEFT JOIN  mwids m  ON m.user_id = r.idUsera
      AND  m.`type` = 'insert'
    WHERE  r.dataZalozenia >= '2016-01-01'
      AND  r.dataZalozenia <  '2016-01-01' + 12 MONTH
      and  r.`status` = 'zabookowana'
    ORDER BY  r.idUsera

But you will be getting a random action_date.  So maybe you want MIN() or MAX()?


问:
SQL Function to return sequential id's
Consider this simple INSERT

```<code>INSERT INTO Assignment (CustomerId,UserId)
SELECT CustomerId,123 FROM Customers
</code>```

That will obviously assign UserId=123 to all customers.

What I need to do is assign them to 3 userId's sequentially, so 3 users get one third of the accounts equally.

```<code>INSERT INTO Assignment (CustomerId,UserId)
SELECT CustomerId,fnGetNextId() FROM Customers
</code>```

Could I create a function to return sequentially from a list of 3 ID's?, i.e. each time the function is called it returns the next one in the list?

Thanks

答:
Here's one way to produce Assignment as an automatically rebalancing view:

```<code>CREATE VIEW dbo.Assignment WITH SCHEMABINDING AS
    WITH SeqUsers AS (
        SELECT UserID, ROW_NUMBER() OVER (ORDER BY UserID) - 1 AS _ord
        FROM dbo.Users
    ), SeqCustomers AS (
        SELECT CustomerID, ROW_NUMBER() OVER (ORDER BY CustomerID) - 1 AS _ord
        FROM dbo.Customers
    )
    -- INSERT Assignment(CustomerID, UserID)
    SELECT SeqCustomers.CustomerID, SeqUsers.UserID
    FROM SeqUsers
    JOIN SeqCustomers ON SeqUsers._ord = SeqCustomers._ord % (SELECT COUNT(*) FROM SeqUsers)
;
</code>```

This shifts assignments around if you insert a new user, which could be quite undesirable, and it's also not efficient if you had to JOIN on it. You can easily repurpose the query it contains for one-time inserts (the commented-out INSERT). The key technique there is joining on ROW_NUMBER()s.

Title: SQL Function to return sequential id's

Body:
Consider this simple INSERT

INSERT INTO Assignment (CustomerId,UserId)
SELECT CustomerId,123 FROM Customers

That will obviously assign UserId=123 to all customers.

What I need to do is assign them to 3 userId's sequentially, so 3 users get one third of the accounts equally.

INSERT INTO Assignment (CustomerId,UserId)
SELECT CustomerId,fnGetNextId() FROM Customers

Could I create a function to return sequentially from a list of 3 ID's?, i.e. each time the function is called it returns the next one in the list?

Thanks

Body:
Here's one way to produce Assignment as an automatically rebalancing view:

CREATE VIEW dbo.Assignment WITH SCHEMABINDING AS
    WITH SeqUsers AS (
        SELECT UserID, ROW_NUMBER() OVER (ORDER BY UserID) - 1 AS _ord
        FROM dbo.Users
    ), SeqCustomers AS (
        SELECT CustomerID, ROW_NUMBER() OVER (ORDER BY CustomerID) - 1 AS _ord
        FROM dbo.Customers
    )
    -- INSERT Assignment(CustomerID, UserID)
    SELECT SeqCustomers.CustomerID, SeqUsers.UserID
    FROM SeqUsers
    JOIN SeqCustomers ON SeqUsers._ord = SeqCustomers._ord % (SELECT COUNT(*) FROM SeqUsers)
;

This shifts assignments around if you insert a new user, which could be quite undesirable, and it's also not efficient if you had to JOIN on it. You can easily repurpose the query it contains for one-time inserts (the commented-out INSERT). The key technique there is joining on ROW_NUMBER()s.


问:
Database backup using dynamic SQL
I am creating a job which takes backup of a database and with the filename suffixing today's date. But I'm getting below error.

```<code>DECLARE @Query NVARCHAR(MAX)
SET @Query = 'BACKUP DATABASE [DBName] TO DISK = ''D:\Backups\DBName_'+cast(convert(date,getdate())as varchar)+'.bak'
EXEC sp_executeSql @Query
</code>```

Error Message:

```<code>Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string 'D:\Backups\DBName_2017-07-07.bak'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'D:\Backups\DBName_2017-07-07.bak'.
</code>```

答:
You are missing the last closing quote. It should end in .txt'''

```<code>SET @Query = 'BACKUP DATABASE [MetaCost] TO DISK = ''D:\Backups\DBName.bak_'+cast(convert(date,getdate())as varchar)+'.txt'''
</code>```

Also typically you use the .bak extension for a sql database backup.

Title: Database backup using dynamic SQL

Body:
I am creating a job which takes backup of a database and with the filename suffixing today's date. But I'm getting below error.

DECLARE @Query NVARCHAR(MAX)
SET @Query = 'BACKUP DATABASE [DBName] TO DISK = ''D:\Backups\DBName_'+cast(convert(date,getdate())as varchar)+'.bak'
EXEC sp_executeSql @Query

Error Message:

Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string 'D:\Backups\DBName_2017-07-07.bak'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'D:\Backups\DBName_2017-07-07.bak'.

Body:
You are missing the last closing quote. It should end in .txt'''

SET @Query = 'BACKUP DATABASE [MetaCost] TO DISK = ''D:\Backups\DBName.bak_'+cast(convert(date,getdate())as varchar)+'.txt'''

Also typically you use the .bak extension for a sql database backup.


问:
How to get Null values of records in aerospike

I'm working with aerospike. Using AQL, I inserted some data. I want to get null values of records with particular fields in aerospike. I'm tagging picture in that picture one record does not have a name its empty space

答:
Ran some test code - the record key is valid with some other bins:

```<code>userRecord = client.get(null, userKey, "notThereBin");
    if (userRecord != null) {
        console.printf("\nINFO: User record with notThereBin read successfully! Here are the details:\n");
        console.printf("notThereBin:  " + userRecord.getValue("notThereBin") + "\n");
    } else {
        console.printf("ERROR: User record not found!\n");
    }
</code>```

and the output is:

```<code>    INFO: User record with notThereBin read successfully! Here are the details:

notThereBin:  null
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Ran some test code - the record key is valid with some other bins:

userRecord = client.get(null, userKey, "notThereBin");
    if (userRecord != null) {
        console.printf("\nINFO: User record with notThereBin read successfully! Here are the details:\n");
        console.printf("notThereBin:  " + userRecord.getValue("notThereBin") + "\n");
    } else {
        console.printf("ERROR: User record not found!\n");
    }

and the output is:

    INFO: User record with notThereBin read successfully! Here are the details:

notThereBin:  null


问:
PrimeNg DropDown - User can't clear the value
I'm implementing primeNg dropdown component in my Angular2 application.

```<code><p-dropdown [options]="listCustomers_itm" placeholder="Selezionare" [(ngModel)]="Customer_itm" [ngModelOptions]="{standalone: true}" [style]="{'width':'225px'}" filter="filter"  (onChange)="onCustomerSelect($event.value)">
</p-dropdown>
</code>```

All works fine except one annoing thing:

Once time the user has selected an option, he can't clear the selected value...

Can you help me?

答:
To fix this, I had to set a placeholder for the dropdown. The code I used is something like:

template.html

```<code><p-dropdown ...
            placeholder="Select"
            #dropDownThing></p-dropdown>

<button (click)="onButtonClick()"></button>
</code>```

component.ts

```<code>import { Dropdown } from "primeng/components/dropdown/dropdown";
...
@ViewChild('dropDownThing')
dropDownThing: Dropdown;
...
onButtonClick() {
    this.dropDownThing.value = <someValueNotInTheDropdown'sList>;
}
...
</code>```

When the code above is run without a placeholder, the currently-selected option remains selected.

When the code above is run with a placeholder, the dropdown's value changes to the provided placeholder.

Body:
I'm implementing primeNg dropdown component in my Angular2 application.

All works fine except one annoing thing:

Once time the user has selected an option, he can't clear the selected value...

Can you help me?

Body:
To fix this, I had to set a placeholder for the dropdown. The code I used is something like:

template.html

<p-dropdown ...
            placeholder="Select"
            #dropDownThing></p-dropdown>

<button (click)="onButtonClick()"></button>

component.ts

import { Dropdown } from "primeng/components/dropdown/dropdown";
...
@ViewChild('dropDownThing')
dropDownThing: Dropdown;
...
onButtonClick() {
    this.dropDownThing.value = <someValueNotInTheDropdown'sList>;
}
...

When the code above is run without a placeholder, the currently-selected option remains selected.

When the code above is run with a placeholder, the dropdown's value changes to the provided placeholder.


问:
what is the difference between mamp and xamp and port numbers?
I know what xampp and mamp stand for I am looking for a simple definition for both and port number?
From what I know port number is just a way that to service can talk but in this sense what are the different ports mamp and xampp? how can I find available ports?</p>

答:
XAMPP and MAMP are more or less similar servers, when you compare mamp with xampp, mamp provides additional service (python) where xampp server doesn't have python support.
There is nothing to worry about port numbers on mamp and xampp. On both servers Apache runs on port 80, MySQL runs on port 3306. you can have custom port numbers by editing conf files


问:
Python Argparse, How to Properly Organize ArgParse Code
I haven't used argparse in 10 years, but I understand it and what I have below does work as I want it to work... but this is going to get a lot more complicated as I continue adding commands, parsers and subparsers. I'm wondering what the best way is to organize this? In my mind I should be able to see the command sequence in the text nearly as clearly as I see it in my diagram... but everytime I look at it, after being away for a while, my brain swims as I try to follow it. There has to be a better way to organize this right?

```<code>import argparse
from modules import cli_tools

#LVL 1: create the top-level parser for the "sacs" command.
sacs_parser = argparse.ArgumentParser(prog = 'sacs', description = 'Master Command For Controlling SACS.')
sacs_subparsers = sacs_parser.add_subparsers(help='Management Module Selector.')

#LVL 2: create the second-level parsers for the "sacs [module]" commands.
csv_parser = sacs_subparsers.add_parser('csv', help='Generic CSV Management Module.')
am_parser = sacs_subparsers.add_parser('am', help='SACS Asset Management Module.')
mm_parser = sacs_subparsers.add_parser('mm', help='SACS Metric Management Module.')

#LVL 3: create the third-level subparser for the "sacs [module] [action]" commands.
csv_action_subparser = csv_parser.add_subparsers(help='The action to perform.')
mm_action_subparser = mm_parser.add_subparsers(help='The action to perform.')

#LVL 4: create the fourth-level subparser for the "sacs [module] [action] [type]" commands.
mm_create_parser = mm_action_subparser.add_parser('create', help='Used to Create a new event/asset input file.')
mm_create_type_parser = mm_create_parser.add_subparsers(help='The type of file to create.')

#LVL 5: create the fifth-level parser for the "sacs [module] [action] [type]" commands.
csv_reconcile_parser = csv_action_subparser.add_parser('reconcile', help='reconcile two csvs.')
mm_create_asset_parser = mm_create_type_parser.add_parser('assets', help='Create an Asset File.')
mm_create_asset_subtype_parser = mm_create_asset_parser.add_subparsers(help='The type of file to create.')
mm_create_event_parser = mm_create_type_parser.add_parser('events', help='Create an Event File.')

#LVL 6: create the sixth-level parser for the "sacs [module] [action] [type] [subtype]" commands.
mm_create_asset_uaid_parser = mm_create_asset_subtype_parser.add_parser('uaid', help='Create an Asset File with UAID as the primary key.')
mm_create_asset_vid_parser = mm_create_asset_subtype_parser.add_parser('vid', help='Create an Asset File with Vulnerability ID as the primary key.')

#COMMAND ARGS: Add Arguments to the final command "sacs csv reconcile [args]"
csv_reconcile_parser.add_argument('key', help='The name of the field that holds the unique ID to compare against.')
csv_reconcile_parser.add_argument('inputfile1', help='The master file (used when same record exists in both files).')
csv_reconcile_parser.add_argument('inputfile2', help='The secondary file, which is trumped by the master file.')
csv_reconcile_parser.add_argument('outputfile', help='The output file; note it will be overwritten if it exists.')
csv_reconcile_parser.set_defaults(func=cli_tools.csv_reconcile)

#COMMAND ARGS: Add Arguments to the final command "sacs mm create assets uaid [args]"
mm_create_asset_uaid_parser.add_argument('appmapp_file', help='The input file.')
mm_create_asset_uaid_parser.add_argument('output_file', help='The output file.')
mm_create_asset_uaid_parser.set_defaults(func=cli_tools.asset_create_uaid)

#COMMAND ARGS: Add Arguments to the final command "sacs mm create assets vid [args]"
mm_create_asset_vid_parser.add_argument('vulnerability_file', help='The input file.')
mm_create_asset_vid_parser.add_argument('appmapp_file', help='The output file.')
mm_create_asset_vid_parser.add_argument('output_file', help='The output file.')
mm_create_asset_vid_parser.set_defaults(func=cli_tools.asset_create_vid)

args = sacs_parser.parse_args()
args.func(args)
</code>```

Potential avenues to better way:

parser/subparser renaming.

change the ordering of the statements.

some way to indent without messing with python.

All ideas are on the table, I want to see how others deal with this while designing complex commands.

答:
The usual way of adding clarity to Python code is to package steps in functions and even classes.  argparse itself is a set of classes.  Each of your parsers (including subparsers) are argparse.ArgumentParser objects.  Each add_argument creates an argparse.Action subclass object.  The add_subparsers creates (and returns) a specialized Action subclass that handles subparsers.  And finally parse_args returns an argparse.Namespace object.

Whether any of that is applicable in your case, I don't know.  Your code is readable, so I easily get an idea of what you are doing.  I've never seen anyone use so many levels of subparsers.  In fact using more than one level is something of a novelty (judging from some earlier SO questions).

I like to stress that the first job of argparse is to figure out what your user wants.  The parsing is  the first priority.  Secondly it should make it easy to express what they want.  I wonder whether this multilevel subparsing is easy to use.  The way that argparse splits the help among subparsers makes it hard to display an big overview.

At some point big packages start to write their own helps, and even customize the parser to suit their needs.

You might get a better answer on CodeReview.  The regulars there seem to more interested in code organization and naming issues.  SO is more oriented to problem solving.  I discourage referrals to CR if the topic is too specialized, but this is more of a general Python question than an argparse specific one.  But read up on what CR expects in a question.

Multiple level argparse subparsers

Argparse with required subparser

argparse subparser monolithic help output

Python argparser repeat subparse

Body:
I haven't used argparse in 10 years, but I understand it and what I have below does work as I want it to work... but this is going to get a lot more complicated as I continue adding commands, parsers and subparsers. I'm wondering what the best way is to organize this? In my mind I should be able to see the command sequence in the text nearly as clearly as I see it in my diagram... but everytime I look at it, after being away for a while, my brain swims as I try to follow it. There has to be a better way to organize this right?

import argparse
from modules import cli_tools

#LVL 1: create the top-level parser for the "sacs" command.
sacs_parser = argparse.ArgumentParser(prog = 'sacs', description = 'Master Command For Controlling SACS.')
sacs_subparsers = sacs_parser.add_subparsers(help='Management Module Selector.')

#LVL 2: create the second-level parsers for the "sacs [module]" commands.
csv_parser = sacs_subparsers.add_parser('csv', help='Generic CSV Management Module.')
am_parser = sacs_subparsers.add_parser('am', help='SACS Asset Management Module.')
mm_parser = sacs_subparsers.add_parser('mm', help='SACS Metric Management Module.')

#LVL 3: create the third-level subparser for the "sacs [module] [action]" commands.
csv_action_subparser = csv_parser.add_subparsers(help='The action to perform.')
mm_action_subparser = mm_parser.add_subparsers(help='The action to perform.')

#LVL 4: create the fourth-level subparser for the "sacs [module] [action] [type]" commands.
mm_create_parser = mm_action_subparser.add_parser('create', help='Used to Create a new event/asset input file.')
mm_create_type_parser = mm_create_parser.add_subparsers(help='The type of file to create.')

#LVL 5: create the fifth-level parser for the "sacs [module] [action] [type]" commands.
csv_reconcile_parser = csv_action_subparser.add_parser('reconcile', help='reconcile two csvs.')
mm_create_asset_parser = mm_create_type_parser.add_parser('assets', help='Create an Asset File.')
mm_create_asset_subtype_parser = mm_create_asset_parser.add_subparsers(help='The type of file to create.')
mm_create_event_parser = mm_create_type_parser.add_parser('events', help='Create an Event File.')

#LVL 6: create the sixth-level parser for the "sacs [module] [action] [type] [subtype]" commands.
mm_create_asset_uaid_parser = mm_create_asset_subtype_parser.add_parser('uaid', help='Create an Asset File with UAID as the primary key.')
mm_create_asset_vid_parser = mm_create_asset_subtype_parser.add_parser('vid', help='Create an Asset File with Vulnerability ID as the primary key.')

#COMMAND ARGS: Add Arguments to the final command "sacs csv reconcile [args]"
csv_reconcile_parser.add_argument('key', help='The name of the field that holds the unique ID to compare against.')
csv_reconcile_parser.add_argument('inputfile1', help='The master file (used when same record exists in both files).')
csv_reconcile_parser.add_argument('inputfile2', help='The secondary file, which is trumped by the master file.')
csv_reconcile_parser.add_argument('outputfile', help='The output file; note it will be overwritten if it exists.')
csv_reconcile_parser.set_defaults(func=cli_tools.csv_reconcile)

#COMMAND ARGS: Add Arguments to the final command "sacs mm create assets uaid [args]"
mm_create_asset_uaid_parser.add_argument('appmapp_file', help='The input file.')
mm_create_asset_uaid_parser.add_argument('output_file', help='The output file.')
mm_create_asset_uaid_parser.set_defaults(func=cli_tools.asset_create_uaid)

#COMMAND ARGS: Add Arguments to the final command "sacs mm create assets vid [args]"
mm_create_asset_vid_parser.add_argument('vulnerability_file', help='The input file.')
mm_create_asset_vid_parser.add_argument('appmapp_file', help='The output file.')
mm_create_asset_vid_parser.add_argument('output_file', help='The output file.')
mm_create_asset_vid_parser.set_defaults(func=cli_tools.asset_create_vid)

args = sacs_parser.parse_args()
args.func(args)

Potential avenues to better way:

parser/subparser renaming.

change the ordering of the statements.

some way to indent without messing with python.

All ideas are on the table, I want to see how others deal with this while designing complex commands.


问:
Python two variables one input
I want to save an user input directly into two variables like: </p>

```<code>n,k = input("Geben Sie eine Zahl ein: " )

print(n)
print(k)
</code>```

<p>n and k should print the same value. </p>

答:
for same value in two variable:

```<code>n = k = input("enter two values:")
</code>```

for two value in two variable:

```<code>n, k = input("enter two values:").split(' ')
</code>```

Title: Python two variables one input

Body:
I want to save an user input directly into two variables like:

n,k = input("Geben Sie eine Zahl ein: " )

print(n)
print(k)

n and k should print the same value.

Body:
for same value in two variable:

n = k = input("enter two values:")

for two value in two variable:

n, k = input("enter two values:").split(' ')


问:
C -> Shell - Block on a Write Until Read
I want to send a character from a c program to a shell program. I am using a named pipe to send the letter 'a' whenever it is requsted. I should only have to open the pipe once. Here's an example:

```<code>#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main(){
    int fd;
    mkfifo("/tmp/test", 0666);
    fd = open("/tmp/test", O_WRONLY);
    printf("Opened\n");
    char * a = "a";
    while(1){
            printf("Writing to pipe...\n");
            write(fd,a,1);
            sleep(1);
    }
}
</code>```

And the shell executes this command as many times as it wants...

```<code>head -c 1 /tmp/test
</code>```

The issue is after one head, the c will endlessly stream into the pipe, even if nobody's there.

I noticed that open() blocks until someone is on the other end. How to I tell write() to block until somebody is reading?

I would rather have this feature on write() than read(), as I think there's lots of overhead on opening the file for each request.

Thanks!

UPDATE

This is how I'm handling it in Java, it waits until I have somebody listening  on this pipe before it continues on. Maybe just because it's a higher level language.

```<code>public static void writeToPipe(int val, String pipename){
    try{
        pipe_out = new PrintStream("/tmp/" + pipename);
    }catch(Exception e){
        System.out.println("Could not open a pipe for output!");
        e.printStackTrace();
    }
    try{
        pipe_out.println(val);
    }catch(Exception e){
        System.out.println("Could not write to pipe!");
        e.printStackTrace();
    }

    try{
        pipe_out.close();
    }catch(Exception e){
        System.out.println("Could not close the output pipe!");
        e.printStackTrace();
    }
}
</code>```

UPDATE #2 - THIS IS THE SOLUTION

Here is my code based on David's idea, it's rough, but it works. I'm not checking if the named pipe exists and just supressing it from quitting.

```<code>#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, char **argv){
    mkfifo("/tmp/test", 0666);
    while(1){
      int fd, status;
            if ((fd = open ("/tmp/test", O_WRONLY)) == -1) {
         perror ("open failed");
         return 1;
            }
     printf("Opened Pipe\n");
     char a = 'a';
            int f  = fork();
            if(f == -1){
                    perror("fork");
                    exit(1);
            }else if(f == 0){
                    //This is by the child process
                    if (write (fd, &a, 1) == -1) {
                            close(fd);
                    perror ("open failed");
                            return 1;
         }

            }else{
                    //This is the parent process
                    int w = waitpid(f, &status, WUNTRACED | WCONTINUED);
                    if (w == -1){
                            perror("waitpid");
                            exit(EXIT_FAILURE);
                    }
            }
    }
}
</code>```

答:
You can do what you are attempting, but understand you must limit your read to one-char on the shell side since there will be no '\n' written to the pipe. Also, you may write many more times than the shell reads. For example, you can add validations as Mr. Pursell suggests to insure your C-program is functioning and blocking on write with something similar to:

```<code>#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>

int main (int argc, char **argv) {

    int fd;
    errno = 0;

    if (mkfifo (argc > 1 ? argv[1] : "/tmp/test", 0666)) {
        perror ("mkfifo failed");
        return 1;
    }
    if ((fd = open ("/tmp/test", O_WRONLY)) == -1) {
        perror ("open failed");
        return 1;
    }

    printf ("Opened\n");
    char a = 'a';

    while (1) {
        printf ("Writing to pipe...\n");
        if (write (fd, &a, 1) == -1) {
            perror ("open failed");
            return 1;
        }
    }

    return 0;
}
</code>```

You can test with a simple:

```<code>$ declare -i c=0; while test "$c" -lt 10 && read -n 1 ch; do
    echo "read: $ch"
    ((c++))
done </tmp/test
</code>```

Example Shell Output

```<code>read: a
read: a
read: a
read: a
read: a
read: a
read: a
read: a
read: a
read: a
</code>```

You will write until the fifo buffer is full resulting in more Writing to pipe... than you have read: a.

Rough Example with fork

Continuing from the comments here is a rough example of using fork to spawn child processes to insure your C-program is always blocking on write for the shell. This example is limited to 3 repetitions, but you could just use while (1) for a continual cycle. I also added a quick counter for the write (just for my curiosity) e.g.

```<code>#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int crt_fifo_write (char *fname);
int file_exists (char *f);

int main (int argc, char **argv) {

    int n = 0;
    errno = 0;

    while (n < 3) {         /* limit example to 3 child processes */

        pid_t cpid, w;
        int status;

        cpid = fork();
        if (cpid == -1) {
            perror("fork");
            exit(EXIT_FAILURE);
        }

        if (cpid == 0) {    /* Code executed by child */
            if (!crt_fifo_write (argc > 1 ? argv[1] : "/tmp/test"))
                fprintf (stderr, "crt_fifo_write() failed.\n");
        }
        else {              /* Code executed by parent */
            do {
                w = waitpid (cpid, &status, WUNTRACED | WCONTINUED);
                if (w == -1) {
                    perror("waitpid");
                    exit(EXIT_FAILURE);
                }
                if (WIFSIGNALED(status)) /* signal on close of read end */
                    printf("shell read complete. %s\n",
                            n < 2 ? "restarting" : "done");
            } while (!WIFEXITED(status) && !WIFSIGNALED(status));
        }
        n++;
    }

    return 0;
}

/** your write 'a' to the fifo with check for existence & unlink */
int crt_fifo_write (char *fname)
{
    int fd, n = 0;
    errno = 0;

    if (!fname || !*fname) return 0;

    if (file_exists (fname))
        if (unlink (fname) == -1) {
            perror ("fifo exists unlink failed");
            return 0;
        }

    if (mkfifo (fname, 0666)) {
        perror ("mkfifo failed");
        return 1;
    }
    if ((fd = open (fname, O_WRONLY)) == -1) {
        perror ("open failed");
        return 1;
    }

    printf ("Opened\n");
    char a = 'a';

    while (write (fd, &a, 1) != -1) {
        printf ("%3d - Writing to pipe...\n", n++);
    }

    return 0;
}

/** atomic test that file exists (1 success, 0 otherwise) */
int file_exists (char *f)
{
    errno = 0;
    int flags = O_CREAT | O_WRONLY | O_EXCL;
    int mode = S_IRUSR | S_IWUSR;
    int fd = open (f, flags, mode);

    if (fd < 0 && errno == EEXIST)
        return 1;
    else if (fd) {  /* created, like bash touch */
        close (fd);
        unlink (f);
    }

    return 0;
}
</code>```

Example Program Use/Output

```<code>$ ./bin/pipe_write_shell_fork
Opened
  0 - Writing to pipe...
  1 - Writing to pipe...
  2 - Writing to pipe...
  3 - Writing to pipe...
  4 - Writing to pipe...
    ...
138 - Writing to pipe...
139 - Writing to pipe...
140 - Writing to pipe...
shell read complete. restarting
Opened
  0 - Writing to pipe...
  1 - Writing to pipe...
  2 - Writing to pipe...
  3 - Writing to pipe...
  4 - Writing to pipe...
    ...
    130 - Writing to pipe...
131 - Writing to pipe...
shell read complete. restarting
Opened
  0 - Writing to pipe...
  1 - Writing to pipe...
  2 - Writing to pipe...
  3 - Writing to pipe...
  4 - Writing to pipe...
    ...
144 - Writing to pipe...
145 - Writing to pipe...
shell read complete. done
</code>```

Example Shell Read/Output

```<code>$ declare -i c=0; while test "$c" -lt 10 && read -n 8 ch; do \
echo "read: $ch"; ((c++)); done </tmp/test
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
</code>```

(repeated 2 more times)

Body:
I want to send a character from a c program to a shell program. I am using a named pipe to send the letter 'a' whenever it is requsted. I should only have to open the pipe once. Here's an example:

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main(){
    int fd;
    mkfifo("/tmp/test", 0666);
    fd = open("/tmp/test", O_WRONLY);
    printf("Opened\n");
    char * a = "a";
    while(1){
            printf("Writing to pipe...\n");
            write(fd,a,1);
            sleep(1);
    }
}

And the shell executes this command as many times as it wants...

head -c 1 /tmp/test

The issue is after one head, the c will endlessly stream into the pipe, even if nobody's there.

I noticed that open() blocks until someone is on the other end. How to I tell write() to block until somebody is reading?

I would rather have this feature on write() than read(), as I think there's lots of overhead on opening the file for each request.

Thanks!

UPDATE

This is how I'm handling it in Java, it waits until I have somebody listening  on this pipe before it continues on. Maybe just because it's a higher level language.

public static void writeToPipe(int val, String pipename){
    try{
        pipe_out = new PrintStream("/tmp/" + pipename);
    }catch(Exception e){
        System.out.println("Could not open a pipe for output!");
        e.printStackTrace();
    }
    try{
        pipe_out.println(val);
    }catch(Exception e){
        System.out.println("Could not write to pipe!");
        e.printStackTrace();
    }

    try{
        pipe_out.close();
    }catch(Exception e){
        System.out.println("Could not close the output pipe!");
        e.printStackTrace();
    }
}

UPDATE #2 - THIS IS THE SOLUTION

Here is my code based on David's idea, it's rough, but it works. I'm not checking if the named pipe exists and just supressing it from quitting.

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, char **argv){
    mkfifo("/tmp/test", 0666);
    while(1){
      int fd, status;
            if ((fd = open ("/tmp/test", O_WRONLY)) == -1) {
         perror ("open failed");
         return 1;
            }
     printf("Opened Pipe\n");
     char a = 'a';
            int f  = fork();
            if(f == -1){
                    perror("fork");
                    exit(1);
            }else if(f == 0){
                    //This is by the child process
                    if (write (fd, &a, 1) == -1) {
                            close(fd);
                    perror ("open failed");
                            return 1;
         }

            }else{
                    //This is the parent process
                    int w = waitpid(f, &status, WUNTRACED | WCONTINUED);
                    if (w == -1){
                            perror("waitpid");
                            exit(EXIT_FAILURE);
                    }
            }
    }
}

Body:
You can do what you are attempting, but understand you must limit your read to one-char on the shell side since there will be no '\n' written to the pipe. Also, you may write many more times than the shell reads. For example, you can add validations as Mr. Pursell suggests to insure your C-program is functioning and blocking on write with something similar to:

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>

int main (int argc, char **argv) {

    int fd;
    errno = 0;

    if (mkfifo (argc > 1 ? argv[1] : "/tmp/test", 0666)) {
        perror ("mkfifo failed");
        return 1;
    }
    if ((fd = open ("/tmp/test", O_WRONLY)) == -1) {
        perror ("open failed");
        return 1;
    }

    printf ("Opened\n");
    char a = 'a';

    while (1) {
        printf ("Writing to pipe...\n");
        if (write (fd, &a, 1) == -1) {
            perror ("open failed");
            return 1;
        }
    }

    return 0;
}

You can test with a simple:

$ declare -i c=0; while test "$c" -lt 10 && read -n 1 ch; do
    echo "read: $ch"
    ((c++))
done </tmp/test

Example Shell Output

read: a
read: a
read: a
read: a
read: a
read: a
read: a
read: a
read: a
read: a

You will write until the fifo buffer is full resulting in more Writing to pipe... than you have read: a.

Rough Example with fork

Continuing from the comments here is a rough example of using fork to spawn child processes to insure your C-program is always blocking on write for the shell. This example is limited to 3 repetitions, but you could just use while (1) for a continual cycle. I also added a quick counter for the write (just for my curiosity) e.g.

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int crt_fifo_write (char *fname);
int file_exists (char *f);

int main (int argc, char **argv) {

    int n = 0;
    errno = 0;

    while (n < 3) {         /* limit example to 3 child processes */

        pid_t cpid, w;
        int status;

        cpid = fork();
        if (cpid == -1) {
            perror("fork");
            exit(EXIT_FAILURE);
        }

        if (cpid == 0) {    /* Code executed by child */
            if (!crt_fifo_write (argc > 1 ? argv[1] : "/tmp/test"))
                fprintf (stderr, "crt_fifo_write() failed.\n");
        }
        else {              /* Code executed by parent */
            do {
                w = waitpid (cpid, &status, WUNTRACED | WCONTINUED);
                if (w == -1) {
                    perror("waitpid");
                    exit(EXIT_FAILURE);
                }
                if (WIFSIGNALED(status)) /* signal on close of read end */
                    printf("shell read complete. %s\n",
                            n < 2 ? "restarting" : "done");
            } while (!WIFEXITED(status) && !WIFSIGNALED(status));
        }
        n++;
    }

    return 0;
}

/** your write 'a' to the fifo with check for existence & unlink */
int crt_fifo_write (char *fname)
{
    int fd, n = 0;
    errno = 0;

    if (!fname || !*fname) return 0;

    if (file_exists (fname))
        if (unlink (fname) == -1) {
            perror ("fifo exists unlink failed");
            return 0;
        }

    if (mkfifo (fname, 0666)) {
        perror ("mkfifo failed");
        return 1;
    }
    if ((fd = open (fname, O_WRONLY)) == -1) {
        perror ("open failed");
        return 1;
    }

    printf ("Opened\n");
    char a = 'a';

    while (write (fd, &a, 1) != -1) {
        printf ("%3d - Writing to pipe...\n", n++);
    }

    return 0;
}

/** atomic test that file exists (1 success, 0 otherwise) */
int file_exists (char *f)
{
    errno = 0;
    int flags = O_CREAT | O_WRONLY | O_EXCL;
    int mode = S_IRUSR | S_IWUSR;
    int fd = open (f, flags, mode);

    if (fd < 0 && errno == EEXIST)
        return 1;
    else if (fd) {  /* created, like bash touch */
        close (fd);
        unlink (f);
    }

    return 0;
}

Example Program Use/Output

$ ./bin/pipe_write_shell_fork
Opened
  0 - Writing to pipe...
  1 - Writing to pipe...
  2 - Writing to pipe...
  3 - Writing to pipe...
  4 - Writing to pipe...
    ...
138 - Writing to pipe...
139 - Writing to pipe...
140 - Writing to pipe...
shell read complete. restarting
Opened
  0 - Writing to pipe...
  1 - Writing to pipe...
  2 - Writing to pipe...
  3 - Writing to pipe...
  4 - Writing to pipe...
    ...
    130 - Writing to pipe...
131 - Writing to pipe...
shell read complete. restarting
Opened
  0 - Writing to pipe...
  1 - Writing to pipe...
  2 - Writing to pipe...
  3 - Writing to pipe...
  4 - Writing to pipe...
    ...
144 - Writing to pipe...
145 - Writing to pipe...
shell read complete. done

Example Shell Read/Output

$ declare -i c=0; while test "$c" -lt 10 && read -n 8 ch; do \
echo "read: $ch"; ((c++)); done </tmp/test
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa
read: aaaaaaaa

(repeated 2 more times)


问:
Correct import on bring header xcode
im working with swift3 in IOS and library https://github.com/gpolak/LFHeatMap,
when I create my bring header:

```<code>//
//  MocaAdmin-Bridging-Header.h
//  MocaAdmin
//

#import <LFHeatMap/LFHeatMap.h>
</code>```

But when I try to compile, Xcode show me:

What Im doing wrong?

答: Have you added $(SRCROOT)/ Before project name ?</p>

Title: Correct import on bring header xcode

Body:
im working with swift3 in IOS and library https://github.com/gpolak/LFHeatMap,
when I create my bring header:

//
//  MocaAdmin-Bridging-Header.h
//  MocaAdmin
//

#import <LFHeatMap/LFHeatMap.h>

But when I try to compile, Xcode show me:

What Im doing wrong?


问:
How do I convert an NSMutableString into a regular NSString?
How can I convert a NSMutable String into a regular NSString?</p>

答:
```<code>[aMutableString copy]
</code>```

will return a NSString.

Body:
[aMutableString copy]

will return a NSString.

ContentLicense: CC BY-SA 2.5


问:
symfony 3 formbuilder order properties
Using symfony 3, how can I customize form property order?

In my BookType class, I add my properties in my custom order, but when rendered, form will display in another order. Why?

```<code>class BookType extends AbstractType{

    public function buildForm(FormBuilderInterface $builder, array $options){

        $builder
        ->add('title')
        ->add('author')
        ->add('pages')
        ->add('published_date')
        ->add('views');

    }

}
</code>```

And this is the result:

author

title

pages

views

published_date

Thx in advance

答:
You can customize your form result by using form_row(form.author) for each field you have to display. have a look there:

https://symfony.com/doc/current/form/form_customization.html#form-rendering-basics

Title: symfony 3 formbuilder order properties

Body:
Using symfony 3, how can I customize form property order?

In my BookType class, I add my properties in my custom order, but when rendered, form will display in another order. Why?

class BookType extends AbstractType{

    public function buildForm(FormBuilderInterface $builder, array $options){

        $builder
        ->add('title')
        ->add('author')
        ->add('pages')
        ->add('published_date')
        ->add('views');

    }

}

And this is the result:

author

title

pages

views

published_date

Thx in advance


问:
Problems with Java Agent for Bytecode Instrumentation
Its is my first time implementing a java agent and im trying to learn something about bytecode instrumentation. After reading several introductions and tutorials i coded a small Application with two classes (Summer and Application). Now i want to run a java agent via premain method to show the execution path using the following code:

```<code>public class TestJavaAgent {
    public static void premain(String agentArgument,
                               Instrumentation instrumentation){
        instrumentation.addTransformer(new ClassFileTransformer() {

            @Override
            public byte[] transform(ClassLoader classLoader, String s, Class<?> aClass, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException {

                ClassPool cp = ClassPool.getDefault();
                    try {
                        CtClass cc = cp.get("Summer");
                        CtMethod methods [] = cc.getMethods();

                        for( CtMethod method : methods){
                            System.out.println("Entering "+method.getName());
                            method.addLocalVariable("elapsedTime", CtClass.longType);
                            method.insertBefore("elapsedTime = System.currentTimeMillis();");
                            method.insertAfter("{elapsedTime = System.currentTimeMillis() - elapsedTime;"
                                    + "System.out.println(\"Method Executed in ms: \" + elapsedTime);}");
                        }
                        return cc.toBytecode();

                    } catch (Exception ex) {
                        return bytes;
                    }
            }
        });
    }
}
</code>```

I started the Agent via java -javaagent{Agent JAR} -jar {Application Jar} but it did not print anything of the inserted messages. After debugging the code i realized everything after "ClassPool.getDefault()" will not be reached but i dont know why. Can someone help me?

答:
The transformer is supposed to transform the class being passed as parameter, not some arbitrary class you like. And after registration, it will be called for all classes that are loaded, including the classes you are using yourself (ClassPool at first). So you are creating a circular dependency.

You have to check the class name argument and wait until your method has been called for the class you want to transform. For all other classes, just return null.

```<code>public class TestJavaAgent {
    public static void premain(String agentArgument, Instrumentation instrumentation) {
        instrumentation.addTransformer(new ClassFileTransformer() {

            @Override
            public byte[] transform(ClassLoader classLoader,
                String className, Class<?> aClass, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException {

                if(!className.equals("Summer")) return null;

                ClassPool cp = ClassPool.getDefault();
                try {
                    // use the class bytes your received as parameter
                    cp.insertClassPath(new ByteArrayClassPath(className, bytes));

                    CtClass cc = cp.get("Summer");
                    CtMethod[] methods = cc.getMethods();

                    for( CtMethod method : methods){
                        System.out.println("Entering "+method.getName());
                        method.addLocalVariable("elapsedTime", CtClass.longType);
                        method.insertBefore("elapsedTime = System.currentTimeMillis();");
                        method.insertAfter("{elapsedTime = System.currentTimeMillis() - elapsedTime;"
                                + "System.out.println(\"Method Executed in ms: \" + elapsedTime);}");
                    }
                    return cc.toBytecode();

                } catch (Exception ex) {
                    return null;
                }
            }
        });
    }
}
</code>```

Note that returning null is preferred to returning the original array if you didn’t change anything as then the JVM can immediately recognize that you didn’t change anything, without looking into the array contents.

Body:
Its is my first time implementing a java agent and im trying to learn something about bytecode instrumentation. After reading several introductions and tutorials i coded a small Application with two classes (Summer and Application). Now i want to run a java agent via premain method to show the execution path using the following code:

public class TestJavaAgent {
    public static void premain(String agentArgument,
                               Instrumentation instrumentation){
        instrumentation.addTransformer(new ClassFileTransformer() {

            @Override
            public byte[] transform(ClassLoader classLoader, String s, Class<?> aClass, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException {

                ClassPool cp = ClassPool.getDefault();
                    try {
                        CtClass cc = cp.get("Summer");
                        CtMethod methods [] = cc.getMethods();

                        for( CtMethod method : methods){
                            System.out.println("Entering "+method.getName());
                            method.addLocalVariable("elapsedTime", CtClass.longType);
                            method.insertBefore("elapsedTime = System.currentTimeMillis();");
                            method.insertAfter("{elapsedTime = System.currentTimeMillis() - elapsedTime;"
                                    + "System.out.println(\"Method Executed in ms: \" + elapsedTime);}");
                        }
                        return cc.toBytecode();

                    } catch (Exception ex) {
                        return bytes;
                    }
            }
        });
    }
}

I started the Agent via java -javaagent{Agent JAR} -jar {Application Jar} but it did not print anything of the inserted messages. After debugging the code i realized everything after "ClassPool.getDefault()" will not be reached but i dont know why. Can someone help me?

Body:
The transformer is supposed to transform the class being passed as parameter, not some arbitrary class you like. And after registration, it will be called for all classes that are loaded, including the classes you are using yourself (ClassPool at first). So you are creating a circular dependency.

You have to check the class name argument and wait until your method has been called for the class you want to transform. For all other classes, just return null.

public class TestJavaAgent {
    public static void premain(String agentArgument, Instrumentation instrumentation) {
        instrumentation.addTransformer(new ClassFileTransformer() {

            @Override
            public byte[] transform(ClassLoader classLoader,
                String className, Class<?> aClass, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException {

                if(!className.equals("Summer")) return null;

                ClassPool cp = ClassPool.getDefault();
                try {
                    // use the class bytes your received as parameter
                    cp.insertClassPath(new ByteArrayClassPath(className, bytes));

                    CtClass cc = cp.get("Summer");
                    CtMethod[] methods = cc.getMethods();

                    for( CtMethod method : methods){
                        System.out.println("Entering "+method.getName());
                        method.addLocalVariable("elapsedTime", CtClass.longType);
                        method.insertBefore("elapsedTime = System.currentTimeMillis();");
                        method.insertAfter("{elapsedTime = System.currentTimeMillis() - elapsedTime;"
                                + "System.out.println(\"Method Executed in ms: \" + elapsedTime);}");
                    }
                    return cc.toBytecode();

                } catch (Exception ex) {
                    return null;
                }
            }
        });
    }
}

Note that returning null is preferred to returning the original array if you didn’t change anything as then the JVM can immediately recognize that you didn’t change anything, without looking into the array contents.


答:
Your statement will output

BACKUP DATABASE [DBName] TO DISK = 'D:\Backups\DBName.bak_2017-07-07.txt

You need to add '.txt'''

Title: Database backup using dynamic SQL


问:
How to execute second query based on first query result
I have a situation where i need to execute a second query based on first query result.

here is my first query result:

```<code>id  current_date    starts_on   ends_on Product_id  days_remaining
1   2017-06-21T12:00:00 2017-06-20T12:00:00Z    2017-06-23T12:00:00Z    3   2
2   2017-06-21T12:00:00 2017-06-01T12:00:00Z    2017-06-03T12:00:00Z    4   0
3   2017-06-21T12:00:00 2017-06-01T12:00:00Z    2017-06-03T12:00:00Z    7   0
4   2017-06-21T12:00:00 2017-07-01T12:00:00Z    2017-07-03T12:00:00Z    5   12
</code>```

Here you can see remaining_days having 2 zeros(0) as result  on that occurence i want to get all product_name from product table

My Both the Tables and Query for Above result is implemented but for
  getting product_name is not implemented. please help me here

here is my sqlfiddle:  http://sqlfiddle.com/#!9/5bf34/1

MY QUESTION:  i want to get all product_name if days_remaining (see above result)  is 0

in short get all product_name if days_remaining is 0

答:
using your own query, I expanded it:</p>

```<code>#assume this is the date as NOW()
SET @mycurrentDate = '2017-06-21T12:00:00';
SELECT * FROM product WHERE product_id IN (
  SELECT product_id FROM (
    SELECT
      id,
      @mycurrentDate AS `current_date`,
      `tn`.`start` AS `starts_on`,
      `tn`.`end` AS `ends_on`,
      `tn`.`product_id` AS `Product_id`,
      IF(`tn`.`end` >= @mycurrentDate,
         DATEDIFF(`tn`.`end`, @mycurrentDate), #show days until event ends
         0 #the event has already passed
      ) AS `days_remaining`
    FROM `booking` AS `tn`
  ) tmp1
  WHERE `days_remaining` = 0
)
</code>```

Body:
I have a situation where i need to execute a second query based on first query result.

here is my first query result:

id  current_date    starts_on   ends_on Product_id  days_remaining
1   2017-06-21T12:00:00 2017-06-20T12:00:00Z    2017-06-23T12:00:00Z    3   2
2   2017-06-21T12:00:00 2017-06-01T12:00:00Z    2017-06-03T12:00:00Z    4   0
3   2017-06-21T12:00:00 2017-06-01T12:00:00Z    2017-06-03T12:00:00Z    7   0
4   2017-06-21T12:00:00 2017-07-01T12:00:00Z    2017-07-03T12:00:00Z    5   12

Here you can see remaining_days having 2 zeros(0) as result  on that occurence i want to get all product_name from product table

My Both the Tables and Query for Above result is implemented but for
  getting product_name is not implemented. please help me here

here is my sqlfiddle:  http://sqlfiddle.com/#!9/5bf34/1

MY QUESTION:  i want to get all product_name if days_remaining (see above result)  is 0

in short get all product_name if days_remaining is 0

Body:
using your own query, I expanded it:

#assume this is the date as NOW()
SET @mycurrentDate = '2017-06-21T12:00:00';
SELECT * FROM product WHERE product_id IN (
  SELECT product_id FROM (
    SELECT
      id,
      @mycurrentDate AS `current_date`,
      `tn`.`start` AS `starts_on`,
      `tn`.`end` AS `ends_on`,
      `tn`.`product_id` AS `Product_id`,
      IF(`tn`.`end` >= @mycurrentDate,
         DATEDIFF(`tn`.`end`, @mycurrentDate), #show days until event ends
         0 #the event has already passed
      ) AS `days_remaining`
    FROM `booking` AS `tn`
  ) tmp1
  WHERE `days_remaining` = 0
)


问:
Phing does just the default target
I have a problem with Phing. He only does the default job. Has anyone encountered such behavior? The environment works on Windows 10.
Thank you for your help.</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="Test" default="start">
    <!-- ============================================  -->
    <!-- Target: start                                 -->
    <!-- ============================================  -->
    <target name="start">
        <echo msg="Start build" />
    </target>
    <!-- ============================================  -->
    <!-- Target: prepareDirectory                      -->
    <!-- ============================================  -->
    <target name="prepareDirectory" depends="start">
        <echo msg="Making directory build ./build" />
        <mkdir dir="./build" />
        <echo msg="Making directory install ./install" />
        <mkdir dir="./install" />
    </target>
    <!-- ============================================  -->
    <!-- Target: build                                 -->
    <!-- ============================================  -->
    <target name="build" depends="prepareDirectory">
        <echo msg="Copying files to build directory..." />

        <echo msg="Copying ./about.php to ./build directory..." />
        <copy file="./about.php" tofile="./build/about.php" />

        <echo msg="Copying ./browsers.php to ./build directory..." />
        <copy file="./browsers.php" tofile="./build/browsers.php" />

        <echo msg="Copying ./contact.php to ./build directory..." />
        <copy file="./contact.php" tofile="./build/contact.php" />
    </target>
</project>
</code>```

答:
You need to set dependencies the other way around. Your target "start" does not trigger any other targets with your current code.

Try this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="Test" default="build">
    <!-- ============================================  -->
    <!-- Target: start                                 -->
    <!-- ============================================  -->
    <target name="start">
        <echo msg="Start build" />
    </target>
    <!-- ============================================  -->
    <!-- Target: prepareDirectory                      -->
    <!-- ============================================  -->
    <target name="prepareDirectory" depends="start">
        <echo msg="Making directory build ./build" />
        <mkdir dir="./build" />
        <echo msg="Making directory install ./install" />
        <mkdir dir="./install" />
    </target>
    <!-- ============================================  -->
    <!-- Target: build                                 -->
    <!-- ============================================  -->
    <target name="build" depends="prepareDirectory">
        <echo msg="Copying files to build directory..." />

        <echo msg="Copying ./about.php to ./build directory..." />
        <copy file="./about.php" tofile="./build/about.php" />

        <echo msg="Copying ./browsers.php to ./build directory..." />
        <copy file="./browsers.php" tofile="./build/browsers.php" />

        <echo msg="Copying ./contact.php to ./build directory..." />
        <copy file="./contact.php" tofile="./build/contact.php" />
    </target>
</project>
</code>```

The execution order will be: start -> prepareDirectory -> build

Hope that works!

Title: Phing does just the default target

Body:
I have a problem with Phing. He only does the default job. Has anyone encountered such behavior? The environment works on Windows 10.
Thank you for your help.

<?xml version="1.0" encoding="UTF-8"?>
<project name="Test" default="start">

    <target name="start">
        <echo msg="Start build" />
    </target>

    <target name="prepareDirectory" depends="start">
        <echo msg="Making directory build ./build" />
        <mkdir dir="./build" />
        <echo msg="Making directory install ./install" />
        <mkdir dir="./install" />
    </target>

    <target name="build" depends="prepareDirectory">
        <echo msg="Copying files to build directory..." />

        <echo msg="Copying ./about.php to ./build directory..." />
        <copy file="./about.php" tofile="./build/about.php" />

        <echo msg="Copying ./browsers.php to ./build directory..." />
        <copy file="./browsers.php" tofile="./build/browsers.php" />

        <echo msg="Copying ./contact.php to ./build directory..." />
        <copy file="./contact.php" tofile="./build/contact.php" />
    </target>
</project>

Body:
You need to set dependencies the other way around. Your target "start" does not trigger any other targets with your current code.

Try this:

<?xml version="1.0" encoding="UTF-8"?>
<project name="Test" default="build">
    <!-- ============================================  -->
    <!-- Target: start                                 -->
    <!-- ============================================  -->
    <target name="start">
        <echo msg="Start build" />
    </target>
    <!-- ============================================  -->
    <!-- Target: prepareDirectory                      -->
    <!-- ============================================  -->
    <target name="prepareDirectory" depends="start">
        <echo msg="Making directory build ./build" />
        <mkdir dir="./build" />
        <echo msg="Making directory install ./install" />
        <mkdir dir="./install" />
    </target>
    <!-- ============================================  -->
    <!-- Target: build                                 -->
    <!-- ============================================  -->
    <target name="build" depends="prepareDirectory">
        <echo msg="Copying files to build directory..." />

        <echo msg="Copying ./about.php to ./build directory..." />
        <copy file="./about.php" tofile="./build/about.php" />

        <echo msg="Copying ./browsers.php to ./build directory..." />
        <copy file="./browsers.php" tofile="./build/browsers.php" />

        <echo msg="Copying ./contact.php to ./build directory..." />
        <copy file="./contact.php" tofile="./build/contact.php" />
    </target>
</project>

The execution order will be: start -> prepareDirectory -> build

Hope that works!


问:
LINQ XML - Select all parent elements where a child has a given value
From the XML below,  I need to find information about all flights where  FlightSegmentReference ref equals BA2759,  and then pass some details from the parent elements to a class

```<code> If Len(inFlightNo) > 0 Then
     Dim xdoc As XDocument = XDocument.Parse(rawXML)
     Dim results As IEnumerable(Of Offer) =
         From offer In xdoc.Descendants(myns + "FlightSegmentReference")
             Where offer.Attribute("ref") = inFlightNo
                 Select New Offer With
                 {.FlightRef = offer.Attribute("ref")}
     'Return results
 End If
</code>```

This example works fine...  however I need to get more data to  pass to my class,  such as TotalAmount SimpleCurrancyPrice and OfferItemID

```<code> If Len(inFlightNo) > 0 Then
     Dim xdoc As XDocument = XDocument.Parse(rawXML)
     Dim results As IEnumerable(Of Offer) =
         From offer In xdoc.Descendants(myns + "FlightSegmentReference")
             Where offer.Attribute("ref") = inFlightNo
                 Select New Offer With
                 {.FlightRef = offer.Attribute("ref"),
                  .Price = ????,
                  .OfferItemID = ????
                 }
     'Return results
 End If
</code>```

What is the best practice method of getting SimpleCurrencyPrice and populating Price in my class

Here is the XML

```<code><AirlineOffers>
   <TotalOfferQuantity>1156</TotalOfferQuantity>
   <Owner>BA</Owner>
   <AirlineOffer RequestedDateInd="true">
      <OfferID Owner="BA">OFFER1</OfferID>
      <TotalPrice>
         <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
      </TotalPrice>
      <PricedOffer>
         <OfferPrice OfferItemID="1">
            <RequestedDate>
               <PriceDetail>
                  <TotalAmount>
                     <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
                  </TotalAmount>
                  <BaseAmount Code="GBP">84.00</BaseAmount>
                  <Taxes>
                     <Total Code="GBP">45.50</Total>
                  </Taxes>
               </PriceDetail>
               <Associations>
                  <AssociatedTraveler>
                     <TravelerReferences>SH1</TravelerReferences>
                  </AssociatedTraveler>
               </Associations>
            </RequestedDate>
         </OfferPrice>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2759">
                  <ClassOfService>
                     <Code>O</Code>
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2764">
                  <ClassOfService>
                     <Code>Q</Code>
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
      </PricedOffer>
   </AirlineOffer>
   <AirlineOffer RequestedDateInd="true">
      <OfferID Owner="BA">OFFER2</OfferID>
      <TotalPrice>
         <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
      </TotalPrice>
      <PricedOffer>
         <OfferPrice OfferItemID="1">
            <RequestedDate>
               <PriceDetail>
                  <TotalAmount>
                     <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
                  </TotalAmount>
                  <BaseAmount Code="GBP">84.00</BaseAmount>
                  <Taxes>
                     <Total Code="GBP">45.50</Total>
                  </Taxes>
               </PriceDetail>
               <Associations>
                  <AssociatedTraveler>
                     <TravelerReferences>SH1</TravelerReferences>
                  </AssociatedTraveler>
               </Associations>
            </RequestedDate>
         </OfferPrice>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2765">
                  <ClassOfService>
                     <Code>O</Code>
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2764">
                  <ClassOfService>
                     <Code>Q</Code>
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
      </PricedOffer>
   </AirlineOffer>
</AirlineOffers>
</code>```

答:
I'm not a VB developer but I think is easy what I going to propose, instead of select FlightSegmentReference nodes, select PricedOffer which is the element that have all the info you need, so it would be:

```<code>Dim results As IEnumerable(Of Offer) =
      From offer In xdoc.Descendants(myns + "PricedOffer")
      Where offer.Descendants(myns +"FlightSegmentReference")
                  .Any(Function(e) e.Attribute("ref").Value = inFlightNo)
      Select New Offer() With {
                          .FlightRef = inFlightNo,
                          .Price = offer.Descendants(myns +"SimpleCurrencyPrice").FirstOrDefault().Value
                          .OfferItemID =offer.Element(myns +"OfferPrice").Attribute("OfferItemID").Value
}
</code>```

Body:
From the XML below,  I need to find information about all flights where  FlightSegmentReference ref equals BA2759,  and then pass some details from the parent elements to a class

 If Len(inFlightNo) > 0 Then
     Dim xdoc As XDocument = XDocument.Parse(rawXML)
     Dim results As IEnumerable(Of Offer) =
         From offer In xdoc.Descendants(myns + "FlightSegmentReference")
             Where offer.Attribute("ref") = inFlightNo
                 Select New Offer With
                 {.FlightRef = offer.Attribute("ref")}
     'Return results
 End If

This example works fine...  however I need to get more data to  pass to my class,  such as TotalAmount SimpleCurrancyPrice and OfferItemID

 If Len(inFlightNo) > 0 Then
     Dim xdoc As XDocument = XDocument.Parse(rawXML)
     Dim results As IEnumerable(Of Offer) =
         From offer In xdoc.Descendants(myns + "FlightSegmentReference")
             Where offer.Attribute("ref") = inFlightNo
                 Select New Offer With
                 {.FlightRef = offer.Attribute("ref"),
                  .Price = ????,
                  .OfferItemID = ????
                 }
     'Return results
 End If

What is the best practice method of getting SimpleCurrencyPrice and populating Price in my class

Here is the XML

<AirlineOffers>
   <TotalOfferQuantity>1156</TotalOfferQuantity>
   <Owner>BA</Owner>
   <AirlineOffer RequestedDateInd="true">
      <OfferID Owner="BA">OFFER1</OfferID>
      <TotalPrice>
         <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
      </TotalPrice>
      <PricedOffer>
         <OfferPrice OfferItemID="1">
            <RequestedDate>
               <PriceDetail>
                  <TotalAmount>
                     <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
                  </TotalAmount>
                  <BaseAmount Code="GBP">84.00</BaseAmount>
                  <Taxes>
                     <Total Code="GBP">45.50</Total>
                  </Taxes>
               </PriceDetail>
               <Associations>
                  <AssociatedTraveler>
                     <TravelerReferences>SH1</TravelerReferences>
                  </AssociatedTraveler>
               </Associations>
            </RequestedDate>
         </OfferPrice>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2759">
                  <ClassOfService>
                     O
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2764">
                  <ClassOfService>
                     Q
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
      </PricedOffer>
   </AirlineOffer>
   <AirlineOffer RequestedDateInd="true">
      <OfferID Owner="BA">OFFER2</OfferID>
      <TotalPrice>
         <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
      </TotalPrice>
      <PricedOffer>
         <OfferPrice OfferItemID="1">
            <RequestedDate>
               <PriceDetail>
                  <TotalAmount>
                     <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
                  </TotalAmount>
                  <BaseAmount Code="GBP">84.00</BaseAmount>
                  <Taxes>
                     <Total Code="GBP">45.50</Total>
                  </Taxes>
               </PriceDetail>
               <Associations>
                  <AssociatedTraveler>
                     <TravelerReferences>SH1</TravelerReferences>
                  </AssociatedTraveler>
               </Associations>
            </RequestedDate>
         </OfferPrice>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2765">
                  <ClassOfService>
                     O
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2764">
                  <ClassOfService>
                     Q
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
      </PricedOffer>
   </AirlineOffer>
</AirlineOffers>

Body:
I'm not a VB developer but I think is easy what I going to propose, instead of select FlightSegmentReference nodes, select PricedOffer which is the element that have all the info you need, so it would be:

Dim results As IEnumerable(Of Offer) =
      From offer In xdoc.Descendants(myns + "PricedOffer")
      Where offer.Descendants(myns +"FlightSegmentReference")
                  .Any(Function(e) e.Attribute("ref").Value = inFlightNo)
      Select New Offer() With {
                          .FlightRef = inFlightNo,
                          .Price = offer.Descendants(myns +"SimpleCurrencyPrice").FirstOrDefault().Value
                          .OfferItemID =offer.Element(myns +"OfferPrice").Attribute("OfferItemID").Value
}


问:
multiple if statements in Swift
```<code>@IBAction func addtoCart(_ sender: Any) {
    if UserDataSingleton.sharedDataContainer.is_guest == "guest"  {
        //segue, user is a guest
    }

    if sizebtn.isHidden == false {
        if Size.selectedItem == nil {
            // show alert , nothing is selected from items
        }
    } else {
        // do API call
    }
}
</code>```

The code above skips api calls if the user is not a guest and has selected something from item. How can I check if :

user is not a guest

if UIButton isn't hidden and user has selected from item

答:
You can use "&&" logic operator to do second statement </p>

```<code>@IBAction func addtoCart(_ sender: Any) {

   if  UserDataSingleton.sharedDataContainer.is_guest == "guest"  {
      //segue, user is a guest
      return
   }

   if (sizebtn.isHidden == false) && (Size.selectedItem != nil) {
      // do API call , SOMETHING is selected from items
   } else {
      //show alert nothing is selected
   }
}
</code>```

Title: multiple if statements in Swift

Body:
@IBAction func addtoCart(_ sender: Any) {
    if UserDataSingleton.sharedDataContainer.is_guest == "guest"  {
        //segue, user is a guest
    }

    if sizebtn.isHidden == false {
        if Size.selectedItem == nil {
            // show alert , nothing is selected from items
        }
    } else {
        // do API call
    }
}

The code above skips api calls if the user is not a guest and has selected something from item. How can I check if :

user is not a guest

if UIButton isn't hidden and user has selected from item

Body:
You can use "&&" logic operator to do second statement

@IBAction func addtoCart(_ sender: Any) {

   if  UserDataSingleton.sharedDataContainer.is_guest == "guest"  {
      //segue, user is a guest
      return
   }

   if (sizebtn.isHidden == false) && (Size.selectedItem != nil) {
      // do API call , SOMETHING is selected from items
   } else {
      //show alert nothing is selected
   }
}


问:
laravel result array of array
I have this eloquent query

```<code>$data= \App\Logs::select('id', 'created_at')
    ->get()
    ->groupBy(function($val) {
        return Carbon::parse($val->created_at)->format('d-M-');
    })->toArray();
</code>```

and this retun something like that

```<code>array:2 [▼
  "06-Jul-" => array:1 [▼
    0 => array:2 [▼
      "id" => 1
      "created_at" => "2017-07-06 13:21:15"
    ]
  ]
  "07-Jul-" => array:3 [▼
    0 => array:2 [▼
      "id" => 2
      "created_at" => "2017-07-07 13:43:23"
    ]
    1 => array:2 [▼
      "id" => 3
      "created_at" => "2017-07-07 14:18:36"
    ]
    2 => array:2 [▼
      "id" => 4
      "created_at" => "2017-07-07 14:18:41"
    ]
  ]
]
</code>```

and i want return just the count

"06-Jul-" => "1"

"07-Jul-" => "3"

how i can do that?

答:
You can use/chain map/transform after your groupBy for example:

$data = \App\Logs::select('id', 'created_at')
->get()
->groupBy(function($val) {
    return Carbon::parse($val->created_at)->format('d-M-');
})
->transform(function ($collection, $key) {
    return $collection->count();
});
```

Title: laravel result array of array

Body:
I have this eloquent query

$data= \App\Logs::select('id', 'created_at')
    ->get()
    ->groupBy(function($val) {
        return Carbon::parse($val->created_at)->format('d-M-');
    })->toArray();

and this retun something like that

array:2 [▼
  "06-Jul-" => array:1 [▼
    0 => array:2 [▼
      "id" => 1
      "created_at" => "2017-07-06 13:21:15"
    ]
  ]
  "07-Jul-" => array:3 [▼
    0 => array:2 [▼
      "id" => 2
      "created_at" => "2017-07-07 13:43:23"
    ]
    1 => array:2 [▼
      "id" => 3
      "created_at" => "2017-07-07 14:18:36"
    ]
    2 => array:2 [▼
      "id" => 4
      "created_at" => "2017-07-07 14:18:41"
    ]
  ]
]

and i want return just the count

"06-Jul-" => "1"

"07-Jul-" => "3"

how i can do that?


问:
The target principal name is incorrect. Cannot generate SSPI context
I am struggling to get a SQL Server connection from machine A to machine B which is running the SQL Server.

I have Googled extensively and all the things I have found have not worked. Nor do they lead you step by step through the process of solving this.

We are not using Kerberos, but NTLM where configured.

The machines involved are (xx is used to obscure some of the machine name for security purposes):

xxPRODSVR001 - Windows Server 2012 Domain Controller

xxDEVSVR003 - Windows Server 2012 (This machine is generating the error)

xxDEVSVR002 - Windows Server 2012 (This machine is running SQL Server 2012)

The following SPN's are registered on the DC (xxPRODSVR001). I have obscured the domain with yyy for security purposes:

Registered ServicePrincipalNames for CN=xxDEVSVR002,CN=Computers,DC=yyy,DC=local:

```<code>            MSSQLSvc/xxDEVSVR002.yyy.local:49298

            MSSQLSvc/xxDEVSVR002.yyy.local:TFS

            RestrictedKrbHost/xxDEVSVR002

            RestrictedKrbHost/xxDEVSVR002.yyy.local

            Hyper-V Replica Service/xxDEVSVR002

            Hyper-V Replica Service/xxDEVSVR002.yyy.local

            Microsoft Virtual System Migration Service/xxDEVSVR002

            Microsoft Virtual System Migration Service/xxDEVSVR002.yyy.local

            Microsoft Virtual Console Service/xxDEVSVR002

            Microsoft Virtual Console Service/xxDEVSVR002.yyy.local

            SMTPSVC/xxDEVSVR002

            SMTPSVC/xxDEVSVR002.yyy.local

            WSMAN/xxDEVSVR002

            WSMAN/xxDEVSVR002.yyy.local

            Dfsr-12F9A27C-BF97-4787-9364-D31B6C55EB04/xxDEVSVR002.yyy.local

            TERMSRV/xxDEVSVR002

            TERMSRV/xxDEVSVR002.yyy.local

            HOST/xxDEVSVR002

            HOST/xxDEVSVR002.yyy.local
</code>```

Registered ServicePrincipalNames for CN=xxDEVSVR003,CN=Computers,DC=yyy,DC=local:

```<code>            MSSQLSvc/xxDEVSVR003.yyy.local:1433

            MSSQLSvc/xxDEVSVR003.yyy.local

            Hyper-V Replica Service/xxDEVSVR003

            Hyper-V Replica Service/xxDEVSVR003.yyy.local

            Microsoft Virtual System Migration Service/xxDEVSVR003

            Microsoft Virtual System Migration Service/xxDEVSVR003.yyy.local

            Microsoft Virtual Console Service/xxDEVSVR003

            Microsoft Virtual Console Service/xxDEVSVR003.yyy.local

            WSMAN/xxDEVSVR003

            WSMAN/xxDEVSVR003.yyy.local

            TERMSRV/xxDEVSVR003

            TERMSRV/xxDEVSVR003.yyy.local

            RestrictedKrbHost/xxDEVSVR003

            HOST/xxDEVSVR003

            RestrictedKrbHost/xxDEVSVR003.yyy.local

            HOST/xxDEVSVR003.yyy.local
</code>```

Now if only the SQL Server error message was more descriptive and told me what principal name it was trying to connect to I might be able to diagnose this.

So can anyone step me through how to solve this one or can you see anything in what I have provided that is wrong?

I would be happy to generate more debug info, just tell me what you need.

答:
Integrated Security=false

Make this flag as false in webconfig connection string. It will work!

Body:
I am struggling to get a SQL Server connection from machine A to machine B which is running the SQL Server.

I have Googled extensively and all the things I have found have not worked. Nor do they lead you step by step through the process of solving this.

We are not using Kerberos, but NTLM where configured.

The machines involved are (xx is used to obscure some of the machine name for security purposes):

xxPRODSVR001 - Windows Server 2012 Domain Controller

xxDEVSVR003 - Windows Server 2012 (This machine is generating the error)

xxDEVSVR002 - Windows Server 2012 (This machine is running SQL Server 2012)

The following SPN's are registered on the DC (xxPRODSVR001). I have obscured the domain with yyy for security purposes:

Registered ServicePrincipalNames for CN=xxDEVSVR002,CN=Computers,DC=yyy,DC=local:

            MSSQLSvc/xxDEVSVR002.yyy.local:49298

            MSSQLSvc/xxDEVSVR002.yyy.local:TFS

            RestrictedKrbHost/xxDEVSVR002

            RestrictedKrbHost/xxDEVSVR002.yyy.local

            Hyper-V Replica Service/xxDEVSVR002

            Hyper-V Replica Service/xxDEVSVR002.yyy.local

            Microsoft Virtual System Migration Service/xxDEVSVR002

            Microsoft Virtual System Migration Service/xxDEVSVR002.yyy.local

            Microsoft Virtual Console Service/xxDEVSVR002

            Microsoft Virtual Console Service/xxDEVSVR002.yyy.local

            SMTPSVC/xxDEVSVR002

            SMTPSVC/xxDEVSVR002.yyy.local

            WSMAN/xxDEVSVR002

            WSMAN/xxDEVSVR002.yyy.local

            Dfsr-12F9A27C-BF97-4787-9364-D31B6C55EB04/xxDEVSVR002.yyy.local

            TERMSRV/xxDEVSVR002

            TERMSRV/xxDEVSVR002.yyy.local

            HOST/xxDEVSVR002

            HOST/xxDEVSVR002.yyy.local

Registered ServicePrincipalNames for CN=xxDEVSVR003,CN=Computers,DC=yyy,DC=local:

            MSSQLSvc/xxDEVSVR003.yyy.local:1433

            MSSQLSvc/xxDEVSVR003.yyy.local

            Hyper-V Replica Service/xxDEVSVR003

            Hyper-V Replica Service/xxDEVSVR003.yyy.local

            Microsoft Virtual System Migration Service/xxDEVSVR003

            Microsoft Virtual System Migration Service/xxDEVSVR003.yyy.local

            Microsoft Virtual Console Service/xxDEVSVR003

            Microsoft Virtual Console Service/xxDEVSVR003.yyy.local

            WSMAN/xxDEVSVR003

            WSMAN/xxDEVSVR003.yyy.local

            TERMSRV/xxDEVSVR003

            TERMSRV/xxDEVSVR003.yyy.local

            RestrictedKrbHost/xxDEVSVR003

            HOST/xxDEVSVR003

            RestrictedKrbHost/xxDEVSVR003.yyy.local

            HOST/xxDEVSVR003.yyy.local

Now if only the SQL Server error message was more descriptive and told me what principal name it was trying to connect to I might be able to diagnose this.

So can anyone step me through how to solve this one or can you see anything in what I have provided that is wrong?

I would be happy to generate more debug info, just tell me what you need.


答:
```<code>@IBAction func addtoCart(_ sender: Any) {

    if  UserDataSingleton.sharedDataContainer.is_guest == "guest"  {
       //segue, user is a guest
       return
    }

    if sizebtn.isHidden == false && Size.selectedItem == nil {
       // show alert , nothing is selected from items
       return
    }

    // do API call
 }
</code>```

Use return when to don't want to execute your code further.

Title: multiple if statements in Swift

Body:
@IBAction func addtoCart(_ sender: Any) {

    if  UserDataSingleton.sharedDataContainer.is_guest == "guest"  {
       //segue, user is a guest
       return
    }

    if sizebtn.isHidden == false && Size.selectedItem == nil {
       // show alert , nothing is selected from items
       return
    }

    // do API call
 }

Use return when to don't want to execute your code further.