问:
proxy authentication required in azure table using java
I need to access azure cloud table using java. My internet works behind proxy and needs authentication. I searched on internet and found this -

```<code>System.setProperty("http.proxyHost", "172.16.2.1");
System.setProperty("http.proxyPort", "3128");
System.setProperty("http.proxyUser", "username");
System.setProperty("http.proxyPassword", "password");
</code>```

but it gives the following error,

The Azure storage client library sample TableBasics starting...
Got an exception from running samples. Exception details:
com.microsoft.windowsazure.services.core.storage.StorageException: The server encountered an unknown failure: Proxy Authentication Required
    at com.microsoft.windowsazure.services.core.storage.StorageException.translateException(StorageException.java:129)
    at com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation.materializeException(StorageOperation.java:158)
    at com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine.executeWithRetry(ExecutionEngine.java:142)
    at com.microsoft.windowsazure.services.table.client.QueryTableOperation.performRetrieve(QueryTableOperation.java:218)
    at com.microsoft.windowsazure.services.table.client.TableOperation.execute(TableOperation.java:562)
    at com.microsoft.windowsazure.services.table.client.CloudTableClient.execute(CloudTableClient.java:262)
    at com.microsoft.windowsazure.services.table.client.CloudTable.exists(CloudTable.java:416)
    at com.microsoft.windowsazure.services.table.client.CloudTable.createIfNotExist(CloudTable.java:223)
    at com.microsoft.windowsazure.services.table.client.CloudTable.createIfNotExist(CloudTable.java:186)
    at test1.TableBasics.main(TableBasics.java:63)

The Azure storage client library sample TableBasics completed.

答:
Use "https" instead of "http" to proxy user and proxy password of system property

```<code>System.setProperty("http.proxyHost", "172.16.2.1");
System.setProperty("http.proxyPort", "3128");
System.setProperty("http.proxyUser", "username");
System.setProperty("http.proxyPassword", "password");
</code>```

instead of

```<code>System.setProperty("http.proxyHost", "172.16.2.1");
System.setProperty("http.proxyPort", "3128");
System.setProperty("https.proxyUser", "username"); // if domain name applicable then System.setProperty("https.proxyUser", "domain\\username");
System.setProperty("https.proxyPassword", "password");
</code>```

Body:
I need to access azure cloud table using java. My internet works behind proxy and needs authentication. I searched on internet and found this -

System.setProperty("http.proxyHost", "172.16.2.1");
System.setProperty("http.proxyPort", "3128");
System.setProperty("http.proxyUser", "username");
System.setProperty("http.proxyPassword", "password");

but it gives the following error,

The Azure storage client library sample TableBasics starting...
Got an exception from running samples. Exception details:
com.microsoft.windowsazure.services.core.storage.StorageException: The server encountered an unknown failure: Proxy Authentication Required
    at com.microsoft.windowsazure.services.core.storage.StorageException.translateException(StorageException.java:129)
    at com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation.materializeException(StorageOperation.java:158)
    at com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine.executeWithRetry(ExecutionEngine.java:142)
    at com.microsoft.windowsazure.services.table.client.QueryTableOperation.performRetrieve(QueryTableOperation.java:218)
    at com.microsoft.windowsazure.services.table.client.TableOperation.execute(TableOperation.java:562)
    at com.microsoft.windowsazure.services.table.client.CloudTableClient.execute(CloudTableClient.java:262)
    at com.microsoft.windowsazure.services.table.client.CloudTable.exists(CloudTable.java:416)
    at com.microsoft.windowsazure.services.table.client.CloudTable.createIfNotExist(CloudTable.java:223)
    at com.microsoft.windowsazure.services.table.client.CloudTable.createIfNotExist(CloudTable.java:186)
    at test1.TableBasics.main(TableBasics.java:63)

The Azure storage client library sample TableBasics completed.

Body:
Use "https" instead of "http" to proxy user and proxy password of system property

System.setProperty("http.proxyHost", "172.16.2.1");
System.setProperty("http.proxyPort", "3128");
System.setProperty("http.proxyUser", "username");
System.setProperty("http.proxyPassword", "password");

instead of

System.setProperty("http.proxyHost", "172.16.2.1");
System.setProperty("http.proxyPort", "3128");
System.setProperty("https.proxyUser", "username"); // if domain name applicable then System.setProperty("https.proxyUser", "domain\\username");
System.setProperty("https.proxyPassword", "password");


来源: stackexchange

问:
Click on image as Button?
```<code><button class="close" type="button" data-dismiss="modal" aria-label="Close">
<img src="/images/ic_highlight_removegray.svg" alt="">
</button>
</code>```

I have tried click this pop up (X)image, which is link. I have done this with all possible selectors including Xpath, class & cssSelectors but no result. Please suggest is this a special case of image/button.

```<code>driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(35000);
driver.findElement(By.xpath(".//*[@id='share_preview_modal']/div/div[1]/button")).click();
</code>```

I also tried same with wait, relative & absolute xpath, .sendKeys(Keys.ENTER);  - failure

```<code>    <div id="share_preview_modal" class="modal fade pro_info_member in dashboard-modal" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="user_profile" style="display: block;">
<div class="modal-dialog " role="document">
<div class="modal-header">
<div class="preview-header">
<span class="success-msg white_box_info" style="display:none">Restricted email access to domains </span>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<img src="http://some-url/images/ic_highlight_removegray.svg" alt="">
</button>
</div>
<div class="modal-content white-popup " style="background-image: url("");">
<!-- white popoup -->
</div>
</div>
</code>```

答:
You can try this xpath to click on Close button:

xpath 1:

```<code>driver.findElement(By.xpath("//div[id='share_preview_modal']//button[@class='close']")).click();
</code>```

xpath 2:

```<code>driver.findElement(By.xpath("//div[@id='share_preview_modal']//button[@class='close']")).click();
</code>```

xpath 3:

```<code>driver.findElement(By.xpath("//div[*id='share_preview_modal']//button[@class='close']")).click();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Click on image as Button?

Body:
<button class="close" type="button" data-dismiss="modal" aria-label="Close">

</button>

I have tried click this pop up (X)image, which is link. I have done this with all possible selectors including Xpath, class & cssSelectors but no result. Please suggest is this a special case of image/button.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(35000);
driver.findElement(By.xpath(".//*[@id='share_preview_modal']/div/div[1]/button")).click();

I also tried same with wait, relative & absolute xpath, .sendKeys(Keys.ENTER);  - failure

Restricted email access to domains
<button class="close" type="button" data-dismiss="modal" aria-label="Close">

</button>

Body:
You can try this xpath to click on Close button:

xpath 1:

driver.findElement(By.xpath("//div[id='share_preview_modal']//button[@class='close']")).click();

xpath 2:

driver.findElement(By.xpath("//div[@id='share_preview_modal']//button[@class='close']")).click();

xpath 3:

driver.findElement(By.xpath("//div[*id='share_preview_modal']//button[@class='close']")).click();

ContentLicense: CC BY-SA 4.0


问:
Grouped Product won't be added to cart and there is a message "Please specify the quantity of product(s)."
I am developing a store and the product I tried to add is a grouped product which I had done some design and configuration on the front end. Then, I added sample grouped product and when I click "Add to cart" , there is message "Please specify the quantity of product(s)."

Please see the website (Sorry the website is in Thai but you can try to increase the Quantity of each product and then click add to cart - Pink button)

http://www.preciosathailand.com/eyeline-0001.html

This is PHP code that I made the configuration

```<code><?php if ($_hasAssociatedProducts): ?>
<?php foreach ($_associatedProducts as $_item): ?>
    <?php $_finalPriceInclTax = $this->helper('tax')->getPrice($_item, $_item->getFinalPrice(), true) ?>
    <tr>
        <td width="80%"><span class="product-<?php echo $_item->getId() ?>"><?php echo $this->escapeHtml($_item->getName()) ?></span></td>
        <?php if ($this->getCanShowProductPrice($_product)): ?>
        <td class="a-right">
            <?php if ($this->getCanShowProductPrice($_item)): ?>
            <?php echo $this->getPriceHtml($_item, true) ?>
            <?php echo $this->getTierPriceHtml($_item) ?>
            <?php endif; ?>
        </td>
        <?php endif; ?>
        <?php if ($_product->isSaleable()): ?>
        <td class="a-center" width="20%">
        <?php if ($_item->isSaleable()) : ?>
            <div class="qty-tools">
                <div class="minus-qty minus-<?php echo $_item->getId() ?>"><a class="click-to-minus" id="minus-<?php echo $_item->getId() ?>" href="#" data-id-p="<?php echo $_item->getId() ?>">-</a></div>
                <div class="input-qty-wrapper">
                <input type="text" name="super_group[<?php echo $_item->getId() ?>]" data-qty-product-id="<?php echo $_item->getId() ?>" maxlength="12" value="<?php echo $_item->getQty()*1 ?>" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Qty')) ?>" class="input-text qty" />
                </div>
                <div class="plus-qty plus-<?php echo $_item->getId() ?>"><a class="click-to-plus" href="#" id="plus-<?php echo $_item->getId() ?>" data-id-p="<?php echo $_item->getId() ?>">+</a></div>
            </div>
        <?php else: ?>
            <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
        <?php endif; ?>
        </td>
        <?php endif; ?>
    </tr>
