问:
Swift function generic parameter
So, I am using alamofire and object mapper library from github.

In my function there is this code

```<code>Alamofire.request(urlRequest).responseObject { (response: DataResponse<News>) in }
</code>```

I do the response checking together with the status code also

```<code>switch response.result {
            case .success:
                if let object = responseObject {
                    completion(object)
                }
                break;
            case .failure(let error):
                print(error)
                if let statusCode = response.response?.statusCode {
                    var message = String()
                    switch statusCode {
                        //status code checking here
                    }
                }
                else {
                    var message = String()
                    message = error.localizedDescription
                }
                break;
        }
</code>```

So i have several api calling and all of the api calling will also implement this status code checking. I don't want to keep copy pasting this chunk of code for all my api call function

So what i am planning to do is to create a dedicated function to check the status code from the api call

But i face one problem. How can I create a generic function parameter that accept all type of DataResponse<>?

I tried to run this code but failed

```<code>// validateResponse function
static func validateResponse(dataResponse: DataResponse<Any>) -> String {
    // status code checking here
}

// inside the alamofire.request response
validateResponse(dataResponse: response)

// return me this error
Cannot convert value of type 'DataResponse<News>' to expected argument type 'DataResponse<Any>'
</code>```

The DataResponse<> will always change based on the model provided into the alamofire.responseObject

Can anyone guide me on how to do it properly? Thanks!

答:
You need to use generics!

```<code>static func validateResponse<T>(dataResponse: DataResponse<T>) -> String {
    // status code checking here
}
</code>```

Usage:

```<code>validateResponse(dataResponse: response)
</code>```

The generic parameter T will be inferred be News it will be as if the method is like this:

```<code>static func validateResponse(dataResponse: DataResponse<News>) -> String {
    // status code checking here
}
</code>```

Title: Swift function generic parameter

Body:
So, I am using alamofire and object mapper library from github.

In my function there is this code

Alamofire.request(urlRequest).responseObject { (response: DataResponse<News>) in }

I do the response checking together with the status code also

switch response.result {
            case .success:
                if let object = responseObject {
                    completion(object)
                }
                break;
            case .failure(let error):
                print(error)
                if let statusCode = response.response?.statusCode {
                    var message = String()
                    switch statusCode {
                        //status code checking here
                    }
                }
                else {
                    var message = String()
                    message = error.localizedDescription
                }
                break;
        }

So i have several api calling and all of the api calling will also implement this status code checking. I don't want to keep copy pasting this chunk of code for all my api call function

So what i am planning to do is to create a dedicated function to check the status code from the api call

But i face one problem. How can I create a generic function parameter that accept all type of DataResponse<>?

I tried to run this code but failed

// validateResponse function
static func validateResponse(dataResponse: DataResponse<Any>) -> String {
    // status code checking here
}

// inside the alamofire.request response
validateResponse(dataResponse: response)

// return me this error
Cannot convert value of type 'DataResponse<News>' to expected argument type 'DataResponse<Any>'

The DataResponse<> will always change based on the model provided into the alamofire.responseObject

Can anyone guide me on how to do it properly? Thanks!

Body:
You need to use generics!

static func validateResponse<T>(dataResponse: DataResponse<T>) -> String {
    // status code checking here
}

Usage:

validateResponse(dataResponse: response)

The generic parameter T will be inferred be News it will be as if the method is like this:

static func validateResponse(dataResponse: DataResponse<News>) -> String {
    // status code checking here
}


来源: stackexchange

问:
Facebook account kit(API) loginCallback doesn't execute
I am currently implementing the facebook account kit for my Rails application. I just use the smslogin function, no email. I got the verification code, enter it to the popup window, it verifies successfully. However, the function loginCallback doesn't execute after that. Actually, there are a couple of times it is executed. I am really frustrated here because I don't now what is going with the code, it is totally out of my control. It would be helpful if somebody can give some hints or tips here.
This is the code for my login page:

fb_account_kit.htm.haml:

```<code>!!!
%html
  %head
    %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
    %title Passwordless Authentication: Facebook Account Kit
    / Include the Account Kit SDK
    %script{:src => "https://sdk.accountkit.com/vi_VN/sdk.js"}
  %body
    .ui.container
      = form_tag('https://www.accountkit.com/v1.0/basic/dialog/sms_login/', method: :get, class: 'ui form') do
        = hidden_field_tag :authenticity_token, form_authenticity_token
        .field
          = text_field_tag 'country_code', '+84', {class: 'ui input'}
        .field
          = text_field_tag 'phone_number', nil, {placeholder: 'phone number', class: 'ui input'}
        .field
          = button_tag 'Login via SMS', {onclick: 'javascript:smsLogin()', class: 'ui primary button'}

      -#Login success form
      = form_tag('/login_success', method: :post, class: 'ui form', id: 'login_success') do
        = hidden_field_tag 'code'
        = hidden_field_tag 'csrf'

:javascript
  // initialize Account Kit with CSRF protection
  AccountKit_OnInteractive = function(){
    AccountKit.init(
      {
        debug: true,
        appId: "myapp_id_goes_here",
        state: $('#authenticity_token').val(),
        version: "v1.0",
        fbAppEventsEnabled: true
      }
    );
  };

  // login callback
  function loginCallback(response) {
    alert('inside loginCallback NOW!!!');
    alert('response object: ' + JSON.stringify(response));
    if (response.status === "PARTIALLY_AUTHENTICATED") {
      document.getElementById("code").value = response.code;
      document.getElementById("csrf").value = response.state;
      console.log('login_success form is gonna be submitted!!!');
      document.getElementById("login_success").submit();
    }
    else if (response.status === "NOT_AUTHENTICATED") {
      alert('authentication failed')
    }
    else if (response.status === "BAD_PARAMS") {
      alert('bad parameters')
    }
  }

  // phone form submission handler
  function smsLogin() {
    var countryCode = document.getElementById("country_code").value;
    var phoneNumber = document.getElementById("phone_number").value;
    AccountKit.login(
      'PHONE',
      {countryCode: countryCode, phoneNumber: phoneNumber},
      loginCallback
    );
  }
</code>```

答:
If you want to handle the response by client side Javascript callback, then you don't have to add redirect option.
The redirect option just for server handling the login callback.

Hence, this configuration should make your example work

```<code>  // initialize Account Kit with CSRF protection
  AccountKit_OnInteractive = function(){
    AccountKit.init(
      {
        debug: true,
        appId: "myapp_id_goes_here",
        state: $('#authenticity_token').val(),
        version: "v1.0",
        fbAppEventsEnabled: true
      }
    );
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently implementing the facebook account kit for my Rails application. I just use the smslogin function, no email. I got the verification code, enter it to the popup window, it verifies successfully. However, the function loginCallback doesn't execute after that. Actually, there are a couple of times it is executed. I am really frustrated here because I don't now what is going with the code, it is totally out of my control. It would be helpful if somebody can give some hints or tips here.
This is the code for my login page:

fb_account_kit.htm.haml:

!!!
%html
  %head
    %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
    %title Passwordless Authentication: Facebook Account Kit
    / Include the Account Kit SDK
    %script{:src => "https://sdk.accountkit.com/vi_VN/sdk.js"}
  %body
    .ui.container
      = form_tag('https://www.accountkit.com/v1.0/basic/dialog/sms_login/', method: :get, class: 'ui form') do
        = hidden_field_tag :authenticity_token, form_authenticity_token
        .field
          = text_field_tag 'country_code', '+84', {class: 'ui input'}
        .field
          = text_field_tag 'phone_number', nil, {placeholder: 'phone number', class: 'ui input'}
        .field
          = button_tag 'Login via SMS', {onclick: 'javascript:smsLogin()', class: 'ui primary button'}

      -#Login success form
      = form_tag('/login_success', method: :post, class: 'ui form', id: 'login_success') do
        = hidden_field_tag 'code'
        = hidden_field_tag 'csrf'

:javascript
  // initialize Account Kit with CSRF protection
  AccountKit_OnInteractive = function(){
    AccountKit.init(
      {
        debug: true,
        appId: "myapp_id_goes_here",
        state: $('#authenticity_token').val(),
        version: "v1.0",
        fbAppEventsEnabled: true
      }
    );
  };

  // login callback
  function loginCallback(response) {
    alert('inside loginCallback NOW!!!');
    alert('response object: ' + JSON.stringify(response));
    if (response.status === "PARTIALLY_AUTHENTICATED") {
      document.getElementById("code").value = response.code;
      document.getElementById("csrf").value = response.state;
      console.log('login_success form is gonna be submitted!!!');
      document.getElementById("login_success").submit();
    }
    else if (response.status === "NOT_AUTHENTICATED") {
      alert('authentication failed')
    }
    else if (response.status === "BAD_PARAMS") {
      alert('bad parameters')
    }
  }

  // phone form submission handler
  function smsLogin() {
    var countryCode = document.getElementById("country_code").value;
    var phoneNumber = document.getElementById("phone_number").value;
    AccountKit.login(
      'PHONE',
      {countryCode: countryCode, phoneNumber: phoneNumber},
      loginCallback
    );
  }

Body:
If you want to handle the response by client side Javascript callback, then you don't have to add redirect option.
The redirect option just for server handling the login callback.

Hence, this configuration should make your example work

  // initialize Account Kit with CSRF protection
  AccountKit_OnInteractive = function(){
    AccountKit.init(
      {
        debug: true,
        appId: "myapp_id_goes_here",
        state: $('#authenticity_token').val(),
        version: "v1.0",
        fbAppEventsEnabled: true
      }
    );
  }


问:
Best way to show all subfolders and its files in uwp
I have stored all subfolder names and it's corresponding file names(from local folder) in a class. Now I want to display it in a good way. And also need to access that files when user selects it. What is the best way to achieve it?</p>

```<code> public class SubFolders
    {
        public string ItemName { get; set; }
        public ObservableCollection<SubFolderFiles> SubItemsList { get; set; }
    }

    public class SubFolderFiles
    {
        public string SubItemName { get; set; }
    }
