问:
Parsing a Quickbook IIF format file
I'm working with Quickbook's IIF file format and I need to write a parser to read and write IIF files and I'm running into some issues reading the files.

The files are simple, they're tab deliminated. Every line is either a table definition or a row. Definitions begin with'!' and the table name, and rows begin with just the table name. Here's the problem I'm running into: some of the fields allow line breaks.

When I first encountered this, I thought, okay just parse it tab by tab instead of line by line, but to do that I had to replace the line breaks with tabs, and wound up with more values than there were columns, but I wound up with the values with line breaks spread out across too many columns.

How would you parse such a file?

Edit: An example

```<code>!CUST   NAME    REFNUM  TIMESTAMP   BADDR1  BADDR2  BADDR3  BADDR4  BADDR5  SADDR1  SADDR2  SADDR3  SADDR4  SADDR5  PHONE1  PHONE2  FAXNUM  CONT1   CONT2   CTYPE   TERMS   TAXABLE LIMIT   RESALENUM   REP TAXITEM NOTEPAD SALUTATION  COMPANYNAME FIRSTNAME   MIDINIT LASTNAME    CUSTFLD1    CUSTFLD2    CUSTFLD3    CUSTFLD4    CUSTFLD5    CUSTFLD6    CUSTFLD7    CUSTFLD8    CUSTFLD9    CUSTFLD10   CUSTFLD11   CUSTFLD12   CUSTFLD13   CUSTFLD14   CUSTFLD15   JOBDESC JOBTYPE JOBSTATUS   JOBSTART    JOBPROJEND  JOBEND  HIDDEN  DELCOUNT
CUST    St. Mark    359 1176670332  Saint Mark Catholic Church  609 W Main St   City, State Zip
!CLASS  NAME    REFNUM  TIMESTAMP   HIDDEN  DELCOUNT
!INVITEM    NAME    REFNUM  TIMESTAMP   INVITEMTYPE DESC    PURCHASEDESC    ACCNT   ASSETACCNT  COGSACCNT   QNTY    QNTY    PRICE   COST    TAXABLE PAYMETH TAXVEND TAXDIST PREFVEND    REORDERPOINT    EXTRA   CUSTFLD1    CUSTFLD2    CUSTFLD3    CUSTFLD4    CUSTFLD5    DEP_TYPE    ISPASSEDTHRU    HIDDEN  DELCOUNT    USEID
INVITEM Labor   1   1119915308  SERV    Labor                                                                                0
!TIMEACT    DATE    JOB EMP ITEM    PITEM   DURATION    PROJ    NOTE    XFERTOPAYROLL   BILLINGSTATUS
TIMEACT 3/8/08  876 Development Jane Doe {Consultant}   Labor       00:15       Renewing all domain name for 876 Development.
REIMBURSEMENT: 44.72 for one year renewal on all domain names.  N   1
TIMEACT 3/17/08 Greg:Bridge Jane Doe {Consultant}   Labor       01:00       Preparing Studio    N   1
TIMEACT 3/17/08 John Doe and Associates Jane Doe {Consultant}   Labor       00:06       REIMBURSEMENT: Toner cartridge on ebay & Fuser from FastPrinters- ask wendell before invoicing to see if this fixed the problem
49.99 (include tax) toner
$175.18 (include tax) fuser
    N   1
TIMEACT 3/17/08 John Doe II Jane Doe {Consultant}   Labor       01:00       Fixing Kandis's computer - replaced entire computer with similar system N   1
</code>```

答:
I run into this sort of thing all the time.  The key is to handling special cases like this when you're doing parsing is to replace the special case with something that's extremely unlikely to occur in the text, and then replace it again when you're done.

For example, you have line breaks in the output which can be readily detected with a Regex.  Use Regex.Replace to convert them to something like LINEBREAK.  Make it something that stands out in an editor for debugging.  Then do the rest of your parsing as normal, and as the last step, replace the special token with the original value (or something new).

OwnerDisplayName: Malfist

Title: Parsing a Quickbook IIF format file

Body:
I'm working with Quickbook's IIF file format and I need to write a parser to read and write IIF files and I'm running into some issues reading the files.

The files are simple, they're tab deliminated. Every line is either a table definition or a row. Definitions begin with'!' and the table name, and rows begin with just the table name. Here's the problem I'm running into: some of the fields allow line breaks.

When I first encountered this, I thought, okay just parse it tab by tab instead of line by line, but to do that I had to replace the line breaks with tabs, and wound up with more values than there were columns, but I wound up with the values with line breaks spread out across too many columns.

How would you parse such a file?

Edit: An example

!CUST   NAME    REFNUM  TIMESTAMP   BADDR1  BADDR2  BADDR3  BADDR4  BADDR5  SADDR1  SADDR2  SADDR3  SADDR4  SADDR5  PHONE1  PHONE2  FAXNUM  CONT1   CONT2   CTYPE   TERMS   TAXABLE LIMIT   RESALENUM   REP TAXITEM NOTEPAD SALUTATION  COMPANYNAME FIRSTNAME   MIDINIT LASTNAME    CUSTFLD1    CUSTFLD2    CUSTFLD3    CUSTFLD4    CUSTFLD5    CUSTFLD6    CUSTFLD7    CUSTFLD8    CUSTFLD9    CUSTFLD10   CUSTFLD11   CUSTFLD12   CUSTFLD13   CUSTFLD14   CUSTFLD15   JOBDESC JOBTYPE JOBSTATUS   JOBSTART    JOBPROJEND  JOBEND  HIDDEN  DELCOUNT
CUST    St. Mark    359 1176670332  Saint Mark Catholic Church  609 W Main St   City, State Zip
!CLASS  NAME    REFNUM  TIMESTAMP   HIDDEN  DELCOUNT
!INVITEM    NAME    REFNUM  TIMESTAMP   INVITEMTYPE DESC    PURCHASEDESC    ACCNT   ASSETACCNT  COGSACCNT   QNTY    QNTY    PRICE   COST    TAXABLE PAYMETH TAXVEND TAXDIST PREFVEND    REORDERPOINT    EXTRA   CUSTFLD1    CUSTFLD2    CUSTFLD3    CUSTFLD4    CUSTFLD5    DEP_TYPE    ISPASSEDTHRU    HIDDEN  DELCOUNT    USEID
INVITEM Labor   1   1119915308  SERV    Labor                                                                                0
!TIMEACT    DATE    JOB EMP ITEM    PITEM   DURATION    PROJ    NOTE    XFERTOPAYROLL   BILLINGSTATUS
TIMEACT 3/8/08  876 Development Jane Doe {Consultant}   Labor       00:15       Renewing all domain name for 876 Development.
REIMBURSEMENT: 44.72 for one year renewal on all domain names.  N   1
TIMEACT 3/17/08 Greg:Bridge Jane Doe {Consultant}   Labor       01:00       Preparing Studio    N   1
TIMEACT 3/17/08 John Doe and Associates Jane Doe {Consultant}   Labor       00:06       REIMBURSEMENT: Toner cartridge on ebay & Fuser from FastPrinters- ask wendell before invoicing to see if this fixed the problem
49.99 (include tax) toner
$175.18 (include tax) fuser
    N   1
TIMEACT 3/17/08 John Doe II Jane Doe {Consultant}   Labor       01:00       Fixing Kandis's computer - replaced entire computer with similar system N   1

LastEditorDisplayName: Malfist

OwnerDisplayName: Wade Hatler


来源: stackexchange

问:
Validation message tokens no longer being replaced in my Rails app
Something happened in my Rails app today, and now all of my validation errors are appearing like this, without all of the tokens replaced.  I have no idea what I could've done, I've tried rebooting, switching branches, and rolling my code back to previous versions.</p>

```<code>{{count}} errors prohibited this {{model}} from being saved

There were problems with the following fields:

    * {{attribute}} {{message}}
    * {{attribute}} {{message}}
    * {{attribute}} {{message}}
    * {{attribute}} {{message}}
</code>```

答: Somehow I ended up with two versions of the activemodel gem installed, 2.3.5 (for Rails 2.3.5, which we are running) and 3.0.3.  Once I uninstalled activemodel 3.0.3, things were back to normal.</p>

ContentLicense: CC BY-SA 2.5

Body:
Something happened in my Rails app today, and now all of my validation errors are appearing like this, without all of the tokens replaced.  I have no idea what I could've done, I've tried rebooting, switching branches, and rolling my code back to previous versions.

{{count}} errors prohibited this {{model}} from being saved

There were problems with the following fields:

    * {{attribute}} {{message}}
    * {{attribute}} {{message}}
    * {{attribute}} {{message}}
    * {{attribute}} {{message}}


问:
Side bar cell items should change its color on click
I have to change button title color and image of only one cell which is selected. suppose I have clicked side bar button from main view controller then in side bar, only home buttton should be in blue color and others should be in black.  I have attached screen shot to show an example.

I have written my code as below

```<code>- (IBAction)home:(id)sender {
titleSelected = [NSUserDefaults standardUserDefaults];
[titleSelected setObject:@"home" forKey:@"CellIdentifier"];
[titleSelected synchronize];
NSLog(@"defaultValue %@",[titleSelected stringForKey:@"CellIdentifier"]);
}
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ if (indexPath.row==0) {

    static NSString *simpleTableIdentifier = @"but1";

    _oneCell= (oneTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (_oneCell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"oneTableViewCell" owner:self options:nil];

        _oneCell = [nib objectAtIndex:0];

    }
    _oneCell.titleImage.layer.cornerRadius = _oneCell.titleImage.frame.size.width / 2;
    _oneCell.titleImage.clipsToBounds = YES;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"Imagekey"] != nil) {
        NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"Imagekey"];
        _oneCell.titleImage.image = [UIImage imageWithData:imageData];
    } else {
        _oneCell.titleImage.image = [UIImage imageNamed:@"user.png"];
    }

    return _oneCell;
}
 if (indexPath.row==1) {
    static NSString *simpleTableIdentifier = @"but2";

    _oneCell= (oneTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if ([[titleSelected stringForKey:@"CellIdentifier"] isEqualToString:@"home"]) {
        NSLog(@"defaultValue %@",[titleSelected stringForKey:@"CellIdentifier"]);
     [_oneCell.homeButtonpressed setTitleColor:[UIColor colorWithRed:(5/255.0) green:(103/255.0) blue:(169/255.0) alpha:1.0] forState:UIControlStateNormal];

    }
    return _oneCell;
       }

NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

return cell;
</code>```

but it is not working. Please Help me.

答:
try this line of code

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
 UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //Get your cell for selected row
 cell.leftMenuItemLabel.textColor = [UIColor redColor];//Configure whatever color you want
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have to change button title color and image of only one cell which is selected. suppose I have clicked side bar button from main view controller then in side bar, only home buttton should be in blue color and others should be in black.  I have attached screen shot to show an example.

I have written my code as below