<?php endforeach; ?>
<?php else: ?>
   <tr>
       <td colspan="<?php if ($_product->isSaleable()): ?>4<?php else : ?>3<?php endif; ?>"><?php echo $this->__('No options of this product are available.') ?></td>
   </tr>
<?php endif; ?>
</code>```

This is jQuery that I have done.

```<code> jQuery(document).ready(function(){

    jQuery('.click-to-minus').click(function(){

        var IDInput = jQuery(this).data('id-p');
        var CurrentVal = jQuery('input[name="super_group['+IDInput+']"]').val();
        var minusedVal = CurrentVal-1;

        jQuery('input#'+IDInput).val(minusedVal);

    });

    jQuery('.click-to-plus').click(function(){

        var pIDInput = jQuery(this).data('id-p');
        var CurrentPlusVal = jQuery('input[name="super_group['+pIDInput+']"]').val();
       /* if ( CountPlus == 0){

            var plusedVal = 1;

        }else{
            jQuery('input#'+pIDInput).val('');
            var plusedVal = CurrentPlusVal+1;
        }*/

        var plusedVal = +CurrentPlusVal+1;
        jQuery('input[data-qty-product-id="'+pIDInput+'"]').val(plusedVal);

    });

});
</code>```

Did I do anything wrong?

答:
Are you trying to group configurable products, then you should know that magento doesnt allow it.

you can check this answer  here

Body:
I am developing a store and the product I tried to add is a grouped product which I had done some design and configuration on the front end. Then, I added sample grouped product and when I click "Add to cart" , there is message "Please specify the quantity of product(s)."

Please see the website (Sorry the website is in Thai but you can try to increase the Quantity of each product and then click add to cart - Pink button)

http://www.preciosathailand.com/eyeline-0001.html

This is PHP code that I made the configuration

<?php if ($_hasAssociatedProducts): ?>
<?php foreach ($_associatedProducts as $_item): ?>
    <?php $_finalPriceInclTax = $this->helper('tax')->getPrice($_item, $_item->getFinalPrice(), true) ?>

        <span class="product-<?php echo $_item->getId() ?>"><?php echo $this->escapeHtml($_item->getName()) ?>
        <?php if ($this->getCanShowProductPrice($_product)): ?>

            <?php if ($this->getCanShowProductPrice($_item)): ?>
            <?php echo $this->getPriceHtml($_item, true) ?>
            <?php echo $this->getTierPriceHtml($_item) ?>
            <?php endif; ?>

        <?php endif; ?>
        <?php if ($_product->isSaleable()): ?>

        <?php if ($_item->isSaleable()) : ?>

                <div class="minus-qty minus-<?php echo $_item->getId() ?>"><a class="click-to-minus" id="minus-<?php echo $_item->getId() ?>" href="#" data-id-p="<?php echo $_item->getId() ?>">-

                <input type="text" name="super_group[<?php echo $_item->getId() ?>]" data-qty-product-id="<?php echo $_item->getId() ?>" maxlength="12" value="<?php echo $_item->getQty()*1 ?>" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Qty')) ?>" class="input-text qty" />

                <div class="plus-qty plus-<?php echo $_item->getId() ?>"><a class="click-to-plus" href="#" id="plus-<?php echo $_item->getId() ?>" data-id-p="<?php echo $_item->getId() ?>">+

        <?php else: ?>

<?php echo $this->__('Out of stock') ?>

        <?php endif; ?>

        <?php endif; ?>

<?php endforeach; ?>
<?php else: ?>

       <td colspan="<?php if ($_product->isSaleable()): ?>4<?php else : ?>3<?php endif; ?>"><?php echo $this->__('No options of this product are available.') ?>

<?php endif; ?>

This is jQuery that I have done.

 jQuery(document).ready(function(){

    jQuery('.click-to-minus').click(function(){

        var IDInput = jQuery(this).data('id-p');
        var CurrentVal = jQuery('input[name="super_group['+IDInput+']"]').val();
        var minusedVal = CurrentVal-1;

        jQuery('input#'+IDInput).val(minusedVal);

    });

    jQuery('.click-to-plus').click(function(){

        var pIDInput = jQuery(this).data('id-p');
        var CurrentPlusVal = jQuery('input[name="super_group['+pIDInput+']"]').val();
       /* if ( CountPlus == 0){

            var plusedVal = 1;

        }else{
            jQuery('input#'+pIDInput).val('');
            var plusedVal = CurrentPlusVal+1;
        }*/

        var plusedVal = +CurrentPlusVal+1;
        jQuery('input[data-qty-product-id="'+pIDInput+'"]').val(plusedVal);

    });

});

Did I do anything wrong?


问:
Excluding specific iPhone types from App Store submission
I created a SpriteKit game that needs large screen area to be played so I decided not to write the code for the iPhone SE, but now I'm not sure if I can submit it to the App Store for all devices except the SE. Please let me know whether it's possible, and if so how to do it (i.e. where on iTunes Connect would you do it).

I looked up a lot but I couldn't find anything that could help.
I also couldn't find anything in the API.

答: As far as I know, you cannot exclude certain devices. You can exclude iPad/iPhone, or require a minimum iOS version.</p>


问:
How to access form control from within ToString method of nested struct
I am building a small windows form application in C#.  Within the form code I define a public struct with a ToString method that must build part of its output from items in comboBoxes on the same form.  This doesn't sound like it should be difficult

```<code>public partial class Form1 : Form
{
 public struct OrderLineItem
    {
     string someString;
     int index;
     string ToString()
        {return someString + ActiveForm.sizeComboBox.Items[index].ToString();}
    }
}
</code>```

It complains that it cannot find a definition for sizeComboBox.  If I explicitly use the name of the form, it says an object reference is required for the static field...
I'm not quite sure what it means by that.  Using this.sizeComboBox refers to the struct, not the form.  Using just sizeComboBox, again, an object reference is required.

答:
The struct knows about its containing class type, but it doesn't know about any particular instance of that type, unless you tell it. For example, you can create a constructor that takes a Form1 object, and it can save a reference to that form in a member variable.

```<code>public partial class Form1 : Form
{
 public struct OrderLineItem
    {
     string someString;
     int index;
     Form1 parentForm;

     internal OrderLineItem(Form1 parentForm)
     {
         this = new OrderLineItem();
         this.parentForm = parentForm;
     }

     string ToString()
     {
         if (parentForm == null)
             return string.Empty;
         else
             return someString + parentForm.sizeComboBox.Items[index].ToString();
     }
    }
}
</code>```

That said, this is a seriously questionable design.

The tiered structure of this application appears to be upside-down. The order-line-item objects should exist at a lower level than the user interface layer. The UI can sometimes see the business objects (order, order-line-item, etc.), but the business objects should not know anything about the UI.

If you can invert this structure, it will make the code much cleaner.

ContentLicense: CC BY-SA 2.5

Body:
I am building a small windows form application in C#.  Within the form code I define a public struct with a ToString method that must build part of its output from items in comboBoxes on the same form.  This doesn't sound like it should be difficult

public partial class Form1 : Form
{
 public struct OrderLineItem
    {
     string someString;
     int index;
     string ToString()
        {return someString + ActiveForm.sizeComboBox.Items[index].ToString();}
    }
}

It complains that it cannot find a definition for sizeComboBox.  If I explicitly use the name of the form, it says an object reference is required for the static field...
I'm not quite sure what it means by that.  Using this.sizeComboBox refers to the struct, not the form.  Using just sizeComboBox, again, an object reference is required.

Body:
The struct knows about its containing class type, but it doesn't know about any particular instance of that type, unless you tell it. For example, you can create a constructor that takes a Form1 object, and it can save a reference to that form in a member variable.

public partial class Form1 : Form
{
 public struct OrderLineItem
    {
     string someString;
     int index;
     Form1 parentForm;

     internal OrderLineItem(Form1 parentForm)
     {
         this = new OrderLineItem();
         this.parentForm = parentForm;
     }

     string ToString()
     {
         if (parentForm == null)
             return string.Empty;
         else
             return someString + parentForm.sizeComboBox.Items[index].ToString();
     }
    }
}

That said, this is a seriously questionable design.

The tiered structure of this application appears to be upside-down. The order-line-item objects should exist at a lower level than the user interface layer. The UI can sometimes see the business objects (order, order-line-item, etc.), but the business objects should not know anything about the UI.

If you can invert this structure, it will make the code much cleaner.


问:
Can scrapy be used to scrape dynamic content from websites that are using AJAX?
I have recently been learning Python and am dipping my hand into building a web-scraper.  It's nothing fancy at all; its only purpose is to get the data off of a betting website and have this data put into Excel.

Most of the issues are solvable and I'm having a good little mess around. However I'm hitting a massive hurdle over one issue. If a site loads a table of horses and lists current betting prices this information is not in any source file. The clue is that this data is live sometimes, with the numbers being updated obviously from some remote server. The HTML on my PC simply has a hole where their servers are pushing through all the interesting data that I need.

Now my experience with dynamic web content is low, so this thing is something I'm having trouble getting my head around.

I think Java or Javascript is a key, this pops up often.

The scraper is simply a odds comparison engine.  Some sites have APIs but I need this for those that don't. I'm using the scrapy library with Python 2.7

I do apologize if this question is too open-ended. In short, my question is: how can scrapy be used to scrape this dynamic data so that I can use it?  So that I can scrape this betting odds data in real-time?

See also: How can I scrape a page with dynamic content (created by JavaScript) in Python? for the general case.

答:
how can scrapy be used to scrape this dynamic data so that I can use
  it?

I wonder why no one has posted the solution using Scrapy only.

Check out the blog post from Scrapy team SCRAPING INFINITE SCROLLING PAGES
. The example scraps http://spidyquotes.herokuapp.com/scroll website which uses infinite scrolling.

The idea is to use Developer Tools of your browser and notice the AJAX requests, then based on that information create the requests for Scrapy.

```<code>import json
import scrapy