</code>```

答:
Best way to show all subfolders and its files in uwp.

For this requirement, you need to create a relatively complete model like the following Illustration.

The above is recursive model, and I have make a class to match it.

```<code>public class Folder
{
    public string FolderName { get; set; }
    private ObservableCollection<File> _subFiles;
    public ObservableCollection<File> SubFiles
    {
        get { return _subFiles ?? (_subFiles = new ObservableCollection<File>()); }
        set
        {
            _subFiles = value;
        }
    }

    private ObservableCollection<Folder> _subFolder;
    public ObservableCollection<Folder> SubFolders
    {
        get { return _subFolder ?? (_subFolder = new ObservableCollection<Folder>()); }
        set
        {
            _subFolder = value;
        }
    }

    public Folder()
    {

    }
}
public class File
{
    public string FileName { get; set; }
}
</code>```

As you know, if you want to display the folders and files where in one folder on the ListView, you need to converter them into abstract listview items.

```<code>  public class Item
    {
        public string ItemName { get; set; }
        public ItemType IType { get; set; }
    }
    public enum ItemType
    {
        File,
        Folder
    }
</code>```

Usage

FolderService.cs

```<code> public class FolderService
 {
     //  private Folder FolderModel;
     public async static Task<Folder> GetFolderInfoAsync(StorageFolder SelectFolder)
     {
         var FolderModel = new Folder();

         FolderModel.FolderName = SelectFolder.Name;
         IReadOnlyList<StorageFile> fileList = await SelectFolder?.GetFilesAsync();

         foreach (StorageFile file in fileList)
         {
             var subFile = new File();
             subFile.FileName = file.Name;
             FolderModel.SubFiles.Add(subFile);

         }
         IReadOnlyList<StorageFolder> folderList = await SelectFolder?.GetFoldersAsync();

         foreach (StorageFolder folder in folderList)
         {
             var subFolder = new Folder();
             subFolder.FolderName = folder.Name;
             FolderModel.SubFolders.Add(subFolder);

         }

         return FolderModel;
     }
     public async static Task<ObservableCollection<Item>>GetItems(StorageFolder SelectFolder)
     {
         var Model = await GetFolderInfoAsync(SelectFolder);
         var Items = new ObservableCollection<Item>();
         foreach (var file in Model.SubFiles)
         {
             var item = new Item
             {
                 ItemName = file.FileName,
                 IType = ItemType.File
             };
             Items.Add(item);
         }
         foreach (var folder in Model.SubFolders)
         {
             var item = new Item
             {
                 ItemName = folder.FolderName,
                 IType = ItemType.Folder
             };
             Items.Add(item);
         }
         return Items;
     }
 }
</code>```

ManPageViewModel.cs

```<code>public class MainViewModel : INotifyPropertyChanged
{
    public MainViewModel()
    {
    }
    public Command PickCommand => new Command(() => this.BtnClick());

    private async void BtnClick()
    {
        StorageFolder Selectfolder = ApplicationData.Current.LocalFolder;
        this.Items = await FolderService.GetItems(Selectfolder);
    }
    private ObservableCollection<Item> _items;

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string PropertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
    }
    public ObservableCollection<Item> Items
    {
        get { return _items; }
        set
        {
            _items = value;
            OnPropertyChanged();
        }
    }
}
</code>```

Body:
I have stored all subfolder names and it's corresponding file names(from local folder) in a class. Now I want to display it in a good way. And also need to access that files when user selects it. What is the best way to achieve it?

 public class SubFolders
    {
        public string ItemName { get; set; }
        public ObservableCollection<SubFolderFiles> SubItemsList { get; set; }
    }

    public class SubFolderFiles
    {
        public string SubItemName { get; set; }
    }

Body:
Best way to show all subfolders and its files in uwp.

For this requirement, you need to create a relatively complete model like the following Illustration.

The above is recursive model, and I have make a class to match it.

public class Folder
{
    public string FolderName { get; set; }
    private ObservableCollection<File> _subFiles;
    public ObservableCollection<File> SubFiles
    {
        get { return _subFiles ?? (_subFiles = new ObservableCollection<File>()); }
        set
        {
            _subFiles = value;
        }
    }

    private ObservableCollection<Folder> _subFolder;
    public ObservableCollection<Folder> SubFolders
    {
        get { return _subFolder ?? (_subFolder = new ObservableCollection<Folder>()); }
        set
        {
            _subFolder = value;
        }
    }

    public Folder()
    {

    }
}
public class File
{
    public string FileName { get; set; }
}

As you know, if you want to display the folders and files where in one folder on the ListView, you need to converter them into abstract listview items.

  public class Item
    {
        public string ItemName { get; set; }
        public ItemType IType { get; set; }
    }
    public enum ItemType
    {
        File,
        Folder
    }

Usage

FolderService.cs

 public class FolderService
 {
     //  private Folder FolderModel;
     public async static Task<Folder> GetFolderInfoAsync(StorageFolder SelectFolder)
     {
         var FolderModel = new Folder();

         FolderModel.FolderName = SelectFolder.Name;
         IReadOnlyList<StorageFile> fileList = await SelectFolder?.GetFilesAsync();

         foreach (StorageFile file in fileList)
         {
             var subFile = new File();
             subFile.FileName = file.Name;
             FolderModel.SubFiles.Add(subFile);

         }
         IReadOnlyList<StorageFolder> folderList = await SelectFolder?.GetFoldersAsync();

         foreach (StorageFolder folder in folderList)
         {
             var subFolder = new Folder();
             subFolder.FolderName = folder.Name;
             FolderModel.SubFolders.Add(subFolder);

         }

         return FolderModel;
     }
     public async static Task<ObservableCollection<Item>>GetItems(StorageFolder SelectFolder)
     {
         var Model = await GetFolderInfoAsync(SelectFolder);
         var Items = new ObservableCollection<Item>();
         foreach (var file in Model.SubFiles)
         {
             var item = new Item
             {
                 ItemName = file.FileName,
                 IType = ItemType.File
             };
             Items.Add(item);
         }
         foreach (var folder in Model.SubFolders)
         {
             var item = new Item
             {
                 ItemName = folder.FolderName,
                 IType = ItemType.Folder
             };
             Items.Add(item);
         }
         return Items;
     }
 }

ManPageViewModel.cs

public class MainViewModel : INotifyPropertyChanged
{
    public MainViewModel()
    {
    }
    public Command PickCommand => new Command(() => this.BtnClick());

    private async void BtnClick()
    {
        StorageFolder Selectfolder = ApplicationData.Current.LocalFolder;
        this.Items = await FolderService.GetItems(Selectfolder);
    }
    private ObservableCollection<Item> _items;

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string PropertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
    }
    public ObservableCollection<Item> Items
    {
        get { return _items; }
        set
        {
            _items = value;
            OnPropertyChanged();
        }
    }
}


问:
Spring tool suite installation
I successfully installed STS 2.9.0 on windows 7, but it is showing internal error occurred during initializing spring UAA. Please guide me how can I resolve this issue.</p>

答:
To start eclipse with -clean in windows.

Quit Eclipse if it is running.

Go to the Eclipse installation directory

Open the file eclipse.ini in a text editor. Search for the line -vmargs

After the line -vmargs,

put -clean

Start eclipse and check if that solves the problem

Title: Spring tool suite installation


问:
Magento2 theme layout files suddenly stopped working
I am brand new to Magento, and am using Magento 2. I have a custom theme that has been working just fine. Suddenly, the files in my custom theme's Magento_Theme/layout folder seem to not be loading. In my layout folder I have default_head_blocks.xml and default.xml. BOTH files suddenly stopped working.

Here is my default_head_blocks.xml:

```<code><?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <head>
    <css src="css/bootstrap.min.css" />
    <css src="css/styles-m.css" />
    <css src="css/styles-l.css" media="screen and (min-width: 768px)"/>

    <script src="js/bootstrap.min.js"/>
    <script src="js/site.js"></script>
 </head>
</page>
</code>```

And my default.xml:

```<code><?xml version="1.0"?>
 <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <body>
    <referenceContainer name="header.panel">
        <block class="Magento\Framework\View\Element\Html\Links" name="header.links">
            <arguments>
                <argument name="css_class" xsi:type="string">header links</argument>
            </arguments>
        </block>
    </referenceContainer>
    <referenceContainer name="footer">
        <block class="Magento\Theme\Block\Html\Footer" name="absolute_footer" template="html/absolute_footer.phtml" />
    </referenceContainer>
    <referenceBlock name="report.bugs" remove="true"/>
    <referenceBlock name="store.settings.currency" remove="true"/>
    <referenceBlock name="catalog.compare.sidebar" remove="true"/>
    <referenceBlock name="advanced-search-link" remove="true"/>
    <referenceBlock name="skip_to_content" remove="true"/>
    <referenceBlock name="store_switcher" remove="true"/>
    <referenceBlock name="navigation.sections" remove="true"/>
    <referenceBlock name="top.search" remove="true"/>
    <referenceBlock name="footer_links" remove="true"/>
    <move element="copyright" destination="before.body.end"/>
    <move element="logo" destination="navigation.sections"/>
    <move element="form.subscribe" destination="footer"/>
    <move element="catalog.topnav" destination="header.container"/>
    <move element="top.links" destination="footer"/>
 </body>