- (IBAction)home:(id)sender {
titleSelected = [NSUserDefaults standardUserDefaults];
[titleSelected setObject:@"home" forKey:@"CellIdentifier"];
[titleSelected synchronize];
NSLog(@"defaultValue %@",[titleSelected stringForKey:@"CellIdentifier"]);
}
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ if (indexPath.row==0) {

    static NSString *simpleTableIdentifier = @"but1";

    _oneCell= (oneTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (_oneCell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"oneTableViewCell" owner:self options:nil];

        _oneCell = [nib objectAtIndex:0];

    }
    _oneCell.titleImage.layer.cornerRadius = _oneCell.titleImage.frame.size.width / 2;
    _oneCell.titleImage.clipsToBounds = YES;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"Imagekey"] != nil) {
        NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"Imagekey"];
        _oneCell.titleImage.image = [UIImage imageWithData:imageData];
    } else {
        _oneCell.titleImage.image = [UIImage imageNamed:@"user.png"];
    }

    return _oneCell;
}
 if (indexPath.row==1) {
    static NSString *simpleTableIdentifier = @"but2";

    _oneCell= (oneTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if ([[titleSelected stringForKey:@"CellIdentifier"] isEqualToString:@"home"]) {
        NSLog(@"defaultValue %@",[titleSelected stringForKey:@"CellIdentifier"]);
     [_oneCell.homeButtonpressed setTitleColor:[UIColor colorWithRed:(5/255.0) green:(103/255.0) blue:(169/255.0) alpha:1.0] forState:UIControlStateNormal];

    }
    return _oneCell;
       }

NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

return cell;

but it is not working. Please Help me.

Body:
try this line of code

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
 UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //Get your cell for selected row
 cell.leftMenuItemLabel.textColor = [UIColor redColor];//Configure whatever color you want
}


问:
Set default radio button in Woocommerce using Javascript
I'm working on a WC Appointment Bookings product, and I managed to set up a default for a simple numeric field using a custom script:

// Set default value to 0 for Input multiplier (for additional hours)
jQuery(document).ready(function(){
    jQuery('.addon-input_multiplier').val("0");
});```
</div>
</div>
</p>

<p>But I can't tweak that script to set a radio button to be a default. Here's the HTML of the button I want to make the default...</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="form-row form-row-wide addon-wrap-520-language-0-0">
  <label><input type="radio" class="addon addon-radio" name="addon-520-language-0[]" data-raw-price="" data-price="" value="spanish"  /> Spanish </label>
</p></code>```

For the numeric field, I put the id into the Javascript, but the radio button doesn't have an id. I can't tweak the HTML, because it's generated, and this doesn't seem like something that would require getting into the PHP.

What am I missing?

答:
Solved. Here's the line I needed:

     jQuery( "input[name='addon-520-language-0[]'][value='spanish']" ).prop('checked',true);```

Body:
I'm working on a WC Appointment Bookings product, and I managed to set up a default for a simple numeric field using a custom script:

// Set default value to 0 for Input multiplier (for additional hours)
jQuery(document).ready(function(){
    jQuery('.addon-input_multiplier').val("0");
});

But I can't tweak that script to set a radio button to be a default. Here's the HTML of the button I want to make the default...

  <input type="radio" class="addon addon-radio" name="addon-520-language-0[]" data-raw-price="" data-price="" value="spanish"  /> Spanish

For the numeric field, I put the id into the Javascript, but the radio button doesn't have an id. I can't tweak the HTML, because it's generated, and this doesn't seem like something that would require getting into the PHP.

What am I missing?


问:
boost shared pointer custom deleter example
I'm using the libmodbus library. i need to pass instances of the modbus_t pointer between threads. I am having difficulty with just raw pointers and I think i can solve the problem with using boost_shared_ptr with custom deleter.

i don't get any compiler issues but when i run the program it crashes.
i was hoping if someone can give me a usage example of boost shared pointer with custom deleter.

the program crashes at line where m_mb.reset() is called the first time in the OpenModBusConnection() function.

```<code>m_mb = boost::shared_ptr<modbus_t>( modbus_new_rtu(m_heatercomport.c_str(),9600,'N',8,1), freemodbus);

    void freemodbus(modbus_t *mb)
    {
       if(mb != NULL)
       {
          modbus_close(mb);
          modbus_free(mb);
       }
    }

    void OpenModBusConnection()
    {
        if(m_mb.get() != NULL)
        {
            wxString msg("Closing port \"");
            msg.append(m_heatercomport);
            msg.append("\" modbus port ");
            wxLogMessage(msg);

            readoutput->AppendText("Modbus Connection Closed\n");

            m_mb.reset();

        }

        // open modbus connection
        m_mb.reset();
        modbus_set_slave(m_mb.get(),1);

        if(modbus_connect(m_mb.get()) == -1)
        {
            wxString msg("Failed to open port \"");
            msg.append(m_heatercomport);
            msg.append("\" modbus port ");
            wxLogMessage(msg);

            readoutput->AppendText("Modbus Connection Failed\n");

            return false;
        }
        else
        {
            wxString msg("Opening port \"");
            msg.append(m_heatercomport);
            msg.append("\" modbus port ");
            wxLogMessage(msg);

            readoutput->AppendText("Modbus Connection Established\n");

            return true;
        }
    }
</code>```

error message i get is

```<code>First-chance exception at 0x7717bb47 in test.exe: 0xC0000008: An invalid handle was specified.
</code>```

答:
```<code>m_mb.reset();
modbus_set_slave(m_mb.get(),1);

if(modbus_connect(m_mb.get()) == -1)
</code>```

This is effectively the same as

```<code>m_mb.reset();
modbus_set_slave(nullptr,1);

if(modbus_connect(nullptr) == -1)
</code>```

If you want to free and reset the m_mb back to a fresh modbus handle you need to do

```<code>m_mb = boost::shared_ptr<modbus_t>( modbus_new_rtu(m_heatercomport.c_str(),9600,'N',8,1), freemodbus);
</code>```

again expliticly.

Body:
I'm using the libmodbus library. i need to pass instances of the modbus_t pointer between threads. I am having difficulty with just raw pointers and I think i can solve the problem with using boost_shared_ptr with custom deleter.

i don't get any compiler issues but when i run the program it crashes.
i was hoping if someone can give me a usage example of boost shared pointer with custom deleter.

the program crashes at line where m_mb.reset() is called the first time in the OpenModBusConnection() function.

m_mb = boost::shared_ptr<modbus_t>( modbus_new_rtu(m_heatercomport.c_str(),9600,'N',8,1), freemodbus);

    void freemodbus(modbus_t *mb)
    {
       if(mb != NULL)
       {
          modbus_close(mb);
          modbus_free(mb);
       }
    }

    void OpenModBusConnection()
    {
        if(m_mb.get() != NULL)
        {
            wxString msg("Closing port \"");
            msg.append(m_heatercomport);
            msg.append("\" modbus port ");
            wxLogMessage(msg);

            readoutput->AppendText("Modbus Connection Closed\n");

            m_mb.reset();

        }

        // open modbus connection
        m_mb.reset();
        modbus_set_slave(m_mb.get(),1);

        if(modbus_connect(m_mb.get()) == -1)
        {
            wxString msg("Failed to open port \"");
            msg.append(m_heatercomport);
            msg.append("\" modbus port ");
            wxLogMessage(msg);

            readoutput->AppendText("Modbus Connection Failed\n");

            return false;
        }
        else
        {
            wxString msg("Opening port \"");
            msg.append(m_heatercomport);
            msg.append("\" modbus port ");
            wxLogMessage(msg);

            readoutput->AppendText("Modbus Connection Established\n");

            return true;
        }
    }

error message i get is

First-chance exception at 0x7717bb47 in test.exe: 0xC0000008: An invalid handle was specified.

Body:
m_mb.reset();
modbus_set_slave(m_mb.get(),1);

if(modbus_connect(m_mb.get()) == -1)

This is effectively the same as

m_mb.reset();
modbus_set_slave(nullptr,1);

if(modbus_connect(nullptr) == -1)

If you want to free and reset the m_mb back to a fresh modbus handle you need to do

m_mb = boost::shared_ptr<modbus_t>( modbus_new_rtu(m_heatercomport.c_str(),9600,'N',8,1), freemodbus);

again expliticly.


问:
Spark dataset. Group struct column in array
I have two json files that I want to combine.

They look like this:

Elements:

```<code>{
  "id" : 1,
  "style": {
      "availableColors": [1,3,5,8]
      "material" : "Iron"
       .
       .
       .
      }
  .
  .
  .
}
</code>```

Colors:

```<code>{
  "colorId" : 1,
  "definition": {
      "R": 13,
      "G" : 23,
      "B" : 4
      }
   "tags": ["...", "..."]
  .
  .
  .
}
</code>```

I've converted each in a DF and I am joining them as follows:

```<code>val joined = elemDF.join(colorDF, $"style.id".cast("string").contains($"colorId"))
</code>```

But in that case each id has as many entries as colorIds.

How can I "group" the colors inside an array, so in the end it would be like adding an array of color structs to each element?

Maybe using a udf instead of joining the dataframes?

I would like to avoid using classes to represent the rows, as the json can have many fields and levels which I should not care at this point.

答:
Finally got a solution. I'll add it in case anyone has the same problem.</p>

```<code>def toColumns(colNames: Array[String]) = {
  colNames.map(x => col(x))
}