class SpidyQuotesSpider(scrapy.Spider):
    name = 'spidyquotes'
    quotes_base_url = 'http://spidyquotes.herokuapp.com/api/quotes?page=%s'
    start_urls = [quotes_base_url % 1]
    download_delay = 1.5

    def parse(self, response):
        data = json.loads(response.body)
        for item in data.get('quotes', []):
            yield {
                'text': item.get('text'),
                'author': item.get('author', {}).get('name'),
                'tags': item.get('tags'),
            }
        if data['has_next']:
            next_page = data['page'] + 1
            yield scrapy.Request(self.quotes_base_url % next_page)
</code>```

Body:
how can scrapy be used to scrape this dynamic data so that I can use
  it?

I wonder why no one has posted the solution using Scrapy only.

Check out the blog post from Scrapy team SCRAPING INFINITE SCROLLING PAGES
. The example scraps http://spidyquotes.herokuapp.com/scroll website which uses infinite scrolling.

The idea is to use Developer Tools of your browser and notice the AJAX requests, then based on that information create the requests for Scrapy.

import json
import scrapy

class SpidyQuotesSpider(scrapy.Spider):
    name = 'spidyquotes'
    quotes_base_url = 'http://spidyquotes.herokuapp.com/api/quotes?page=%s'
    start_urls = [quotes_base_url % 1]
    download_delay = 1.5

    def parse(self, response):
        data = json.loads(response.body)
        for item in data.get('quotes', []):
            yield {
                'text': item.get('text'),
                'author': item.get('author', {}).get('name'),
                'tags': item.get('tags'),
            }
        if data['has_next']:
            next_page = data['page'] + 1
            yield scrapy.Request(self.quotes_base_url % next_page)


问:
Android 2.3 Custom ArrayAdapter getView Method Not Being Called
EDIT: Solved...mostly. Calls to Lod.g(...) inside getView() are still not showing up in LogCat but everything seems to be working. Code below has been updated to working version.

My ArrayAdapter class:

```<code>public class PostAdapter extends ArrayAdapter<Post> {

//fields
private LayoutInflater inflater;
private ArrayList<Post> posts;

//constructor
public PostAdapter(Context context, ArrayList<Post> posts) {
    super(context, R.layout.post_layout, R.id.title, posts);
    this.inflater = LayoutInflater.from(context);
    this.posts = posts;
}

//methods
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //get data item for this position
    Post post = (Post)getItem(position);
    //check if existing view is being reused, otherwise inflate the view
    if(convertView == null) {
        convertView = inflater.inflate(R.layout.post_layout, parent, false);
    }
    //Populate views with data
    TextView title = (TextView) convertView.findViewById(R.id.title);
    title.setText(post.getTitle());
    TextView subTitle = (TextView) convertView.findViewById(R.id.subTitle);
    subTitle.setText(post.getDescription());

    //return completed view to render on screen
    return convertView;
}

@Override
public int getCount() {
    return posts.size();
}
</code>```

}

And the code where I create the ArrayAdapter:

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

    //Initializing feed variables
    posts = new ArrayList<>();
    postAdapter = new PostAdapter(this, posts);
    list = (ListView) findViewById(R.id.list);

    //attaching Adapter to ListView
    list.setAdapter(postAdapter);

    DatabaseReference p = database.getReference("posts");
    p.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            //get reference to post
            HashMap<Object, Object> entry = (HashMap<Object, Object>) dataSnapshot.getValue();

            //convert to Post.class datatype
            Post post = new Post();
            if (entry.get("category") != null) { post.setCategory(entry.get("category").toString()); }
            if (entry.get("title") != null) { post.setTitle(entry.get("title").toString()); }
            if (entry.get("description") != null) { post.setDescription(entry.get("description").toString()); }
            if (entry.get("hasImg") != null) { post.setImg((boolean)entry.get("hasImg")); }
            if (entry.get("postKey") != null) { post.setPostKey(entry.get("postKey").toString()); }
            if (entry.get("posterID") != null) { post.setPosterID(entry.get("posterID").toString()); }
            if (entry.get("schoolID") != null) { post.setSchoolID(entry.get("schoolID").toString()); }
            if (entry.get("flagged") != null) { post.setFlagged((long)entry.get("flagged")); }
            if (entry.get("time") != null) { post.setTime((long)entry.get("time")); };

            //add to ArrayList
            posts.add(post);
            postAdapter.notifyDataSetChanged();

            Log.d("LIST", "Post Added: Posts: " + postAdapter.getCount());
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

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

答:
```<code>#List adapter is getting initialized with zero posts elements.
#list.setAdapter(postAdapter) : put into childAdded listener.

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

    //retrieve post data from firebase
    posts = new ArrayList<>();

    //ListView and PostAdapter
    list = (ListView) findViewById(R.id.list);
    postAdapter = new PostAdapter(this, posts);

    DatabaseReference p = database.getReference("posts");
    p.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            //get reference to post
            HashMap<Object, Object> entry = (HashMap<Object, Object>) dataSnapshot.getValue();

            //convert to Post.class datatype
            Post post = new Post();
            if (entry.get("category") != null) { post.setCategory(entry.get("category").toString()); }
            if (entry.get("title") != null) { post.setTitle(entry.get("title").toString()); }
            if (entry.get("description") != null) { post.setDescription(entry.get("description").toString()); }
            if (entry.get("hasImg") != null) { post.setImg((boolean)entry.get("hasImg")); }
            if (entry.get("postKey") != null) { post.setPostKey(entry.get("postKey").toString()); }
            if (entry.get("posterID") != null) { post.setPosterID(entry.get("posterID").toString()); }
            if (entry.get("schoolID") != null) { post.setSchoolID(entry.get("schoolID").toString()); }
            if (entry.get("flagged") != null) { post.setFlagged((long)entry.get("flagged")); }
            if (entry.get("time") != null) { post.setTime((long)entry.get("time")); };

            //add to ArrayList
            posts.add(post);
            postAdapter.add(post);

             //attaching Adapter to ListView
            list.setAdapter(postAdapter);
            Log.d("LIST", "Item count: " + postAdapter.getCount());

            postAdapter.notifyDataSetChanged();
            Log.d("LIST", "Post Added: Posts: " + postAdapter.getCount());

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    }
}
</code>```

Body:
EDIT: Solved...mostly. Calls to Lod.g(...) inside getView() are still not showing up in LogCat but everything seems to be working. Code below has been updated to working version.

My ArrayAdapter class:

public class PostAdapter extends ArrayAdapter<Post> {

//fields
private LayoutInflater inflater;
private ArrayList<Post> posts;

//constructor
public PostAdapter(Context context, ArrayList<Post> posts) {
    super(context, R.layout.post_layout, R.id.title, posts);
    this.inflater = LayoutInflater.from(context);
    this.posts = posts;
}

//methods
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //get data item for this position
    Post post = (Post)getItem(position);
    //check if existing view is being reused, otherwise inflate the view
    if(convertView == null) {
        convertView = inflater.inflate(R.layout.post_layout, parent, false);
    }
    //Populate views with data
    TextView title = (TextView) convertView.findViewById(R.id.title);
    title.setText(post.getTitle());
    TextView subTitle = (TextView) convertView.findViewById(R.id.subTitle);
    subTitle.setText(post.getDescription());

    //return completed view to render on screen
    return convertView;
}

@Override
public int getCount() {
    return posts.size();
}

}

And the code where I create the ArrayAdapter:

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

    //Initializing feed variables
    posts = new ArrayList<>();
    postAdapter = new PostAdapter(this, posts);
    list = (ListView) findViewById(R.id.list);

    //attaching Adapter to ListView
    list.setAdapter(postAdapter);

    DatabaseReference p = database.getReference("posts");
    p.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            //get reference to post
            HashMap<Object, Object> entry = (HashMap<Object, Object>) dataSnapshot.getValue();

            //convert to Post.class datatype
            Post post = new Post();
            if (entry.get("category") != null) { post.setCategory(entry.get("category").toString()); }
            if (entry.get("title") != null) { post.setTitle(entry.get("title").toString()); }
            if (entry.get("description") != null) { post.setDescription(entry.get("description").toString()); }
            if (entry.get("hasImg") != null) { post.setImg((boolean)entry.get("hasImg")); }
            if (entry.get("postKey") != null) { post.setPostKey(entry.get("postKey").toString()); }
            if (entry.get("posterID") != null) { post.setPosterID(entry.get("posterID").toString()); }
            if (entry.get("schoolID") != null) { post.setSchoolID(entry.get("schoolID").toString()); }
            if (entry.get("flagged") != null) { post.setFlagged((long)entry.get("flagged")); }
            if (entry.get("time") != null) { post.setTime((long)entry.get("time")); };

            //add to ArrayList
            posts.add(post);
            postAdapter.notifyDataSetChanged();

            Log.d("LIST", "Post Added: Posts: " + postAdapter.getCount());
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}


问:
Linq select from database table where matching property from List
I have a List with records of following class which is something like this

```<code>  public class TestRecord
  {
     public int RecordsId{get;set;}
public string Name{get;set;}
-- and more such properties.

  }