</page>
</code>```

As I stated the files were working perfectly fine at one point.

The files in my Magento_Theme/templates/html folder load just fine.  Seems to only be the files in my layout folder.

Any ideas why this would be happening or how to fix it?

答:
From my experience, instances like this would require you to do the following.

Clean Cache:

```<code>php bin/magento cache:clean
</code>```

Flush Cache:

```<code>php bin/magento cache:flush
</code>```

(optional) if clearing cache doesn't seem to show any changes, you might need to do a static deploy.

Static Deploy: Note: this will take a bit of time depending on your system.

```<code>php ./bin/magento setup:static-content:deploy --theme <your theme example myTheme/Default>
</code>```

After these processes you can try and reload the page again.

Body:
I am brand new to Magento, and am using Magento 2. I have a custom theme that has been working just fine. Suddenly, the files in my custom theme's Magento_Theme/layout folder seem to not be loading. In my layout folder I have default_head_blocks.xml and default.xml. BOTH files suddenly stopped working.

Here is my default_head_blocks.xml:

<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <css src="css/bootstrap.min.css" />
    <css src="css/styles-m.css" />
    <css src="css/styles-l.css" media="screen and (min-width: 768px)"/>

</page>

And my default.xml:

<?xml version="1.0"?>
 <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <referenceContainer name="header.panel">
        <block class="Magento\Framework\View\Element\Html\Links" name="header.links">
            <arguments>
                <argument name="css_class" xsi:type="string">header links</argument>
            </arguments>
        </block>
    </referenceContainer>
    <referenceContainer name="footer">
        <block class="Magento\Theme\Block\Html\Footer" name="absolute_footer" template="html/absolute_footer.phtml" />
    </referenceContainer>
    <referenceBlock name="report.bugs" remove="true"/>
    <referenceBlock name="store.settings.currency" remove="true"/>
    <referenceBlock name="catalog.compare.sidebar" remove="true"/>
    <referenceBlock name="advanced-search-link" remove="true"/>
    <referenceBlock name="skip_to_content" remove="true"/>
    <referenceBlock name="store_switcher" remove="true"/>
    <referenceBlock name="navigation.sections" remove="true"/>
    <referenceBlock name="top.search" remove="true"/>
    <referenceBlock name="footer_links" remove="true"/>
    <move element="copyright" destination="before.body.end"/>
    <move element="logo" destination="navigation.sections"/>
    <move element="form.subscribe" destination="footer"/>
    <move element="catalog.topnav" destination="header.container"/>
    <move element="top.links" destination="footer"/>

</page>

As I stated the files were working perfectly fine at one point.

The files in my Magento_Theme/templates/html folder load just fine.  Seems to only be the files in my layout folder.

Any ideas why this would be happening or how to fix it?

Body:
From my experience, instances like this would require you to do the following.

Clean Cache:

php bin/magento cache:clean

Flush Cache:

php bin/magento cache:flush

(optional) if clearing cache doesn't seem to show any changes, you might need to do a static deploy.

Static Deploy: Note: this will take a bit of time depending on your system.

php ./bin/magento setup:static-content:deploy --theme <your theme example myTheme/Default>

After these processes you can try and reload the page again.


问:
understanding super() on a baseclass
```<code>class Property:
    def __init__(self, square_feet='', beds='',
            baths='', **kwargs):
        super().__init__(**kwargs)
        self.square_feet = square_feet
        self.num_bedrooms = beds
        self.num_baths = baths
    def display(self):
        print("PROPERTY DETAILS")
        print("================")
        print("square footage: {}".format(self.square_feet))
        print("bedrooms: {}".format(self.num_bedrooms))
        print("bathrooms: {}".format(self.num_baths))
        print()
    @staticmethod
    def prompt_init():
        return dict(square_feet=input("Enter the square feet: "),
            beds=input("Enter number of bedrooms: "),
            baths=input("Enter number of baths:"))

class Apartment(Property):
    valid_laundries = ("coin", "ensuite", "none")
    valid_balconies = ("yes", "no", "solarium")
    def __init__(self, balcony='', laundry='', **kwargs):
        super().__init__(**kwargs)
        self.balcony = balcony
        self.laundry = laundry
    def display(self):
        super().display()
        print("APARTMENT DETAILS")
        print("laundry: %s" % self.laundry)
        print("has balcony: %s" % self.balcony)
    @staticmethod
    def prompt_init():
        parent_init = Property.prompt_init()
        laundry = get_valid_input('What laundry facilities does '
        'the property have? ', Apartment.valid_laundries)
        while laundry.lower() not in \
            Apartment.valid_laundries:
            laundry = input("What laundry facilities does "
                "the property have? ({})".format(
                    ", ".join(Apartment.valid_laundries)))
        balcony = ''
        while balcony.lower() not in \
            Apartment.valid_balconies:
            balcony = input(
                "Does the property have a balcony? "
                "({})".format(
                ", ".join(Apartment.valid_balconies)))
        parent_init.update({
            "laundry": laundry,
            "balcony": balcony
        })
        return parent_init

class House(Property):
    valid_garage = ("attached", "detached", "none")
    valid_fenced = ("yes", "no")
    def __init__(self, num_stories='',
        garage='', fenced='', **kwargs):
        super().__init__(**kwargs)
        self.garage = garage
        self.fenced = fenced
        self.num_stories = num_stories
    def display(self):
        super().display()
        print("HOUSE DETAILS")
        print("# of stories: {}".format(self.num_stories))
        print("garage: {}".format(self.garage))
        print("fenced yard: {}".format(self.fenced))
    @staticmethod
    def prompt_init():
        parent_init = Property.prompt_init()
        fenced = get_valid_input("Is the yard fenced? ",
                House.valid_fenced)
        garage = get_valid_input("Is there a garage? ",
                House.valid_garage)
        num_stories = input("How many stories? ")
        parent_init.update({
            "fenced": fenced,
            "garage": garage,
            "num_stories": num_stories
        })
        return parent_init

def get_valid_input(input_string, valid_options):
    input_string += " ({}) ".format(", ".join(valid_options))
    response = input(input_string)
    while response.lower() not in valid_options:
        response = input(input_string)
    return response

class Purchase:
    def __init__(self, price='', taxes='', **kwargs):
        super().__init__(**kwargs)
        self.price = price
        self.taxes = taxes
    def display(self):
        super().display()
        print("PURCHASE DETAILS")
        print("selling price: {}".format(self.price))
        print("estimated taxes: {}".format(self.taxes))
        @staticmethod
        def prompt_init():
            return dict(
                price=input("What is the selling price? "),
                taxes=input("What are the estimated taxes? "))

class Rental:
    def __init__(self, furnished='', utilities='',
        rent='', **kwargs):
        super().__init__(**kwargs)
        self.furnished = furnished
        self.rent = rent
        self.utilities = utilities
    def display(self):
        super().display()
        print("RENTAL DETAILS")
        print("rent: {}".format(self.rent))
        print("estimated utilities: {}".format(
            self.utilities))
        print("furnished: {}".format(self.furnished))
    @staticmethod
    def prompt_init():
        return dict(
            rent=input("What is the monthly rent? "),
            utilities=input(
                "What are the estimated utilities? "),
            furnished = get_valid_input(
                "Is the property furnished? ",
                    ("yes", "no")))
class HouseRental(Rental, House):
    @staticmethod
    def prompt_init():
        init = House.prompt_init()
        init.update(Rental.prompt_init())
        return init

init = HouseRental.prompt_init()
print(init)
house = HouseRental(**init) #I assume this holds the input from all the prompt_init, from class Property to class Rental.
house.display()
</code>```

My question is how super interacts with a class with no parent class. In the last line, house.display() is called and class HouseRental inherits 2 classes, the first which has no parent class. I see that when house.display() is called, it calls Rental.display() first, then the super() call in Rental.display() does not raise an error, but points to the next inherited class, House.display(), which then the super() call in House.display() points to its parent class, Property.

I get the gist of how super() works in this kind of way but I don't fully understand why super() in a base class points to the next class in the MRO instead of raising an error (something like "no parent class available")

Here is the output of house.display if you're interested:

```<code>{'square_feet': '1', 'beds': '2', 'baths': '3', 'fenced': 'no', 'garage': 'none', 'num_stories': '3', 'rent': '1', 'utilities': '4', 'furnished': 'no'}
PROPERTY DETAILS
================
square footage: 1
bedrooms: 2
bathrooms: 3