val joined = elemDF.join(colorDF, $"style.id".cast("string").contains($"colorId"))
                   .withColumn("color",
                            struct(toColumns(colorDF.schema.fieldNames): _*)

joined.groupBy(toColumns(elemDF.schema.fieldNames): _*)
      .agg(collect_list($"color").as("colors"))
</code>```

Body:
I have two json files that I want to combine.

They look like this:

Elements:

{
  "id" : 1,
  "style": {
      "availableColors": [1,3,5,8]
      "material" : "Iron"
       .
       .
       .
      }
  .
  .
  .
}

Colors:

{
  "colorId" : 1,
  "definition": {
      "R": 13,
      "G" : 23,
      "B" : 4
      }
   "tags": ["...", "..."]
  .
  .
  .
}

I've converted each in a DF and I am joining them as follows:

val joined = elemDF.join(colorDF, $"style.id".cast("string").contains($"colorId"))

But in that case each id has as many entries as colorIds.

How can I "group" the colors inside an array, so in the end it would be like adding an array of color structs to each element?

Maybe using a udf instead of joining the dataframes?

I would like to avoid using classes to represent the rows, as the json can have many fields and levels which I should not care at this point.

Body:
Finally got a solution. I'll add it in case anyone has the same problem.

def toColumns(colNames: Array[String]) = {
  colNames.map(x => col(x))
}

val joined = elemDF.join(colorDF, $"style.id".cast("string").contains($"colorId"))
                   .withColumn("color",
                            struct(toColumns(colorDF.schema.fieldNames): _*)

joined.groupBy(toColumns(elemDF.schema.fieldNames): _*)
      .agg(collect_list($"color").as("colors"))


问:
Sending Advanced Parameters to ASP.Net MVC
I don't know how to phrase this question properly but basically I haven an ASP.Net Application. I send the following request to the controller from my view:

```<code>http://localhost:59112/Contacts/IndexJson?current=1&rowCount=50&sort%5BLastName%5D=desc&searchPhrase=&_=1490960196673
</code>```

I have written two classes that are not working 100% as follows for a structure for this request data:

```<code>public class RequestData
{
    public int current { get; set; }
    public int rowCount { get; set; }
    public string searchPhrase { get; set; }
    public IEnumerable<SortData> sortItems { get; set; }
}
public class SortData
{
    public string Field { get; set; } // FIeld Name
    public string Type { get; set; } // ASC or DESC
}
</code>```

Then in my controller I have the following:

```<code>public JsonResult IndexJson(RequestData model)
{
    /* Irrelevant code */
}
</code>```

The model works and fills everything correctly except the sortItems returns null. How can I get the sortItems Field and Type defined in my class?

Since the parameter coming in from the RequestData is sort[Field]=Type.

Edit

I changed my RequestData class to this:

```<code>public class RequestData
{
    public int current { get; set; }
    public int rowCount { get; set; }
    public Dictionary<string, string> sort { get; set; }
    public string searchPhrase { get; set; }
    public Guid id { get; set; }
}
</code>```

Now the model holds the sort as {[Field, Type]} (an example of data).

If this is a good practice, how to I access Field and Type?

答:
You can achieve this a number of different ways; your problem in each case was simply not following the modelbinder conventions for that data type.

First and foremost, IEnumerable is out if you intend to post back to it. It's not an indexable type, so the modelbinder will never be able to bind to it. However, using something like List instead, is just fine. Then, your param names simply need to be in the format of: ListProperty[N].Property, where N is the index. So for your situation you could have used sortItems[0].Field=LastName&sortItems[0].Type=desc, and it would have bound just fine to your model.

For using a dictionary, your names should be in the format of DictionaryProperty[N].Key and DictionaryProperty[N].Value, where again, N is the index. In your scenarion that would look like sort[0].Key=LastName&sort[0].Value=desc.

ContentLicense: CC BY-SA 4.0

Body:
I don't know how to phrase this question properly but basically I haven an ASP.Net Application. I send the following request to the controller from my view:

http://localhost:59112/Contacts/IndexJson?current=1&rowCount=50&sort%5BLastName%5D=desc&searchPhrase=&_=1490960196673

I have written two classes that are not working 100% as follows for a structure for this request data:

public class RequestData
{
    public int current { get; set; }
    public int rowCount { get; set; }
    public string searchPhrase { get; set; }
    public IEnumerable<SortData> sortItems { get; set; }
}
public class SortData
{
    public string Field { get; set; } // FIeld Name
    public string Type { get; set; } // ASC or DESC
}

Then in my controller I have the following:

public JsonResult IndexJson(RequestData model)
{
    /* Irrelevant code */
}

The model works and fills everything correctly except the sortItems returns null. How can I get the sortItems Field and Type defined in my class?

Since the parameter coming in from the RequestData is sort[Field]=Type.

Edit

I changed my RequestData class to this:

public class RequestData
{
    public int current { get; set; }
    public int rowCount { get; set; }
    public Dictionary<string, string> sort { get; set; }
    public string searchPhrase { get; set; }
    public Guid id { get; set; }
}

Now the model holds the sort as {[Field, Type]} (an example of data).

If this is a good practice, how to I access Field and Type?


问:
Error ng new projectName
I have updated me angular version to 4, but since i have a probelm to create new project with angular/cli, i know that the problem is a bout a packag.json file in my home directory how must be deleted but i cannot know how to find it.

```<code>@angular/cli: 1.0.0
node: 7.6.0
os: linux x64
@angular/animations: 4.0.1
@angular/common: 4.0.1
@angular/compiler: 4.0.1
@angular/compiler-cli: 4.0.1
@angular/core: 4.0.1
@angular/forms: 4.0.1
@angular/http: 4.0.1
@angular/platform-browser: 4.0.1
@angular/platform-browser-dynamic: 4.0.1
@angular/platform-server: 4.0.1
@angular/router: 4.0.1
@angular/cli: 1.0.0
</code>```

in the terminal:

```<code> ng new test4
 You cannot use the new command inside an Angular CLI project.
</code>```

Thanks for your help

答:
I found the error, i have a package.json
file in my home directory, when I delete this file everything working well

thanks

Title: Error ng new projectName

Body:
I have updated me angular version to 4, but since i have a probelm to create new project with angular/cli, i know that the problem is a bout a packag.json file in my home directory how must be deleted but i cannot know how to find it.

@angular/cli: 1.0.0
node: 7.6.0
os: linux x64
@angular/animations: 4.0.1
@angular/common: 4.0.1
@angular/compiler: 4.0.1
@angular/compiler-cli: 4.0.1
@angular/core: 4.0.1
@angular/forms: 4.0.1
@angular/http: 4.0.1
@angular/platform-browser: 4.0.1
@angular/platform-browser-dynamic: 4.0.1
@angular/platform-server: 4.0.1
@angular/router: 4.0.1
@angular/cli: 1.0.0

in the terminal:

 ng new test4
 You cannot use the new command inside an Angular CLI project.

Thanks for your help


问:
iphone click to call from app in OS 4.0 does not prompt for confirmation
I am using the click to call feature in the iPhone App to call a number when the user clicks on a link.

```<code>  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://tel:%@",selectedPhoneNumber]];
</code>```

In iPhone 3Gs this prompts the user "Are you sure you want to call..."

But in iPhone 4 this does not prompt but instead directly makes the call.

Is there any way I can set this to prompt the user in iPhone 4 also?

答:
You can check the device hardware and show an alert if the device is iPhone 4.

See this post: Determine device (iPhone, iPod Touch) with iPhone SDK

Body:
I am using the click to call feature in the iPhone App to call a number when the user clicks on a link.

  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://tel:%@",selectedPhoneNumber]];

In iPhone 3Gs this prompts the user "Are you sure you want to call..."

But in iPhone 4 this does not prompt but instead directly makes the call.

Is there any way I can set this to prompt the user in iPhone 4 also?


问:
How to get rid of duplicates in a graph
I'm building a social graph from a list of tuples 'friends' like this:

```<code>(4118181 {'last_name': 'Belousov', 'first_name': 'Mikhail'})
</code>```

Here's the function:

```<code>def addToGraph (g, start, friends):
    g.add_nodes_from(friends)
    egdes_to_add = [(start, entry[0]) for entry in friends]
    g.add_edges_from(edges_to_add)
    return g
</code>```

As a result I get a graph with duplicated amount of nodes, the 1st with attributes, coming from

```<code>g.add_nodes_from(friends)
</code>```

and the second is from

```<code> g.add_edges_from(edges_to_add)
</code>```

I read the docs, but can't figure out, how can I add both nodes with attributes and edges between those nodes?

答:
So your function adds edges between the node start and every node in friends. I tried your code and I don't get any duplicate nodes. Here is my full example (note that I corrected a couple of errors in your code).

```<code>import networkx as nx

friends = [
    (4118181, {'last_name': 'Belousov', 'first_name': 'Mikhail'}),
    (1111111, {'last_name': 'A', 'first_name': 'B'}),
    (2222222, {'last_name': 'C', 'first_name': 'D'}),
    (3333333, {'last_name': 'E', 'first_name': 'F'})
]

def addToGraph(g, start, friends):
    g.add_nodes_from(friends)
    edges_to_add = [(start, entry[0]) for entry in friends]
    g.add_edges_from(edges_to_add)

G = nx.Graph()
addToGraph(G, 4118181, friends)

print('Nodes:', G.nodes())
print('Edges:', G.edges())
</code>```

Output:

```<code>Nodes: [3333333, 4118181, 2222222, 1111111]
Edges: [(3333333, 4118181), (4118181, 4118181), (4118181, 2222222), (4118181, 1111111)]
</code>```

Title: How to get rid of duplicates in a graph

Body:
I'm building a social graph from a list of tuples 'friends' like this:

(4118181 {'last_name': 'Belousov', 'first_name': 'Mikhail'})

Here's the function:

def addToGraph (g, start, friends):
    g.add_nodes_from(friends)
    egdes_to_add = [(start, entry[0]) for entry in friends]
    g.add_edges_from(edges_to_add)
    return g

As a result I get a graph with duplicated amount of nodes, the 1st with attributes, coming from

g.add_nodes_from(friends)

and the second is from

 g.add_edges_from(edges_to_add)

I read the docs, but can't figure out, how can I add both nodes with attributes and edges between those nodes?

Body:
So your function adds edges between the node start and every node in friends. I tried your code and I don't get any duplicate nodes. Here is my full example (note that I corrected a couple of errors in your code).

import networkx as nx

friends = [
    (4118181, {'last_name': 'Belousov', 'first_name': 'Mikhail'}),
    (1111111, {'last_name': 'A', 'first_name': 'B'}),
    (2222222, {'last_name': 'C', 'first_name': 'D'}),
    (3333333, {'last_name': 'E', 'first_name': 'F'})
]

def addToGraph(g, start, friends):
    g.add_nodes_from(friends)
    edges_to_add = [(start, entry[0]) for entry in friends]
    g.add_edges_from(edges_to_add)

G = nx.Graph()
addToGraph(G, 4118181, friends)

print('Nodes:', G.nodes())
print('Edges:', G.edges())

Output:

Nodes: [3333333, 4118181, 2222222, 1111111]
Edges: [(3333333, 4118181), (4118181, 4118181), (4118181, 2222222), (4118181, 1111111)]


问:
Getting price from JSON
I'm trying to get the JSON key and value called price. I can get the key but the price is just undefined.

```<code>    for(var item in prices.response){
        console.log(item);
        console.log(prices.response.price)
    }
</code>```

Snippet of JSON

```<code>"response": {
    "AK-47 | Aquamarine Revenge (Battle-Scarred)": {
        "price": 962,
        "quantity": 192
    }
</code>```

答:
You are iterating over object so item is name of object property not value. Try this

```<code>for(var key in prices.response){
    console.log(key);
    console.log(prices.response[key].price)
}
</code>```

Title: Getting price from JSON

Body:
I'm trying to get the JSON key and value called price. I can get the key but the price is just undefined.

    for(var item in prices.response){
        console.log(item);
        console.log(prices.response.price)
    }

Snippet of JSON

"response": {
    "AK-47 | Aquamarine Revenge (Battle-Scarred)": {
        "price": 962,
        "quantity": 192
    }

Body:
You are iterating over object so item is name of object property not value. Try this

for(var key in prices.response){
    console.log(key);
    console.log(prices.response[key].price)
}


问:
I used Adapter class to inflate the RecyclerView-Mainactivity. How can I navigate from X-Activity(navigated from adapter class) to MainActivity
I used an Adapter class to inflate the RecyclerView which is in MainActivity. When I click on the sub-item of the RecyclerView it navigated to SomeOtherActivity. Now I want to navigate back to MainActivity and change the sub-item (RecyclerAdapter). How can I access the RecyclerAdapter class? How can I access the list item using MyViewHolder?

答: Not getting your question. By default back press will lead to your desired activity. If not then override onBackPressed() method of Activity class. If not solved then elaborate more.</p>


问:
Java Choco solver error (IntVar read as Int)
I'm trying to use java choco solver, a CP solver, to color a graph. However i can't seem to get it to work. Even the code in the tutorial doesn't work:

```<code>    int n = 8;
    Model model = new Model(n + "-queens problem");
    IntVar[] vars = new IntVar[n];
    for(int q = 0; q < n; q++){
        vars[q] = (IntVar) model.intVar("Q_"+q, 1, n);
    }
    for(int i  = 0; i < n-1; i++){
        for(int j = i + 1; j < n; j++){
            model.arithm(vars[i], "!=",vars[j]).post();
            model.arithm(vars[i], "!=", vars[j], "-", j - i).post();
            model.arithm(vars[i], "!=", vars[j], "+", j - i).post();
        }
    }
    Solution solution = model.getSolver().findSolution();
    if(solution != null){
        System.out.println(solution.toString());
    }
</code>```

I always get the folowing error:

The method arithm(IntVar, String, int) in the type IIntConstraintFactory is not applicable for the arguments (IntVar, String, IntVar), which i don't understand because vars[j], should be an IntVar.

I hope someone can help!

Kind Regards,

Nicholas

答:
Your code works for me! Maybe your IDE is not well configured. I do not understand the error message because there is a method model.arithm(IntVar, String, IntVar)... Do you see it in the source code when ctrl+click on it? Can you show your imports?

PS: The cast in IntVar is useless (if your IDE asks for it, then you have a configuration issue).

Body:
I'm trying to use java choco solver, a CP solver, to color a graph. However i can't seem to get it to work. Even the code in the tutorial doesn't work:

    int n = 8;
    Model model = new Model(n + "-queens problem");
    IntVar[] vars = new IntVar[n];
    for(int q = 0; q < n; q++){
        vars[q] = (IntVar) model.intVar("Q_"+q, 1, n);
    }
    for(int i  = 0; i < n-1; i++){
        for(int j = i + 1; j < n; j++){
            model.arithm(vars[i], "!=",vars[j]).post();
            model.arithm(vars[i], "!=", vars[j], "-", j - i).post();
            model.arithm(vars[i], "!=", vars[j], "+", j - i).post();
        }
    }
    Solution solution = model.getSolver().findSolution();
    if(solution != null){
        System.out.println(solution.toString());
    }

I always get the folowing error:

The method arithm(IntVar, String, int) in the type IIntConstraintFactory is not applicable for the arguments (IntVar, String, IntVar), which i don't understand because vars[j], should be an IntVar.

I hope someone can help!

Kind Regards,

Nicholas


问:
Sort descending based on part of a title in Wordpress?
I'm having an issue how to sort a title in Wordpress. If I just know how I would solve this in MySQL it would be great. (If someone has an answer specific for wordpress that would be a lot easier for me though)

I have a database where the title (one field in the database-table) is called post_title. The title stores name AND year with a space between

eg.

```<code>Sweden 2017
Sweden 2016
Norway 2018
Norway 2019
</code>```

I want to sort above like this: (descending by year and ascending by name)

```<code>Norway 2019
Norway 2018
Sweden 2017
Sweden 2016
</code>```

UPDATE:
I've tried with Wordpress-builtin sorting with WP_Query:

```<code>$module_args = array(
                'posts_per_page' => -1,
                'post_type' => 'project',
                'include_children' => false,
                'orderby' => 'title',
                'order' => 'DESC',
                'no_found_rows' => true          //No pagination needed
            );

//Do the filtering and retrieve all projects with current service
$projects = get_posts( $module_args );
</code>```

but then I get this result:

```<code>Yacht 2011
Vasastan 2008
Ulrikagatan 2008
Thailand 2010 (?)
Strandvägen 2007
</code>```

but it should be:

```<code>Yacht 2011
Thailand 2010
Ulrikagatan 2008
Vasastan 2008
Strandvägen 2007
</code>```

答:
Thanks all for your input! It was of good help when coming up with a solution.

This is my solution:

```<code>$newsort_projects = array();
foreach ( $projects as $key_item=>$arr_item)
{
    $title = $arr_item->post_title;
    $year_title = substr($title,-4,4);

    $newsort_projects[] = array(
        'ID' => $arr_item->ID,
        'year'=>$year_title
    );

    }
    usort($newsort_projects, array($this, 'sort_by_year'));

    $newarr_projects = array();
    foreach ( $newsort_projects as $key_item=>$arr_item )
    {
        foreach($projects as $pkey => $p)
        {
            if ($arr_item['ID'] == $p->ID) {
                $key_to_add = $pkey;
                break;
             }
         }
         $newarr_projects[] = $projects[$key_to_add];
    }
</code>```

and then I had a function in the class that sorts the mutlidimensional array by key year:

```<code>private function sort_by_year($a, $b) {
       return $b['year']-$a['year'];
}
</code>```

Body:
I'm having an issue how to sort a title in Wordpress. If I just know how I would solve this in MySQL it would be great. (If someone has an answer specific for wordpress that would be a lot easier for me though)

I have a database where the title (one field in the database-table) is called post_title. The title stores name AND year with a space between

eg.

Sweden 2017
Sweden 2016
Norway 2018
Norway 2019

I want to sort above like this: (descending by year and ascending by name)

Norway 2019
Norway 2018
Sweden 2017
Sweden 2016

UPDATE:
I've tried with Wordpress-builtin sorting with WP_Query:

$module_args = array(
                'posts_per_page' => -1,
                'post_type' => 'project',
                'include_children' => false,
                'orderby' => 'title',
                'order' => 'DESC',
                'no_found_rows' => true          //No pagination needed
            );

//Do the filtering and retrieve all projects with current service
$projects = get_posts( $module_args );

but then I get this result:

Yacht 2011
Vasastan 2008
Ulrikagatan 2008
Thailand 2010 (?)
Strandvägen 2007

but it should be:

Yacht 2011
Thailand 2010
Ulrikagatan 2008
Vasastan 2008
Strandvägen 2007

Body:
Thanks all for your input! It was of good help when coming up with a solution.

This is my solution:

$newsort_projects = array();
foreach ( $projects as $key_item=>$arr_item)
{
    $title = $arr_item->post_title;
    $year_title = substr($title,-4,4);

    $newsort_projects[] = array(
        'ID' => $arr_item->ID,
        'year'=>$year_title
    );

    }
    usort($newsort_projects, array($this, 'sort_by_year'));

    $newarr_projects = array();
    foreach ( $newsort_projects as $key_item=>$arr_item )
    {
        foreach($projects as $pkey => $p)
        {
            if ($arr_item['ID'] == $p->ID) {
                $key_to_add = $pkey;
                break;
             }
         }
         $newarr_projects[] = $projects[$key_to_add];
    }

and then I had a function in the class that sorts the mutlidimensional array by key year:

private function sort_by_year($a, $b) {
       return $b['year']-$a['year'];
}


问:
OpenCV Error: Assertion failed in matrix.cpp line 522, /matrix.cpp:522: error: (-215)
I am trying to create an ROI above the face detected to place a hat like shown in the image: Plz click here : ROI created above face to place a hat

I have made sure that the ROI created is withing the bounds of the image. It looks like this:
 // Create an ROI
 // where face is the detected face ROI

```<code>    if (0<=face.x && 0<=face.x-face.width*0.08<=image.cols && 0<=face.x+face.width+face.width*0.08<=image.cols
         && 0<=face.y && 0<=face.y-face.height*0.28<=image.rows)
    {
      Mat ROI_hat = image(Rect(abs(face.x-face.width*0.08),abs(face.y-face.height*0.28),abs(face.x+face.width+face.width*0.08),abs(face.y)));
      rectangle(image,Point(abs(face.x-face.width*0.08),abs(face.y-face.height*0.28)),Point(abs(face.x+face.width+face.width*0.08),abs(face.y)),Scalar(255, 0, 0), 1, 4);

      cout<<"Within the bounds of Image"<<endl;
    }
    else{
     cout<<" Out of bounds of Image "<<endl;
        }
</code>```

There are no negative values and for every frame it says ROI is withing the bounds. But I still get assertion error:

OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in Mat, file /home/user/OpenCV_Installed/opencv-3.2.0/modules/core/src/matrix.cpp, line 522 terminate called after throwing an instance of 'cv::Exception' what(): /home/user/OpenCV_Installed/opencv-3.2.0/modules/core/src/matrix.cpp:522: error: (-215) 0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows in function Mat Aborted (core dumped)

Can someone please tell me where I'm going wrong?

答:
The error means that your ROI is outside of the image, so your conditions are wrong.

Since it's pretty easy to get confused, I usually apply this small trick that is based on the intersection of the roi with a dummy roi roiImg that contains all the image:

```<code>Rect roiImg(0, 0, image.cols, image.rows);
Rect roi = ... // Very complex way of setting up the ROI

if( (roi.area() > 0) && ((roiImg & roi).area() == roi.area()) ) {
    // roi is inside the image, and is non-empty
    // VALID roi
} else {
    // roi is at least partially outside of the image, or it's empty
    // INVALID roi
}
</code>```

Body:
I am trying to create an ROI above the face detected to place a hat like shown in the image: Plz click here : ROI created above face to place a hat

I have made sure that the ROI created is withing the bounds of the image. It looks like this:
 // Create an ROI
 // where face is the detected face ROI

    if (0<=face.x && 0<=face.x-face.width*0.08<=image.cols && 0<=face.x+face.width+face.width*0.08<=image.cols
         && 0<=face.y && 0<=face.y-face.height*0.28<=image.rows)
    {
      Mat ROI_hat = image(Rect(abs(face.x-face.width*0.08),abs(face.y-face.height*0.28),abs(face.x+face.width+face.width*0.08),abs(face.y)));
      rectangle(image,Point(abs(face.x-face.width*0.08),abs(face.y-face.height*0.28)),Point(abs(face.x+face.width+face.width*0.08),abs(face.y)),Scalar(255, 0, 0), 1, 4);

      cout<<"Within the bounds of Image"<<endl;
    }
    else{
     cout<<" Out of bounds of Image "<<endl;
        }

There are no negative values and for every frame it says ROI is withing the bounds. But I still get assertion error:

OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in Mat, file /home/user/OpenCV_Installed/opencv-3.2.0/modules/core/src/matrix.cpp, line 522 terminate called after throwing an instance of 'cv::Exception' what(): /home/user/OpenCV_Installed/opencv-3.2.0/modules/core/src/matrix.cpp:522: error: (-215) 0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows in function Mat Aborted (core dumped)

Can someone please tell me where I'm going wrong?

Body:
The error means that your ROI is outside of the image, so your conditions are wrong.

Since it's pretty easy to get confused, I usually apply this small trick that is based on the intersection of the roi with a dummy roi roiImg that contains all the image:

Rect roiImg(0, 0, image.cols, image.rows);
Rect roi = ... // Very complex way of setting up the ROI

if( (roi.area() > 0) && ((roiImg & roi).area() == roi.area()) ) {
    // roi is inside the image, and is non-empty
    // VALID roi
} else {
    // roi is at least partially outside of the image, or it's empty
    // INVALID roi
}


问:
z-index issue in ie
i know this issue is well documented but i cant find a working solution from what ive been reading. I have a pretty large site and i want a div to sit ontop of everything else on the site. now ive tried giving the div "position:absolute; z-index:99999;", this will work in everything apart from ie. How can i do this in ie?

答:
so i tried this jquery script i found

```<code>$(function () {
    var zIndexNumber = 1000;
   $('div').each(function () {

        $(this).css('zIndex', zIndexNumber);
        zIndexNumber -= 10;
    });
});
</code>```

i added another wrapper around it to check if the broswer is ie before hand. this seems to fix the issue but does mean pages are slower loading in ie as every div is being treated. when the page loads.

Title: z-index issue in ie

Body:
so i tried this jquery script i found

$(function () {
    var zIndexNumber = 1000;
   $('div').each(function () {

        $(this).css('zIndex', zIndexNumber);
        zIndexNumber -= 10;
    });
});

i added another wrapper around it to check if the broswer is ie before hand. this seems to fix the issue but does mean pages are slower loading in ie as every div is being treated. when the page loads.


问:
Cleanest way to copy Hibernate entities like POJOs in another project
I have multi-module Maven project:

JPA module (Hibernate implementation) with Annotated Entities.

Rest-Service module - have dependency to module 1. and Endpoints serialize JSON using Entities from module 1.

Rest-Client module: This library is based on retrofit2 (this jar library is used in Java-EE web project and Android too) and for deserializing JSON model its needs to have dependency to module 1. too. But here Entities needs to be simple POJOs (without JPA annotations)

I don`t want module 3 to have dependency to module 1 and include all Hibernate jars in RestClient (its not need it).

I don`t want to copy Entities only in module 3 and manually to remove annotations.. It`s hard to change Entities next in two places.

I`m trying with Maven Dependency plugin to copy Entities only.. but its not clear if its possible to remove annotations with this plugin? and is this the most cleanest way of doing it?

答:
After many researches I have add swagger support to my RestService:

https://github.com/zhouhao/swagger-spring-boot-jersey

Rest Client module is generated with swagger-codegen-maven-plugin for Java and swagger-codegen-gradle-plugin for Android Gradle project.
This is my configuration for gradle-plugin:

```<code>swagger {
    inputSpec = 'http://petstore.swagger.io/v2/swagger.json'

    outputDir = "${rootDir}/swagger-client"
    lang = 'java'

        additionalProperties = [
                'groupId'           : 'com.orgname',
                'artifactId'        : 'swagger-java-client',
                'artifactVersion'   : '1.0.0',
                'invokerPackage'    : 'com.orgname.client.retrofit2',
                'modelPackage'      : 'com.orgname.client.retrofit2.model',
                'apiPackage'        : 'com.orgname.client.retrofit2.api',
                'library'           : 'retrofit2',
                'useRxJava2'        : 'true',
                'useGzipFeature'    : 'true',
                'serializableModel' : 'true',
                'dateLibrary'       : 'java7',
                'templateDir'       : "src/main/resources/Java/libraries/retrofit2"
        ]
    }
</code>```

Model is generated from RestService and there is not need to have dependency to Hibernate Entities model and I think that this is the cleanest way with minimum human effort.

Body:
After many researches I have add swagger support to my RestService:

https://github.com/zhouhao/swagger-spring-boot-jersey

Rest Client module is generated with swagger-codegen-maven-plugin for Java and swagger-codegen-gradle-plugin for Android Gradle project.
This is my configuration for gradle-plugin:

swagger {
    inputSpec = 'http://petstore.swagger.io/v2/swagger.json'

    outputDir = "${rootDir}/swagger-client"
    lang = 'java'

        additionalProperties = [
                'groupId'           : 'com.orgname',
                'artifactId'        : 'swagger-java-client',
                'artifactVersion'   : '1.0.0',
                'invokerPackage'    : 'com.orgname.client.retrofit2',
                'modelPackage'      : 'com.orgname.client.retrofit2.model',
                'apiPackage'        : 'com.orgname.client.retrofit2.api',
                'library'           : 'retrofit2',
                'useRxJava2'        : 'true',
                'useGzipFeature'    : 'true',
                'serializableModel' : 'true',
                'dateLibrary'       : 'java7',
                'templateDir'       : "src/main/resources/Java/libraries/retrofit2"
        ]
    }

Model is generated from RestService and there is not need to have dependency to Hibernate Entities model and I think that this is the cleanest way with minimum human effort.


问:
generating json from bad mysql-formatted dates in asp
I was thrown in a new project, which is apparently more than just oudated. The application saves opening hours in a very weird pattern in the DB and this is driving me crazy for over a week now.

Please have a look at this image:

As you might see, the opening hours are saved in a pattern like:

```<code>dayFrom  | dayTo  | timeFrom | timeTo
=======================================
monday   | friday | 07:00    | 17:00
saturday |        | 08:00    | 12:00
</code>```

Just to prevent any misunderstanding:

Open MO - FR from 07:00 to 17:00

Open SA from 08:00 to 12:00

Closed on Sunday

Now, this seems to be kinda off already, but sticking with that, a table could look like this:

```<code>dayFrom   | dayTo   | timeFrom | timeTo
=======================================
monday    | tuesday | 07:00    | 14:00
wednesday |         | 08:00    | 12:00
thursday  | friday  | 07:30    | 13:00
saturday  |         | 08:00    | 12:00
</code>```

So, now my problem: I need to make a loop (or something like this) to create a valid json-string, containing all these opening hours.

Right now, I have this:

jsonAppendix = "{""openingHours"":["
for i = 1 To cint(hoechsterTag)
    jsonAppendix = jsonAppendix & "{""dayOfWeek"":" & i & ", ""from1"":""" & rs("ZeitVon") & """, ""to1"":""" & rs("ZeitBis") & """},"
next
'Remove last comma
jsonAppendix = LEFT(jsonAppendix, (LEN(jsonAppendix)-1))
jsonAppendix = jsonAppendix & "]}"
```
<p>If I have only a "monday-friday", it works already, but the 2nd (or next entries) aren't taken into account.</p>
<p>The output looks like this, which is apparently kinda correct:</p>
```{
    "openingHours":[
        {
            "dayOfWeek":1,
            "from1":"07:00",
            "to1":"17:00"
        },
        {
            "dayOfWeek":2,
            "from1":"07:00",
            "to1":"17:00"
        },
        {
            "dayOfWeek":3,
            "from1":"07:00",
            "to1":"17:00"
        },
        {
            "dayOfWeek":4,
            "from1":"07:00",
            "to1":"17:00"
        },
        {
            "dayOfWeek":5,
            "from1":"07:00",
            "to1":"17:00"
        }
    ]
}
```
<p>But the "Saturday" is not being recognized.</p>
<p>My function looks like this:</p>
<pre class="lang-vb prettyprint-override"><code>SQL = "SELECT * FROM StandortOpen WHERE S_ID = " & iStandortId & " AND OpenArt = '" & sArt & "' ORDER BY Sort,OpenArt DESC"
call openRS(SQL)

'day-mapping
tageV(0) = replace(rs("TagVon"),"Mo", 1)
tageV(1) = replace(rs("TagVon"),"Di", 2)
tageV(2) = replace(rs("TagVon"),"Mi", 3)
tageV(3) = replace(rs("TagVon"),"Do", 4)
tageV(4) = replace(rs("TagVon"),"Fr", 5)
tageV(5) = replace(rs("TagVon"),"Sa", 6)
tageV(6) = 7

tageB(0) = replace(rs("TagBis"),"Mo", 1)
tageB(1) = replace(rs("TagBis"),"Di", 2)
tageB(2) = replace(rs("TagBis"),"Mi", 3)
tageB(3) = replace(rs("TagBis"),"Do", 4)
tageB(4) = replace(rs("TagBis"),"Fr", 5)
tageB(5) = replace(rs("TagBis"),"Sa", 6)

'for example: mo - fr
for each item in tageV
    'save smallest weekday
    if(isNumeric(item) AND item > "") then
        if(cint(item) <= cint(niedrigsterTag)) then
            niedrigsterTag = cint(item)
        end if
    end if
next

for each item in tageB
    'save highest weekday
    if(isNumeric(item) AND item > "") then
        if(cint(item) >= cint(hoechsterTag)) then
            hoechsterTag = cint(item)
        end if
    end if
next
</code>```

And the openRS()-Function:

sub openRS(str_sql)
'Response.write "SQL: " & str_sql & "
"
set rs = CreateObject("ADODB.Recordset")
rs.open str_sql,conn,1,3
end sub
```

So basically: Mapping numbers to the days, iterating through (or compare them to get a timespan).

I'm using a RecordSet as well. Maybe I need to use arrays or something like this? Any help would be really appreciated.

I can't alter the table nor the design of that, I have to stick with that gargabe

答:
If you want to create the dataset in SQL Server, consider the following

Example

Declare @YourTable table (dayFrom varchar(25),dayTo varchar(25),timeFrom varchar(25),timeTo varchar(25))
Insert Into @YourTable values
('monday'   ,'tuesday','07:00','14:00'),
('wednesday',''       ,'08:00','12:00'),
('thursday' ,'friday' ,'07:30','13:00'),
('saturday' ,''       ,'08:00','12:00')

;with cteD as (Select * From (Values(1,'Monday'),(2,'Tuesday'),(3,'Wednesday'),(4,'Thursday'),(5,'Friday'),(6,'Saturday'),(7,'Sunday')) DDD(DD,DDD) ),
      cteR as (
                Select A.*
                      ,R1 = B.DD
                      ,R2 = IsNull(C.DD,B.DD)
                 From  @YourTable A
                 Left Join cteD B on dayFrom = B.DDD
                 Left Join cteD C on dayTo   = C.DDD
                 Where 1=1  -- Your WHERE STATEMENT HERE
              )
 Select daySeq    = A.DD
       ,dayOfWeek = A.DDD
       ,from1     = IsNull(B.TimeFrom,'Closed')
       ,from2     = IsNull(B.TimeTo,'Closed')
 From   cteD A
 Left Join   cteR B on A.DD between B.R1 and B.R2
 Order By 1
```

<p><strong>Returns</strong></p>

<p><img src="https://i.stack.imgur.com/sSbsd.jpg" alt="enter image description here"></p>

<p><strong>Note:</strong> The Closed is Optional.  Remove the "LEFT" Join in the final query</p>

<p>Now, if you want to create the JSON String in SQL Server, and you're NOT on 2016, we can tweak the final query and add a UDF.</p>

<pre class="lang-sql prettyprint-override"><code>Select JSON=[dbo].[udf-Str-JSON](0,0,(
     Select daySeq    = A.DD
           ,dayOfWeek = A.DDD
           ,from1     = IsNull(B.TimeFrom,'Closed')
           ,from2     = IsNull(B.TimeTo,'Closed')
     From   cteD A
     Left Join   cteR B on A.DD between B.R1 and B.R2
     Order By 1
     For XML RAW
))
</code>```

Returned JSON String

```<code>[{
    "daySeq": "1",
    "dayOfWeek": "Monday",
    "from1": "07:00",
    "from2": "14:00"
}, {
    "daySeq": "2",
    "dayOfWeek": "Tuesday",
    "from1": "07:00",
    "from2": "14:00"
}, {
    "daySeq": "3",
    "dayOfWeek": "Wednesday",
    "from1": "08:00",
    "from2": "12:00"
}, {
    "daySeq": "4",
    "dayOfWeek": "Thursday",
    "from1": "07:30",
    "from2": "13:00"
}, {
    "daySeq": "5",
    "dayOfWeek": "Friday",
    "from1": "07:30",
    "from2": "13:00"
}, {
    "daySeq": "6",
    "dayOfWeek": "Saturday",
    "from1": "08:00",
    "from2": "12:00"
}, {
    "daySeq": "7",
    "dayOfWeek": "Sunday",
    "from1": "Closed",
    "from2": "Closed"
}]
</code>```

The UDF if Interested

CREATE FUNCTION [dbo].[udf-Str-JSON] (@IncludeHead int,@ToLowerCase int,@XML xml)
Returns varchar(max)
AS
Begin
    Declare @Head varchar(max) = '',@JSON varchar(max) = ''
    ; with cteEAV as (Select RowNr     =Row_Number() over (Order By (Select NULL))
                            ,Entity    = xRow.value('@*[1]','varchar(100)')
                            ,Attribute = xAtt.value('local-name(.)','varchar(100)')
                            ,Value     = xAtt.value('.','varchar(max)')
                       From  @XML.nodes('/row') As R(xRow)
                       Cross Apply R.xRow.nodes('./@*') As A(xAtt) )
          ,cteSum as (Select Records=count(Distinct Entity)
                            ,Head = IIF(@IncludeHead=0,IIF(count(Distinct Entity)<=1,'[getResults]','[[getResults]]'),Concat('{"status":{"successful":"true","timestamp":"',Format(GetUTCDate(),'yyyy-MM-dd hh:mm:ss '),'GMT','","rows":"',count(Distinct Entity),'"},"retults":[[getResults]]}') )
                       From  cteEAV)
          ,cteBld as (Select *
                            ,NewRow=IIF(Lag(Entity,1)  over (Partition By Entity Order By (Select NULL))=Entity,'',',{')
                            ,EndRow=IIF(Lead(Entity,1) over (Partition By Entity Order By (Select NULL))=Entity,',','}')
                            ,JSON=Concat('"',IIF(@ToLowerCase=1,Lower(Attribute),Attribute),'":','"',Value,'"')
                       From  cteEAV )
    Select @JSON = @JSON+NewRow+JSON+EndRow,@Head = Head From cteBld, cteSum
    Return Replace(@Head,'[getResults]',Stuff(@JSON,1,1,''))
End
-- Parameter 1: @IncludeHead 1/0
-- Parameter 2: @ToLowerCase 1/0 (converts field name to lowercase
-- Parameter 3: (Select * From ... for XML RAW)
-- Syntax : Select [dbo].[udf-Str-JSON](0,1,(Select Top 2 RN=Row_Number() over (Order By (Select NULL)),* from [Chinrus-Shared].[dbo].[ZipCodes] Where StateCode in ('RI') for XML RAW))
/*
Declare @User table (ID int,Active bit,First_Name varchar(50),Last_Name varchar(50),EMail varchar(50))
Insert into @User values
(1,1,'John','Smith','john.smith@email.com'),(2,0,'Jane','Doe'  ,'jane.doe@email.com')

Declare @XML xml = (Select * from @User for XML RAW)
Select A.ID
      ,B.JSON
 From  @User A
 Cross Apply (Select JSON=[dbo].[udf-Str-JSON](0,0,(Select A.* For XML Raw)) ) B
*/
```

Body:
I was thrown in a new project, which is apparently more than just oudated. The application saves opening hours in a very weird pattern in the DB and this is driving me crazy for over a week now.

Please have a look at this image:

As you might see, the opening hours are saved in a pattern like:

dayFrom  | dayTo  | timeFrom | timeTo
=======================================
monday   | friday | 07:00    | 17:00
saturday |        | 08:00    | 12:00

Just to prevent any misunderstanding:

Open MO - FR from 07:00 to 17:00

Open SA from 08:00 to 12:00

Closed on Sunday

Now, this seems to be kinda off already, but sticking with that, a table could look like this:

dayFrom   | dayTo   | timeFrom | timeTo
=======================================
monday    | tuesday | 07:00    | 14:00
wednesday |         | 08:00    | 12:00
thursday  | friday  | 07:30    | 13:00
saturday  |         | 08:00    | 12:00

So, now my problem: I need to make a loop (or something like this) to create a valid json-string, containing all these opening hours.

Right now, I have this:

jsonAppendix = "{""openingHours"":["
for i = 1 To cint(hoechsterTag)
    jsonAppendix = jsonAppendix & "{""dayOfWeek"":" & i & ", ""from1"":""" & rs("ZeitVon") & """, ""to1"":""" & rs("ZeitBis") & """},"
next
'Remove last comma
jsonAppendix = LEFT(jsonAppendix, (LEN(jsonAppendix)-1))
jsonAppendix = jsonAppendix & "]}"

If I have only a "monday-friday", it works already, but the 2nd (or next entries) aren't taken into account.

The output looks like this, which is apparently kinda correct:

{
    "openingHours":[
        {
            "dayOfWeek":1,
            "from1":"07:00",
            "to1":"17:00"
        },
        {
            "dayOfWeek":2,
            "from1":"07:00",
            "to1":"17:00"
        },
        {
            "dayOfWeek":3,
            "from1":"07:00",
            "to1":"17:00"
        },
        {
            "dayOfWeek":4,
            "from1":"07:00",
            "to1":"17:00"
        },
        {
            "dayOfWeek":5,
            "from1":"07:00",
            "to1":"17:00"
        }
    ]
}

But the "Saturday" is not being recognized.

My function looks like this:

SQL = "SELECT * FROM StandortOpen WHERE S_ID = " & iStandortId & " AND OpenArt = '" & sArt & "' ORDER BY Sort,OpenArt DESC"
call openRS(SQL)

'day-mapping
tageV(0) = replace(rs("TagVon"),"Mo", 1)
tageV(1) = replace(rs("TagVon"),"Di", 2)
tageV(2) = replace(rs("TagVon"),"Mi", 3)
tageV(3) = replace(rs("TagVon"),"Do", 4)
tageV(4) = replace(rs("TagVon"),"Fr", 5)
tageV(5) = replace(rs("TagVon"),"Sa", 6)
tageV(6) = 7

tageB(0) = replace(rs("TagBis"),"Mo", 1)
tageB(1) = replace(rs("TagBis"),"Di", 2)
tageB(2) = replace(rs("TagBis"),"Mi", 3)
tageB(3) = replace(rs("TagBis"),"Do", 4)
tageB(4) = replace(rs("TagBis"),"Fr", 5)
tageB(5) = replace(rs("TagBis"),"Sa", 6)

'for example: mo - fr
for each item in tageV
    'save smallest weekday
    if(isNumeric(item) AND item > "") then
        if(cint(item) <= cint(niedrigsterTag)) then
            niedrigsterTag = cint(item)
        end if
    end if
next

for each item in tageB
    'save highest weekday
    if(isNumeric(item) AND item > "") then
        if(cint(item) >= cint(hoechsterTag)) then
            hoechsterTag = cint(item)
        end if
    end if
next

And the openRS()-Function:

sub openRS(str_sql)
'Response.write "SQL: " & str_sql & "
"
set rs = CreateObject("ADODB.Recordset")
rs.open str_sql,conn,1,3
end sub

So basically: Mapping numbers to the days, iterating through (or compare them to get a timespan).

I'm using a RecordSet as well. Maybe I need to use arrays or something like this? Any help would be really appreciated.

I can't alter the table nor the design of that, I have to stick with that gargabe

Body:
If you want to create the dataset in SQL Server, consider the following

Example

Declare @YourTable table (dayFrom varchar(25),dayTo varchar(25),timeFrom varchar(25),timeTo varchar(25))
Insert Into @YourTable values
('monday'   ,'tuesday','07:00','14:00'),
('wednesday',''       ,'08:00','12:00'),
('thursday' ,'friday' ,'07:30','13:00'),
('saturday' ,''       ,'08:00','12:00')

;with cteD as (Select * From (Values(1,'Monday'),(2,'Tuesday'),(3,'Wednesday'),(4,'Thursday'),(5,'Friday'),(6,'Saturday'),(7,'Sunday')) DDD(DD,DDD) ),
      cteR as (
                Select A.*
                      ,R1 = B.DD
                      ,R2 = IsNull(C.DD,B.DD)
                 From  @YourTable A
                 Left Join cteD B on dayFrom = B.DDD
                 Left Join cteD C on dayTo   = C.DDD
                 Where 1=1  -- Your WHERE STATEMENT HERE
              )
 Select daySeq    = A.DD
       ,dayOfWeek = A.DDD
       ,from1     = IsNull(B.TimeFrom,'Closed')
       ,from2     = IsNull(B.TimeTo,'Closed')
 From   cteD A
 Left Join   cteR B on A.DD between B.R1 and B.R2
 Order By 1

Returns

Note: The Closed is Optional.  Remove the "LEFT" Join in the final query

Now, if you want to create the JSON String in SQL Server, and you're NOT on 2016, we can tweak the final query and add a UDF.

Select JSON=[dbo].[udf-Str-JSON](0,0,(
     Select daySeq    = A.DD
           ,dayOfWeek = A.DDD
           ,from1     = IsNull(B.TimeFrom,'Closed')
           ,from2     = IsNull(B.TimeTo,'Closed')
     From   cteD A
     Left Join   cteR B on A.DD between B.R1 and B.R2
     Order By 1
     For XML RAW
))

Returned JSON String

[{
    "daySeq": "1",
    "dayOfWeek": "Monday",
    "from1": "07:00",
    "from2": "14:00"
}, {
    "daySeq": "2",
    "dayOfWeek": "Tuesday",
    "from1": "07:00",
    "from2": "14:00"
}, {
    "daySeq": "3",
    "dayOfWeek": "Wednesday",
    "from1": "08:00",
    "from2": "12:00"
}, {
    "daySeq": "4",
    "dayOfWeek": "Thursday",
    "from1": "07:30",
    "from2": "13:00"
}, {
    "daySeq": "5",
    "dayOfWeek": "Friday",
    "from1": "07:30",
    "from2": "13:00"
}, {
    "daySeq": "6",
    "dayOfWeek": "Saturday",
    "from1": "08:00",
    "from2": "12:00"
}, {
    "daySeq": "7",
    "dayOfWeek": "Sunday",
    "from1": "Closed",
    "from2": "Closed"
}]

The UDF if Interested

CREATE FUNCTION [dbo].[udf-Str-JSON] (@IncludeHead int,@ToLowerCase int,@XML xml)
Returns varchar(max)
AS
Begin
    Declare @Head varchar(max) = '',@JSON varchar(max) = ''
    ; with cteEAV as (Select RowNr     =Row_Number() over (Order By (Select NULL))
                            ,Entity    = xRow.value('@*[1]','varchar(100)')
                            ,Attribute = xAtt.value('local-name(.)','varchar(100)')
                            ,Value     = xAtt.value('.','varchar(max)')
                       From  @XML.nodes('/row') As R(xRow)
                       Cross Apply R.xRow.nodes('./@*') As A(xAtt) )
          ,cteSum as (Select Records=count(Distinct Entity)
                            ,Head = IIF(@IncludeHead=0,IIF(count(Distinct Entity)<=1,'[getResults]','[[getResults]]'),Concat('{"status":{"successful":"true","timestamp":"',Format(GetUTCDate(),'yyyy-MM-dd hh:mm:ss '),'GMT','","rows":"',count(Distinct Entity),'"},"retults":[[getResults]]}') )
                       From  cteEAV)
          ,cteBld as (Select *
                            ,NewRow=IIF(Lag(Entity,1)  over (Partition By Entity Order By (Select NULL))=Entity,'',',{')
                            ,EndRow=IIF(Lead(Entity,1) over (Partition By Entity Order By (Select NULL))=Entity,',','}')
                            ,JSON=Concat('"',IIF(@ToLowerCase=1,Lower(Attribute),Attribute),'":','"',Value,'"')
                       From  cteEAV )
    Select @JSON = @JSON+NewRow+JSON+EndRow,@Head = Head From cteBld, cteSum
    Return Replace(@Head,'[getResults]',Stuff(@JSON,1,1,''))
End
-- Parameter 1: @IncludeHead 1/0
-- Parameter 2: @ToLowerCase 1/0 (converts field name to lowercase
-- Parameter 3: (Select * From ... for XML RAW)
-- Syntax : Select [dbo].[udf-Str-JSON](0,1,(Select Top 2 RN=Row_Number() over (Order By (Select NULL)),* from [Chinrus-Shared].[dbo].[ZipCodes] Where StateCode in ('RI') for XML RAW))
/*
Declare @User table (ID int,Active bit,First_Name varchar(50),Last_Name varchar(50),EMail varchar(50))
Insert into @User values
(1,1,'John','Smith','john.smith@email.com'),(2,0,'Jane','Doe'  ,'jane.doe@email.com')

Declare @XML xml = (Select * from @User for XML RAW)
Select A.ID
      ,B.JSON
 From  @User A
 Cross Apply (Select JSON=[dbo].[udf-Str-JSON](0,0,(Select A.* For XML Raw)) ) B
*/


问:
How to pull with rebase by default in IntelliJ Idea?
By company policy, all pulls unless agreed with tech lead must be done with rebase rather than merge.

I use Eclipse and successfully set the default pull mode to rebase to all my branches (despite Eclipse suggests merge as default mode).

My deskmate, working on my same project, uses IntelliJ Idea. Guess what? He always forgets to check pull-with-rebase when pulling, ending up in endless merge commits.

I often have to complain with him for violating the rule I took so long to make a standard, then I need to do force pushing to fix the tree from the mess. Only 2 people here use IntelliJ, other use Eclipse and have no problems with Git.

How do I set the default pull mode in IntelliJ Idea?

答: Leave alone IntelliJ IDEA. Run git config --global pull.rebase true in his git bash. Or set this on a per-branch basis, by git config --global branch.<name>.rebase true, which is safer and more flexible.


问:
How to replace an element in an array field in mongodb
Field tags is array in scenes document. I wanna replace element 'Bad' with 'Good' in the array as:

```<code>db.scenes.update({ 'tags': 'Bad' }, { $set: { 'tags.$' : 'Good' } }, { 'multi':true});
</code>```

I don't know how to do it in doctrine. I tried

```<code>    $dm->createQueryBuilder('SceneBundle:Scene')
        ->update()
        ->field('tags.$')->set($tag)
        ->field('tags')->equals($oldTag)
        ->multiple(true)
        ->getQuery()
        ->execute();
</code>```

but not work.

Thanks.

答:
it's been a long time, but just to not leave this post without a good answer I found a link (Mongodb array $push and $pull) which can help us.

The issue is that MongoDB doesn’t allow multiple operations on the
  same property in the same update call. This means that the two
  operations must happen in two individually atomic operations.

Body:
Field tags is array in scenes document. I wanna replace element 'Bad' with 'Good' in the array as:

db.scenes.update({ 'tags': 'Bad' }, { $set: { 'tags.$' : 'Good' } }, { 'multi':true});

I don't know how to do it in doctrine. I tried

    $dm->createQueryBuilder('SceneBundle:Scene')
        ->update()
        ->field('tags.$')->set($tag)
        ->field('tags')->equals($oldTag)
        ->multiple(true)
        ->getQuery()
        ->execute();

but not work.

Thanks.


问:
ant.launcher from script issue
I have a small script in rhel6 that basically goes like this:

```<code>#!/bin/bash

if [ "$JAVA_HOME" = "" ]; then
    echo The environment variable JAVA_HOME is not set.  Deploy failed.
    exit 1
else
    CLASSPATH=./lib/ant-nodeps.jar:./lib/ant.jar:./lib/ant-launcher.jar:./lib/tools.jar

    #echo classpath: $CLASSPATH
    "$JAVA_HOME/bin/java" -Dant.home=./ant org.apache.tools.ant.launch.Launcher -Dinstaller.requested=false  -buildfile deploy.xml
fi
</code>```

I have tried many things and i still get this launcher not found error.
ant version -1.9.9

In .bash_profile

```<code>PATH=/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.41.x86_64/jre/bin/:/opt/WebSphere/AppServer/java/bin:/usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin:/root/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/usr/bin/mozilla:/usr/bin/firefox:/usr/local/apache-ant-1.9.9/bin:/bin/bash:/usr/bin/java:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.41.x86_64/jre/bin/:/opt/WebSphere/AppServer/java/bin:/usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.41.x86_64/bin:/usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin:/usr/local/apache-ant-1.9.9/lib/ant-launcher.jar

JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.41.x86_64
ANT_HOME=/usr/local/apache-ant-1.9.9
</code>```

I have also tried setting ANT_LIB in bash_profile but with no luck..What can i do next??

The error is :
Error: Could not find or load main class org.apache.tools.ant.launch.Launcher

答:
Your classpath contains relative paths as indicated by the dot in ./lib/ant.jar

```<code>CLASSPATH=./lib/ant-nodeps.jar:./lib/ant.jar
</code>```

The dot means "here", if you are at your home directory, that's /home/[your username].
You should also add the classpath var to the command:

```<code>$JAVA_HOME/bin/java -cp $CLASSPATH ...
</code>```

You can fix in several ways

Add to the script a cd /some/dir to the path were /lib/ant.jar is

Build the CLASSPATH var using absolute paths.

Verify that classpath is correctly set in build.xml if that's the case.

workaround:
Run the script from the path were /lib/ant.jar is.

Title: ant.launcher from script issue

Body:
I have a small script in rhel6 that basically goes like this:

#!/bin/bash

if [ "$JAVA_HOME" = "" ]; then
    echo The environment variable JAVA_HOME is not set.  Deploy failed.
    exit 1
else
    CLASSPATH=./lib/ant-nodeps.jar:./lib/ant.jar:./lib/ant-launcher.jar:./lib/tools.jar

    #echo classpath: $CLASSPATH
    "$JAVA_HOME/bin/java" -Dant.home=./ant org.apache.tools.ant.launch.Launcher -Dinstaller.requested=false  -buildfile deploy.xml
fi

I have tried many things and i still get this launcher not found error.
ant version -1.9.9

In .bash_profile

PATH=/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.41.x86_64/jre/bin/:/opt/WebSphere/AppServer/java/bin:/usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin:/root/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/usr/bin/mozilla:/usr/bin/firefox:/usr/local/apache-ant-1.9.9/bin:/bin/bash:/usr/bin/java:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.41.x86_64/jre/bin/:/opt/WebSphere/AppServer/java/bin:/usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.41.x86_64/bin:/usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin:/usr/local/apache-ant-1.9.9/lib/ant-launcher.jar

JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.41.x86_64
ANT_HOME=/usr/local/apache-ant-1.9.9

I have also tried setting ANT_LIB in bash_profile but with no luck..What can i do next??

The error is :
Error: Could not find or load main class org.apache.tools.ant.launch.Launcher

Body:
Your classpath contains relative paths as indicated by the dot in ./lib/ant.jar

CLASSPATH=./lib/ant-nodeps.jar:./lib/ant.jar

The dot means "here", if you are at your home directory, that's /home/[your username].
You should also add the classpath var to the command:

$JAVA_HOME/bin/java -cp $CLASSPATH ...

You can fix in several ways

Add to the script a cd /some/dir to the path were /lib/ant.jar is

Build the CLASSPATH var using absolute paths.

Verify that classpath is correctly set in build.xml if that's the case.

workaround:
Run the script from the path were /lib/ant.jar is.


问:
How do I remove the warning: Control reaches end of non-void function?
I know it's caused by the absence of return at the end of the function, but what if i only want it to return under a specific condition. I tried to transfer the return in the of the function, but it returns the first dim it sees which i do not want to happen. </p>

```<code>char dimension(void)
{
    char dim,d;
    printf("2D or 3D?\n");
    dim=getchar();
    if(dim=='2'||dim=='3')
    {
        d=getchar();
        if(d=='\n')
        {
            printf("You selected %cD\n",dim);
            return dim;
        }
        else
        {
            for(;d!='\n';d=getchar());
            if(d=='\n')
            dimension();
        }
    }
    else
    {
        for(;d!='\n';d=getchar());
        if(d=='\n')
        dimension();
    }
//return dim; --> undesired return value.

}
</code>```

答:
Your program seems more complex than it needs to be, and the problems seem to center around disposal of the trailing newline.

Better to write a function dedicated to clearing the input stream. Also note that getchar() returns EOF in the event of an error, or if the user signals EOF from the keyboard, or potentially if input has been redirected from a file. The clear_stdin() function below checks for both \n and EOF to avoid an infinite loop in such a case.

As pointed out by @IanAbbott, dim should be an int, since the return type of getchar() is int, and a char may not hold the value of EOF. If there were and error in getchar(), an infinite recursion would be entered unless dimension() explicitly checks for EOF. I have added code that prints an error message and returns '?' if dim is EOF. The calling function can handle the error by checking for '?'; the program could instead exit() when an error is detected.

Also note that a function that is declared with a return value must return a value. Here, if the user's input is acceptable it is returned, otherwise the result of calling dimension() again is returned.

```<code>#include <stdio.h>

char dimension(void);
void clear_stdin(void);

int main(void)
{
    char c = dimension();

    printf("%c returned from dimension()\n", c);

    return 0;
}

char dimension(void)
{
    int dim;

    printf("2D or 3D?\n");
    dim = getchar();

    if (dim == EOF) {
        printf("Error or EOF in getchar()\n");
        return '?';
    }

    if (dim == '2' || dim == '3') {
        int c;
        if ((c = getchar()) == '\n' || c == EOF) {
            printf("You selected %cD\n",dim);
            return dim;
        }
    }

    clear_stdin();

    puts("Invalid selection");
    return dimension();
}

void clear_stdin(void)
{
    int c;
    while((c = getchar()) != '\n' && c != EOF) {
        continue;
    }
}
</code>```

Sample interaction

2D or 3D?
1
Invalid selection
2D or 3D?
23
Invalid selection
2D or 3D?
4
Invalid selection
2D or 3D?
3
You selected 3D
3 returned from dimension()
```

Body:
I know it's caused by the absence of return at the end of the function, but what if i only want it to return under a specific condition. I tried to transfer the return in the of the function, but it returns the first dim it sees which i do not want to happen.

char dimension(void)
{
    char dim,d;
    printf("2D or 3D?\n");
    dim=getchar();
    if(dim=='2'||dim=='3')
    {
        d=getchar();
        if(d=='\n')
        {
            printf("You selected %cD\n",dim);
            return dim;
        }
        else
        {
            for(;d!='\n';d=getchar());
            if(d=='\n')
            dimension();
        }
    }
    else
    {
        for(;d!='\n';d=getchar());
        if(d=='\n')
        dimension();
    }
//return dim; --> undesired return value.

}

Body:
Your program seems more complex than it needs to be, and the problems seem to center around disposal of the trailing newline.

Better to write a function dedicated to clearing the input stream. Also note that getchar() returns EOF in the event of an error, or if the user signals EOF from the keyboard, or potentially if input has been redirected from a file. The clear_stdin() function below checks for both \n and EOF to avoid an infinite loop in such a case.

As pointed out by @IanAbbott, dim should be an int, since the return type of getchar() is int, and a char may not hold the value of EOF. If there were and error in getchar(), an infinite recursion would be entered unless dimension() explicitly checks for EOF. I have added code that prints an error message and returns '?' if dim is EOF. The calling function can handle the error by checking for '?'; the program could instead exit() when an error is detected.

Also note that a function that is declared with a return value must return a value. Here, if the user's input is acceptable it is returned, otherwise the result of calling dimension() again is returned.

#include <stdio.h>

char dimension(void);
void clear_stdin(void);

int main(void)
{
    char c = dimension();

    printf("%c returned from dimension()\n", c);

    return 0;
}

char dimension(void)
{
    int dim;

    printf("2D or 3D?\n");
    dim = getchar();

    if (dim == EOF) {
        printf("Error or EOF in getchar()\n");
        return '?';
    }

    if (dim == '2' || dim == '3') {
        int c;
        if ((c = getchar()) == '\n' || c == EOF) {
            printf("You selected %cD\n",dim);
            return dim;
        }
    }

    clear_stdin();

    puts("Invalid selection");
    return dimension();
}

void clear_stdin(void)
{
    int c;
    while((c = getchar()) != '\n' && c != EOF) {
        continue;
    }
}

Sample interaction

2D or 3D?
1
Invalid selection
2D or 3D?
23
Invalid selection
2D or 3D?
4
Invalid selection
2D or 3D?
3
You selected 3D
3 returned from dimension()


问:
how to make dots inherit the width of the image? (slick)
There is a block 225px. Inside you insert a picture large size (850px). And she goes outside.

It looks like this:

.content {display: inline-block;}

.column {float:right; width:225px;}

.slider {
  border: 1px solid;
  width: 220px;
  padding: 5px;
}

.single-slide img {
  width: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
    <div class="column">
      <div class="slider single-slide">
        <div><img src='https://s-media-cache-ak0.pinimg.com/736x/2c/d0/19/2cd0197c5eb8c1f84e81734f97e80cd3.jpg' /></div>
        <div>to place the center of the image</div>
      </div>
    </div>
  </div></code>```

Using slick slider. I want to add dots to control the slider.

When I add the dots they are placed in the middle of the block. It's okay, I understand. But I want to place them in the center of the picture. How to do it?

UPD: The image goes beyond the block, that's right! And I need to do to the dots were at the center of the image, not the block

答:
Updated: The inherit keyword specifies that a property should inherit its value from its parent element [ Source ]. and image can't be a parent element. see this example.

Here is a solution on based on inherit and position on your latest update.
See the html section I have added a class "img-holder" on div which hold the img and add a class "div_center" on div which contain text's.

img inherit width from its parent div class "img-holder". "img-holder" and "div_center" inherit width from parent div class slider.

N.B: if  you set the img width auto text will always center of the div class slider.

.content {
  display: inline-block;
}

.column {
  float: right;
  width: 225px;
}

.slider {
  border: 1px solid #000;
  width: 220px;
  padding: 5px;
  position:relative;
}

.img-holder {
  width: inherit;

}

.img-holder img {
  width: inherit;/*width auto default value. The browser calculates the width*/

}

.div_center {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  text-align: center;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="content">
    <div class="column">
      <div class="slider single-slide">
        <div class="img-holder">
          <img src='https://s-media-cache-ak0.pinimg.com/736x/2c/d0/19/2cd0197c5eb8c1f84e81734f97e80cd3.jpg' />
         </div><!--./ img-holder -->
        <div class="div_center">
           to place the center of the image
        </div><!--end of txt_center -->

      </div><!--./ slider single-slide-->
    </div><!--./ column -->
  </div><!--./ content --></code>```

Previous: Position absolute for slick-dots class but you dont set any relative position for that. so you need to add position relative to your slide div.
And make the image responsive. I have added responsive property for your image on css section and added border on li for clear view.

.content {display: inline-block;}

.column {float:right; width:225px;}

.slider {
  border: 1px solid;
  width: 220px;
  padding: 5px;
 position: relative;
}

.single-slide img {
  max-width:100%;
  display:block;
  height:auto;
  margin:0 auto;
}

.slick-dotted.slick-slider
{
    margin-bottom: 30px;
}

.slick-dots
{
    position: absolute;
    top:50%;
    left:0;
    right:0;
    display: block;

    width: 100%;
    padding: 0;
    margin: 0;

    list-style: none;

    text-align: center;
}
.slick-dots li
{

    position: relative;
    display: inline-block;

    width: 20px;
    height: 20px;
    margin: 0 5px;
    padding: 0;
    border:2px solid red;
    cursor: pointer;
}
.slick-dots li button
{
    font-size: 0;
    line-height: 0;

    display: block;

    width: 20px;
    height: 20px;
    padding: 5px;

    cursor: pointer;
    right: 0;
    bottom: 0;
    left: 0;
    color: transparent;
    border: 0;
    outline: none;
    background: transparent;
}
.slick-dots li button:hover,
.slick-dots li button:focus
{
    outline: none;
}
.slick-dots li button:hover:before,
.slick-dots li button:focus:before
{
    opacity: 1;
}
.slick-dots li button:before
{
    font-family: 'slick';
    font-size: 12px;
    line-height: 20px;

    position: absolute;
    top: 0;
    left: 0;

    width: 20px;
    height: 20px;

    content: '•';
    text-align: center;

    opacity: .25;
    color: black;

    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
.slick-dots li.slick-active button:before
{
    opacity: .75;
    color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
    <div class="column">
      <div class="slider single-slide">
        <div><img src='https://s-media-cache-ak0.pinimg.com/736x/2c/d0/19/2cd0197c5eb8c1f84e81734f97e80cd3.jpg' /></div>
        <ul class="slick-dots">
          <li class="active"><button></button></li>
          <li><button></button></li>
          <li><button></button></li>
        </ul>
      </div>
    </div>
  </div></code>```

Body:
There is a block 225px. Inside you insert a picture large size (850px). And she goes outside.

It looks like this:

.content {display: inline-block;}

.column {float:right; width:225px;}

.slider {
  border: 1px solid;
  width: 220px;
  padding: 5px;
}

.single-slide img {
  width: auto;
}

to place the center of the image

Using slick slider. I want to add dots to control the slider.

When I add the dots they are placed in the middle of the block. It's okay, I understand. But I want to place them in the center of the picture. How to do it?

UPD: The image goes beyond the block, that's right! And I need to do to the dots were at the center of the image, not the block

Body:
Updated: The inherit keyword specifies that a property should inherit its value from its parent element [ Source ]. and image can't be a parent element. see this example.

Here is a solution on based on inherit and position on your latest update.
See the html section I have added a class "img-holder" on div which hold the img and add a class "div_center" on div which contain text's.

img inherit width from its parent div class "img-holder". "img-holder" and "div_center" inherit width from parent div class slider.

N.B: if  you set the img width auto text will always center of the div class slider.

.content {
  display: inline-block;
}

.column {
  float: right;
  width: 225px;
}

.slider {
  border: 1px solid #000;
  width: 220px;
  padding: 5px;
  position:relative;
}

.img-holder {
  width: inherit;

}

.img-holder img {
  width: inherit;/*width auto default value. The browser calculates the width*/

}

.div_center {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  text-align: center;

}

 <div class="content">
    <div class="column">
      <div class="slider single-slide">
        <div class="img-holder">
          <img src='https://s-media-cache-ak0.pinimg.com/736x/2c/d0/19/2cd0197c5eb8c1f84e81734f97e80cd3.jpg' />
         </div><!--./ img-holder -->
        <div class="div_center">
           to place the center of the image
        </div><!--end of txt_center -->

      </div><!--./ slider single-slide-->
    </div><!--./ column -->
  </div><!--./ content -->

Previous: Position absolute for slick-dots class but you dont set any relative position for that. so you need to add position relative to your slide div.
And make the image responsive. I have added responsive property for your image on css section and added border on li for clear view.

.content {display: inline-block;}

.column {float:right; width:225px;}

.slider {
  border: 1px solid;
  width: 220px;
  padding: 5px;
 position: relative;
}

.single-slide img {
  max-width:100%;
  display:block;
  height:auto;
  margin:0 auto;
}

.slick-dotted.slick-slider
{
    margin-bottom: 30px;
}

.slick-dots
{
    position: absolute;
    top:50%;
    left:0;
    right:0;
    display: block;

    width: 100%;
    padding: 0;
    margin: 0;

    list-style: none;

    text-align: center;
}
.slick-dots li
{

    position: relative;
    display: inline-block;

    width: 20px;
    height: 20px;
    margin: 0 5px;
    padding: 0;
    border:2px solid red;
    cursor: pointer;
}
.slick-dots li button
{
    font-size: 0;
    line-height: 0;

    display: block;

    width: 20px;
    height: 20px;
    padding: 5px;

    cursor: pointer;
    right: 0;
    bottom: 0;
    left: 0;
    color: transparent;
    border: 0;
    outline: none;
    background: transparent;
}
.slick-dots li button:hover,
.slick-dots li button:focus
{
    outline: none;
}
.slick-dots li button:hover:before,
.slick-dots li button:focus:before
{
    opacity: 1;
}
.slick-dots li button:before
{
    font-family: 'slick';
    font-size: 12px;
    line-height: 20px;

    position: absolute;
    top: 0;
    left: 0;

    width: 20px;
    height: 20px;

    content: '•';
    text-align: center;

    opacity: .25;
    color: black;

    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
.slick-dots li.slick-active button:before
{
    opacity: .75;
    color: black;
}

<div class="content">
    <div class="column">
      <div class="slider single-slide">
        <div><img src='https://s-media-cache-ak0.pinimg.com/736x/2c/d0/19/2cd0197c5eb8c1f84e81734f97e80cd3.jpg' /></div>
        <ul class="slick-dots">
          <li class="active"><button></button></li>
          <li><button></button></li>
          <li><button></button></li>
        </ul>
      </div>
    </div>
  </div>


问:
Secure communication basics
Till now I haven't really studied secure communication and I have some basic questions. Assume there is a browser(the client) and a server. From what I have understood, the server has both a public and a private key. The public key is known by everyone and the private key only by the server. So when the client sends a message to the server, it is encrypted with the public key of the server and only the server can decrypt it(cause only the server has the private key).

Now to my question: What happens when the server wants to send a message to the client? The server encrypts the message with its private key and the client decrypts it with the public key(it is known by everyone). So far so good. But if someone sniff the traffic, he can also decrypt the message, cause everyone knows the public key. How is it secure? I am sure I don't understand something really basic here:(

Thanks in advance!

Best regards,
Petar

答:
Simplifying a lot: the client generates a key for symmetric cryptography and sends it to the server, crypting it with the public key of the server.
In this way a secure key exchange takes place.
From there on client and server use symmetric cryptography with the exchanged key.
Standard way is the Diffie-Hellman key exchange which is a little more complicated than the given example.</p>

Title: Secure communication basics