</code>```

Now I have database table which I access from linq which contains RecordId column , values which will match RecordId value from above List.

```<code>  var result=from p in _context.Details
</code>```

however I am thinking I could do where/ contains on this linq query and provide it with a clause to match RecordId from a list

```<code> List<TestRecord> records -- this has let's say 100 records.
</code>```

Doing simply this does not work as linq can't join with generic List

```<code>    var finalresult = from p in context.details
                      join a in records on p.recordId equals a.recordId
</code>```

Any solutions for this using Linq?

答:
You can use Contains() like

```<code>var finalresult = context.details.Where(d => records.Contains(d.recordId));
</code>```

Body:
I have a List with records of following class which is something like this

  public class TestRecord
  {
     public int RecordsId{get;set;}
public string Name{get;set;}
-- and more such properties.

  }

Now I have database table which I access from linq which contains RecordId column , values which will match RecordId value from above List.

  var result=from p in _context.Details

however I am thinking I could do where/ contains on this linq query and provide it with a clause to match RecordId from a list

 List<TestRecord> records -- this has let's say 100 records.

Doing simply this does not work as linq can't join with generic List

    var finalresult = from p in context.details
                      join a in records on p.recordId equals a.recordId

Any solutions for this using Linq?

Body:
You can use Contains() like

var finalresult = context.details.Where(d => records.Contains(d.recordId));


问:
WooCommerce codex : how to set the user/customer on an order
I am writing a WooCommerce Plugin that takes care of payment and delivery.

Right now I am at the point of creating an order based on the current shopping cart.

That all works fine getting the items and costs correct, the only problem is that the order shows as being made by "Guest", instead of by the currently logged on user (even though the correct email address for that user is on the order).

Here is my code :

```<code>    $cart = WC()->cart;
    $checkout = WC()->checkout();
    $order_id = $checkout->create_order();
    $order = wc_get_order( $order_id );
    $order->user_id = apply_filters( 'woocommerce_checkout_customer_id', get_current_user_id() );
    $order->calculate_totals();
    $order->payment_complete();
    $cart->empty_cart();
</code>```

Here is what I see in the backend after running this :

Why is the order placed as "Guest" instead of the user that placed the order?

And how do I get to have the correct user attached?

答:
You will need to add _customer_user to post_meta table with order ID and meta value should be the user ID which you want to link to this order.

I hope that this will help you:

```<code>update_post_meta($order_id, '_customer_user', get_current_user_id());
</code>```

Body:
I am writing a WooCommerce Plugin that takes care of payment and delivery.

Right now I am at the point of creating an order based on the current shopping cart.

That all works fine getting the items and costs correct, the only problem is that the order shows as being made by "Guest", instead of by the currently logged on user (even though the correct email address for that user is on the order).

Here is my code :

    $cart = WC()->cart;
    $checkout = WC()->checkout();
    $order_id = $checkout->create_order();
    $order = wc_get_order( $order_id );
    $order->user_id = apply_filters( 'woocommerce_checkout_customer_id', get_current_user_id() );
    $order->calculate_totals();
    $order->payment_complete();
    $cart->empty_cart();

Here is what I see in the backend after running this :

Why is the order placed as "Guest" instead of the user that placed the order?

And how do I get to have the correct user attached?

Body:
You will need to add _customer_user to post_meta table with order ID and meta value should be the user ID which you want to link to this order.

I hope that this will help you:

update_post_meta($order_id, '_customer_user', get_current_user_id());


问:
Issue reading in a char array using sscanf in octal using either C or C++
When trying to read in the octal value for "24" to an unsigned int, I get 0. Simply passing in the decimal value as a char array works.

I need the final value as a 32 bit unsigned int. The initial value is read in from a binary file.

MCVE

simple.cpp

```<code>#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    char count[4] = "\030\000\000"; // Just "24" works
    __uint32_t value;
    sscanf(count, "%x", &value);
    fprintf(stderr, "%x", value);
    return 0;
}
</code>```

Compiled and executed using

```<code>$ g++ simple.cpp -g
$ ./a.out
0
$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
</code>```

答:
I assumed that you get 4 bytes in a record coming from a binary file, and you want to convert those 4 bytes to an uint32_t value. I also assume that the bytes come with the expected endianness.

The simplest (and most standard conformant way) to do the conversion is to copy the byte representation to a variable:

```<code>#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    char count[4] = "\030\000\000"; // Just "24" works
    __uint32_t value;
    memcpy(&value, count, sizeof(value));
    fprintf(stderr, "%d", value);
    return 0;
}
</code>```

will return as expected 24.

Body:
When trying to read in the octal value for "24" to an unsigned int, I get 0. Simply passing in the decimal value as a char array works.

I need the final value as a 32 bit unsigned int. The initial value is read in from a binary file.

MCVE

simple.cpp

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    char count[4] = "\030\000\000"; // Just "24" works
    __uint32_t value;
    sscanf(count, "%x", &value);
    fprintf(stderr, "%x", value);
    return 0;
}

Compiled and executed using

$ g++ simple.cpp -g
$ ./a.out
0
$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

Body:
I assumed that you get 4 bytes in a record coming from a binary file, and you want to convert those 4 bytes to an uint32_t value. I also assume that the bytes come with the expected endianness.

The simplest (and most standard conformant way) to do the conversion is to copy the byte representation to a variable:

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    char count[4] = "\030\000\000"; // Just "24" works
    __uint32_t value;
    memcpy(&value, count, sizeof(value));
    fprintf(stderr, "%d", value);
    return 0;
}

will return as expected 24.


问:
Change cssclass of button inside datalist using jquery in asp.net
I have a button inside datalist, if I click one button have to change the css of other button in jquery.

I have more images in my page. my code accept only one "like".
I want to differentiate which one I selected.

jquery

```<code>function Addlike(btnlike, hdnId, term, cId) {
    $.ajax({
        type: "POST",
        url: "CommonFunction.aspx/SaveToLike",
        data: '{user: ' + JSON.stringify(user) + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {

            $(btnlike).attr("class", "btn btn-success");
            //  alert("Data added successfully.");

        },
        error: function (response) {
            alert("Unexpected error occurred.");
        }
    });
    return false;
}
</code>```

aspx code

```<code><asp:DataList ID="dtlist" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" OnItemDataBound="dtlist_OnItemDataBound">
    <ItemTemplate>
        <asp:LinkButton ID="btnlike" runat="server" CommandArgument='<%# Eval("Id") %>'><i class="fa fa-users"></i></asp:LinkButton>
    </ItemTemplate>