HOUSE DETAILS
# of stories: 3
garage: none
fenced yard: no
RENTAL DETAILS
rent: 1
estimated utilities: 4
furnished: no
</code>```

答:
All classes in Python implicitly inherit from the Object type: Python class inherits object.

Calling super().__init__ in a class with "no super class" will simply call the constructor for Object.

Title: understanding super() on a baseclass

Body:
class Property:
    def __init__(self, square_feet='', beds='',
            baths='', **kwargs):
        super().__init__(**kwargs)
        self.square_feet = square_feet
        self.num_bedrooms = beds
        self.num_baths = baths
    def display(self):
        print("PROPERTY DETAILS")
        print("================")
        print("square footage: {}".format(self.square_feet))
        print("bedrooms: {}".format(self.num_bedrooms))
        print("bathrooms: {}".format(self.num_baths))
        print()
    @staticmethod
    def prompt_init():
        return dict(square_feet=input("Enter the square feet: "),
            beds=input("Enter number of bedrooms: "),
            baths=input("Enter number of baths:"))

class Apartment(Property):
    valid_laundries = ("coin", "ensuite", "none")
    valid_balconies = ("yes", "no", "solarium")
    def __init__(self, balcony='', laundry='', **kwargs):
        super().__init__(**kwargs)
        self.balcony = balcony
        self.laundry = laundry
    def display(self):
        super().display()
        print("APARTMENT DETAILS")
        print("laundry: %s" % self.laundry)
        print("has balcony: %s" % self.balcony)
    @staticmethod
    def prompt_init():
        parent_init = Property.prompt_init()
        laundry = get_valid_input('What laundry facilities does '
        'the property have? ', Apartment.valid_laundries)
        while laundry.lower() not in \
            Apartment.valid_laundries:
            laundry = input("What laundry facilities does "
                "the property have? ({})".format(
                    ", ".join(Apartment.valid_laundries)))
        balcony = ''
        while balcony.lower() not in \
            Apartment.valid_balconies:
            balcony = input(
                "Does the property have a balcony? "
                "({})".format(
                ", ".join(Apartment.valid_balconies)))
        parent_init.update({
            "laundry": laundry,
            "balcony": balcony
        })
        return parent_init

class House(Property):
    valid_garage = ("attached", "detached", "none")
    valid_fenced = ("yes", "no")
    def __init__(self, num_stories='',
        garage='', fenced='', **kwargs):
        super().__init__(**kwargs)
        self.garage = garage
        self.fenced = fenced
        self.num_stories = num_stories
    def display(self):
        super().display()
        print("HOUSE DETAILS")
        print("# of stories: {}".format(self.num_stories))
        print("garage: {}".format(self.garage))
        print("fenced yard: {}".format(self.fenced))
    @staticmethod
    def prompt_init():
        parent_init = Property.prompt_init()
        fenced = get_valid_input("Is the yard fenced? ",
                House.valid_fenced)
        garage = get_valid_input("Is there a garage? ",
                House.valid_garage)
        num_stories = input("How many stories? ")
        parent_init.update({
            "fenced": fenced,
            "garage": garage,
            "num_stories": num_stories
        })
        return parent_init

def get_valid_input(input_string, valid_options):
    input_string += " ({}) ".format(", ".join(valid_options))
    response = input(input_string)
    while response.lower() not in valid_options:
        response = input(input_string)
    return response

class Purchase:
    def __init__(self, price='', taxes='', **kwargs):
        super().__init__(**kwargs)
        self.price = price
        self.taxes = taxes
    def display(self):
        super().display()
        print("PURCHASE DETAILS")
        print("selling price: {}".format(self.price))
        print("estimated taxes: {}".format(self.taxes))
        @staticmethod
        def prompt_init():
            return dict(
                price=input("What is the selling price? "),
                taxes=input("What are the estimated taxes? "))

class Rental:
    def __init__(self, furnished='', utilities='',
        rent='', **kwargs):
        super().__init__(**kwargs)
        self.furnished = furnished
        self.rent = rent
        self.utilities = utilities
    def display(self):
        super().display()
        print("RENTAL DETAILS")
        print("rent: {}".format(self.rent))
        print("estimated utilities: {}".format(
            self.utilities))
        print("furnished: {}".format(self.furnished))
    @staticmethod
    def prompt_init():
        return dict(
            rent=input("What is the monthly rent? "),
            utilities=input(
                "What are the estimated utilities? "),
            furnished = get_valid_input(
                "Is the property furnished? ",
                    ("yes", "no")))
class HouseRental(Rental, House):
    @staticmethod
    def prompt_init():
        init = House.prompt_init()
        init.update(Rental.prompt_init())
        return init

init = HouseRental.prompt_init()
print(init)
house = HouseRental(**init) #I assume this holds the input from all the prompt_init, from class Property to class Rental.
house.display()

My question is how super interacts with a class with no parent class. In the last line, house.display() is called and class HouseRental inherits 2 classes, the first which has no parent class. I see that when house.display() is called, it calls Rental.display() first, then the super() call in Rental.display() does not raise an error, but points to the next inherited class, House.display(), which then the super() call in House.display() points to its parent class, Property.

I get the gist of how super() works in this kind of way but I don't fully understand why super() in a base class points to the next class in the MRO instead of raising an error (something like "no parent class available")

Here is the output of house.display if you're interested:

{'square_feet': '1', 'beds': '2', 'baths': '3', 'fenced': 'no', 'garage': 'none', 'num_stories': '3', 'rent': '1', 'utilities': '4', 'furnished': 'no'}
PROPERTY DETAILS
================
square footage: 1
bedrooms: 2
bathrooms: 3

HOUSE DETAILS
# of stories: 3
garage: none
fenced yard: no
RENTAL DETAILS
rent: 1
estimated utilities: 4
furnished: no


问:
Kubernetes different container args depending on number of pods in replica set
I want to scale an application with workers.

There could be 1 worker or 100, and I want to scale them seamlessly.

The idea is using replica set. However due to domain-specific reasons, the appropriate way to scale them is for each worker to know its: ID and the total number of workers.

For example, in case I have 3 workers, I'd have this:

```<code>id:0, num_workers:3
id:1, num_workers:3
id:2, num_workers:3
</code>```

Is there a way of using kubernetes to do so?

I pass this information in command line arguments to the app, and I assume it would be fine having it in environment variables too.

It's ok on size changes for all workers to be killed and new ones spawned.

答:
Before giving the kubernetes-specific answer, I wanted to point out that it seems like the problem is trying to push cluster-coordination down into the app, which is almost by definition harder than using a distributed system primitive designed for that task. For example, if every new worker identifies themselves in etcd, then they can watch keys to detect changes, meaning no one needs to destroy a running application just to update its list of peers, their contact information, their capacity, current workload, whatever interesting information you would enjoy having while building a distributed worker system.

But, on with the show:

If you want stable identifiers, then StatefulSets is the modern answer to that. Whether that is an exact fit for your situation depends on whether (for your problem domain) id:0 being "rebooted" still counts as id:0 or the fact that it has stopped and started now disqualifies it from being id:0.

The running list of cluster size is tricky. If you are willing to be flexible in the launch mechanism, then you can have a pre-launch binary populate the environment right before spawning the actual worker (that example is for reading from etcd directly, but the same principle holds for interacting with the kubernetes API, then launching).

You could do that same trick in a more static manner by having an initContainer write the current state of affairs to a file, which the app would then read in. Or, due to all Pod containers sharing networking, the app could contact a "sidecar" container on localhost to obtain that information via an API.

So far so good, except for the

on size changes for all workers to be killed and new one spawned

The best answer I have for that requirement is that if the app must know its peers at launch time, then I am pretty sure you have left the realm of "scale $foo --replicas=5" and entered into the "destroy the peers and start all afresh" realm, with kubectl delete pods -l some-label=of-my-pods; which is, thankfully, what updateStrategy: type: OnDelete does, when combined with the delete pods command.

ContentLicense: CC BY-SA 4.0

Body:
I want to scale an application with workers.

There could be 1 worker or 100, and I want to scale them seamlessly.

The idea is using replica set. However due to domain-specific reasons, the appropriate way to scale them is for each worker to know its: ID and the total number of workers.

For example, in case I have 3 workers, I'd have this:

id:0, num_workers:3
id:1, num_workers:3
id:2, num_workers:3

Is there a way of using kubernetes to do so?

I pass this information in command line arguments to the app, and I assume it would be fine having it in environment variables too.

It's ok on size changes for all workers to be killed and new ones spawned.


问:
Extension of Binary search algo to find the first and last index of the key value to be searched in an array
The problem is to extend the binary search algorithm to find all occurrences of a target value in a sorted array in the most efficient way.
Concretely speaking, the input of the algorithm is (1) a sorted array of integers, where some numbers may appear more than once, and (2) a target integer to be searched. The output of the algorithm should be a pair of index values, indicating the first and last occurrence of the integer in the array, if it does occur.
The source code could be in c#, c, c++.

Also, what is the max and min number of comparisons that we might need to find the indexes?

答:
I have created two binary search methods for returning first and last occurrences respectively.</p>

```<code>public static void main(String[] args) {
    int a[] ={1,2,2,2,2,2,5,5,6,8,9,10};

    System.out.println(5+" first = "+first(a, 5, 0, a.length-1));
    System.out.println(5+" last = "+right(a, 5, 0, a.length-1));

    System.out.println(1+" first = "+first(a, 1, 0, a.length-1));
    System.out.println(1+" last = "+right(a, 1, 0, a.length-1));

    System.out.println(2+" first = "+first(a, 2, 0, a.length-1));
    System.out.println(2+" last = "+right(a, 2, 0, a.length-1));

    System.out.println(10+" first = "+first(a, 10, 0, a.length-1));
    System.out.println(10+" last = "+right(a, 10, 0, a.length-1));

    System.out.println(8+" first = "+first(a, 8, 0, a.length-1));
    System.out.println(8+" last = "+right(a, 8, 0, a.length-1));

    System.out.println(11+" first = "+first(a, 11, 0, a.length-1));
    System.out.println(11+" last = "+right(a, 11, 0, a.length-1));

}

private static int first(int [] a, int x, int l, int h){
    if(l>h){
        return -1;
    }
    int mid = (h-l)/2+l;
    if(a[mid] == x && (mid==0 || a[mid-1] != x) ){
        return mid;
    }else if(a[mid] == x){
        return first(a, x, l, mid-1);
    }else if(a[mid]>x){
        return first(a, x, l, mid-1);
    }else{
        return first(a, x, mid+1, h);
    }
}

private static int right(int [] a, int x, int l, int h){
    if(l>h){
        return -1;
    }
    int mid = (h-l)/2+l;
    if(a[mid] == x && (mid==a.length-1 || a[mid+1] != x) ){
        return mid;
    }else if(a[mid] == x){
        return right(a, x, mid+1, h);
    }else if(a[mid]>x){
        return right(a, x, l, mid-1);
    }else{
        return right(a, x, mid+1, h);
    }
}

Output:
    1 first = 0
    1 last = 0
    2 first = 1
    2 last = 5
    10 first = 11
    10 last = 11
    8 first = 9
    8 last = 9
    11 first = -1
    11 last = -1
