问:
Print Text 'Loading' with dots going forward and backward in python shell
I want to print Text 'Loading...' But its dots would be moving back and forward (in shell).

I am creating a text game and for that it will look better.

I know writing slowly a word but dots also have to go back.

I am thinking that I should forget dots to come back.And for that:

```<code>import sys
import time
shell = sys.stdout.shell
shell.write('Loading',"stdout")
str = '........'
for letter in str:
    sys.stdout.write(letter)
    time.sleep(0.1)
</code>```

What do you think?

If you have that dots would be moving back and forward Then please share with me.

If you want more information I am ready to Provide to you.

Thanks

答:
Check This Module Keyboard with many features. Install It, perhaps with this command:

```<code>pip3 install keyboard
</code>```

Then Write the following code in File textdot.py:

```<code>def text(text_to_print,num_of_dots,num_of_loops):
    from time import sleep
    import keyboard
    import sys
    shell = sys.stdout.shell
    shell.write(text_to_print,'stdout')
    dotes = int(num_of_dots) * '.'
    for last in range(0,num_of_loops):
        for dot in dotes:
            keyboard.write('.')
            sleep(0.1)
        for dot in dotes:
            keyboard.write('\x08')
            sleep(0.1)
</code>```

Now Paste the file in Lib from your python folder.

Now you Can use it like following example:

```<code>import textdot
textdot.text('Loading',6,3)
</code>```

Thanks

Body:
I want to print Text 'Loading...' But its dots would be moving back and forward (in shell).

I am creating a text game and for that it will look better.

I know writing slowly a word but dots also have to go back.

I am thinking that I should forget dots to come back.And for that:

import sys
import time
shell = sys.stdout.shell
shell.write('Loading',"stdout")
str = '........'
for letter in str:
    sys.stdout.write(letter)
    time.sleep(0.1)

What do you think?

If you have that dots would be moving back and forward Then please share with me.

If you want more information I am ready to Provide to you.

Thanks

Body:
Check This Module Keyboard with many features. Install It, perhaps with this command:

pip3 install keyboard

Then Write the following code in File textdot.py:

def text(text_to_print,num_of_dots,num_of_loops):
    from time import sleep
    import keyboard
    import sys
    shell = sys.stdout.shell
    shell.write(text_to_print,'stdout')
    dotes = int(num_of_dots) * '.'
    for last in range(0,num_of_loops):
        for dot in dotes:
            keyboard.write('.')
            sleep(0.1)
        for dot in dotes:
            keyboard.write('\x08')
            sleep(0.1)

Now Paste the file in Lib from your python folder.

Now you Can use it like following example:

import textdot
textdot.text('Loading',6,3)

Thanks


来源: stackexchange

问:
How to rotate drag/dropped Image using Jquery
I am having an issue in Jquery rotate  below is my HTML code

```<code><div id="frame" style="height:100;width:100;" >
<img alt="" id="Img1" runat="server" src="~/Images/pdfcar.png"
style="height:30px;width:30px;"/>
</code>```

The below code is working fine,

Javascript:Jquery rotate