</asp:DataList>
</code>```

I just want to change other buttons cssclass. how to find the control?

答:
You can loop all the LinkButtons in the DataList with jQuery.</p>

```<code>$('#<%=dtlist.ClientID%> a').each(function (i, obj) {
    $(this).addClass("btn btn-success");
});
</code>```

Body:
I have a button inside datalist, if I click one button have to change the css of other button in jquery.

I have more images in my page. my code accept only one "like".
I want to differentiate which one I selected.

jquery

function Addlike(btnlike, hdnId, term, cId) {
    $.ajax({
        type: "POST",
        url: "CommonFunction.aspx/SaveToLike",
        data: '{user: ' + JSON.stringify(user) + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {

            $(btnlike).attr("class", "btn btn-success");
            //  alert("Data added successfully.");

        },
        error: function (response) {
            alert("Unexpected error occurred.");
        }
    });
    return false;
}

aspx code

<asp:DataList ID="dtlist" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" OnItemDataBound="dtlist_OnItemDataBound">
    <ItemTemplate>
        <asp:LinkButton ID="btnlike" runat="server" CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
    </ItemTemplate>
</asp:DataList>

I just want to change other buttons cssclass. how to find the control?

Body:
You can loop all the LinkButtons in the DataList with jQuery.

$('#<%=dtlist.ClientID%> a').each(function (i, obj) {
    $(this).addClass("btn btn-success");
});


问:
How can I pipe the output of an Akka Streams Merge to another Flow?
I'm playing with Akka Streams, and have figured out most of the basics, but I'm not clear on how to take the results of a Merge and do further operations (map, filter, fold, etc) on it.

I'd like to modify the following code so that, instead of piping the merge to a sink, that I could instead manipulate the data further.

```<code>implicit val materializer = FlowMaterializer()

val items_a = Source(List(10,20,30,40,50))
val items_b = Source(List(60,70,80,90,100))
val sink = ForeachSink(println)