</code>```

Body:
I have created two binary search methods for returning first and last occurrences respectively.

public static void main(String[] args) {
    int a[] ={1,2,2,2,2,2,5,5,6,8,9,10};

    System.out.println(5+" first = "+first(a, 5, 0, a.length-1));
    System.out.println(5+" last = "+right(a, 5, 0, a.length-1));

    System.out.println(1+" first = "+first(a, 1, 0, a.length-1));
    System.out.println(1+" last = "+right(a, 1, 0, a.length-1));

    System.out.println(2+" first = "+first(a, 2, 0, a.length-1));
    System.out.println(2+" last = "+right(a, 2, 0, a.length-1));

    System.out.println(10+" first = "+first(a, 10, 0, a.length-1));
    System.out.println(10+" last = "+right(a, 10, 0, a.length-1));

    System.out.println(8+" first = "+first(a, 8, 0, a.length-1));
    System.out.println(8+" last = "+right(a, 8, 0, a.length-1));

    System.out.println(11+" first = "+first(a, 11, 0, a.length-1));
    System.out.println(11+" last = "+right(a, 11, 0, a.length-1));

}

private static int first(int [] a, int x, int l, int h){
    if(l>h){
        return -1;
    }
    int mid = (h-l)/2+l;
    if(a[mid] == x && (mid==0 || a[mid-1] != x) ){
        return mid;
    }else if(a[mid] == x){
        return first(a, x, l, mid-1);
    }else if(a[mid]>x){
        return first(a, x, l, mid-1);
    }else{
        return first(a, x, mid+1, h);
    }
}

private static int right(int [] a, int x, int l, int h){
    if(l>h){
        return -1;
    }
    int mid = (h-l)/2+l;
    if(a[mid] == x && (mid==a.length-1 || a[mid+1] != x) ){
        return mid;
    }else if(a[mid] == x){
        return right(a, x, mid+1, h);
    }else if(a[mid]>x){
        return right(a, x, l, mid-1);
    }else{
        return right(a, x, mid+1, h);
    }
}

Output:
    1 first = 0
    1 last = 0
    2 first = 1
    2 last = 5
    10 first = 11
    10 last = 11
    8 first = 9
    8 last = 9
    11 first = -1
    11 last = -1


问:
Why is matrix subtraction much slower than dot product in numpy?
Let's say we have a vector and a matrix:

```<code>X = np.random.random((1, 384)).astype('float32')
Y = np.random.random((500000, 384)).astype('float32')
</code>```

Why is np.dot(X, Y.T) much faster than X - Y?

```<code>In [8]: %timeit np.dot(X, Y.T)
10 loops, best of 3: 42.4 ms per loop

In [9]: %timeit X - Y
1 loop, best of 3: 501 ms per loop
</code>```

What can I do to make subtraction like this as faster as dot product?

答: Using the np.subtract(X,Y) almost halves the execution time. It is faster than X-Y but the speed is till lower than the dot product. Might help

Body:
Let's say we have a vector and a matrix:

X = np.random.random((1, 384)).astype('float32')
Y = np.random.random((500000, 384)).astype('float32')

Why is np.dot(X, Y.T) much faster than X - Y?

In [8]: %timeit np.dot(X, Y.T)
10 loops, best of 3: 42.4 ms per loop

In [9]: %timeit X - Y
1 loop, best of 3: 501 ms per loop

What can I do to make subtraction like this as faster as dot product?


问:
"_user" & the use of underscore is this a shortcut?
I have been reading through some PHP code and I'm confused about one thing. I'm sorry if it may be basics, but I couldn't find anything about this (tbh no idea how to search for it).

there is a time where they use "_user". I have found out that it refers to class USER. However, I can't find anywhere where they refer _user to the USER class.

Does the underscore _ has a special meaning?

where and how did they link USER class with _user?

order.php file:

```<code>class ORDER
{
// order properties
private $_db = null;
private $_settings = null;
private $_user = null;

private $_userLevel = 1;

...

/**
 * Order Constructor
 * @param $db
 * @param $settings
 * @param $user
 * @param $need_db_record
 * @return ORDER
 */
public function __construct(&$db, &$settings, &$user, $need_db_record=false, $check_user_change = true)
{
    $this->_db = $db;
    $this->_settings = $settings;
    $this->_user = $user;
...
}

/**
 * Returns class instance
 * @return USER
 */
public function user()
{
    return $this->_user;
}
</code>```

答:
1) Some people use an underscore before variable names to denote a private variable. This is just a convention though and has no effect on the functionality of the code. If you want to know more about visiblity of variables, see: http://php.net/manual/en/language.oop5.visibility.php.

2) <s>This question can not be answered without us seeing more of the code. Somewhere in the class there is either a setter method for $_user or it gets set in the constructor of the class. Since it seems to be private, these are are the only two options.</s> <- More code was provided. New answer:

2) The variable $user is introduced via the constructor of the class ORDER. Somewhere in your code you will find the class USER, which describes how the object $user is built. If you want to know from where exactly $user is coming, search for "new Order(" in your code. You will find all places, where ORDER instances are created and you will see the arguments that are used. You can do the same with "new User(" and you will find all the places where USER instances are created.

If you are new to OOP I propose you read some introductory articles. You can start with the article from the PHP site itself: http://php.net/manual/en/language.oop5.php or look for some online courses or tutorials, like for example: https://www.codecademy.com/courses/web-beginner-en-bH5s3/0/1

An important aspect of the ORDER class you provided is that the variables $db, $settings and $user are given as references. That means if one would manipulate anything on the $db instance, these changes would be global. Chances are there is only one instance of $db, $settings and $user in the system, which are passed around by reference. See also: http://php.net/manual/en/language.references.pass.php

Body:
I have been reading through some PHP code and I'm confused about one thing. I'm sorry if it may be basics, but I couldn't find anything about this (tbh no idea how to search for it).

there is a time where they use "_user". I have found out that it refers to class USER. However, I can't find anywhere where they refer _user to the USER class.

Does the underscore _ has a special meaning?

where and how did they link USER class with _user?

order.php file:

class ORDER
{
// order properties
private $_db = null;
private $_settings = null;
private $_user = null;

private $_userLevel = 1;

...

/**
 * Order Constructor
 * @param $db
 * @param $settings
 * @param $user
 * @param $need_db_record
 * @return ORDER
 */
public function __construct(&$db, &$settings, &$user, $need_db_record=false, $check_user_change = true)
{
    $this->_db = $db;
    $this->_settings = $settings;
    $this->_user = $user;
...
}

/**
 * Returns class instance
 * @return USER
 */
public function user()
{
    return $this->_user;
}


问:
How can I make custom SQL with order by in codeigniter
My code is here Sql Query :

```<code>$sql ="select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc";
$product=$this->db->query($sql)->result_array();
</code>```

view all products by using customs SQL but still not showing order by desc.

答:
You can try this solution for your problem :

```<code>$query = $this->db->query('select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc');
$row_array = $query->result_array();
</code>```

I Hop it will help you.

Body:
My code is here Sql Query :

$sql ="select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc";
$product=$this->db->query($sql)->result_array();

view all products by using customs SQL but still not showing order by desc.

Body:
You can try this solution for your problem :

$query = $this->db->query('select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc');
$row_array = $query->result_array();

I Hop it will help you.


问:
Moving UIImage Up and Down with Animation in Swift
I have just recently started with Xcode and Swift and I am trying to get my image to move up and down and have it switch directions when the user taps the screen. My image just will not move at all and the app will either crash or just freeze.

```<code>import UIKit
import SpriteKit
import Darwin

let startButton = UIButton(frame: CGRect(x: 200, y: 100, width: 100, height: 50))
let screenSize = UIScreen.main.bounds
let gameButton = UIButton(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height))

var dot: UIImage = UIImage(named: "dot")!
var dotPic = UIImageView(image: dot)

public var goingUp = true

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = .white

    startButton.addTarget(self, action: #selector(startButtonAction), for: .touchUpInside)
    startButton.setImage(UIImage.init(named: "startButton"), for: .normal)

    self.view.addSubview(startButton)
}

func startButtonAction(sender: UIButton!) {
    print("button clicked")
    startButton.isEnabled = false
    startButton.setImage(UIImage.init(named: "nothing"), for: .normal)
    self.view.backgroundColor = .gray
    dotPic.frame = CGRect(x: 50, y: 300, width: 20, height: 20)

    self.view.addSubview(dotPic)
    self.view.addSubview(gameButton)

    playGame()
}

func playGame(){
    gameButton.addTarget(self, action: #selector(gameButtonAction), for: .touchUpInside)
    gameButton.setImage(UIImage.init(named: "nothing"), for: .normal)
}

func gameButtonAction(sender: UIButton!) {
    goingUp = !goingUp
    print(goingUp)
    print("clicked up/down")

    func rep(){
        repeat{
            dotPic.frame = CGRect(x: 50, y: 300-1, width: 20, height: 20)
            sleep(UInt32(0.3))
        }while goingUp==true
        repeat{
            dotPic.frame = CGRect(x: 50, y: 300-1, width: 20, height: 20)
            sleep(UInt32(0.3))
        }while goingUp==false
    }
    rep()
}

}
</code>```

I have tried using animateWithDuration() too but it has always frozen the app. What am I doing wrong?

答:
Tried to use this code in swift...</p>

```<code>self.hintImageView.frame = CGRect(x: x, y: 55, width: 200, height: 40)
UIView.animate(withDuration: 0.5, delay: 0, options: [.repeat, .autoreverse] , animations: {
        self.hintImageView.frame = CGRect(x: x, y: 65, width: 200, height: 40);
    }) { (completed) in

    }