```<code> var test = 5;
 $(function() {
     $('#Img1').live('mousedown', function(event) {
              test = test + 15;
              **$('#Img1').rotate({ angle: test });**

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

But my scenario is to acheive the rotation of dropped images,when i try the below code its not working

```<code>var test = 5;
 $(function() {
     $('#frame img').live('mousedown', function(event) {
              test = test + 15;
              **$('#frame img').rotate({ angle: test });**

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

What's wrong in the above code or how to achieve it??

Full JQuery code

```<code>var counter = 1;
  $(function() {
  $('#frame img').live('click', function(event) {

          if ((counter > 0) && (counter < 350)) {
              $(this).rotate(counter + 45);
              counter = counter + 45;
          }
          else if ((counter > -1) && (counter > 350)) {

              counter = 1;
          }
      });

  });

  $(function() {

      $('#frame img').live('dblclick', function(ev, ui) {
      // $(this).resizable("destroy")

      $(this).hide();
      var currentId = $(this).attr('id');
      var deleteimage = 1;
      saveCoords(ev.clientX, ev.clientY, currentId, document.getElementById("<%=trafficID.ClientID%>").value, deleteimage);

          //$(this).unbind("resizable"); not working
          //$(this).removeclass(); not working
      });
  });

  $(document).ready(function() {
      //Counter
      counter = 0;

      //Make element draggable
      $("#fd img").draggable({
          helper: 'clone',
          containment: '#frame',
          //When first dragged
          stop: function(ev, ui) {

              var pos = $(ui.helper).offset();
              objName = "#clonediv" + counter
              $(objName).css({ "left": pos.left, "top": pos.top });
              $(objName).removeClass("drag");
              //When an existiung object is dragged
              $(objName).draggable({
                  containment: 'parent',
                  stop: function(ev, ui) {
                      var pos = $(ui.helper).offset();
                      //console.log($(this).attr("id"));
                      //console.log(pos.left)
                      //console.log(pos.top)
                  }
              });
          }
      });
      //Make element droppable
      $("#frame").droppable({

      drop: function(ev, ui) {

              if (ui.helper.attr('id').search(/drag[0-9]/) != -1) {
                  var pos = $(ui.helper).offset();
                  counter++;
                  var element = $(ui.helper).clone();
                  //var element = element1.resizable();
                  element.addClass("tempclass");
                  $(this).append(element);
                  var deleteimage = 0;
                  element.attr("id", ui.helper.attr('id') + counter);
                  saveCoords(ui.absolutePosition.left, ui.absolutePosition.top, ui.helper.attr('id') + counter, document.getElementById("<%=trafficID.ClientID%>").value, deleteimage);
                  $(".tempclass").attr("id", "clonediv" + counter);
                  $("#clonediv" + counter).removeClass("tempclass");
                  //$(".tempclass").attr("onclick",function(){ $(this).remove(););
                  //$("#clonediv" + counter).removeClass("tempclass");
                  //Get the dynamically item id
                  draggedNumber = ui.helper.attr('id').search(/drag([0-9])/);
                  itemDragged = "dragged" + RegExp.$1;
                  //console.log(itemDragged)
                  //alert('left' + pos.left + ',top' + pos.top + 'of item' + itemDragged);
                  $("#clonediv" + counter).addClass(itemDragged);
              }
          }
      });
      //Make the element resizable

  });
</code>```

答:
```<code>var test = 5;
 $(function() {
     $('#frame img').live('mousedown', function(event) {
              test = test + 15;
              $('#frame img').rotate({ 'angle': test });//Error is here

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

ContentLicense: CC BY-SA 2.5

Body:
I am having an issue in Jquery rotate  below is my HTML code

The below code is working fine,

Javascript:Jquery rotate

 var test = 5;
 $(function() {
     $('#Img1').live('mousedown', function(event) {
              test = test + 15;
              **$('#Img1').rotate({ angle: test });**

     });
 });

But my scenario is to acheive the rotation of dropped images,when i try the below code its not working

var test = 5;
 $(function() {
     $('#frame img').live('mousedown', function(event) {
              test = test + 15;
              **$('#frame img').rotate({ angle: test });**

     });
 });

What's wrong in the above code or how to achieve it??

Full JQuery code

var counter = 1;
  $(function() {
  $('#frame img').live('click', function(event) {

          if ((counter > 0) && (counter < 350)) {
              $(this).rotate(counter + 45);
              counter = counter + 45;
          }
          else if ((counter > -1) && (counter > 350)) {

              counter = 1;
          }
      });

  });

  $(function() {

      $('#frame img').live('dblclick', function(ev, ui) {
      // $(this).resizable("destroy")

      $(this).hide();
      var currentId = $(this).attr('id');
      var deleteimage = 1;
      saveCoords(ev.clientX, ev.clientY, currentId, document.getElementById("<%=trafficID.ClientID%>").value, deleteimage);

          //$(this).unbind("resizable"); not working
          //$(this).removeclass(); not working
      });
  });

  $(document).ready(function() {
      //Counter
      counter = 0;

      //Make element draggable
      $("#fd img").draggable({
          helper: 'clone',
          containment: '#frame',
          //When first dragged
          stop: function(ev, ui) {

              var pos = $(ui.helper).offset();
              objName = "#clonediv" + counter
              $(objName).css({ "left": pos.left, "top": pos.top });
              $(objName).removeClass("drag");
              //When an existiung object is dragged
              $(objName).draggable({
                  containment: 'parent',
                  stop: function(ev, ui) {
                      var pos = $(ui.helper).offset();
                      //console.log($(this).attr("id"));
                      //console.log(pos.left)
                      //console.log(pos.top)
                  }
              });
          }
      });
      //Make element droppable
      $("#frame").droppable({

      drop: function(ev, ui) {

              if (ui.helper.attr('id').search(/drag[0-9]/) != -1) {
                  var pos = $(ui.helper).offset();
                  counter++;
                  var element = $(ui.helper).clone();
                  //var element = element1.resizable();
                  element.addClass("tempclass");
                  $(this).append(element);
                  var deleteimage = 0;
                  element.attr("id", ui.helper.attr('id') + counter);
                  saveCoords(ui.absolutePosition.left, ui.absolutePosition.top, ui.helper.attr('id') + counter, document.getElementById("<%=trafficID.ClientID%>").value, deleteimage);
                  $(".tempclass").attr("id", "clonediv" + counter);
                  $("#clonediv" + counter).removeClass("tempclass");
                  //$(".tempclass").attr("onclick",function(){ $(this).remove(););
                  //$("#clonediv" + counter).removeClass("tempclass");
                  //Get the dynamically item id
                  draggedNumber = ui.helper.attr('id').search(/drag([0-9])/);
                  itemDragged = "dragged" + RegExp.$1;
                  //console.log(itemDragged)
                  //alert('left' + pos.left + ',top' + pos.top + 'of item' + itemDragged);
                  $("#clonediv" + counter).addClass(itemDragged);
              }
          }
      });
      //Make the element resizable

  });


问:
How to hide a session parameters in Swagger with Springfox
```<code>    @ApiOperation(value = "获取打卡信息", notes = "获取打卡信息")
@RequestMapping(method = RequestMethod.GET, value = "/{mPhone}/{mPassword}/{date}")
@ApiImplicitParams({
        @ApiImplicitParam(name = "mPhone", value = "手机号", required = true, dataType = "String",defaultValue="13268690268",paramType="Path"),
        @ApiImplicitParam(name = "mPassword", value = "密码", required = true, dataType = "String",defaultValue="111111",paramType="Path"),
        @ApiImplicitParam(name = "date", value = "日期", required = true, dataType = "String",defaultValue="2017-07-04",paramType="Path"),
        @ApiImplicitParam(name = "httpSession", value = "Session", required = false)})
public @ResponseBody String getSignInfo(@PathVariable String mPhone, @PathVariable String mPassword,
        @PathVariable String date,
        HttpSession httpSession) {
.......
 }
</code>```

enter image description here

I want to remove this parameter (httpSession) from the document, and I need help。

答:
Springfox won't show these values by default. The reason why httpSession is visible in your case, is because you added it by yourself as an implicit parameter:

@ApiImplicitParam(name = "httpSession", value = "Session", required = false)
```

<p>If you don't want the <code>httpSession</code> to pop up, remove that from your implicit parameters. Additionally, you don't even have to use <code>@ApiImplicitParam</code> in your case, you can use <code>@ApiParam</code>:</p>

<pre class="lang-java prettyprint-override"><code>@ApiOperation(value = "获取打卡信息", notes = "获取打卡信息")
@RequestMapping(method = RequestMethod.GET, value = "/{mPhone}/{mPassword}/{date}")
public @ResponseBody String getSignInfo(
        @ApiParam(value = "手机号", required = true, dataType = "String",defaultValue="13268690268")
        @PathVariable String mPhone,
        @ApiParam(value = "密码", required = true, dataType = "String",defaultValue="111111")
        @PathVariable String mPassword,
        @ApiParam(value = "日期", required = true, dataType = "String",defaultValue="2017-07-04")
        @PathVariable String date,
        HttpSession httpSession) {
    // ...
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
    @ApiOperation(value = "获取打卡信息", notes = "获取打卡信息")
@RequestMapping(method = RequestMethod.GET, value = "/{mPhone}/{mPassword}/{date}")
@ApiImplicitParams({
        @ApiImplicitParam(name = "mPhone", value = "手机号", required = true, dataType = "String",defaultValue="13268690268",paramType="Path"),
        @ApiImplicitParam(name = "mPassword", value = "密码", required = true, dataType = "String",defaultValue="111111",paramType="Path"),
        @ApiImplicitParam(name = "date", value = "日期", required = true, dataType = "String",defaultValue="2017-07-04",paramType="Path"),
        @ApiImplicitParam(name = "httpSession", value = "Session", required = false)})
public @ResponseBody String getSignInfo(@PathVariable String mPhone, @PathVariable String mPassword,
        @PathVariable String date,
        HttpSession httpSession) {
.......
 }

enter image description here

I want to remove this parameter (httpSession) from the document, and I need help。

Body:
Springfox won't show these values by default. The reason why httpSession is visible in your case, is because you added it by yourself as an implicit parameter:

@ApiImplicitParam(name = "httpSession", value = "Session", required = false)

If you don't want the httpSession to pop up, remove that from your implicit parameters. Additionally, you don't even have to use @ApiImplicitParam in your case, you can use @ApiParam:

@ApiOperation(value = "获取打卡信息", notes = "获取打卡信息")
@RequestMapping(method = RequestMethod.GET, value = "/{mPhone}/{mPassword}/{date}")
public @ResponseBody String getSignInfo(
        @ApiParam(value = "手机号", required = true, dataType = "String",defaultValue="13268690268")
        @PathVariable String mPhone,
        @ApiParam(value = "密码", required = true, dataType = "String",defaultValue="111111")
        @PathVariable String mPassword,
        @ApiParam(value = "日期", required = true, dataType = "String",defaultValue="2017-07-04")
        @PathVariable String date,
        HttpSession httpSession) {
    // ...
 }


问:
how to find a an error message in angular JS using protractor?
error message

MyProtractorCode

How to find the text "VAT Number is required."?

I tried with:

err = element(by.css('.invalid error-msg')).getAttribute();
expect(err.getText()).toEqual('VAT Number is invalid.');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><em class="invalid error-msg">
  <div> VAT Number is required.</div>
</em></code>```

答:
You can use below code.</p>

```<code>var EC=protractor.ExpectedConditions;
var errWebElement = element(by.css('.invalid.error-msg'));

expect(errWebElement.getText()).toEqual("VAT Number is required.");
 **OR**
expect(EC.visibilityOf(errWebElement)).toBe(true);
</code>```

Body:
error message

MyProtractorCode

How to find the text "VAT Number is required."?

I tried with:

err = element(by.css('.invalid error-msg')).getAttribute();
expect(err.getText()).toEqual('VAT Number is invalid.');

 VAT Number is required.

Body:
You can use below code.

var EC=protractor.ExpectedConditions;
var errWebElement = element(by.css('.invalid.error-msg'));

expect(errWebElement.getText()).toEqual("VAT Number is required.");
 **OR**
expect(EC.visibilityOf(errWebElement)).toBe(true);


问:
UITextfield validation
I am trying to validate my text fields. I have two textfields Username and Password. I want to check that if the username textfield is kept empty then do not allow the user to move to the password textfield until he enters the username. Any sample code to do this will be much appreciated.

Thanks in advance.

答:
You want to check this in – textFieldDidBeginEditing: delegate

```<code>- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if(textField==passwordField)
{
if([userField.text isEqualToString:@""])
//Dont leave user field empty
}
}
</code>```

Title: UITextfield validation

Body:
You want to check this in – textFieldDidBeginEditing: delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if(textField==passwordField)
{
if([userField.text isEqualToString:@""])
//Dont leave user field empty
}
}


问:
How to check whether a system is big endian or little endian?
How to check whether a system is big endian or little endian?</p>

答:
A one-liner with Perl (which should be installed by default on almost all systems):

```<code>perl -e 'use Config; print $Config{byteorder}'
</code>```

If the output starts with a 1 (least-significant byte), it's a little-endian system. If the output starts with a higher digit (most-significant byte), it's a big-endian system. See documentation of the Config module.

Body:
A one-liner with Perl (which should be installed by default on almost all systems):

perl -e 'use Config; print $Config{byteorder}'

If the output starts with a 1 (least-significant byte), it's a little-endian system. If the output starts with a higher digit (most-significant byte), it's a big-endian system. See documentation of the Config module.


问:
Mapping the sentences, which are of variable length to particular key
I'm a newbie to Python as well as to this forum. Below is the question

The file is as mentioned in the image
File Format.
I'm able to split the text in text2 column and write to different rows with the below code

```<code>myfile=open('Output.csv,'w')
wr=csv.writer(myfile,lineterminator='\n')
df=pd.read_excel("Input.xlsx")

for txt in df['Text2']:
   sentence.append(txt.split('.'))
for pharse in sentence:
    for words in pharse:
        wr.writerow([words])
</code>```

I need a help on how to map the sentences, which are of variable length to the key.Also, how to achieve the specific format as mentioned in attached image file.
Also, the writerow function starts writing in the first row but how to specify to begin with column three.

Any help on this is much appreciated!!

答:
Try this:

```<code>myfile = open('Output.csv','w')
wr = csv.writer(myfile, lineterminator='\n')
entries = {}
for k, txt1, txt2 in df.values:
    sentences = [s.strip() for s in txt2.split('.') if len(s.strip()) > 0]
    # sentences = [s.strip() + '.' for s in txt2.split('.') if len(s.strip()) > 0]
    entries[k] = [txt1, sentences]
for k in entries.keys():
    txt1, txt2 = entries[k]
    wr.writerow([k, txt1, txt2[0]])
    for s in txt2[1:]:
        wr.writerow(['', '', s])
myfile.close()
</code>```

Use alternative sentences = ... line (the line commented in the above code) if you want to have a dot at the end of each sentence in the csv file. From your example image it is not clear what needs to happen to the dot (sometimes it appears in the output and sometimes it does not).

Also, if so desired, the code can be further simplified by combining the two loops into one loop:

```<code>myfile = open('Output.csv','w')
wr = csv.writer(myfile,lineterminator='\n')
for k, txt1, txt2 in df.values:
    sentences = [s.strip() for s in txt2.split('.') if len(s.strip()) > 0]
    wr.writerow([k, txt1, sentences[0]])
    for s in sentences[1:]:
        wr.writerow([None,'',s])
myfile.close()
</code>```

Body:
I'm a newbie to Python as well as to this forum. Below is the question

The file is as mentioned in the image
File Format.
I'm able to split the text in text2 column and write to different rows with the below code

myfile=open('Output.csv,'w')
wr=csv.writer(myfile,lineterminator='\n')
df=pd.read_excel("Input.xlsx")

for txt in df['Text2']:
   sentence.append(txt.split('.'))
for pharse in sentence:
    for words in pharse:
        wr.writerow([words])

I need a help on how to map the sentences, which are of variable length to the key.Also, how to achieve the specific format as mentioned in attached image file.
Also, the writerow function starts writing in the first row but how to specify to begin with column three.

Any help on this is much appreciated!!

Body:
Try this:

myfile = open('Output.csv','w')
wr = csv.writer(myfile, lineterminator='\n')
entries = {}
for k, txt1, txt2 in df.values:
    sentences = [s.strip() for s in txt2.split('.') if len(s.strip()) > 0]
    # sentences = [s.strip() + '.' for s in txt2.split('.') if len(s.strip()) > 0]
    entries[k] = [txt1, sentences]
for k in entries.keys():
    txt1, txt2 = entries[k]
    wr.writerow([k, txt1, txt2[0]])
    for s in txt2[1:]:
        wr.writerow(['', '', s])
myfile.close()

Use alternative sentences = ... line (the line commented in the above code) if you want to have a dot at the end of each sentence in the csv file. From your example image it is not clear what needs to happen to the dot (sometimes it appears in the output and sometimes it does not).

Also, if so desired, the code can be further simplified by combining the two loops into one loop:

myfile = open('Output.csv','w')
wr = csv.writer(myfile,lineterminator='\n')
for k, txt1, txt2 in df.values:
    sentences = [s.strip() for s in txt2.split('.') if len(s.strip()) > 0]
    wr.writerow([k, txt1, sentences[0]])
    for s in sentences[1:]:
        wr.writerow([None,'',s])
myfile.close()


问:
Export products table via CSV in CMS
Ive been trying to extend ProductCatalogAdmin, because thats the ModelAdmin that holds the Products I want to export. The code below works fine when added to core code (Which I don't want to do), but fails to do anything when added as an Extension.

PHP

```<code><?php

class ProductCatalogAdminExtension extends DataExtension {

    public function getExportFields() {
            return array(
                'ID' => 'ID',
                'InternalItemID' => 'InternalItemID',
                'Model' => 'Model',
                'Content' => 'Content',
                'CostPrice' => 'CostPrice',
                'BasePrice' => 'BasePrice',
                'Weight' => 'Weight',
                'Height' => 'Height',
                'Width' => 'Width',
                'Depth' => 'Depth',
                'Featured' => 'Featured',
                'AllowPurchase' => 'AllowPurchase',
                'Popularity' => 'Popularity',
                'PromoActive' => 'PromoActive',
                'PromoDisplay' => 'PromoDisplay',
                'PromoType' => 'PromoType',
                'PromoAmount' => 'PromoAmount',
                'PromoPercent' => 'PromoPercent',
                'PromoStartDate' => 'PromoStartDate',
                'PromoEndDate' => 'PromoEndDate',
                'Image.URL' => 'Image',
                'WholesalePrice' => 'WholesalePrice',
                'ParentID' => 'ParentID',
                'ProductCategory.ID' => 'AdditionalCategories'
            );
    }

}
</code>```

YML

```<code>---
Name: mysite
After:
  - 'framework/*'
  - 'cms/*'
---
# YAML configuration for SilverStripe
# See http://doc.silverstripe.org/framework/en/topics/configuration
# Caution: Indentation through two spaces, not tabs
SSViewer:
  theme: 'simple'
SiteConfig:
  extensions:
    - SiteConfigExtension
ProductCatalogAdmin:
  extensions:
    - ProductCatalogAdminExtension
</code>```

I've been told, ModelAdmin's getExportFields() doesn't have an extend() call, so I'll have to use inheritance rather than an Extension. However doing it under inheritance for ModelAdmin seems to do nothing also.
Interestingly I get no error messages, it doesn't really fail.

答:
yes, you need to subclass ProductCatalogAdmin in this case and tell SilverStripe to use your subclass instead.

```<code>class MyProductCatalogAdmin extends ProductCatalogAdmin

    public function getExportFields() {
        //your stuff here
    }
}
</code>```

And in your config.yml you write:

```<code>Injector:
  ProductCatalogAdmin:
    class: MyProductCatalogAdmin
</code>```

Now when anywhere ProductCatalogAdmin::create() is called, your subclass will be returned by the Injector. It won't work with new ProductCatalogAdmin()

See also Injector Docs

Title: Export products table via CSV in CMS

Body:
Ive been trying to extend ProductCatalogAdmin, because thats the ModelAdmin that holds the Products I want to export. The code below works fine when added to core code (Which I don't want to do), but fails to do anything when added as an Extension.

PHP

<?php

class ProductCatalogAdminExtension extends DataExtension {

    public function getExportFields() {
            return array(
                'ID' => 'ID',
                'InternalItemID' => 'InternalItemID',
                'Model' => 'Model',
                'Content' => 'Content',
                'CostPrice' => 'CostPrice',
                'BasePrice' => 'BasePrice',
                'Weight' => 'Weight',
                'Height' => 'Height',
                'Width' => 'Width',
                'Depth' => 'Depth',
                'Featured' => 'Featured',
                'AllowPurchase' => 'AllowPurchase',
                'Popularity' => 'Popularity',
                'PromoActive' => 'PromoActive',
                'PromoDisplay' => 'PromoDisplay',
                'PromoType' => 'PromoType',
                'PromoAmount' => 'PromoAmount',
                'PromoPercent' => 'PromoPercent',
                'PromoStartDate' => 'PromoStartDate',
                'PromoEndDate' => 'PromoEndDate',
                'Image.URL' => 'Image',
                'WholesalePrice' => 'WholesalePrice',
                'ParentID' => 'ParentID',
                'ProductCategory.ID' => 'AdditionalCategories'
            );
    }

}

YML

---
Name: mysite
After:
  - 'framework/*'
  - 'cms/*'
---
# YAML configuration for SilverStripe
# See http://doc.silverstripe.org/framework/en/topics/configuration
# Caution: Indentation through two spaces, not tabs
SSViewer:
  theme: 'simple'
SiteConfig:
  extensions:
    - SiteConfigExtension
ProductCatalogAdmin:
  extensions:
    - ProductCatalogAdminExtension

I've been told, ModelAdmin's getExportFields() doesn't have an extend() call, so I'll have to use inheritance rather than an Extension. However doing it under inheritance for ModelAdmin seems to do nothing also.
Interestingly I get no error messages, it doesn't really fail.

Body:
yes, you need to subclass ProductCatalogAdmin in this case and tell SilverStripe to use your subclass instead.

class MyProductCatalogAdmin extends ProductCatalogAdmin

    public function getExportFields() {
        //your stuff here
    }
}

And in your config.yml you write:

Injector:
  ProductCatalogAdmin:
    class: MyProductCatalogAdmin

Now when anywhere ProductCatalogAdmin::create() is called, your subclass will be returned by the Injector. It won't work with new ProductCatalogAdmin()

See also Injector Docs


问:
C: Add auto prefix to hex calculation
This is my C program

```<code>#include <stdio.h>
void main() {
    printf("Diff = %x\n",0xffffffff-0xfffffffa);
}
</code>```

And the standard output would be like this

```<code>C:\Codes>prog.exe
Diff = 5
</code>```

What I'm trying to achieve is to add auto prefix 0x00000005 automatically to the answer so the output would be like this.

```<code>C:\Codes>prog.exe
Diff = 0x00000005
</code>```

or

```<code>C:\Codes>prog.exe
Diff = 0x00000A35
</code>```

I know we can do this manually with this code

```<code>#include <stdio.h>
void main() {
    printf("Diff = 0x0000000%x\n",0xffffffff-0xfffffffa);
}
</code>```

But, is it possible to accomplish this without manually write 0x0000000%x in printf?

答:
Yes it's possible:

```<code>printf("0x%08x\n", 0xffffffff-0xfffffffa);
</code>```

Most good beginners books would have some text about formatting options. And there's always good references to read.

Title: C: Add auto prefix to hex calculation

Body:
This is my C program

#include <stdio.h>
void main() {
    printf("Diff = %x\n",0xffffffff-0xfffffffa);
}

And the standard output would be like this

C:\Codes>prog.exe
Diff = 5

What I'm trying to achieve is to add auto prefix 0x00000005 automatically to the answer so the output would be like this.

C:\Codes>prog.exe
Diff = 0x00000005

or

C:\Codes>prog.exe
Diff = 0x00000A35

I know we can do this manually with this code

#include <stdio.h>
void main() {
    printf("Diff = 0x0000000%x\n",0xffffffff-0xfffffffa);
}

But, is it possible to accomplish this without manually write 0x0000000%x in printf?

Body:
Yes it's possible:

printf("0x%08x\n", 0xffffffff-0xfffffffa);

Most good beginners books would have some text about formatting options. And there's always good references to read.


答: you make your username textfield as firstResponder.Then in Textfield did beginediting method check if characters entered or not.And in textfieldDidEndEditing,check if the textfield is not empty.If its not empty then allow password field to become first responder else keep first responder as username textfield itself.</p>

Title: UITextfield validation

Body:
I am trying to validate my text fields. I have two textfields Username and Password. I want to check that if the username textfield is kept empty then do not allow the user to move to the password textfield until he enters the username. Any sample code to do this will be much appreciated.

Thanks in advance.


问:
Include blank elements in for...each loop in Classic ASP
I'm trying to convert a VBScript array to a querystring to include as a Get in a URL. I've got:

```<code>function array_to_querystring( arrParams )
    dim x : x=1
    for each param in arrParams
        array_to_querystring = "&" & x & "=" & param
        x=x+1
    next
end function
</code>```

The problem is that sometimes an element is an empty string, and I DO want to include that, but my code drops those.

So if I call array_to_querystring( array( "", "hello" ) ) I get:

```<code>&2=hello
</code>```

What I want is:

```<code>&1=&2=hello
</code>```

The for...each loop is dropping params that are empty string. Any idea how to force it to include them?

答:
It is not because of the empty string, but because you are assigning the value to the function name in each iteration.

You should keep adding to a string in each iteration and then assign the string to the function name after the loop.

```<code>function array_to_querystring( arrParams )
    dim x : x=1
    dim output : output=""
    for each param in arrParams
        output = output & "&" & x & "=" & param
        x=x+1
    next

    array_to_querystring = output
end function
</code>```

Body:
I'm trying to convert a VBScript array to a querystring to include as a Get in a URL. I've got:

function array_to_querystring( arrParams )
    dim x : x=1
    for each param in arrParams
        array_to_querystring = "&" & x & "=" & param
        x=x+1
    next
end function

The problem is that sometimes an element is an empty string, and I DO want to include that, but my code drops those.

So if I call array_to_querystring( array( "", "hello" ) ) I get:

&2=hello

What I want is:

&1=&2=hello

The for...each loop is dropping params that are empty string. Any idea how to force it to include them?

Body:
It is not because of the empty string, but because you are assigning the value to the function name in each iteration.

You should keep adding to a string in each iteration and then assign the string to the function name after the loop.

function array_to_querystring( arrParams )
    dim x : x=1
    dim output : output=""
    for each param in arrParams
        output = output & "&" & x & "=" & param
        x=x+1
    next

    array_to_querystring = output
end function


问:
vb.net (1.10) in percentage
i am creating an small application which allows user to calculate sale price by cost price * 10% (profit for example) and result will store in sale price

```<code>dim saleprice as integer
costprice = textbox1.text
percent = textbox2.text
saleprice = costprice * percent
label1.text = saleprice
</code>```

but the problem is when user input 10 in textbox2.text it will multiply by 100 if user input 1.10 then result will be correct but i want to skip this "1." so user will directly put 10 or  whatever but i dont know how to do that please help and thanks in advance

答:
There is a main issue with your code, but also a couple of smaller issues.

The main issue is that you have defined saleprice as an integer, so it can only hold integers. I'm guessing that you also have costprice and percent defined as integers. Instead, define them all as Single or Double.

There is also the issue of converting types. The information you enter into the TextBox is stored as a string. In the real world you would have to make sure that the .Text property is convertable to a numeric value and then convert it. With your current Visual Studio settings, the conversion is done behind the scenes. This makes life easier for beginners, but encourages very sloppy programming.

I would suggest changing your compiler settings so that Option Strict is on ,Option Explicit is on, Option Compare is set to Binary and Option Infer is off.

This will make writing your code a little harder, but in the long run, it will save you time and force you to write better code.

Edit : Whoops

I missed the crucial part of your question - to do away with the "1" part and just enter the percent as a whole number - this should be your code

So.. in its simplest and still error prone form, your code would need to be ..

```<code>Dim costprice As Double
Dim percent As Double
Dim saleprice As Double
costprice = Val(TextBox1.Text)
percent = Val(textbox2.text)/100
saleprice = costprice * (1 + percent)
Label1.Text = saleprice.ToString
</code>```

To increase the cost by 10 percent, simply enter 10 in the Percent textbox. To decrease the cost by 10 percent, enter -10.

Title: vb.net (1.10) in percentage

Body:
i am creating an small application which allows user to calculate sale price by cost price * 10% (profit for example) and result will store in sale price

dim saleprice as integer
costprice = textbox1.text
percent = textbox2.text
saleprice = costprice * percent
label1.text = saleprice

but the problem is when user input 10 in textbox2.text it will multiply by 100 if user input 1.10 then result will be correct but i want to skip this "1." so user will directly put 10 or  whatever but i dont know how to do that please help and thanks in advance

Body:
There is a main issue with your code, but also a couple of smaller issues.

The main issue is that you have defined saleprice as an integer, so it can only hold integers. I'm guessing that you also have costprice and percent defined as integers. Instead, define them all as Single or Double.

There is also the issue of converting types. The information you enter into the TextBox is stored as a string. In the real world you would have to make sure that the .Text property is convertable to a numeric value and then convert it. With your current Visual Studio settings, the conversion is done behind the scenes. This makes life easier for beginners, but encourages very sloppy programming.

I would suggest changing your compiler settings so that Option Strict is on ,Option Explicit is on, Option Compare is set to Binary and Option Infer is off.

This will make writing your code a little harder, but in the long run, it will save you time and force you to write better code.

Edit : Whoops

I missed the crucial part of your question - to do away with the "1" part and just enter the percent as a whole number - this should be your code

So.. in its simplest and still error prone form, your code would need to be ..

Dim costprice As Double
Dim percent As Double
Dim saleprice As Double
costprice = Val(TextBox1.Text)
percent = Val(textbox2.text)/100
saleprice = costprice * (1 + percent)
Label1.Text = saleprice.ToString

To increase the cost by 10 percent, simply enter 10 in the Percent textbox. To decrease the cost by 10 percent, enter -10.


问:
Is sparse tensor multiplication implemented in TensorFlow?

Multiplication of sparse tensors with themselves or with dense tensors does not seem to work in TensorFlow.  The following example

from __future__ import print_function
import tensorflow as tf

x = tf.constant([[1.0,2.0],
                 [3.0,4.0]])
y = tf.SparseTensor(indices=[[0,0],[1,1]], values=[1.0,1.0], shape=[2,2])
z = tf.matmul(x,y)

sess = tf.Session()
sess.run(tf.initialize_all_variables())
print(sess.run([x, y, z]))
```

<p>fails with the error message</p>

<pre class="lang-py prettyprint-override"><code>TypeError: Input 'b' of 'MatMul' Op has type string that does not match type
float32 of argument 'a'
</code>```

Both tensors have values of type float32 as seen by evaluating them  without the multiplication op.  Multiplication of y with itself returns a similar error message.  Multipication of x with itself works fine.

答:
It seems that

```<code>tf.sparse_matmul(
    a,
    b,
    transpose_a=None,
    transpose_b=None,
    a_is_sparse=None,
    b_is_sparse=None,
    name=None
)
</code>```

is not for multiplication of two SparseTensors.

a and b are Tensors not SparseTensors. And I have tried that, it is not working with SparseTensors.

Body:
Multiplication of sparse tensors with themselves or with dense tensors does not seem to work in TensorFlow.  The following example

from __future__ import print_function
import tensorflow as tf

x = tf.constant([[1.0,2.0],
                 [3.0,4.0]])
y = tf.SparseTensor(indices=[[0,0],[1,1]], values=[1.0,1.0], shape=[2,2])
z = tf.matmul(x,y)

sess = tf.Session()
sess.run(tf.initialize_all_variables())
print(sess.run([x, y, z]))

fails with the error message

TypeError: Input 'b' of 'MatMul' Op has type string that does not match type
float32 of argument 'a'

Both tensors have values of type float32 as seen by evaluating them  without the multiplication op.  Multiplication of y with itself returns a similar error message.  Multipication of x with itself works fine.

Body:
It seems that

tf.sparse_matmul(
    a,
    b,
    transpose_a=None,
    transpose_b=None,
    a_is_sparse=None,
    b_is_sparse=None,
    name=None
)

is not for multiplication of two SparseTensors.

a and b are Tensors not SparseTensors. And I have tried that, it is not working with SparseTensors.


问:
Sql conditional sum computation on other column value check
i have following sql query.

```<code>SELECT (SELECT ISNULL(SUM(Qty),0)
From Bills
JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
where SessionID = '" + DBHandler.SessionID(Date) + "'
and BillMaster.ShiftID = " + SHiftID + "
and Bills.ProductID = products.id ) [qty],
products.price , products.name
FROM products.
</code>```

In "Bills" table there is column "isDeal". I want that sum will execute only when "isDeal" = 0
I attached Bills table screenshot in which it can be seen that there is column "isDeal"
and i am attaching output report where i want that when isDeal = 0 then sum will compute other wise sum shouldn't compute

so how can i compute this ?

答:
Please use below query:</p>

```<code>SELECT (SELECT ISNULL(SUM(
CASE
    WHEN IsDeal =0 THEN Qty
    ELSE 0
END,0)
),0)
From Bills
JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
where SessionID = '" + DBHandler.SessionID(Date) + "'
and BillMaster.ShiftID = " + SHiftID + "
and Bills.ProductID = products.id ) [qty],
products.price , products.name
FROM products
</code>```

Body:
i have following sql query.

SELECT (SELECT ISNULL(SUM(Qty),0)
From Bills
JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
where SessionID = '" + DBHandler.SessionID(Date) + "'
and BillMaster.ShiftID = " + SHiftID + "
and Bills.ProductID = products.id ) [qty],
products.price , products.name
FROM products.

In "Bills" table there is column "isDeal". I want that sum will execute only when "isDeal" = 0
I attached Bills table screenshot in which it can be seen that there is column "isDeal"
and i am attaching output report where i want that when isDeal = 0 then sum will compute other wise sum shouldn't compute

so how can i compute this ?

Body:
Please use below query:

SELECT (SELECT ISNULL(SUM(
CASE
    WHEN IsDeal =0 THEN Qty
    ELSE 0
END,0)
),0)
From Bills
JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
where SessionID = '" + DBHandler.SessionID(Date) + "'
and BillMaster.ShiftID = " + SHiftID + "
and Bills.ProductID = products.id ) [qty],
products.price , products.name
FROM products


问:
pass fixture to test class in pytest
Consider the following pseudocode demonstrating my question:

```<code>import pytest

@pytest.fixture
def param1():
    # return smth
    yield "wilma"

@pytest.fixture
def param2():
    # return smth
    yield "fred"

@pytest.fixture
def bar(param1, param2):
    #do smth
    return [Bar(param1, param2), Bar(param1, param2)]

@pytest.fixture
def first_bar(bar):
    return bar[0]

class Test_first_bar:

    # FIXME: how do I do that?
    #def setup_smth???(self, first_bar):
    #    self.bar = first_bar

    def test_first_bar_has_wilma(self):
        # some meaningful check number 1
        assert self.bar.wilma == "wilma"

    def test_first_bar_some_other_check(self):
        # some meaningful check number 2
        assert self.bar.fred == "fred"
</code>```

Basically I want to pass first_bar fixture to my Test_first_bar class in order to reuse that object in all its test methods. How should I go about dealing with such situation?

Python 3, if that matters.

答:
Here, you can define your fixture as autouse. Which would be called automatically for all the tests of your class. Here, I cant understand what is [Bar(param1, param2), Bar(param1, param2)]. Well, that's not the point, if rest of the code is working fine than you can try the below solution. I have replaced the code with static variables to verify if it's working or not and it's working fine at my end.

```<code>import pytest

@pytest.fixture
def param1():
    # return smth
    yield "wilma"

@pytest.fixture
def param2():
    # return smth
    yield "fred"

@pytest.fixture
def bar(param1, param2):
    # do smth
    return [Bar(param1, param2), Bar(param1, param2)]

@pytest.fixture(scope='function', autouse=True)
def first_bar(bar, request):
    request.instance.bar = bar[0]

class Test_first_bar:

    def test_first_bar_has_wilma(self,request):
        print request.instance.bar

    def test_first_bar_some_other_check(self,request):
        print request.instance.bar
</code>```

And if you do not want to make fixture as autouse, than you can call it before your test. Like,

```<code>import pytest

@pytest.fixture
def param1():
    # return smth
    yield "wilma"

@pytest.fixture
def param2():
    # return smth
    yield "fred"

@pytest.fixture
def bar(param1, param2):
    # do smth
    return [Bar(param1, param2), Bar(param1, param2)]

@pytest.fixture(scope='function')
def first_bar(bar, request):
    request.instance.bar = bar[0]

class Test_first_bar:

    @pytest.mark.usefixtures("first_bar")
    def test_first_bar_has_wilma(self,request):
        print request.instance.bar

    @pytest.mark.usefixtures("first_bar")
    def test_first_bar_some_other_check(self,request):
        print request.instance.bar
</code>```

Title: pass fixture to test class in pytest

Body:
Consider the following pseudocode demonstrating my question:

import pytest

@pytest.fixture
def param1():
    # return smth
    yield "wilma"

@pytest.fixture
def param2():
    # return smth
    yield "fred"

@pytest.fixture
def bar(param1, param2):
    #do smth
    return [Bar(param1, param2), Bar(param1, param2)]

@pytest.fixture
def first_bar(bar):
    return bar[0]

class Test_first_bar:

    # FIXME: how do I do that?
    #def setup_smth???(self, first_bar):
    #    self.bar = first_bar

    def test_first_bar_has_wilma(self):
        # some meaningful check number 1
        assert self.bar.wilma == "wilma"

    def test_first_bar_some_other_check(self):
        # some meaningful check number 2
        assert self.bar.fred == "fred"

Basically I want to pass first_bar fixture to my Test_first_bar class in order to reuse that object in all its test methods. How should I go about dealing with such situation?

Python 3, if that matters.

Body:
Here, you can define your fixture as autouse. Which would be called automatically for all the tests of your class. Here, I cant understand what is [Bar(param1, param2), Bar(param1, param2)]. Well, that's not the point, if rest of the code is working fine than you can try the below solution. I have replaced the code with static variables to verify if it's working or not and it's working fine at my end.

import pytest

@pytest.fixture
def param1():
    # return smth
    yield "wilma"

@pytest.fixture
def param2():
    # return smth
    yield "fred"

@pytest.fixture
def bar(param1, param2):
    # do smth
    return [Bar(param1, param2), Bar(param1, param2)]

@pytest.fixture(scope='function', autouse=True)
def first_bar(bar, request):
    request.instance.bar = bar[0]

class Test_first_bar:

    def test_first_bar_has_wilma(self,request):
        print request.instance.bar

    def test_first_bar_some_other_check(self,request):
        print request.instance.bar

And if you do not want to make fixture as autouse, than you can call it before your test. Like,

import pytest

@pytest.fixture
def param1():
    # return smth
    yield "wilma"

@pytest.fixture
def param2():
    # return smth
    yield "fred"

@pytest.fixture
def bar(param1, param2):
    # do smth
    return [Bar(param1, param2), Bar(param1, param2)]

@pytest.fixture(scope='function')
def first_bar(bar, request):
    request.instance.bar = bar[0]

class Test_first_bar:

    @pytest.mark.usefixtures("first_bar")
    def test_first_bar_has_wilma(self,request):
        print request.instance.bar

    @pytest.mark.usefixtures("first_bar")
    def test_first_bar_some_other_check(self,request):
        print request.instance.bar


问:
RealmSwift + ObjectMapper managing String Array (tags)
What I need to represent in RealmSwift is the following JSON scheme:

```<code>{
    "id": 1234,
    "title": "some value",
    "tags": [ "red", "blue", "green" ]
}
</code>```

Its a basic string array that I'm stumbling on. I'm guessing in Realm I need to represent "tags" as

```<code>dynamic id: Int = 0
dynamic title: String = ""
let tags = List<MyTagObject>()
</code>```

making tags its own table in Realm, but how to map it with ObjectMapper? This is how far I got...

```<code>func mapping(map: Map) {
    id <- map["id"]
    title <- map["title"]
    tags <- map["tags"]
}
</code>```

... but the tags line doesn't compile of course because of the List and Realm cannot use a [String] type.

This feels like a somewhat common problem and I'm hoping someone who has faced this can comment or point to a post with a suggestion.

UPDATE 1
The MyTagObject looks like the following:

```<code>class MyTagObject: Object {
    dynamic var name: String = ""
}
</code>```

UPDATE 2
I found this post which deals with the realm object but assumes the array has named elements rather than a simple string.
https://gist.github.com/Jerrot/fe233a94c5427a4ec29b

答:
First of all we should assume that our model extends both Object and Mappable.

Let's create a wrapper model to store the primitive (String) type:

```<code>class StringObject: Object {
    dynamic var value = ""
}
</code>```

Then we describe corresponding properties and mapping rules for the root model (not the wrapper one):

```<code>var tags = List<StringObject>()

var parsedTags: [String] {
    var result = [String]()
    for tag in tags {
        result.append(tag.value)
    }
    return result
}

override static func ignoredProperties() -> [String] {
    return ["parsedTags"]
}

func mapping(map: Map) {
    if let unwrappedTags = map.JSON["tags"] as? [String] {
        for tag in unwrappedTags {
            let tagObject = StringObject()
            tagObject.value = tag
            tags.append(tagObject)
        }
    }
}
</code>```

We need a tags property to store and obtain the data about tags from Realm.
Then a parsedTags property simplifies extraction of tags in the usual array format.
An ignoredProperties definition allows to avoid some failures with Realm while data savings (because of course we can't store non-Realm datatypes in the Realm).
And at last we are manually parsing our tags in the mapping function to store it in the Realm.

Body:
What I need to represent in RealmSwift is the following JSON scheme:

{
    "id": 1234,
    "title": "some value",
    "tags": [ "red", "blue", "green" ]
}

Its a basic string array that I'm stumbling on. I'm guessing in Realm I need to represent "tags" as

dynamic id: Int = 0
dynamic title: String = ""
let tags = List<MyTagObject>()

making tags its own table in Realm, but how to map it with ObjectMapper? This is how far I got...

func mapping(map: Map) {
    id <- map["id"]
    title <- map["title"]
    tags <- map["tags"]
}

... but the tags line doesn't compile of course because of the List and Realm cannot use a [String] type.

This feels like a somewhat common problem and I'm hoping someone who has faced this can comment or point to a post with a suggestion.

UPDATE 1
The MyTagObject looks like the following:

class MyTagObject: Object {
    dynamic var name: String = ""
}

UPDATE 2
I found this post which deals with the realm object but assumes the array has named elements rather than a simple string.
https://gist.github.com/Jerrot/fe233a94c5427a4ec29b

Body:
First of all we should assume that our model extends both Object and Mappable.

Let's create a wrapper model to store the primitive (String) type:

class StringObject: Object {
    dynamic var value = ""
}

Then we describe corresponding properties and mapping rules for the root model (not the wrapper one):

var tags = List<StringObject>()

var parsedTags: [String] {
    var result = [String]()
    for tag in tags {
        result.append(tag.value)
    }
    return result
}

override static func ignoredProperties() -> [String] {
    return ["parsedTags"]
}

func mapping(map: Map) {
    if let unwrappedTags = map.JSON["tags"] as? [String] {
        for tag in unwrappedTags {
            let tagObject = StringObject()
            tagObject.value = tag
            tags.append(tagObject)
        }
    }
}

We need a tags property to store and obtain the data about tags from Realm.
Then a parsedTags property simplifies extraction of tags in the usual array format.
An ignoredProperties definition allows to avoid some failures with Realm while data savings (because of course we can't store non-Realm datatypes in the Realm).
And at last we are manually parsing our tags in the mapping function to store it in the Realm.


问:
Get the displayed size of an image inside an ImageView
The code is simple:

```<code><ImageView android:layout_width="fill_parent"
           android:layout_height="fill_parent"
           android:src="@drawable/cat"/>
</code>```

Notice the ImageView used fill_parent for width and height.

The image cat is a small image and it will be zoomed in to fit the ImageView, and keep the width/height ratio at the same time.

My question is how to get the displayed size of the image? I tried:

```<code>imageView.getDrawable().getIntrinsicHeight()
</code>```

But which it the original height of the image cat.

I tried:

```<code>imageView.getDrawable().getBounds()
</code>```

But which returns Rect(0,0,0,0).

答:
Here is a helper function to get the bounds of image in an imageView.</p>

```<code>/**
 * Helper method to get the bounds of image inside the imageView.
 *
 * @param imageView the imageView.
 * @return bounding rectangle of the image.
 */
public static RectF getImageBounds(ImageView imageView) {
    RectF bounds = new RectF();
    Drawable drawable = imageView.getDrawable();
    if (drawable != null) {
        imageView.getImageMatrix().mapRect(bounds, new RectF(drawable.getBounds()));
    }
    return bounds;
}
</code>```

Body:
The code is simple:

<ImageView android:layout_width="fill_parent"
           android:layout_height="fill_parent"
           android:src="@drawable/cat"/>

Notice the ImageView used fill_parent for width and height.

The image cat is a small image and it will be zoomed in to fit the ImageView, and keep the width/height ratio at the same time.

My question is how to get the displayed size of the image? I tried:

imageView.getDrawable().getIntrinsicHeight()

But which it the original height of the image cat.

I tried:

imageView.getDrawable().getBounds()

But which returns Rect(0,0,0,0).

Body:
Here is a helper function to get the bounds of image in an imageView.

/**
 * Helper method to get the bounds of image inside the imageView.
 *
 * @param imageView the imageView.
 * @return bounding rectangle of the image.
 */
public static RectF getImageBounds(ImageView imageView) {
    RectF bounds = new RectF();
    Drawable drawable = imageView.getDrawable();
    if (drawable != null) {
        imageView.getImageMatrix().mapRect(bounds, new RectF(drawable.getBounds()));
    }
    return bounds;
}


答:
Assuming you have some kind of submit button, I don't recommend trying to artificially keep the user in one field. Instead set the submitButton.enabled = NO until both fields are valid. If you indicate that the fields are required then the user won't be nearly as confused as he would be if he couldn't change the text field focus.

For validation, in IB set both textfields' EditingChanged pointing to a method in your viewContoller, something like ValidateEntry. Give them both unique tags, just 1 and 2 or what have you.

In the ValidateEntry field determine which one is being edited -- the (id)sender will have a tag telling you which is which -- and when both fields are valid make the submit button available, submitButton.enabled = YES. If either is invalid, disable it.

In my opinion this is much friendlier and results in exactly the same thing: no sending empty fields.

Title: UITextfield validation


问:
build kernel with aarch64-linux-gnu-gcc
I am trying to build the kernel source on my platform with the following command:

```<code>make ARCH=arm CROSS_COMPILE=aarch64-linux-gnu- generic-v8-defconfig
</code>```

However, the error messages appear as shown in the following:

```<code>/bin/sh: 1: aarch64-linux-gnu-gcc: not found
</code>```

It's obvious I have not this version of gcc installed on my laptop.

I then followed

http://www.howtoinstall.co/en/ubuntu/trusty/main/gcc-4.8-aarch64-linux-gnu/

This to install gcc-4.8-aarch-linux-gnu,

however, I still get the same error message.

Ubuntu version: 14.04

Please let me know if you know how to fix this.

Thanks

答:
You can use the following commands:

```<code>sudo add-apt-repository ppa:linaro-maintainers/toolchain
sudo apt-get update
sudo apt-get install gcc-**version**-aarch64-linux-gnu
</code>```

Make sure to replace **version** by the correct version.

ContentLicense: CC BY-SA 4.0

Title: build kernel with aarch64-linux-gnu-gcc

Body:
I am trying to build the kernel source on my platform with the following command:

make ARCH=arm CROSS_COMPILE=aarch64-linux-gnu- generic-v8-defconfig

However, the error messages appear as shown in the following:

/bin/sh: 1: aarch64-linux-gnu-gcc: not found

It's obvious I have not this version of gcc installed on my laptop.

I then followed

http://www.howtoinstall.co/en/ubuntu/trusty/main/gcc-4.8-aarch64-linux-gnu/

This to install gcc-4.8-aarch-linux-gnu,

however, I still get the same error message.

Ubuntu version: 14.04

Please let me know if you know how to fix this.

Thanks

Body:
You can use the following commands:

sudo add-apt-repository ppa:linaro-maintainers/toolchain
sudo apt-get update
sudo apt-get install gcc-**version**-aarch64-linux-gnu

Make sure to replace **version** by the correct version.


问:
linked list undefined behavior
An abstract question: Say I have a singly-linked list of the nodes:

```<code>      #node 1      #node 2
root->[data|next]->[data|next]->NULL
</code>```

In C, root is declared:

```<code>struct Node *root = NULL;
</code>```

where *root is the Node pointer 'holding' the address "NULL".

Now, lets say that I want to remove the last node in the linked list, the following code will allow the computer to do such action:

```<code>//pop: pop removes last/latter node in linked list and sets new last node to NULL
void pop(struct Node *root){
    struct Node *last;
    struct Node *current = root;    //current point to same node as root

    while(current->next != NULL){
        if(current->next == NULL) {break;}    //premature break in traversing of linked list; will stop at last node
        last = current;    //last points to same node as current
        current = current->next;    //move current to next node
    }

    last->next = NULL;    //point second-to-last node to NULL, making it defacto last node in list
    free(current);    //free last node to heap

}//end pop
</code>```

after calling pop and passing root to the function, the new linked list looks like this:

```<code>      #node 1
root->[data|next]->NULL
</code>```

If the program calls pop again, we should expect the linked list to look like this:

```<code>root->NULL
</code>```

However, it does not! In the case of a linked list of integer elements in order, we will call pop until we observe strange behaviour:

```<code>List: 1 2 3
Call pop
List: 1 2
Call pop
List: 1
Call pop
List 1980765
</code>```

The above is an example of undefined behavoir caused by a dangling pointer. Now the question is: How can the program avoid this behaviour and produce a side-effect that close to root->NULL from popping all nodes from the linked list until said list is empty?

答:
First:

This condition can never ever be true:

```<code>if(current->next == NULL) {break;}
</code>```

If it was true, we wouldn't reach that line but fall out of the while loop.

Second:

If you do not execute the body of the loop at least once, your pointer last keeps uninitialized. Hence

```<code>last->next = NULL;
</code>```

sets a random memory location to NULL

Third:

When you try to remove the last remaining element, you need to free(root). But you cannot set root to NULL as it is passed by value.

Title: linked list undefined behavior

Body:
An abstract question: Say I have a singly-linked list of the nodes:

      #node 1      #node 2
root->[data|next]->[data|next]->NULL

In C, root is declared:

struct Node *root = NULL;

where *root is the Node pointer 'holding' the address "NULL".

Now, lets say that I want to remove the last node in the linked list, the following code will allow the computer to do such action:

//pop: pop removes last/latter node in linked list and sets new last node to NULL
void pop(struct Node *root){
    struct Node *last;
    struct Node *current = root;    //current point to same node as root

    while(current->next != NULL){
        if(current->next == NULL) {break;}    //premature break in traversing of linked list; will stop at last node
        last = current;    //last points to same node as current
        current = current->next;    //move current to next node
    }

    last->next = NULL;    //point second-to-last node to NULL, making it defacto last node in list
    free(current);    //free last node to heap

}//end pop

after calling pop and passing root to the function, the new linked list looks like this:

      #node 1
root->[data|next]->NULL

If the program calls pop again, we should expect the linked list to look like this:

root->NULL

However, it does not! In the case of a linked list of integer elements in order, we will call pop until we observe strange behaviour:

List: 1 2 3
Call pop
List: 1 2
Call pop
List: 1
Call pop
List 1980765

The above is an example of undefined behavoir caused by a dangling pointer. Now the question is: How can the program avoid this behaviour and produce a side-effect that close to root->NULL from popping all nodes from the linked list until said list is empty?

Body:
First:

This condition can never ever be true:

if(current->next == NULL) {break;}

If it was true, we wouldn't reach that line but fall out of the while loop.

Second:

If you do not execute the body of the loop at least once, your pointer last keeps uninitialized. Hence

last->next = NULL;

sets a random memory location to NULL

Third:

When you try to remove the last remaining element, you need to free(root). But you cannot set root to NULL as it is passed by value.


问:
AnjularJS ng-repeat get item from different scope object
I have two different scope objects. First one is 'Details' object, the second one is 'Country' object. I want to fetch data from my 'Country' object using 'CountryId' which is in the 'Details' object.

I have created a function in my scope and I can fetch my Country data (please see the below code. it is working properly) but I'm sure that it should be a better way in AngularJS.
Is there?

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
    var app = angular.module("myApp", []);
    app.controller("myCtrl", function($scope) {
        $scope.FindSpecificItem = function(obj, field, value, returnField) {
            return jQuery.grep(obj, function(item) {
                return (item[field] == value);
            })[0][returnField];
        };
        $scope.details = [{
            "Name": "John",
            "CountryId": "1"
        }, {
            "Name": "Dave",
            "CountryId": "2"
        }]
        $scope.Countries = [{
            "Id": "1",
            "Country": "USA"
        }, {
            "Id": "2",
            "Country": "England"
        }]
    });
</script>

<body>

    <div ng-app="myApp" ng-controller="myCtrl">
        <table>
            <tr ng-repeat="d in details">
                <td>{{d.Name}}</td>
                <td>{{FindSpecificItem(Countries,"Id",d.CountryId,"Country")}}</td>
            </tr>
        </table>
    </div>

</body>

</html>
</code>```

答:
You can filter Countries using filter function

<!DOCTYPE html>

        {{d.Name}}
        {{getCountry(d.CountryId)}}

```

Body:
I have two different scope objects. First one is 'Details' object, the second one is 'Country' object. I want to fetch data from my 'Country' object using 'CountryId' which is in the 'Details' object.

I have created a function in my scope and I can fetch my Country data (please see the below code. it is working properly) but I'm sure that it should be a better way in AngularJS.
Is there?

<!DOCTYPE html>

                {{d.Name}}
                {{FindSpecificItem(Countries,"Id",d.CountryId,"Country")}}

Body:
You can filter Countries using filter function

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
  var app = angular.module("myApp", []);
  app.controller("myCtrl", function($scope) {

    $scope.getCountry=function(id){
    console.log("Calling "+id);
    var countries=$scope.Countries.filter(function(item){
     console.log(item.Id===id)
        return item.Id===id;

     })
    return countries[0].Country;
    }

    $scope.details = [{
        "Name": "John",
        "CountryId": "1"
      },
      {
        "Name": "Dave",
        "CountryId": "2"
      }
    ]

    $scope.Countries = [{
        "Id": "1",
        "Country": "USA"
      },
      {
        "Id": "2",
        "Country": "England"
      }
    ]
  });
</script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">
    <table>
      <tr ng-repeat="d in details">
        <td>{{d.Name}}</td>
        <td>{{getCountry(d.CountryId)}}

        </td>
      </tr>
    </table>
  </div>

</body>

</html>


问:
How to use $cond in MongoDB Aggregation
I am trying to use $cond in Redash to transform a true/false/null to a meaningful value for a report. When I perform the query I only ever get the false case.

This is my query below. I have included the "isSuggestedProgram" in the projection just so I can verify the values for now.

All results show "Custom" as the result regardless of the value of isSuggestedProgram. What is wrong with the way I am doing the $cond?

```<code>{
    "collection": "Program",
    "aggregate": [
        {
            "$project": {
                "isSuggestedProgram": "$isSuggestedProgram",
                "suggested": {
                    "$cond": {
                        "if": {
                            "$eq": [
                                "$isSuggestedProgram", "true"
                            ]
                        },
                        "then": "Suggested",
                        "else": "Custom"
                    }
                }
            }
        }
    ]
}
</code>```

答:
You stringify your Boolean. What you intend is probably this:</p>

```<code>"$isSuggestedProgram", true
</code>```

Title: How to use $cond in MongoDB Aggregation

Body:
I am trying to use $cond in Redash to transform a true/false/null to a meaningful value for a report. When I perform the query I only ever get the false case.

This is my query below. I have included the "isSuggestedProgram" in the projection just so I can verify the values for now.

All results show "Custom" as the result regardless of the value of isSuggestedProgram. What is wrong with the way I am doing the $cond?

{
    "collection": "Program",
    "aggregate": [
        {
            "$project": {
                "isSuggestedProgram": "$isSuggestedProgram",
                "suggested": {
                    "$cond": {
                        "if": {
                            "$eq": [
                                "$isSuggestedProgram", "true"
                            ]
                        },
                        "then": "Suggested",
                        "else": "Custom"
                    }
                }
            }
        }
    ]
}

Body:
You stringify your Boolean. What you intend is probably this:

"$isSuggestedProgram", true


问:
MySQL : Better Solution To Nested If
I have the link :
Types Of Triangle

My answer is:

SELECT IF (A = B AND A = C AND B = C, 'Equilateral', IF((A = B OR A = C OR B = C) AND (A + B) > C, 'Isosceles', IF (A != B AND A != C AND B != C AND (A + B) > C, 'Scalene', 'Not A Triangle'))) FROM TRIANGLES

So far, its correct but somehow I have used a messy nested IF.

My question is, is there a better way to solve in terms of elegance and efficiency? I'm kinda familiar with SQL queries for years now but its something that I seldom use since I'm more into front end development.

Thanks.

答:
You can use CASE:

```<code>SELECT  CASE
            WHEN A = B AND A = C AND B = C THEN 'Equilateral'
            WHEN A = B OR A = C OR B = C AND (A + B) > C THEN 'Isosceles'
            WHEN A != B AND A != C AND B != C AND (A + B) > C THEN 'Scalene'
            ELSE 'Not A Triangle'
        END
FROM    TRIANGLES
</code>```

Title: MySQL : Better Solution To Nested If

Body:
You can use CASE:

SELECT  CASE
            WHEN A = B AND A = C AND B = C THEN 'Equilateral'
            WHEN A = B OR A = C OR B = C AND (A + B) > C THEN 'Isosceles'
            WHEN A != B AND A != C AND B != C AND (A + B) > C THEN 'Scalene'
            ELSE 'Not A Triangle'
        END
FROM    TRIANGLES


答:
No need to use jquery here. Just return it using simple for loop, don't use angular.forEach(), as it does not support break.

Try this

<!DOCTYPE html>

    {{d.Name}}
    {{FindSpecificItem(d)}}

```

Title: AnjularJS ng-repeat get item from different scope object

Body:
No need to use jquery here. Just return it using simple for loop, don't use angular.forEach(), as it does not support break.

Try this

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
 var app = angular.module("myApp", []);
 app.controller("myCtrl", function ($scope) {

  $scope.FindSpecificItem  = function(value) {
   for (var i = 0; i<$scope.Countries.length; i++) {
    if ($scope.Countries[i].Id == value.CountryId) {
     return $scope.Countries[i].Country;
    }
   }
  };

  $scope.details = [
  {
   "Name": "John",
   "CountryId": "1"
  },
  {
   "Name": "Dave",
   "CountryId": "2"
  }]

  $scope.Countries = [
  {
   "Id": "1",
   "Country": "USA"
  },
  {
   "Id": "2",
   "Country": "England"
  }]
 });
</script>

<body>

 <div ng-app="myApp" ng-controller="myCtrl">
  <table>
   <tr ng-repeat="d in details">
    <td>{{d.Name}}</td>
    <td>{{FindSpecificItem(d)}}</td>
   </tr>
  </table>
 </div>

</body>

</html>


问:
C non-blocking keyboard input
I'm trying to write a program in C (on Linux) that loops until the user presses a key, but shouldn't require a keypress to continue each loop.

Is there a simple way to do this? I figure I could possibly do it with select() but that seems like a lot of work.

Alternatively, is there a way to catch a ctrl-c keypress to do cleanup before the program closes instead of non-blocking io?

答:
You probably want kbhit();

```<code>//Example will loop until a key is pressed
#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
    while(1)
    {
        if(kbhit())
        {
            break;
        }
    }
}
</code>```

this may not work on all environments. A portable way would be to create a monitoring thread and set some flag on getch();

OwnerDisplayName: Zxaos

Title: C non-blocking keyboard input

LastEditorDisplayName: Zxaos

Body:
You probably want kbhit();

//Example will loop until a key is pressed
#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
    while(1)
    {
        if(kbhit())
        {
            break;
        }
    }
}

this may not work on all environments. A portable way would be to create a monitoring thread and set some flag on getch();

OwnerDisplayName: Jon Clegg


问:
Spring maven error
I'm using spring MVC with maven to develop a web application, but when I update my dependencies I get this message:

```
5/6/10 10:09:50 AM CEST: Build errors for amundsen.web; org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.4.1:resources (default-resources) on project amundsen.web: Execution default-resources of goal org.apache.maven.plugins:maven-resources-plugin:2.4.1:resources failed: Plugin org.apache.maven.plugins:maven-resources-plugin:2.4.1 or one of its dependencies could not be resolved: Unable to get dependency information for org.apache.maven.plugins:maven-resources-plugin:maven-plugin:2.4.1: Failed to process POM for org.apache.maven.plugins:maven-resources-plugin:maven-plugin:2.4.1: Non-resolvable parent POM org.apache:apache:6 for org.apache.maven:maven-parent:13: Failed to resolve POM for org.apache:apache:6 due to The repository system is offline and the requested artifact is not locally available at /home/waleed/.m2/repository/org/apache/apache/6/apache-6.pom
  org.apache:apache:pom:6

from the specified remote repositories:
  plexus.snapshots (http://oss.repository.sonatype.org/content/repositories/plexus-snapshots, releases=false, snapshots=true),
  central (http://repo1.maven.org/maven2, releases=true, snapshots=false)
```

My Maven dependencies are:

```<code>    <!-- Junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.3</version>
    </dependency>

        <dependency> <groupId>javax.servlet</groupId>
        <artifactId>com.springsource.javax.servlet.jsp.jstl</artifactId>
        <version>${servlet.jstl.version}</version> </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>${servlet-api.version}</version>
    </dependency>

    <!--<dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>${jstl.version}</version>
    </dependency>

    --><!--<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    --><dependency>
        <groupId>org.apache.taglibs</groupId>
        <artifactId>com.springsource.org.apache.taglibs.standard</artifactId>
        <version>${standard-taglib.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <!--
        <dependency> <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version> </dependency>
    -->

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>com.springsource.org.apache.commons.collections</artifactId>
    </dependency>
    <!-- Compile dependencies -->
    <dependency>
        <groupId>org.apache.log4j</groupId>
        <artifactId>com.springsource.org.apache.log4j</artifactId>
    </dependency>
    <!-- Spring (3.0) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.expression</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.context</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.context.support</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.beans</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.transaction</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>

    <!-- Spring security -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>spring-aop</artifactId>
                <groupId>org.springframework</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core-tiger</artifactId>
        <version>${spring-security-core-tiger.version}</version>
        <exclusions>
            <!-- Exclude 2.0.x spring dependencies -->
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-support</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-acl</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>${commons-dbc.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>3.3.1.GA</version>
    </dependency>

    <!--
        <dependency> <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId> <version>3.3.2.GA</version>
        hibernate-dependencies is a pom, not needed for hibernate-core
        </dependency>
    -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-annotations</artifactId>
        <version>3.4.0.GA</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>3.1.0.GA</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>3.3.0.ga</version>
        <exclusions>
            <exclusion>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate</artifactId>
            </exclusion>
        </exclusions>

    </dependency>
    <dependency>
        <groupId>hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>3.4.0.GA</version>
    </dependency>

    <dependency>
        <groupId>hibernate</groupId>
        <artifactId>hibernate-tools</artifactId>
        <version>3.2.3.GA</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>ejb3-persistence</artifactId>
        <version>1.0.2.GA</version>
    </dependency>

    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
        <version>3.2.1</version>
    </dependency>

    <dependency>
        <groupId>javax.transaction</groupId>
        <artifactId>jta</artifactId>
        <version>${jta.version}</version>
    </dependency>
    <dependency>
        <groupId>antlr</groupId>
        <artifactId>antlr</artifactId>
        <version>${antlr.version}</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>
    <!--

        <dependency> <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId> <version>1.5.6</version>
        </dependency>
    --><!-- concrete Log4J Implementation for SLF4J API-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.5.11</version>
    </dependency>
</dependencies>
</code>```

Any idea?

答:
You are under a proxy?

Try to config mvn proxy.

I was with the same problem and configuring properly the proxy on maven, all works!

Check this post:
Maven error: Unable to get resource / Server redirected too many times

Regards

Title: Spring maven error

Body:
I'm using spring MVC with maven to develop a web application, but when I update my dependencies I get this message:

5/6/10 10:09:50 AM CEST: Build errors for amundsen.web; org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.4.1:resources (default-resources) on project amundsen.web: Execution default-resources of goal org.apache.maven.plugins:maven-resources-plugin:2.4.1:resources failed: Plugin org.apache.maven.plugins:maven-resources-plugin:2.4.1 or one of its dependencies could not be resolved: Unable to get dependency information for org.apache.maven.plugins:maven-resources-plugin:maven-plugin:2.4.1: Failed to process POM for org.apache.maven.plugins:maven-resources-plugin:maven-plugin:2.4.1: Non-resolvable parent POM org.apache:apache:6 for org.apache.maven:maven-parent:13: Failed to resolve POM for org.apache:apache:6 due to The repository system is offline and the requested artifact is not locally available at /home/waleed/.m2/repository/org/apache/apache/6/apache-6.pom
  org.apache:apache:pom:6

from the specified remote repositories:
  plexus.snapshots (http://oss.repository.sonatype.org/content/repositories/plexus-snapshots, releases=false, snapshots=true),
  central (http://repo1.maven.org/maven2, releases=true, snapshots=false)

My Maven dependencies are:

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.3</version>
    </dependency>

        <dependency> <groupId>javax.servlet</groupId>
        <artifactId>com.springsource.javax.servlet.jsp.jstl</artifactId>
        <version>${servlet.jstl.version}</version> </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>${servlet-api.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.taglibs</groupId>
        <artifactId>com.springsource.org.apache.taglibs.standard</artifactId>
        <version>${standard-taglib.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>com.springsource.org.apache.commons.collections</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.log4j</groupId>
        <artifactId>com.springsource.org.apache.log4j</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.expression</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.context</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.context.support</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.beans</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.transaction</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>spring-aop</artifactId>
                <groupId>org.springframework</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core-tiger</artifactId>
        <version>${spring-security-core-tiger.version}</version>
        <exclusions>

            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-support</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-acl</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>${commons-dbc.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>3.3.1.GA</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-annotations</artifactId>
        <version>3.4.0.GA</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>3.1.0.GA</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>3.3.0.ga</version>
        <exclusions>
            <exclusion>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate</artifactId>
            </exclusion>
        </exclusions>

    </dependency>
    <dependency>
        <groupId>hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>3.4.0.GA</version>
    </dependency>

    <dependency>
        <groupId>hibernate</groupId>
        <artifactId>hibernate-tools</artifactId>
        <version>3.2.3.GA</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>ejb3-persistence</artifactId>
        <version>1.0.2.GA</version>
    </dependency>

    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
        <version>3.2.1</version>
    </dependency>

    <dependency>
        <groupId>javax.transaction</groupId>
        <artifactId>jta</artifactId>
        <version>${jta.version}</version>
    </dependency>
    <dependency>
        <groupId>antlr</groupId>
        <artifactId>antlr</artifactId>
        <version>${antlr.version}</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.5.11</version>
    </dependency>
</dependencies>

Any idea?


问:
Set a list of acceped zones in Eureka
Is their a way to ignore zone or define list of accepted zone in Eureka, for example if we have 3 zones ( office, shahbour, joe )

I want the services in zone shahbour to only use services defined in shahbour primary and office as secondary and ignore all other zones in this example joe.

I tried it as below and it is working to prefer same zone but if their is no service on same zone it do load balance on all the others zones

```<code>spring:
  profiles: shahbour
eureka:
  instance:
    metadataMap:
      zone: shahbour
  client:
    region: lebanon
    serviceUrl:
      defaultZone: http://office:8761/eureka/
    preferSameZoneEureka: true
    availabilityZones:
      lebanon: shahbour,office
</code>```

I thought setting availabilityZones set this but it is not .

This is for development environment where i am trying to setup each developer to use his machine as a zone and if service does not exist use office server as backup but don't use other developers .

答:
I did not find any place to set the accepted list of zones in eureka but what i found is that we can create our custom ServerListFilter in Ribbon that is used in both Feign and Zuul so below is the code

```<code>public class DevServerListFilter extends ZonePreferenceServerListFilter {

    private final List<String> acceptedZone = new ArrayList<>();

    public DevServerListFilter(String[] acceptedZones) {
        for (String zone: acceptedZones) {
            this.acceptedZone.add(zone);
        }
    }

    @Override
    public void initWithNiwsConfig(IClientConfig niwsClientConfig) {
        super.initWithNiwsConfig(niwsClientConfig);
    }

    @Override
    public List<Server> getFilteredListOfServers(List<Server> servers) {
        List<Server> zoneAffinityFiltered = super.getFilteredListOfServers(servers);
        Set<Server> candidates = Sets.newHashSet(zoneAffinityFiltered);
        Iterator serverIterator = candidates.iterator();
        while (serverIterator.hasNext()) {
            Server server = (Server)serverIterator.next();
            if(!acceptedZone.contains(server.getZone())) {
                zoneAffinityFiltered.remove(server);
            }

        }
        return zoneAffinityFiltered;
    }

}
</code>```

The above filter extends ZonePreferenceServerListFilter with a check on list of accepted zones , any server not in this list is ignored .

```<code>@Configuration
@RibbonClients(defaultConfiguration = MyDefaultRibbonConfiguration.class)
public class MyRibbonConfiguration {
}
</code>```

Default configuration for all my clients

```<code>@Configuration
public class MyDefaultRibbonConfiguration {

//    @Bean
//    public IPing ribbonPing(IClientConfig config) {
//        return new PingUrl();
//    }

    @Bean
    public ServerListFilter<Server> ribbonServerListFilter(IClientConfig config,EurekaClientConfigBean eurekaClientConfigBean) {
        String[] availabilityZones = eurekaClientConfigBean.getAvailabilityZones(eurekaClientConfigBean.getRegion());

        DevServerListFilter filter = new DevServerListFilter(availabilityZones);
        filter.initWithNiwsConfig(config);
        return filter;
    }

}
</code>```

The Configuration Code , note that this has to be in an excluded path from @ComponentScan as request in documents , and i used the availability zone property but any list can be used.

github sample

Title: Set a list of acceped zones in Eureka

Body:
Is their a way to ignore zone or define list of accepted zone in Eureka, for example if we have 3 zones ( office, shahbour, joe )

I want the services in zone shahbour to only use services defined in shahbour primary and office as secondary and ignore all other zones in this example joe.

I tried it as below and it is working to prefer same zone but if their is no service on same zone it do load balance on all the others zones

spring:
  profiles: shahbour
eureka:
  instance:
    metadataMap:
      zone: shahbour
  client:
    region: lebanon
    serviceUrl:
      defaultZone: http://office:8761/eureka/
    preferSameZoneEureka: true
    availabilityZones:
      lebanon: shahbour,office

I thought setting availabilityZones set this but it is not .

This is for development environment where i am trying to setup each developer to use his machine as a zone and if service does not exist use office server as backup but don't use other developers .

Body:
I did not find any place to set the accepted list of zones in eureka but what i found is that we can create our custom ServerListFilter in Ribbon that is used in both Feign and Zuul so below is the code

public class DevServerListFilter extends ZonePreferenceServerListFilter {

    private final List<String> acceptedZone = new ArrayList<>();

    public DevServerListFilter(String[] acceptedZones) {
        for (String zone: acceptedZones) {
            this.acceptedZone.add(zone);
        }
    }

    @Override
    public void initWithNiwsConfig(IClientConfig niwsClientConfig) {
        super.initWithNiwsConfig(niwsClientConfig);
    }

    @Override
    public List<Server> getFilteredListOfServers(List<Server> servers) {
        List<Server> zoneAffinityFiltered = super.getFilteredListOfServers(servers);
        Set<Server> candidates = Sets.newHashSet(zoneAffinityFiltered);
        Iterator serverIterator = candidates.iterator();
        while (serverIterator.hasNext()) {
            Server server = (Server)serverIterator.next();
            if(!acceptedZone.contains(server.getZone())) {
                zoneAffinityFiltered.remove(server);
            }

        }
        return zoneAffinityFiltered;
    }

}

The above filter extends ZonePreferenceServerListFilter with a check on list of accepted zones , any server not in this list is ignored .

@Configuration
@RibbonClients(defaultConfiguration = MyDefaultRibbonConfiguration.class)
public class MyRibbonConfiguration {
}

Default configuration for all my clients

@Configuration
public class MyDefaultRibbonConfiguration {

//    @Bean
//    public IPing ribbonPing(IClientConfig config) {
//        return new PingUrl();
//    }

    @Bean
    public ServerListFilter<Server> ribbonServerListFilter(IClientConfig config,EurekaClientConfigBean eurekaClientConfigBean) {
        String[] availabilityZones = eurekaClientConfigBean.getAvailabilityZones(eurekaClientConfigBean.getRegion());

        DevServerListFilter filter = new DevServerListFilter(availabilityZones);
        filter.initWithNiwsConfig(config);
        return filter;
    }

}

The Configuration Code , note that this has to be in an excluded path from @ComponentScan as request in documents , and i used the availability zone property but any list can be used.

github sample