val materialized = FlowGraph { implicit builder =>
  import FlowGraphImplicits._
  val merge = Merge[Int]("m1")
  items_a ~> merge
  items_b ~> merge ~> sink
}.run()
</code>```

I guess my primary problem is that I can't figure out how to make a flow component that doesn't have a source, and I can't figure out how to do a merge without using the special Merge object and the ~> syntax.

EDIT: This question and answer was for and worked with Akka Streams 0.11

答:
Or, if you need to preserve the order of the input-sources (e.g. items_a must before items_b and items_b must before items_c) you can use Concat, instead of Merge.</p>

```<code>val items_a :: items_b :: items_c = List(
     Source(List(10,20,30,40,50)),
     Source(List(60,70,80,90,100),
     Source(List(110,120,130,140,1500))
Source.combine(items_a, items_b, items_c : _*)(Concat(_))
</code>```

Body:
I'm playing with Akka Streams, and have figured out most of the basics, but I'm not clear on how to take the results of a Merge and do further operations (map, filter, fold, etc) on it.

I'd like to modify the following code so that, instead of piping the merge to a sink, that I could instead manipulate the data further.

implicit val materializer = FlowMaterializer()

val items_a = Source(List(10,20,30,40,50))
val items_b = Source(List(60,70,80,90,100))
val sink = ForeachSink(println)

val materialized = FlowGraph { implicit builder =>
  import FlowGraphImplicits._
  val merge = Merge[Int]("m1")
  items_a ~> merge
  items_b ~> merge ~> sink
}.run()

I guess my primary problem is that I can't figure out how to make a flow component that doesn't have a source, and I can't figure out how to do a merge without using the special Merge object and the ~> syntax.

EDIT: This question and answer was for and worked with Akka Streams 0.11

Body:
Or, if you need to preserve the order of the input-sources (e.g. items_a must before items_b and items_b must before items_c) you can use Concat, instead of Merge.

val items_a :: items_b :: items_c = List(
     Source(List(10,20,30,40,50)),
     Source(List(60,70,80,90,100),
     Source(List(110,120,130,140,1500))
Source.combine(items_a, items_b, items_c : _*)(Concat(_))


问:
When will I use camelCase in F# when exporting to other .NET languages?
Based on The F# Component Design Guidelines, F# should use PascalCase to conform .NET Framework naming conventions.

Suppose I'm using C# or VB.NET and want to import a F# library, when should I expect a camelCase convention to appear in this library?

答:
Take a look at the FsCheck library, and specifically its Gen module. (There are other examples in the FsCheck source code, but this one's easy to read). FsCheck is designed to be used from both F# and C#, and the design of the Gen module reflects that:

```<code>module Gen =
    // ...

    [<CompiledName("Map"); EditorBrowsable(EditorBrowsableState.Never)>]
    let map f (gen:Gen<_>) = gen.Map f

    [<CompiledName("Sized"); EditorBrowsable(EditorBrowsableState.Never)>]
    let sized fgen = Gen (fun n r -> let (Gen m) = fgen n in m n r)

    [<CompiledName("Sized"); CompilerMessage("This method is not intended for use from F#.", 10001, IsHidden=true, IsError=false)>]
    let sizedFunc (sizedGen : Func<int,Gen<_>>) =
        sized sizedGen.Invoke
</code>```

Ignore the implementation of these functions for a moment and look at their names, and the CompiledName attribute that each has been given. When you invoke the map function from F#, you'll invoke it as Gen.map, but when you use it from C#, the CompiledName attribute will cause you to see it with the name Gen.Map. Likewise with the sized function, which will be called Gen.sized when invoked from F# code, which will be seen with the name Gen.Sized when invoked from C#. Note also how there's a second function with the same CompiledName (when seen from C#), but the F# code has a distinction between Gen.sized and Gen.sizedFunc (and the F# compiler will also warn you if you try to use Gen.sizedFunc that "This method is not intended for use from F#"), because that overload expects the function type used by C# code, and is purely for the convenience of C# coders using the library. (F# functions use the FSharpFunc type, which behaves differently from the C# Func type in some situations).

However, your question wasn't so much "How should I write my F# library so that it can be used by C# coders?". Rather, your question was, "As a C# coder, what should I expect from F# libraries in terms of naming conventions?" And the answer to that question is: It depends on the library you're using.

As you've pointed out, the F# Component Design Guidelines recommend PascalCase names for functions designed to be used from calling code. And FsCheck is a good example of a library that did it right. But not all libraries were written with the intent that they be easily used from C#. Some libraries were written thinking only about other F# code using them, and those libraries will not necessarily conform to the design guidelines, because the F# convention is to use camelCase for function names.

So although this isn't a totally satisfactory answer, it's the best one I can give you, because I don't know which libraries you'll be using.

Body:
Take a look at the FsCheck library, and specifically its Gen module. (There are other examples in the FsCheck source code, but this one's easy to read). FsCheck is designed to be used from both F# and C#, and the design of the Gen module reflects that:

module Gen =
    // ...

    [<CompiledName("Map"); EditorBrowsable(EditorBrowsableState.Never)>]
    let map f (gen:Gen<_>) = gen.Map f

    [<CompiledName("Sized"); EditorBrowsable(EditorBrowsableState.Never)>]
    let sized fgen = Gen (fun n r -> let (Gen m) = fgen n in m n r)

    [<CompiledName("Sized"); CompilerMessage("This method is not intended for use from F#.", 10001, IsHidden=true, IsError=false)>]
    let sizedFunc (sizedGen : Func<int,Gen<_>>) =
        sized sizedGen.Invoke

Ignore the implementation of these functions for a moment and look at their names, and the CompiledName attribute that each has been given. When you invoke the map function from F#, you'll invoke it as Gen.map, but when you use it from C#, the CompiledName attribute will cause you to see it with the name Gen.Map. Likewise with the sized function, which will be called Gen.sized when invoked from F# code, which will be seen with the name Gen.Sized when invoked from C#. Note also how there's a second function with the same CompiledName (when seen from C#), but the F# code has a distinction between Gen.sized and Gen.sizedFunc (and the F# compiler will also warn you if you try to use Gen.sizedFunc that "This method is not intended for use from F#"), because that overload expects the function type used by C# code, and is purely for the convenience of C# coders using the library. (F# functions use the FSharpFunc type, which behaves differently from the C# Func type in some situations).

However, your question wasn't so much "How should I write my F# library so that it can be used by C# coders?". Rather, your question was, "As a C# coder, what should I expect from F# libraries in terms of naming conventions?" And the answer to that question is: It depends on the library you're using.

As you've pointed out, the F# Component Design Guidelines recommend PascalCase names for functions designed to be used from calling code. And FsCheck is a good example of a library that did it right. But not all libraries were written with the intent that they be easily used from C#. Some libraries were written thinking only about other F# code using them, and those libraries will not necessarily conform to the design guidelines, because the F# convention is to use camelCase for function names.

So although this isn't a totally satisfactory answer, it's the best one I can give you, because I don't know which libraries you'll be using.


问:
PostgreSQL search criteria must output missing row
I have two postgreSQL tables, namely: employees and employee_cars.
I need to output all employees that own a 'BMW', 'MERC' AND 'VW', BUT NOT an 'AUDI'.

I have tried below query:

```<code>SELECT DISTINCT a.employee_name, b.car_brand
FROM employees a
LEFT JOIN employee_cars b
ON a.employee_id = b.employee_id
WHERE b.car_brand IN ('BMW','MERC','VW')
AND b.car_brand NOT LIKE 'AUDI';
</code>```

OUTPUT below:

```<code>employee_name,car_brand
"Mary","BMW"
"Mary","MERC"
"Mary","VW"
"Paul","BMW"
"Paul","MERC"
"Paul","VW"
</code>```

Problem is that each vehicle that an employee owns is a row in the employee_cars tables. So for example; I have 'Mary' which owns: 'BMW','MERC','VW','AUDI'.
I have 'Paul' which only owns: 'BMW','MERC','VW'.
My query will display Both Mary and Paul, because they both own 'BMW','MERC','VW'.

I only want to see 'Paul' in my results, because he is missing the 'AUDI'.

Please note that I am not a DB expert, I will appreciate any help and assistance.
Thanks in advance.

答:
Combine this with a not exists condition:

```<code>SELECT distinct emp.employee_name, ec.car_brand
FROM employees emp
  JOIN employee_cars ec ON emp.employee_id = ec.employee_id
WHERE ec.car_brand IN ('BMW','MERC','VW')
  and not exists (select *
                  from employee_cars ec2
                  where ec2.car_brand = 'AUDI'
                    and ec2.employee_id = emp.employee_id);
</code>```

Note that you do not need an outer join between employees and employee_cars

Body:
I have two postgreSQL tables, namely: employees and employee_cars.
I need to output all employees that own a 'BMW', 'MERC' AND 'VW', BUT NOT an 'AUDI'.

I have tried below query:

SELECT DISTINCT a.employee_name, b.car_brand
FROM employees a
LEFT JOIN employee_cars b
ON a.employee_id = b.employee_id
WHERE b.car_brand IN ('BMW','MERC','VW')
AND b.car_brand NOT LIKE 'AUDI';

OUTPUT below:

employee_name,car_brand
"Mary","BMW"
"Mary","MERC"
"Mary","VW"
"Paul","BMW"
"Paul","MERC"
"Paul","VW"

Problem is that each vehicle that an employee owns is a row in the employee_cars tables. So for example; I have 'Mary' which owns: 'BMW','MERC','VW','AUDI'.
I have 'Paul' which only owns: 'BMW','MERC','VW'.
My query will display Both Mary and Paul, because they both own 'BMW','MERC','VW'.

I only want to see 'Paul' in my results, because he is missing the 'AUDI'.

Please note that I am not a DB expert, I will appreciate any help and assistance.
Thanks in advance.

Body:
Combine this with a not exists condition:

SELECT distinct emp.employee_name, ec.car_brand
FROM employees emp
  JOIN employee_cars ec ON emp.employee_id = ec.employee_id
WHERE ec.car_brand IN ('BMW','MERC','VW')
  and not exists (select *
                  from employee_cars ec2
                  where ec2.car_brand = 'AUDI'
                    and ec2.employee_id = emp.employee_id);

Note that you do not need an outer join between employees and employee_cars


问:
How to upload zip file to azure blob then unzip it there
I have lot of zip files, which will have few folders and 50+ files in it. How can I upload those zip files to azure blob then unzip it there.

Unzipping the file in server and uploading files in it one by one to azure blob will be a cumbersome process.

Does azure has any easy way to achieve this or is there any workaround?

I'm implementing this in PHP.

答:
As you prob. already found all over the internet, it's no possible to run workloads INSIDE of the storage servers... but:
You can write a azure function to FileWatch your storage account, and unzip files for you, then upload them</p>


问:
Foreign Key Constraint Problem
The tables in question are:

enquiry

id

accepted_quote_id

supplier_enquiry

id

enquiry_id

quote

id

enquiry_id

supplier_enquiry_id

The constraints are as follows:

CONSTRAINT supplier_enquiry_ibfk_1 FOREIGN KEY (enquiry_id) REFERENCES enquiry (id) ON DELETE CASCADE

CONSTRAINT quote_ibfk_1 FOREIGN KEY (supplier_enquiry_id) REFERENCES supplier_enquiry (id) ON DELETE CASCADE

CONSTRAINT enquiry_ibfk_9 FOREIGN KEY (accepted_quote_id) REFERENCES quote (id)

So the way I expect this to work is:

If you delete an 'enquiry' it deletes the child 'supplier_enquiry' records

If you delete a 'supplier_enquiry' it deletes the child 'quote' records

You cannnot delete a 'quote' if an 'enquiry' references that quote's ID

The problem I'm having is when deleting an 'enquiry' record. Because it needs to delete the child records first, i.e. 'supplier_enquiry' and 'quote', if 'accepted_quote_id' references a 'quote' then the 'enquiry' can't be deleted.

Any idea how I can overcome this issue?

答:
You get rid of the circular reference by making the two other tables dependant on enquiry.

So:

quote.enquiry_id references enquiry.id

And:

supplier_enquiry.enquiry_id references enquiry.id

EDIT: That might be unclear.  I'm suggesting making a new constraint on the quote table that references enquiry_id to enquiry.id, then removing enquiry_ibfk_9

Title: Foreign Key Constraint Problem


问:
JSON error org.json.JSONException: No value for item
After tweaking JSON response a bit the error has changed to W/System.err: org.json.JSONException: No value for retCode.

The complete error:

```<code>04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: org.json.JSONException: No value for retCode
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.ActivityRegister$2.serviceResult(ActivityRegister.java:194)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.Net$1$1.run(Net.java:420)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Looper.loop(Looper.java:148)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-03 12:53:26.703 14366-14454/com.allianz.azemployee V/RenderScript: 0x9d789000 Launching thread(s), CPUs 4
</code>```

This my ActivityRegister.java class:

```<code>public class ActivityRegister extends AppCompatActivity implements View.OnClickListener {

    Button btnRequestPin, btnConfirm, btnRequestNewPin;
    EditText editTextEmail;
    EditText editTextPin;

    private static final String FIRST_START_KEY = "first_start";
    private static final boolean ALWAYS_SEND_FIRST_START_BROADCAST = false;

    private String emailTemp, tokenTemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        btnRequestPin = (Button)findViewById(R.id.btn_request_pin);
        btnConfirm = (Button)findViewById(R.id.btn_confirm);
        btnRequestNewPin = (Button)findViewById(R.id.btn_request_newpin);
        editTextEmail = (EditText) findViewById(R.id.editText_mail);
        editTextPin = (EditText) findViewById(R.id.editText_pin);

        btnRequestPin.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        btnRequestNewPin.setOnClickListener(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        Intent intent = new Intent(this,ActivityLogin.class);
        this.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if(v == btnConfirm){

            final String email = editTextEmail.getText().toString();
            final String token = editTextPin.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            if (token == null || token.length() == 0){
                Toast.makeText(this,"OTP required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            String postBody = Net.getInstance().getJSONForRegister(email,token);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){

                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if (retCodeInt==0) { //Registration success

                                //Store user-email and token
                                Net.getInstance().saveUserWithValues(ActivityRegister.this, email, token, "");
                                //Take user to login screen.
                                ActivityRegister.this.finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for registration. Try again.");
                        }
                    }
                }
            });
        }
        if(v == btnRequestPin || v == btnRequestNewPin){

            final String email = editTextEmail.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            final Button button = (Button) v;
            String postBody = Net.getInstance().getJSONForPinGeneration(email);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){
                        Log.i("Aditi","errorMsg== " +errorMsg);
                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            Log.i("Aditi","retCode===" + retCode + " ,status== "+status);
                            Log.i("Aditi","errorMsg== " +errorMsg);

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if(retCodeInt == 0 && button == btnRequestNewPin){

                                ActivityRegister.this.finish(); //take user to login on success.
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for pin generation. Try again.");
                        }
                    }

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

This is the stringResponse I'm giving:

```<code>public void callServiceWithURLPart(final Activity activity, final String urlPart, final String postBody, final ICallServiceResult callServiceResult){

        final ProgressDialog progress = new ProgressDialog(activity);
        progress.setTitle("Processing..");
        progress.setProgressStyle(android.R.attr.progressBarStyleSmall);
        //progress.setMessage("Connecting...");
        progress.show();

        ConnectivityManager connMgr = (ConnectivityManager)
                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {

            Runnable r = new Runnable() {
                @Override
                public void run() {

                    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).build();

                    try{

                        String servicePath = kURLBase + urlPart;

                        Log.d("OkHttpClient","servicePath = "+servicePath);
                        Log.d("postBody",postBody);

                        Request request = new Request.Builder()
                                .url(servicePath)
                                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody))
                                .build();

                        final Response response = client.newCall(request).execute();
                        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                        //final String stringResponse = response.body().string();

                        final String stringResponse = "{'serviceName': 'registerToken', 'emailID': '', 'token': ''}";

                        if(stringResponse!=null){
                            Log.d("ServiceResponseString",stringResponse);
                        }else {
                            Log.d("ServiceResponseString","null");
                        }

                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
                                    if(stringResponse!=null){
                                        callServiceResult.serviceResult(urlPart,true,stringResponse);
                                    }
                                    else {
                                        callServiceResult.serviceResult(urlPart,false,stringResponse);
                                    }
                                }
                            });
                        }
                    } catch (Exception e){

                        Log.d("OkHttpClient exception",e.toString());
                        final Exception _e = e;
                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
           callServiceResult.serviceResult(urlPart,false,_e.toString());
                                }
                            });
                        }
                    }
                }
            };
            Thread t = new Thread(r);
            t.start();
        } else {
            progress.dismiss();
            fastToast(activity,"Connect to internet and try again.");
        }
    }
</code>```

My base URL is: public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest"; which is being provided when stringResponse is asked.
Any help would be appreciated.

答:
Try this:

```<code>String retCode = jsonObject.optString("retCode");
</code>```

The difference is that optString returns the empty string ("") if the
  key you specify doesn't exist. getString on the other hand throws a
  JSONException. Use getString if it's an error for the data to be
  missing, or optString if you're not sure if it will be there.

Body:
After tweaking JSON response a bit the error has changed to W/System.err: org.json.JSONException: No value for retCode.

The complete error:

04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: org.json.JSONException: No value for retCode
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.ActivityRegister$2.serviceResult(ActivityRegister.java:194)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.Net$1$1.run(Net.java:420)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Looper.loop(Looper.java:148)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-03 12:53:26.703 14366-14454/com.allianz.azemployee V/RenderScript: 0x9d789000 Launching thread(s), CPUs 4

This my ActivityRegister.java class:

public class ActivityRegister extends AppCompatActivity implements View.OnClickListener {

    Button btnRequestPin, btnConfirm, btnRequestNewPin;
    EditText editTextEmail;
    EditText editTextPin;

    private static final String FIRST_START_KEY = "first_start";
    private static final boolean ALWAYS_SEND_FIRST_START_BROADCAST = false;

    private String emailTemp, tokenTemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        btnRequestPin = (Button)findViewById(R.id.btn_request_pin);
        btnConfirm = (Button)findViewById(R.id.btn_confirm);
        btnRequestNewPin = (Button)findViewById(R.id.btn_request_newpin);
        editTextEmail = (EditText) findViewById(R.id.editText_mail);
        editTextPin = (EditText) findViewById(R.id.editText_pin);

        btnRequestPin.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        btnRequestNewPin.setOnClickListener(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        Intent intent = new Intent(this,ActivityLogin.class);
        this.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if(v == btnConfirm){

            final String email = editTextEmail.getText().toString();
            final String token = editTextPin.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            if (token == null || token.length() == 0){
                Toast.makeText(this,"OTP required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            String postBody = Net.getInstance().getJSONForRegister(email,token);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){

                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if (retCodeInt==0) { //Registration success

                                //Store user-email and token
                                Net.getInstance().saveUserWithValues(ActivityRegister.this, email, token, "");
                                //Take user to login screen.
                                ActivityRegister.this.finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for registration. Try again.");
                        }
                    }
                }
            });
        }
        if(v == btnRequestPin || v == btnRequestNewPin){

            final String email = editTextEmail.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            final Button button = (Button) v;
            String postBody = Net.getInstance().getJSONForPinGeneration(email);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){
                        Log.i("Aditi","errorMsg== " +errorMsg);
                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            Log.i("Aditi","retCode===" + retCode + " ,status== "+status);
                            Log.i("Aditi","errorMsg== " +errorMsg);

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if(retCodeInt == 0 && button == btnRequestNewPin){

                                ActivityRegister.this.finish(); //take user to login on success.
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for pin generation. Try again.");
                        }
                    }

                }
            });
        }
    }
}