</code>```

Body:
I have just recently started with Xcode and Swift and I am trying to get my image to move up and down and have it switch directions when the user taps the screen. My image just will not move at all and the app will either crash or just freeze.

import UIKit
import SpriteKit
import Darwin

let startButton = UIButton(frame: CGRect(x: 200, y: 100, width: 100, height: 50))
let screenSize = UIScreen.main.bounds
let gameButton = UIButton(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height))

var dot: UIImage = UIImage(named: "dot")!
var dotPic = UIImageView(image: dot)

public var goingUp = true

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = .white

    startButton.addTarget(self, action: #selector(startButtonAction), for: .touchUpInside)
    startButton.setImage(UIImage.init(named: "startButton"), for: .normal)

    self.view.addSubview(startButton)
}

func startButtonAction(sender: UIButton!) {
    print("button clicked")
    startButton.isEnabled = false
    startButton.setImage(UIImage.init(named: "nothing"), for: .normal)
    self.view.backgroundColor = .gray
    dotPic.frame = CGRect(x: 50, y: 300, width: 20, height: 20)

    self.view.addSubview(dotPic)
    self.view.addSubview(gameButton)

    playGame()
}

func playGame(){
    gameButton.addTarget(self, action: #selector(gameButtonAction), for: .touchUpInside)
    gameButton.setImage(UIImage.init(named: "nothing"), for: .normal)
}

func gameButtonAction(sender: UIButton!) {
    goingUp = !goingUp
    print(goingUp)
    print("clicked up/down")

    func rep(){
        repeat{
            dotPic.frame = CGRect(x: 50, y: 300-1, width: 20, height: 20)
            sleep(UInt32(0.3))
        }while goingUp==true
        repeat{
            dotPic.frame = CGRect(x: 50, y: 300-1, width: 20, height: 20)
            sleep(UInt32(0.3))
        }while goingUp==false
    }
    rep()
}

}

I have tried using animateWithDuration() too but it has always frozen the app. What am I doing wrong?

Body:
Tried to use this code in swift...

self.hintImageView.frame = CGRect(x: x, y: 55, width: 200, height: 40)
UIView.animate(withDuration: 0.5, delay: 0, options: [.repeat, .autoreverse] , animations: {
        self.hintImageView.frame = CGRect(x: x, y: 65, width: 200, height: 40);
    }) { (completed) in

    }


问:
Are Dynamically Loaded Files Cached by the Browser?
I have a question that is related to this answer, $.getScript(filename)

Are dynamically loaded files cached by the browser?

If not, how can I force them to be?

答:
It seems that they are not. Proposed workaround is to redefine the function:

```<code>$.getScript = function(url, callback, cache) {
    $.ajax({
        type: "GET",
        url: url,
        success: callback,
        dataType: "script",
        cache: cache
    });
};
</code>```

which could be used like this:

```<code>$.getScript('/foo.js', function() { }, true);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It seems that they are not. Proposed workaround is to redefine the function:

$.getScript = function(url, callback, cache) {
    $.ajax({
        type: "GET",
        url: url,
        success: callback,
        dataType: "script",
        cache: cache
    });
};

which could be used like this:

$.getScript('/foo.js', function() { }, true);


问:
Spring JDBCTemplate: How to call a View in MySQL schema from Spring Controller
I have a View in MySQL schema that already do the following:
My question is how do I call that View using jdbctemplate instead?</p>

```<code>    // insert person into database
    jdbcTemplate.update(
        "INSERT INTO Person (FirstName, LastName, Address, Phone, City, State, ZipCode) VALUES (?, ?, ?, ?, ?, ?, ?)",
        person.getFirstName(), person.getLastName(), person.getAddress(), person.getPhone(), person.getCity(), person.getState(), person.getZipCode()
    );

    // get this persons generated id from the DB
    int personId = jdbcTemplate.queryForObject(
        "SELECT Id FROM Person WHERE FirstName=? AND LastName=?", new Object[]{person.getFirstName(), person.getLastName()}, int.class);

    // create user account for person
    jdbcTemplate.update(
        "INSERT INTO User (person_Id, active, username, password) VALUES (?, ?, ?, ?)",
        personId, 1, username, password
    );

    int userId = jdbcTemplate.queryForObject(
        "SELECT user_id FROM User WHERE username=? AND password=?", new Object[]{username, password}, int.class);

    // finally add role to user
    // by default, all users are set to Customer roles.
    jdbcTemplate.update(
        "INSERT INTO User_role (user_id, role_id) VALUES (?, ?)",
        userId, Role.CUSTOMER_ROLE
    );
</code>```

答:
Views can be accessed just like any other tables in JDBC while selecting the data. So, something like the following works fine for us.

```<code> int personId = jdbcTemplate.queryForObject(
        "SELECT Id FROM Our_View WHERE FirstName=? AND LastName=?", new Object[]{person.getFirstName(), person.getLastName()}, int.class);
</code>```

But, for Updatable and Insertable views in Mysql, refer here

Body:
I have a View in MySQL schema that already do the following:
My question is how do I call that View using jdbctemplate instead?

    // insert person into database
    jdbcTemplate.update(
        "INSERT INTO Person (FirstName, LastName, Address, Phone, City, State, ZipCode) VALUES (?, ?, ?, ?, ?, ?, ?)",
        person.getFirstName(), person.getLastName(), person.getAddress(), person.getPhone(), person.getCity(), person.getState(), person.getZipCode()
    );

    // get this persons generated id from the DB
    int personId = jdbcTemplate.queryForObject(
        "SELECT Id FROM Person WHERE FirstName=? AND LastName=?", new Object[]{person.getFirstName(), person.getLastName()}, int.class);

    // create user account for person
    jdbcTemplate.update(
        "INSERT INTO User (person_Id, active, username, password) VALUES (?, ?, ?, ?)",
        personId, 1, username, password
    );

    int userId = jdbcTemplate.queryForObject(
        "SELECT user_id FROM User WHERE username=? AND password=?", new Object[]{username, password}, int.class);

    // finally add role to user
    // by default, all users are set to Customer roles.
    jdbcTemplate.update(
        "INSERT INTO User_role (user_id, role_id) VALUES (?, ?)",
        userId, Role.CUSTOMER_ROLE
    );

Body:
Views can be accessed just like any other tables in JDBC while selecting the data. So, something like the following works fine for us.

 int personId = jdbcTemplate.queryForObject(
        "SELECT Id FROM Our_View WHERE FirstName=? AND LastName=?", new Object[]{person.getFirstName(), person.getLastName()}, int.class);

But, for Updatable and Insertable views in Mysql, refer here


问:
CKEditor CDN and config for inline editing
So, I have a page with div's that have contenteditable=true, and I load //cdn.ckeditor.com/4.7.3/standard/ckeditor.js which makes them editable with CKEditor - but since I do not use CKEDITOR.replace() I can't send along a configuration for the editor's. How do I set the toolbar configuration for CKEditor that is being loaded for contenteditable fields?

答:
If you want to use CDN, I'm afraid only option is to use </p>

```<code>CKEDITOR.disableAutoInline = true;
CKEDITOR.inline("div_id", { customConfig: "config.js" });
</code>```

Body:
If you want to use CDN, I'm afraid only option is to use

CKEDITOR.disableAutoInline = true;
CKEDITOR.inline("div_id", { customConfig: "config.js" });


问:
Button's text not change on RecyclerView
I have a code for RecyclerView where I added 3 buttons one of them is Shortlist button. When I am clicking on button, success is coming from server on volley response. I need when I clicked on button then button's text should be changed and another's item will not be effected.

Below is my CardAdapter class where I extends RecyclerView.Adapter

```<code>public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private static final String url ="http://192.168.2.110/xp/shortlist1.php";
private static final String url1 = "http://192.168.2.110/xp/express_intrest.php";
private static final String KEY_MATRI_ID_TO="matriID_to";
private static final String KEY_MATRI_ID_BY="matriID_by";

SessionManager session;
public String matri_id_to, matri_id_by, str_gender;
String str;

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.superheroes_list, parent, false);
    // Session class instance
    session = new SessionManager(context);
    session.checkLogin();
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();
    matri_id_by = user.get(SessionManager.KEY_EMAIL);
    str_gender = user.get(SessionManager.KEY_GENDER);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Getting the particular item from the list
    final SuperHero superHero =  superHeroes.get(position);

    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));

    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewId.setText(superHero.getMglId());
    holder.AgeHeight.setText(superHero.getAgeHeight()+" / "+superHero.getAge());
    holder.Community.setText(superHero.getCommunity()+" / "+superHero.getCaste());
    holder.Occupation.setText(superHero.getOccupation());
    holder.Income.setText(superHero.getIncome());
    //   holder.btnShortlist.setText(superHero.getShortlist());
    //   holder.btnEI.setText(superHero.getExpress_Intrest());

    holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            superHero.setShortlist("Wait...");
            holder.btnShortlist.setText(superHero.getShortlist());
            matri_id_to = superHero.getMglId();
            holder.shortlist(position);
        }
    });

    str = superHero.getShortlist();
    Log.e("sh____________",str);

    if(str.toString().equalsIgnoreCase("shortlisted")) {
        holder.btnShortlist.setText(str);
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
        holder.btnShortlist.setEnabled(false);
    }
    else{
        holder.btnShortlist.setText(str);
    }

    holder.btnViewProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent n = new Intent(holder.itemView.getContext(),BlankActivity.class);
            String str_id = holder.textViewId.getText().toString();
            n.putExtra("ID",str_id);
            holder.itemView.getContext().startActivity(n);
        }
    });

    holder.btnEI.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        }
    });

}

public SuperHero getItem(int position){
    return superHeroes.get(position);
}

@Override
public int getItemCount() {return superHeroes.size();}

class ViewHolder extends RecyclerView.ViewHolder{
    public NetworkImageView imageView;
    public TextView textViewId;
    public TextView AgeHeight;
    public TextView Community;
    public TextView Occupation;
    public TextView Income;
    public Button btnShortlist;
    public Button btnViewProfile;
    public Button btnEI;

    //Initializing Views
    public ViewHolder(final View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewId = (TextView) itemView.findViewById(R.id.textViewId);
        AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
        Community = (TextView) itemView.findViewById(R.id.Community);
        Occupation = (TextView) itemView.findViewById(R.id.Occupation);
        Income = (TextView) itemView.findViewById(R.id.Income);
        btnShortlist = (Button) itemView.findViewById(R.id.btnshort);
        btnViewProfile = (Button) itemView.findViewById(R.id.buttonViewProfile);
        btnEI = (Button) itemView.findViewById(R.id.btnExpressIntrest);
    }

    public void shortlist(final int position) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response.trim().equalsIgnoreCase("success")) {
                    superHeroes.get(position).setShortlist("Shortlisted");
                    holder.btnShortlist.setText(superHero.getShortlist());
                    notifyDataSetChanged();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_MATRI_ID_BY, matri_id_by);
                params.put(KEY_MATRI_ID_TO, matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);
      }
     }
    }
</code>```

答:
You problem is in onClickListener. update the code as mentioned below:

```<code>holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            superHero.setShortlist("Wait...");
            holder.btnShortlist.setText(superHero.getShortlist());
            matri_id_to = superHero.getMglId();
            holder.shortlist(position);
        }
     });
</code>```

If you don't do so then your view will be reset when you scroll or the item will be recycled for the condition you have added:

```<code>if(str.toString().equalsIgnoreCase("shortlisted")) {
    holder.btnShortlist.setText(str);
    holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
    holder.btnShortlist.setEnabled(false);
}
else{
    holder.btnShortlist.setText(str);
}
</code>```

Further,

```<code>public void shortlist(final ViewHolder holder, final int position) {
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if (response.trim().equalsIgnoreCase("success")) {
                // If response is success then button's text should be changed i.e "Shortlisted"
                superHeroes.get(position).setShortlist("Shortlisted");
                holder.btnShortlist.setText(superHero.getShortlist());
                notifyDataSetChanged();
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_MATRI_ID_BY, matri_id_by);
            params.put(KEY_MATRI_ID_TO, matri_id_to);
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);
}
</code>```

If still it will not come then call notifyDataSetChanged() at the last of onClick().

Update you condition and get your required result:

If you change any UI in adapter in if block then there should be proper reflect of the same change in UI for else case otherwise when the view will refreshed, you UI may not recycled as per desired. So updated your code for the condition you have mentioned:

```<code>if (str.toString().equalsIgnoreCase("shortlisted")) {
        holder.btnShortlist.setText(str);
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
        holder.btnShortlist.setEnabled(false);
    } else {
        holder.btnShortlist.setText(str);

        //Color you want in else case
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));

        //State you want in else case
        holder.btnShortlist.setEnabled(false);
    }
</code>```

Body:
I have a code for RecyclerView where I added 3 buttons one of them is Shortlist button. When I am clicking on button, success is coming from server on volley response. I need when I clicked on button then button's text should be changed and another's item will not be effected.

Below is my CardAdapter class where I extends RecyclerView.Adapter

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private static final String url ="http://192.168.2.110/xp/shortlist1.php";
private static final String url1 = "http://192.168.2.110/xp/express_intrest.php";
private static final String KEY_MATRI_ID_TO="matriID_to";
private static final String KEY_MATRI_ID_BY="matriID_by";

SessionManager session;
public String matri_id_to, matri_id_by, str_gender;
String str;

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.superheroes_list, parent, false);
    // Session class instance
    session = new SessionManager(context);
    session.checkLogin();
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();
    matri_id_by = user.get(SessionManager.KEY_EMAIL);
    str_gender = user.get(SessionManager.KEY_GENDER);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Getting the particular item from the list
    final SuperHero superHero =  superHeroes.get(position);

    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));

    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewId.setText(superHero.getMglId());
    holder.AgeHeight.setText(superHero.getAgeHeight()+" / "+superHero.getAge());
    holder.Community.setText(superHero.getCommunity()+" / "+superHero.getCaste());
    holder.Occupation.setText(superHero.getOccupation());
    holder.Income.setText(superHero.getIncome());
    //   holder.btnShortlist.setText(superHero.getShortlist());
    //   holder.btnEI.setText(superHero.getExpress_Intrest());

    holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            superHero.setShortlist("Wait...");
            holder.btnShortlist.setText(superHero.getShortlist());
            matri_id_to = superHero.getMglId();
            holder.shortlist(position);
        }
    });

    str = superHero.getShortlist();
    Log.e("sh____________",str);

    if(str.toString().equalsIgnoreCase("shortlisted")) {
        holder.btnShortlist.setText(str);
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
        holder.btnShortlist.setEnabled(false);
    }
    else{
        holder.btnShortlist.setText(str);
    }

    holder.btnViewProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent n = new Intent(holder.itemView.getContext(),BlankActivity.class);
            String str_id = holder.textViewId.getText().toString();
            n.putExtra("ID",str_id);
            holder.itemView.getContext().startActivity(n);
        }
    });

    holder.btnEI.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        }
    });

}

public SuperHero getItem(int position){
    return superHeroes.get(position);
}

@Override
public int getItemCount() {return superHeroes.size();}

class ViewHolder extends RecyclerView.ViewHolder{
    public NetworkImageView imageView;
    public TextView textViewId;
    public TextView AgeHeight;
    public TextView Community;
    public TextView Occupation;
    public TextView Income;
    public Button btnShortlist;
    public Button btnViewProfile;
    public Button btnEI;

    //Initializing Views
    public ViewHolder(final View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewId = (TextView) itemView.findViewById(R.id.textViewId);
        AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
        Community = (TextView) itemView.findViewById(R.id.Community);
        Occupation = (TextView) itemView.findViewById(R.id.Occupation);
        Income = (TextView) itemView.findViewById(R.id.Income);
        btnShortlist = (Button) itemView.findViewById(R.id.btnshort);
        btnViewProfile = (Button) itemView.findViewById(R.id.buttonViewProfile);
        btnEI = (Button) itemView.findViewById(R.id.btnExpressIntrest);
    }

    public void shortlist(final int position) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response.trim().equalsIgnoreCase("success")) {
                    superHeroes.get(position).setShortlist("Shortlisted");
                    holder.btnShortlist.setText(superHero.getShortlist());
                    notifyDataSetChanged();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_MATRI_ID_BY, matri_id_by);
                params.put(KEY_MATRI_ID_TO, matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);
      }
     }
    }

Body:
You problem is in onClickListener. update the code as mentioned below:

holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            superHero.setShortlist("Wait...");
            holder.btnShortlist.setText(superHero.getShortlist());
            matri_id_to = superHero.getMglId();
            holder.shortlist(position);
        }
     });

If you don't do so then your view will be reset when you scroll or the item will be recycled for the condition you have added:

if(str.toString().equalsIgnoreCase("shortlisted")) {
    holder.btnShortlist.setText(str);
    holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
    holder.btnShortlist.setEnabled(false);
}
else{
    holder.btnShortlist.setText(str);
}

Further,

public void shortlist(final ViewHolder holder, final int position) {
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if (response.trim().equalsIgnoreCase("success")) {
                // If response is success then button's text should be changed i.e "Shortlisted"
                superHeroes.get(position).setShortlist("Shortlisted");
                holder.btnShortlist.setText(superHero.getShortlist());
                notifyDataSetChanged();
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_MATRI_ID_BY, matri_id_by);
            params.put(KEY_MATRI_ID_TO, matri_id_to);
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);
}

If still it will not come then call notifyDataSetChanged() at the last of onClick().

Update you condition and get your required result:

If you change any UI in adapter in if block then there should be proper reflect of the same change in UI for else case otherwise when the view will refreshed, you UI may not recycled as per desired. So updated your code for the condition you have mentioned:

if (str.toString().equalsIgnoreCase("shortlisted")) {
        holder.btnShortlist.setText(str);
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
        holder.btnShortlist.setEnabled(false);
    } else {
        holder.btnShortlist.setText(str);

        //Color you want in else case
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));

        //State you want in else case
        holder.btnShortlist.setEnabled(false);
    }


问:
nul terminating a int array
gcc 4.4.4 c89

I was just experimenting with a int array. And something just came to my mind. Can I nul terminate it. For example, I am using a 0 to nul terminate. However, 0 could well be a valid value in this array.

The code below will terminate after the 5. Even though I mean 0 to be a valid number. However, I could specify the size of the array. But in this case, I don't want to this as I am just interested in this particular problem.

Many thanks for any advice,

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

static void test(int *p);

int main(void)
{
    int arr[] = {30, 450, 14, 5, 0, 10, '\0'};

    test(arr);

    return 0;
}

static void test(int *p)
{
    while(*p) {
        printf("Array values [ %d ]\n", *p++);
    }
}
</code>```

答:
Well, you can also change your sentinel from \0 to \\0. And, accordingly, a slight modification in the condition for while loop will get you around your problem.

```<code>while(*p != '\\0')
</code>```

Now, 0 will not be treated as terminator for the integer array and the whole array gets printed.

Title: nul terminating a int array

Body:
gcc 4.4.4 c89

I was just experimenting with a int array. And something just came to my mind. Can I nul terminate it. For example, I am using a 0 to nul terminate. However, 0 could well be a valid value in this array.

The code below will terminate after the 5. Even though I mean 0 to be a valid number. However, I could specify the size of the array. But in this case, I don't want to this as I am just interested in this particular problem.

Many thanks for any advice,

#include <stdio.h>

static void test(int *p);

int main(void)
{
    int arr[] = {30, 450, 14, 5, 0, 10, '\0'};

    test(arr);

    return 0;
}

static void test(int *p)
{
    while(*p) {
        printf("Array values [ %d ]\n", *p++);
    }
}

Body:
Well, you can also change your sentinel from \0 to \\0. And, accordingly, a slight modification in the condition for while loop will get you around your problem.

while(*p != '\\0')

Now, 0 will not be treated as terminator for the integer array and the whole array gets printed.


问:
Protractor: Count all hyperlinks and test them on a page
I am trying to count the number of hyperlinks on a page and test them to see if they work. I have the ability to count all the links and display that count in JavaScript but I can't seem to return that value in protractor on Command Line.

Update Code based on Answers:

```<code>browser.waitForAngularEnabled(false);
describe('Clicks on the correct Drupal hyperlink', function() {

  it('should find all links', function () {
    browser.get('file:///C:/Users/Dasman/Documents/PROTRACTOR_E2E_TESTING/TestSite.html');
    let allLinks = element.all(by.tagName('a'));
    allLinks.count().then(function(link_tally){
      console.log('There are a total of ' + link_tally + " links on this page with proper tags.")
    })
  browser.sleep(2000);

  // A Protracterized httpGet() promise
function httpGet(siteUrl) {
  var http = require('http');
  var defer = protractor.promise.defer();

  http.get(siteUrl, function(response) {

      var bodyString = '';

      response.setEncoding('utf8');

      response.on("data", function(chunk) {
          bodyString += chunk;
      });

      response.on('end', function() {
          defer.fulfill({
              statusCode: response.statusCode,
              bodyString: bodyString
          });
      });

  }).on('error', function(e) {
      defer.reject("Got http.get error: " + e.message);
  });

  return defer.promise;
}

it('should return 200 and contain proper body', function() {
  httpGet(allLinks).then(function(result) {
    allLinks.count().then(function(statusCode){
      console.log('Status code is: ' + statusCode)
    })
      expect(result.statusCode).toBe(200);
      expect(result.bodyString).toContain('Apache');
  });
});
    });
});
</code>```

In addition I want to "check" the links to see if they open. Is there a way to go to a URL and click all the links and have them open on separate windows? or get an attribute if the link works or has a valid URL?

I originally xpath the id and clicked the link and as the test ran - I visually verified. But with 15-20 links on a average page - I need a more automated way.

Ernst's answer pointed me to the solution, but it did need some code restructuring and encapsulation: https://github.com/SDasman/Angular_Protractor_End2End_Tests/tree/master/LinkCheck

答:
To report your count in the console you can do this:

```<code>//find all links
let linkCount = element.all(by.css('a'));