This is the stringResponse I'm giving:

public void callServiceWithURLPart(final Activity activity, final String urlPart, final String postBody, final ICallServiceResult callServiceResult){

        final ProgressDialog progress = new ProgressDialog(activity);
        progress.setTitle("Processing..");
        progress.setProgressStyle(android.R.attr.progressBarStyleSmall);
        //progress.setMessage("Connecting...");
        progress.show();

        ConnectivityManager connMgr = (ConnectivityManager)
                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {

            Runnable r = new Runnable() {
                @Override
                public void run() {

                    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).build();

                    try{

                        String servicePath = kURLBase + urlPart;

                        Log.d("OkHttpClient","servicePath = "+servicePath);
                        Log.d("postBody",postBody);

                        Request request = new Request.Builder()
                                .url(servicePath)
                                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody))
                                .build();

                        final Response response = client.newCall(request).execute();
                        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                        //final String stringResponse = response.body().string();

                        final String stringResponse = "{'serviceName': 'registerToken', 'emailID': '', 'token': ''}";

                        if(stringResponse!=null){
                            Log.d("ServiceResponseString",stringResponse);
                        }else {
                            Log.d("ServiceResponseString","null");
                        }

                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
                                    if(stringResponse!=null){
                                        callServiceResult.serviceResult(urlPart,true,stringResponse);
                                    }
                                    else {
                                        callServiceResult.serviceResult(urlPart,false,stringResponse);
                                    }
                                }
                            });
                        }
                    } catch (Exception e){

                        Log.d("OkHttpClient exception",e.toString());
                        final Exception _e = e;
                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
           callServiceResult.serviceResult(urlPart,false,_e.toString());
                                }
                            });
                        }
                    }
                }
            };
            Thread t = new Thread(r);
            t.start();
        } else {
            progress.dismiss();
            fastToast(activity,"Connect to internet and try again.");
        }
    }

My base URL is: public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest"; which is being provided when stringResponse is asked.
Any help would be appreciated.

Body:
Try this:

String retCode = jsonObject.optString("retCode");

The difference is that optString returns the empty string ("") if the
  key you specify doesn't exist. getString on the other hand throws a
  JSONException. Use getString if it's an error for the data to be
  missing, or optString if you're not sure if it will be there.


问:
Swift 3 Create UILabel programmatically and add NSLayoutConstraints
Hello I am trying to create a label programmatically and add NSLayoutConstraints so that it is centered in the superview regardless of screen size and orientation etc. I have looked but just can't find an example to follow. Here is what I have:</p>

```<code>let codedLabel:UILabel = UILabel()
codedLabel.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
codedLabel.textAlignment = .center
codedLabel.text = alertText
codedLabel.numberOfLines=1
codedLabel.textColor=UIColor.red
codedLabel.font=UIFont.systemFont(ofSize: 22)
codedLabel.backgroundColor=UIColor.lightGray

let heightConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)

let widthConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)

codedLabel.addConstraints([heightConstraint, widthConstraint])

let verticalConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)

let horizontalConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)

self.contentView.addConstraints([verticalConstraint, horizontalConstraint])

self.contentView.addSubview(codedLabel)
</code>```

答:
```<code>let myLabel: UILabel = {
  let lb = UILabel()
  lb.translatesAutoresizingMaskIntoConstraints = false
  lb.textAlignment = .center
  lb.numberOfLines = 1
  lb.textColor = UIColor.black
  lb.font=UIFont.systemFont(ofSize: 22)
  lb.backgroundColor = UIColor.grey
  return lb
}()
</code>```

In super.viewDidLoad() method, You need add label to your view and
add contraints for the label:

```<code>override func viewDidLoad() {
  super.viewDidLoad()
  self.view.addSubView(myLabel)
  setUpMyLabel()
}

func setUpMyLabel() {
  NSLayoutConstraint.activate([
            myLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            myLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            myLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.7),
            myLabel.heightAnchor.constraint(equalToConstant: 50)])
}
</code>```

I hope the my code can help to you.

Body:
Hello I am trying to create a label programmatically and add NSLayoutConstraints so that it is centered in the superview regardless of screen size and orientation etc. I have looked but just can't find an example to follow. Here is what I have:

let codedLabel:UILabel = UILabel()
codedLabel.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
codedLabel.textAlignment = .center
codedLabel.text = alertText
codedLabel.numberOfLines=1
codedLabel.textColor=UIColor.red
codedLabel.font=UIFont.systemFont(ofSize: 22)
codedLabel.backgroundColor=UIColor.lightGray

let heightConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)

let widthConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)

codedLabel.addConstraints([heightConstraint, widthConstraint])

let verticalConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)

let horizontalConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)

self.contentView.addConstraints([verticalConstraint, horizontalConstraint])

self.contentView.addSubview(codedLabel)

Body:
let myLabel: UILabel = {
  let lb = UILabel()
  lb.translatesAutoresizingMaskIntoConstraints = false
  lb.textAlignment = .center
  lb.numberOfLines = 1
  lb.textColor = UIColor.black
  lb.font=UIFont.systemFont(ofSize: 22)
  lb.backgroundColor = UIColor.grey
  return lb
}()

In super.viewDidLoad() method, You need add label to your view and
add contraints for the label:

override func viewDidLoad() {
  super.viewDidLoad()
  self.view.addSubView(myLabel)
  setUpMyLabel()
}

func setUpMyLabel() {
  NSLayoutConstraint.activate([
            myLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            myLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            myLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.7),
            myLabel.heightAnchor.constraint(equalToConstant: 50)])
}

I hope the my code can help to you.


答:
```<code> var s = from p in tests where names.Contains(p.Name) select p;
</code>```

Title: Linq select from database table where matching property from List

Body:
I have a List with records of following class which is something like this

  public class TestRecord
  {
     public int RecordsId{get;set;}
public string Name{get;set;}
-- and more such properties.

  }

Now I have database table which I access from linq which contains RecordId column , values which will match RecordId value from above List.

  var result=from p in _context.Details

however I am thinking I could do where/ contains on this linq query and provide it with a clause to match RecordId from a list

 List<TestRecord> records -- this has let's say 100 records.

Doing simply this does not work as linq can't join with generic List

    var finalresult = from p in context.details
                      join a in records on p.recordId equals a.recordId

Any solutions for this using Linq?


问:
Type mismatch with generics sum type
I have a sum trait, that looks like as follow:

```<code>sealed trait Sum[+A, +B]

final case class Failure[A](value: A) extends Sum[A, Nothing]

final case class Success[B](value: B) extends Sum[Nothing, B]
</code>```

When I try to create a new variable as:

```<code>val s1: Sum[Int, Nothing] = Success(4)
</code>```

I've got following error:

```<code>Error:(5, 41) type mismatch;
 found   : Int(4)
 required: Nothing
    val s1: Sum[Int, Nothing] = Success(4)
</code>```

Why?

And why this is working:

```<code>val s1: Sum[Int, Int] = Success(4)
</code>```

答:
Because B is the second type parameter, not the first:

```<code>val s1: Sum[Nothing, Int] = Success(4)
</code>```

Title: Type mismatch with generics sum type

Body:
I have a sum trait, that looks like as follow:

sealed trait Sum[+A, +B]

final case class Failure[A](value: A) extends Sum[A, Nothing]

final case class Success[B](value: B) extends Sum[Nothing, B]

When I try to create a new variable as:

val s1: Sum[Int, Nothing] = Success(4)

I've got following error:

Error:(5, 41) type mismatch;
 found   : Int(4)
 required: Nothing
    val s1: Sum[Int, Nothing] = Success(4)

Why?

And why this is working:

val s1: Sum[Int, Int] = Success(4)

Body:
Because B is the second type parameter, not the first:

val s1: Sum[Nothing, Int] = Success(4)


问:
add an horizontal line and some icon with text in bottom like facebook
I want add a footer to a cardview.

my current XML layout in RecyclerView is this:

(this xml code act as row in RecyclerView )

code:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"

        android:layout_margin="@dimen/activity_margin_half"
        app:cardBackgroundColor="@color/placeholder_grey"
        app:cardCornerRadius="6dp"
        app:cardPreventCornerOverlap="false">

        <ProgressBar
            android:id="@+id/movie_progress"
            style="@style/Widget.AppCompat.ProgressBar"
            android:layout_width="@dimen/activity_margin"
            android:layout_height="@dimen/activity_margin"
            android:layout_gravity="center"
            android:theme="@style/CircularProgress"/>

        <ImageView
            android:id="@+id/movie_poster"
            android:layout_width="@dimen/poster_thumb_width"
            android:layout_height="@dimen/poster_thumb_height"/>

    </android.support.v7.widget.CardView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="bottom"
        android:layout_marginTop="@dimen/activity_margin"
        android:background="@drawable/bg_round_rect"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_margin"
        android:paddingEnd="@dimen/activity_margin"
        android:paddingLeft="@dimen/poster_thumb_width"
        android:paddingRight="@dimen/activity_margin"
        android:paddingStart="@dimen/poster_thumb_width"
        android:paddingTop="@dimen/activity_margin_half">

        <TextView
            android:id="@+id/movie_year"
            style="@style/TextAppearance.AppCompat.Caption"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_margin_content"
            android:layout_marginStart="@dimen/activity_margin_content"

            android:alpha="0.38"
            android:gravity="start"
            android:maxLines="1"
            android:textStyle="bold"
            android:textColor="#f14e4e"
            tools:text="2009 | EN"/>

        <TextView
            android:id="@+id/movie_title"
            style="@style/TextAppearance.AppCompat.Subhead"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_margin_content"
            android:layout_marginStart="@dimen/activity_margin_content"
            android:layout_marginTop="@dimen/activity_margin_quarter"
            android:textColor="#9b92b3"
            android:maxLines="1"
            tools:text="Movie Title"/>

        <TextView
            android:id="@+id/movie_desc"
            style="@style/TextAppearance.AppCompat.Caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_margin_content"
            android:layout_marginStart="@dimen/activity_margin_content"
            android:layout_marginTop="@dimen/activity_margin_half"
            android:ellipsize="end"
            android:maxLines="2"
            android:textColor="#9b92b3"
            tools:text="Nowadays, user engagement is considered one of the most important metrics for the success of your app"/>

    </LinearLayout>

</FrameLayout>
</code>```

Now I want add more thing to this code.

I want add an horizontal line. (I think I must View) and some Icon with text like this picture:

how can I do that?

答:
Add a view like this below the cardView

```<code><View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/black"/>
</code>```

then use LinearLayout/RelativeLayout below it to hold the icons and text

Body:
I want add a footer to a cardview.

my current XML layout in RecyclerView is this:

(this xml code act as row in RecyclerView )

code:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"

        android:layout_margin="@dimen/activity_margin_half"
        app:cardBackgroundColor="@color/placeholder_grey"
        app:cardCornerRadius="6dp"
        app:cardPreventCornerOverlap="false">

        <ProgressBar
            android:id="@+id/movie_progress"
            style="@style/Widget.AppCompat.ProgressBar"
            android:layout_width="@dimen/activity_margin"
            android:layout_height="@dimen/activity_margin"
            android:layout_gravity="center"
            android:theme="@style/CircularProgress"/>

        <ImageView
            android:id="@+id/movie_poster"
            android:layout_width="@dimen/poster_thumb_width"
            android:layout_height="@dimen/poster_thumb_height"/>

    </android.support.v7.widget.CardView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="bottom"
        android:layout_marginTop="@dimen/activity_margin"
        android:background="@drawable/bg_round_rect"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_margin"
        android:paddingEnd="@dimen/activity_margin"
        android:paddingLeft="@dimen/poster_thumb_width"
        android:paddingRight="@dimen/activity_margin"
        android:paddingStart="@dimen/poster_thumb_width"
        android:paddingTop="@dimen/activity_margin_half">

        <TextView
            android:id="@+id/movie_year"
            style="@style/TextAppearance.AppCompat.Caption"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_margin_content"
            android:layout_marginStart="@dimen/activity_margin_content"

            android:alpha="0.38"
            android:gravity="start"
            android:maxLines="1"
            android:textStyle="bold"
            android:textColor="#f14e4e"
            tools:text="2009 | EN"/>

        <TextView
            android:id="@+id/movie_title"
            style="@style/TextAppearance.AppCompat.Subhead"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_margin_content"
            android:layout_marginStart="@dimen/activity_margin_content"
            android:layout_marginTop="@dimen/activity_margin_quarter"
            android:textColor="#9b92b3"
            android:maxLines="1"
            tools:text="Movie Title"/>

        <TextView
            android:id="@+id/movie_desc"
            style="@style/TextAppearance.AppCompat.Caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_margin_content"
            android:layout_marginStart="@dimen/activity_margin_content"
            android:layout_marginTop="@dimen/activity_margin_half"
            android:ellipsize="end"
            android:maxLines="2"
            android:textColor="#9b92b3"
            tools:text="Nowadays, user engagement is considered one of the most important metrics for the success of your app"/>

    </LinearLayout>

</FrameLayout>

Now I want add more thing to this code.

I want add an horizontal line. (I think I must View) and some Icon with text like this picture:

how can I do that?

Body:
Add a view like this below the cardView

<View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/black"/>

then use LinearLayout/RelativeLayout below it to hold the icons and text