// count links, with then() resolve promise and log count result
linkCount.count().then(function(cnt){
    console.log('Total links = '+cnt);
});

//here you click each of the links:
linkCount.click()
</code>```

You can find out more about count(), then() and element.all() here: http://protractortest.org/#/api

To check the response code of your links, it will be a bit tricky, because Protractor doesn't support such requests out of the box (see here).

However, there are two SO-Posts here and here, which provide a way to do it.

To get it tested one by one you should be able to use getAttribute('href').
It would be something like this (Note: not tested, but partly copied from above two mentioned SO-Answers)

```<code>linkCount.each(function(elem){
    elem.getAttribute('href').then(function(link){
        this.httpGet("http://localhost:80").then(function(result) {
            expect(result.statusCode).toBe(200);
        });
    });
});

// A Protracterized httpGet() promise
this.httpGet = function(siteUrl) {
    var http = require('http');
    var defer = protractor.promise.defer();

    http.get(siteUrl, function(response) {

        var bodyString = '';

        response.setEncoding('utf8');

        response.on("data", function(chunk) {
            bodyString += chunk;
        });

        response.on('end', function() {
            defer.fulfill({
                statusCode: response.statusCode,
                bodyString: bodyString
            });
        });

    }).on('error', function(e) {
        defer.reject("Got http.get error: " + e.message);
    });

    return defer.promise;
}
</code>```

Body:
I am trying to count the number of hyperlinks on a page and test them to see if they work. I have the ability to count all the links and display that count in JavaScript but I can't seem to return that value in protractor on Command Line.

Update Code based on Answers:

browser.waitForAngularEnabled(false);
describe('Clicks on the correct Drupal hyperlink', function() {

  it('should find all links', function () {
    browser.get('file:///C:/Users/Dasman/Documents/PROTRACTOR_E2E_TESTING/TestSite.html');
    let allLinks = element.all(by.tagName('a'));
    allLinks.count().then(function(link_tally){
      console.log('There are a total of ' + link_tally + " links on this page with proper tags.")
    })
  browser.sleep(2000);

  // A Protracterized httpGet() promise
function httpGet(siteUrl) {
  var http = require('http');
  var defer = protractor.promise.defer();

  http.get(siteUrl, function(response) {

      var bodyString = '';

      response.setEncoding('utf8');

      response.on("data", function(chunk) {
          bodyString += chunk;
      });

      response.on('end', function() {
          defer.fulfill({
              statusCode: response.statusCode,
              bodyString: bodyString
          });
      });

  }).on('error', function(e) {
      defer.reject("Got http.get error: " + e.message);
  });

  return defer.promise;
}

it('should return 200 and contain proper body', function() {
  httpGet(allLinks).then(function(result) {
    allLinks.count().then(function(statusCode){
      console.log('Status code is: ' + statusCode)
    })
      expect(result.statusCode).toBe(200);
      expect(result.bodyString).toContain('Apache');
  });
});
    });
});

In addition I want to "check" the links to see if they open. Is there a way to go to a URL and click all the links and have them open on separate windows? or get an attribute if the link works or has a valid URL?

I originally xpath the id and clicked the link and as the test ran - I visually verified. But with 15-20 links on a average page - I need a more automated way.

Ernst's answer pointed me to the solution, but it did need some code restructuring and encapsulation: https://github.com/SDasman/Angular_Protractor_End2End_Tests/tree/master/LinkCheck

Body:
To report your count in the console you can do this:

//find all links
let linkCount = element.all(by.css('a'));

// count links, with then() resolve promise and log count result
linkCount.count().then(function(cnt){
    console.log('Total links = '+cnt);
});

//here you click each of the links:
linkCount.click()

You can find out more about count(), then() and element.all() here: http://protractortest.org/#/api

To check the response code of your links, it will be a bit tricky, because Protractor doesn't support such requests out of the box (see here).

However, there are two SO-Posts here and here, which provide a way to do it.

To get it tested one by one you should be able to use getAttribute('href').
It would be something like this (Note: not tested, but partly copied from above two mentioned SO-Answers)

linkCount.each(function(elem){
    elem.getAttribute('href').then(function(link){
        this.httpGet("http://localhost:80").then(function(result) {
            expect(result.statusCode).toBe(200);
        });
    });
});

// A Protracterized httpGet() promise
this.httpGet = function(siteUrl) {
    var http = require('http');
    var defer = protractor.promise.defer();

    http.get(siteUrl, function(response) {

        var bodyString = '';

        response.setEncoding('utf8');

        response.on("data", function(chunk) {
            bodyString += chunk;
        });

        response.on('end', function() {
            defer.fulfill({
                statusCode: response.statusCode,
                bodyString: bodyString
            });
        });

    }).on('error', function(e) {
        defer.reject("Got http.get error: " + e.message);
    });

    return defer.promise;
}


答:
Try this</p>

```<code>$this->db->from('products');
$this->db->where("status='1' AND country='5' AND product_price > '50' AND product_price <= '100'", null, false);
$this->db->order_by("product_id", "desc");
$query = $this->db->get();
return $query->result_array();
</code>```

Title: How can I make custom SQL with order by in codeigniter

Body:
Try this

$this->db->from('products');
$this->db->where("status='1' AND country='5' AND product_price > '50' AND product_price <= '100'", null, false);
$this->db->order_by("product_id", "desc");
$query = $this->db->get();
return $query->result_array();


问:
get the windows installation drive using python
How to detect the windows installation path or drive using python code ?</p>

答:
```<code>>>> import os
>>> os.environ['SYSTEMDRIVE']
'C:'
</code>```


问:
Getting attributes from XML using c#
I have the following xml contents inside a string variable. i want to get the value of each attribute (JID) in the form of string.

Below is my xml

```<code>  <query xmlns="http://jabber.org/protocol/muc#admin">
  <item affiliation="member" jid="a@something.com" />
  <item affiliation="member" jid="b@something.com" />
  <item affiliation="member" jid="c@something.com" />
  <item affiliation="member" jid="d@something.com" />
  <item affiliation="member" jid="e@something.com" />
  <item affiliation="member" jid="f@something.com" />
  <item affiliation="member" jid="g@something.com" />
  <item affiliation="member" jid="h@something.com" />
  <item affiliation="member" jid="i@something.com" />
  <item affiliation="member" jid="j@something.com" />
  </query>
</code>```

Anyone please suggest some ideas to find this.
my expected output is like

```<code>   a@something.com
   b@something.com
   c@something.com
   d@something.com
   e@something.com
   f@something.com
</code>```

答:
try this </p>

```<code>  var data = @" <query xmlns=""http://jabber.org/protocol/muc#admin"">
  <item affiliation=""member"" jid=""a@something.com"" />
  <item affiliation=""member"" jid=""b@something.com"" />
  <item affiliation=""member"" jid=""c@something.com"" />
  <item affiliation=""member"" jid=""d@something.com"" />
  <item affiliation=""member"" jid=""e@something.com"" />
  <item affiliation=""member"" jid=""f@something.com"" />
  <item affiliation=""member"" jid=""g@something.com"" />
  <item affiliation=""member"" jid=""h@something.com"" />
  <item affiliation=""member"" jid=""i@something.com"" />
  <item affiliation=""member"" jid=""j@something.com"" />
  </query>";
            var xml = XElement.Parse(data);
            var r = xml.Elements();
            var result = r.Select(item => item.Attribute("jid")?.Value).ToArray();
</code>```

Title: Getting attributes from XML using c#

Body:
I have the following xml contents inside a string variable. i want to get the value of each attribute (JID) in the form of string.

Below is my xml

  <query xmlns="http://jabber.org/protocol/muc#admin">
  <item affiliation="member" jid="a@something.com" />
  <item affiliation="member" jid="b@something.com" />
  <item affiliation="member" jid="c@something.com" />
  <item affiliation="member" jid="d@something.com" />
  <item affiliation="member" jid="e@something.com" />
  <item affiliation="member" jid="f@something.com" />
  <item affiliation="member" jid="g@something.com" />
  <item affiliation="member" jid="h@something.com" />
  <item affiliation="member" jid="i@something.com" />
  <item affiliation="member" jid="j@something.com" />
  </query>

Anyone please suggest some ideas to find this.
my expected output is like

   a@something.com
   b@something.com
   c@something.com
   d@something.com
   e@something.com
   f@something.com

Body:
try this

  var data = @" <query xmlns=""http://jabber.org/protocol/muc#admin"">
  <item affiliation=""member"" jid=""a@something.com"" />
  <item affiliation=""member"" jid=""b@something.com"" />
  <item affiliation=""member"" jid=""c@something.com"" />
  <item affiliation=""member"" jid=""d@something.com"" />
  <item affiliation=""member"" jid=""e@something.com"" />
  <item affiliation=""member"" jid=""f@something.com"" />
  <item affiliation=""member"" jid=""g@something.com"" />
  <item affiliation=""member"" jid=""h@something.com"" />
  <item affiliation=""member"" jid=""i@something.com"" />
  <item affiliation=""member"" jid=""j@something.com"" />
  </query>";
            var xml = XElement.Parse(data);
            var r = xml.Elements();
            var result = r.Select(item => item.Attribute("jid")?.Value).ToArray();