问:
Group custom post types by taxonomy in timber (Wordpress)
I'm having a hard time figuring out how to group a collection of post with the same taxonomy "year" attached to them in Wordpress, without using a separate archive template.

I Finally managed to get it to work with Wordpress, but now I want to translate this to timber, and I just can't seem to be able to do so. Can anyone give me some pointers?

This is the working wordpress code

```<code>$date_now = date('Y-m-d H:i:s');
$ex_terms = get_terms( 'exhibition-year','orderby=name&order=desc' );

foreach ( $ex_terms as $ex_term ) {
    $member_group_query = new WP_Query(
        array(
            'post_type' => 'exhibition',
            'tax_query' => array(
                array(
                'taxonomy' => 'exhibition-year',
                'field' => 'slug',
                'terms' => array( $ex_term->slug ),
                'operator' => 'IN'
                )
            ),
            'meta_query'        => array(
                array(
                'key'           => 'date_end',
                'compare'       => '<',
                'value'         => $date_now,
                'type'          => 'DATETIME'
                )
            )
        )
    );

    if($ex_term->slug <= date('Y')){
    ?>
        <h2><?php echo $ex_term->name; ?></h2>
        <ul>
        <?php
        if ( $member_group_query->have_posts() ) : while ( $member_group_query->have_posts() ) : $member_group_query->the_post(); ?>
            <li><?php echo the_title(); ?></li>
        <?php endwhile; endif; ?>
        </ul>
        <?php
        // Reset things, for good measure
        $member_group_query = null;
        wp_reset_postdata();
    }
}
</code>```

The desired outcome should look something similar to this, I'm only displaying the titles. But it should contain the entire postdata.

The desired outcome

I've looked into:

https://timber.github.io/docs/reference/timber-post/
https://timber.github.io/docs/reference/timber-postquery/
and
https://timber.github.io/docs/reference/timber/#get-terms

Please help, it's driving me insane :)

答:
Two changes to your query,

Current timestamp in meta query

Converting to integer type before comparing it with current year

$current = current_time( 'timestamp' );
$ex_terms = get_terms( 'exhibition-year', 'orderby=name&order=desc' );

foreach ( $ex_terms as $ex_term ):

```<code>$member_group_query = new WP_Query(
    array(
        'post_type' => 'exhibition',
        'tax_query' => array(
            array(
                'taxonomy' => 'exhibition-year',
                'field' => 'slug',
                'terms' => array( $ex_term->slug ),
                'operator' => 'IN'
            )
        ),
        'meta_query'        => array(
            array(
                'key'           => 'date_end',
                'compare'       => '<',
                'value'         => $current
            )
        )
    )
);

if( (int)$ex_term->slug <= date('Y')):

    echo '<h2>'.$ex_term->name.'</h2>';
    echo '<ul>';

    if ( $member_group_query->have_posts() ) :

        while ( $member_group_query->have_posts() ) : $member_group_query->the_post();

            echo '<li>'.get_the_title().'</li>';

        endwhile;

    endif;

    echo '</ul>';

endif;

$member_group_query = null;
wp_reset_postdata();
</code>```

endforeach;

Hope this helps.

Body:
I'm having a hard time figuring out how to group a collection of post with the same taxonomy "year" attached to them in Wordpress, without using a separate archive template.

I Finally managed to get it to work with Wordpress, but now I want to translate this to timber, and I just can't seem to be able to do so. Can anyone give me some pointers?

This is the working wordpress code

$date_now = date('Y-m-d H:i:s');
$ex_terms = get_terms( 'exhibition-year','orderby=name&order=desc' );

foreach ( $ex_terms as $ex_term ) {
    $member_group_query = new WP_Query(
        array(
            'post_type' => 'exhibition',
            'tax_query' => array(
                array(
                'taxonomy' => 'exhibition-year',
                'field' => 'slug',
                'terms' => array( $ex_term->slug ),
                'operator' => 'IN'
                )
            ),
            'meta_query'        => array(
                array(
                'key'           => 'date_end',
                'compare'       => '<',
                'value'         => $date_now,
                'type'          => 'DATETIME'
                )
            )
        )
    );

    if($ex_term->slug <= date('Y')){
    ?>

<?php echo $ex_term->name; ?>

        <?php
        if ( $member_group_query->have_posts() ) : while ( $member_group_query->have_posts() ) : $member_group_query->the_post(); ?>

<?php echo the_title(); ?>

        <?php endwhile; endif; ?>

        <?php
        // Reset things, for good measure
        $member_group_query = null;
        wp_reset_postdata();
    }
}

The desired outcome should look something similar to this, I'm only displaying the titles. But it should contain the entire postdata.

The desired outcome

I've looked into:

https://timber.github.io/docs/reference/timber-post/
https://timber.github.io/docs/reference/timber-postquery/
and
https://timber.github.io/docs/reference/timber/#get-terms

Please help, it's driving me insane :)

Body:
Two changes to your query,

Current timestamp in meta query

Converting to integer type before comparing it with current year

$current = current_time( 'timestamp' );
$ex_terms = get_terms( 'exhibition-year', 'orderby=name&order=desc' );

foreach ( $ex_terms as $ex_term ):

$member_group_query = new WP_Query(
    array(
        'post_type' => 'exhibition',
        'tax_query' => array(
            array(
                'taxonomy' => 'exhibition-year',
                'field' => 'slug',
                'terms' => array( $ex_term->slug ),
                'operator' => 'IN'
            )
        ),
        'meta_query'        => array(
            array(
                'key'           => 'date_end',
                'compare'       => '<',
                'value'         => $current
            )
        )
    )
);

if( (int)$ex_term->slug <= date('Y')):

    echo '<h2>'.$ex_term->name.'</h2>';
    echo '<ul>';

    if ( $member_group_query->have_posts() ) :

        while ( $member_group_query->have_posts() ) : $member_group_query->the_post();

            echo '<li>'.get_the_title().'</li>';

        endwhile;

    endif;

    echo '</ul>';

endif;

$member_group_query = null;
wp_reset_postdata();

endforeach;

Hope this helps.


来源: stackexchange

问:
Get URL redirects with slimerJS and take screenshot of final URL
How can I get all the URL redirects in slimerJS and save them into an array then render a screenshot of the final URL.

For example if I run red.com through slimer but it redirects through php to blue.com which then redirects again to yellow.com through javascript, how can I save these redirects into an array?

Once the redirecting has finished I would then take a screenshot of the final URL, so yellow.com in the example above.

I'm using slimer 1.0 because I want to use slimer in headless mode.

Here's some simplified code I wrote over the weekend.

```<code>call to slimer (windows)
./slimerjs/src/slimerjs.bat --headless slimer-redirects.js http://google.com
</code>```

The call to google.com using the script below doesn't pick up the redirect to google.co.uk (I'm in UK).
Strangely though the code below does detect javascript redirects.
Another problem with the code below is it doesn't seem to pick up multiple i.e > 2 redirects when it does work.

```<code>var system = require("system");
var page;
var myurl = system.args[1];

var renderPage = function(url) {
    page = require('webpage').create();
    page.onNavigationRequested = function(url, type, willNavigate, main) {
        if (url != myurl) {
            myurl = url;
            // page.close(); // makes some redirects hang. google.com for example

            setTimeout('renderPage(myurl)', 1);
        }
    };
     page.open(myurl)
    .then(function (status) {
        if (status === "success") {
            // I would then render screenshot here and exit
            console.log("Final URL is: " + myurl);
            slimer.exit();
        }

    });

};

renderPage(myurl);
</code>```

It seems quite a simple task to just get the redirect URL's but I can't figure it out.
If it's not possible with slimer I would also like to know of other options. Chrome headless with or without puppeteer maybe?

答:
You can use callback onUrlChanged() for saving redirect URL

```<code>var urls = [];
page.onUrlChanged = function(url) {
    urls.push(url);
};
</code>```

This snippet should help you

ContentLicense: CC BY-SA 3.0

Body:
How can I get all the URL redirects in slimerJS and save them into an array then render a screenshot of the final URL.

For example if I run red.com through slimer but it redirects through php to blue.com which then redirects again to yellow.com through javascript, how can I save these redirects into an array?

Once the redirecting has finished I would then take a screenshot of the final URL, so yellow.com in the example above.

I'm using slimer 1.0 because I want to use slimer in headless mode.

Here's some simplified code I wrote over the weekend.

call to slimer (windows)
./slimerjs/src/slimerjs.bat --headless slimer-redirects.js http://google.com

The call to google.com using the script below doesn't pick up the redirect to google.co.uk (I'm in UK).
Strangely though the code below does detect javascript redirects.
Another problem with the code below is it doesn't seem to pick up multiple i.e > 2 redirects when it does work.

var system = require("system");
var page;
var myurl = system.args[1];

var renderPage = function(url) {
    page = require('webpage').create();
    page.onNavigationRequested = function(url, type, willNavigate, main) {
        if (url != myurl) {
            myurl = url;
            // page.close(); // makes some redirects hang. google.com for example

            setTimeout('renderPage(myurl)', 1);
        }
    };
     page.open(myurl)
    .then(function (status) {
        if (status === "success") {
            // I would then render screenshot here and exit
            console.log("Final URL is: " + myurl);
            slimer.exit();
        }

    });

};

renderPage(myurl);

It seems quite a simple task to just get the redirect URL's but I can't figure it out.
If it's not possible with slimer I would also like to know of other options. Chrome headless with or without puppeteer maybe?

Body:
You can use callback onUrlChanged() for saving redirect URL

var urls = [];
page.onUrlChanged = function(url) {
    urls.push(url);
};

This snippet should help you


问:
Docker entrypoint and cmd together
I try to setup a Docker with both entrypoint and cmd.

```<code>FROM debian:stretch
RUN apt-get update && \
apt install gnupg ca-certificates -y
RUN echo "deb http://repo.aptly.info/ squeeze main" > /etc/apt/sources.list.d/aptly.list
RUN apt-key adv --keyserver keys.gnupg.net --recv-keys 9E3E53F19C7DE460
RUN apt update && apt install aptly -y
ADD aptly.conf /etc/aptly.conf
ADD start.sh .
VOLUME ["/aptly"]
ENTRYPOINT ["/start.sh"]
CMD ["aptly", "api", "serve"]
</code>```

But entrypoint script is not stopping...
The cmd command is not launching

Here my script :

```<code>#!/bin/bash
 set -e
 init_aptly() {
 #import pgp key
#create nginx root folder in /aptly
su -c "mkdir -p /aptly/.aptly/public"
echo "12"
 #initialize repository
 #aptly create repo doze-server -   distribution="stable"
  }
  #check for first run
 if [ ! -e /aptly/.aptly/public ]; then
  init_aptly
  echo "13"
 fi
  echo "14"
</code>```

The script always echo 14, I would like only one and then, execute the cmd command from dockerfile

答:
When you use both entrypoint and command, the command section will be appended to entrypoint executable as arguments. Thus in your case:

```<code>ENTRYPOINT ["/start.sh"]
CMD ["aptly", "api", "serve"]
</code>```

Is equivalent to running:

```<code>ENTRYPOINT["/start.sh", "aptly", "api", "serve"]
</code>```

Title: Docker entrypoint and cmd together

Body:
I try to setup a Docker with both entrypoint and cmd.

FROM debian:stretch
RUN apt-get update && \
apt install gnupg ca-certificates -y
RUN echo "deb http://repo.aptly.info/ squeeze main" > /etc/apt/sources.list.d/aptly.list
RUN apt-key adv --keyserver keys.gnupg.net --recv-keys 9E3E53F19C7DE460
RUN apt update && apt install aptly -y
ADD aptly.conf /etc/aptly.conf
ADD start.sh .
VOLUME ["/aptly"]
ENTRYPOINT ["/start.sh"]
CMD ["aptly", "api", "serve"]

But entrypoint script is not stopping...
The cmd command is not launching

Here my script :

#!/bin/bash
 set -e
 init_aptly() {
 #import pgp key
#create nginx root folder in /aptly
su -c "mkdir -p /aptly/.aptly/public"
echo "12"
 #initialize repository
 #aptly create repo doze-server -   distribution="stable"
  }
  #check for first run
 if [ ! -e /aptly/.aptly/public ]; then
  init_aptly
  echo "13"
 fi
  echo "14"

The script always echo 14, I would like only one and then, execute the cmd command from dockerfile

Body:
When you use both entrypoint and command, the command section will be appended to entrypoint executable as arguments. Thus in your case:

ENTRYPOINT ["/start.sh"]
CMD ["aptly", "api", "serve"]

Is equivalent to running:

ENTRYPOINT["/start.sh", "aptly", "api", "serve"]


问:
Comparing dates in Django does not work
I have a problem comparing dates in Django. I followed the hint How to compare dates in Django but it does not work. Maybe you can help me.

My code:

modelys.py

```<code>class Customer(models.Model):
last_updated = models.DateTimeField(auto_now_add=True)
</code>```

views.py

```<code>@property
def is_past_due(self):
return (date.today() - self.date)> timedelta(1)
</code>```

home.html

```<code>{% if customer.last_updated.is_past_due %}
<td class="table-danger">{{ customer.last_updated }}</td>
{% else %}
<td class="align-middle">{{ customer.last_updated }}</td>
{% endif %}
</code>```

I am using Bootstrap, so when the difference between two dates has a more than one day I want a tablefield to become 'danger'-ous ;-), but nothing changes.

Thanks in advance.

PS: edited the typo in def timdedelta to timedelta.

答:
you can use days property of datetime to get the exact gap between days.

(datetime.today()- self.last_updated).days > 1

where self.last_updated is field name of "Customer" Model

Title: Comparing dates in Django does not work

Body:
I have a problem comparing dates in Django. I followed the hint How to compare dates in Django but it does not work. Maybe you can help me.

My code:

modelys.py

class Customer(models.Model):
last_updated = models.DateTimeField(auto_now_add=True)

views.py

@property
def is_past_due(self):
return (date.today() - self.date)> timedelta(1)

home.html

{% if customer.last_updated.is_past_due %}
{{ customer.last_updated }}
{% else %}
{{ customer.last_updated }}
{% endif %}

I am using Bootstrap, so when the difference between two dates has a more than one day I want a tablefield to become 'danger'-ous ;-), but nothing changes.

Thanks in advance.

PS: edited the typo in def timdedelta to timedelta.


问:
What DNSs have API access?
I saw this over on slashdot and realized if I could program in dns control into some of my apps it would make life a lot easier. Someone over there recommended dynect which apparently had a wonderful api. Unfortunately not a lot else was recomended. I don't know anything about managing dns servers I mostly work with the lamp stack, so on linux I understand bind is the way to go but other then a basic setup I'd be lost. I'd rather outsource the details.

What DNS services have API's and are easy to use without breaking the bank?

答:
Has anyone seen any of the following DNS providers with APIs:

http://durabledns.com/

https://dnsimple.com/ (also supports registration by API)

http://www.loaddns.com/

OwnerDisplayName: wizard

Title: What DNSs have API access?

ContentLicense: CC BY-SA 2.5


问:
Why emulator is very slow in Android Studio?
I just setup Android Studio on my PC, which is new launch to develop Android application.

My problem is that, when I try to run my small app in emulator, it take to much time to launch and after then emulator is working slow too.

AVD settings

AVD Name: Glaxy

Device: Glaxy Nexus (4.65", 720x 1280: xhdpi)

Target: Android 4.2.2 - API Level 17

Memory Option: Ram 500, VM Heap 64

Internal Storage: 200MiB

I have good window pc: Intel Core 2 Duo    2.93Ghz and Ram is 3gb

I am new in Android development and java.

答:
Check this list:

install Intel HAXM

just use x86 AVD

use small size screen


问:
Tag names are missing in the XML parsed except the root element
I am reading a dynamic XML file (without any known structure) and putting the relevant tag name and value to a hashmap (ex: metadata<tagName, Value> ).

My issue here is, I can not get the tagName but it only adds the root tagName and all the values of entire xml.

my XML is:

```<code><?xml version="1.0" encoding="UTF-8"?>
            <form kwf="VARA">
                <sec1>
                    <docID>2d2c5bf209b79d8b1a1f840ce4ce4030e66a76d6</docID>
                    <qrCode>xx.jpg</qrCode>
                    <title>NOOO FORM NAME</title>
                    <ELO_VARAFNAME>NO</ELO_VARAFNAME>
                    <ELO_VARALNAME>NAME</ELO_VARALNAME>
                    <ELO_VARAEMAIL>noname@gmail.com</ELO_VARAEMAIL>
                    <ELO_VARAORBEONDOCID>2d2c5bf209b79d8b1a1f840ce4ce4030e66a76d6</ELO_VARAORBEONDOCID>
                </sec1>
            </form>
</code>```

My Code is:

```<code>public static Map<String,String> getMetaDataFromOrbeonXML(File fXmlFile) throws SAXException, ParserConfigurationException, IOException
  {
    Map metaData = new HashMap();
    String formName="";
    String docID = "";
    try {

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

       doc.getDocumentElement().normalize();

       System.out.println("Root element :" +        doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("form");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);
        System.out.println("\nCurrent Element :" + nNode.getNodeName());

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
              Element eElement = (Element) nNode;

             docID = eElement.getElementsByTagName("docID").item(0).getTextContent();
                metaData.put("docID", docID);
                metaData.put("appName", APP_NAME);
                metaData.put(eElement.getTagName(), eElement.getTextContent());

                System.out.println("META DATA MAP: "+ metaData.toString());

        }
      }

    } catch (Exception e) {
        e.printStackTrace();
    }

      return metaData;
 }
</code>```

And the out put is:

```<code>{form=                  2d2c5bf209b79d8b1a1f840ce4ce4030e66a76d6
                        xx.jpg
                        NOOO FORM NAME
                        NO
                        NAME
                        noname@gmail.com
                        2d2c5bf209b79d8b1a1f840ce4ce4030e66a76d6

                , docID=2d2c5bf209b79d8b1a1f840ce4ce4030e66a76d6, appName=VIRGINAUSI, formName=AITSLForm}
</code>```

Tag names are missing in the map except the root element. Please help !

答:
The code above correctly adds 2 entries in the map. The first entry, maps element Form to it's text content (which is the collection of the text content of all it's descendant nodes).

If you want to access the descendant nodes you'll need to use eElement.getChildNodes() and iterate over the NodeList returned.

This might be useful:
Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

Body:
I am reading a dynamic XML file (without any known structure) and putting the relevant tag name and value to a hashmap (ex: metadata<tagName, Value> ).

My issue here is, I can not get the tagName but it only adds the root tagName and all the values of entire xml.

my XML is:

<?xml version="1.0" encoding="UTF-8"?>
            <form kwf="VARA">
                <sec1>
                    <docID>2d2c5bf209b79d8b1a1f840ce4ce4030e66a76d6</docID>
                    <qrCode>xx.jpg</qrCode>
                    <title>NOOO FORM NAME</title>
                    <ELO_VARAFNAME>NO</ELO_VARAFNAME>
                    <ELO_VARALNAME>NAME</ELO_VARALNAME>
                    <ELO_VARAEMAIL>noname@gmail.com</ELO_VARAEMAIL>
                    <ELO_VARAORBEONDOCID>2d2c5bf209b79d8b1a1f840ce4ce4030e66a76d6</ELO_VARAORBEONDOCID>
                </sec1>
            </form>

My Code is:

public static Map<String,String> getMetaDataFromOrbeonXML(File fXmlFile) throws SAXException, ParserConfigurationException, IOException
  {
    Map metaData = new HashMap();
    String formName="";
    String docID = "";
    try {

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

       doc.getDocumentElement().normalize();

       System.out.println("Root element :" +        doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("form");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);
        System.out.println("\nCurrent Element :" + nNode.getNodeName());

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
              Element eElement = (Element) nNode;

             docID = eElement.getElementsByTagName("docID").item(0).getTextContent();
                metaData.put("docID", docID);
                metaData.put("appName", APP_NAME);
                metaData.put(eElement.getTagName(), eElement.getTextContent());

                System.out.println("META DATA MAP: "+ metaData.toString());

        }
      }

    } catch (Exception e) {
        e.printStackTrace();
    }

      return metaData;
 }

And the out put is:

{form=                  2d2c5bf209b79d8b1a1f840ce4ce4030e66a76d6
                        xx.jpg
                        NOOO FORM NAME
                        NO
                        NAME
                        noname@gmail.com
                        2d2c5bf209b79d8b1a1f840ce4ce4030e66a76d6

                , docID=2d2c5bf209b79d8b1a1f840ce4ce4030e66a76d6, appName=VIRGINAUSI, formName=AITSLForm}

Tag names are missing in the map except the root element. Please help !


问:
TFS 2017 Query Related Items In Build upon release
I've received a request to create a custom report email for our executives. When we do a major release they want a list of Features of that release. What i need to do is read the related Tasks to the release then traverse up parent nodes until i get to the features that are marked with a tag "Executive". My Issue is that I can't find any document on how get the "Work items linked to associated changes".
I've been able to just through to get the specific build
GET http://XXX.MYTFSSERVER.COM/tfs/Collection/Project/e5e632e2-ae70-41c9-9d72-6686d2375f14/_apis/build/Builds/69330

But I don't see any link to get the workitems associated to the build.

答:
There isn't any build-in way to achieve this such as through TFS work item query. You need to build a extension to get all work items of specific release and filter them later.

The steps to achieve that with extension:

Get specify release to get build id

Get work items of that build per build id

Get related work items

Filter the work items which you actually need

A detail simple code of extension to get work items of specific release that you can refer to this link: TFS 2017 Release Management: How to display parent PBI for Tasks under Release


问:
Showing only values which are larger than the user entered value in C#

Question

After finishing this product order manager, I was tasked with adding a feature which lets the user enter a double value, which once entered, will only show the products with prices greater than the chosen value.

I am lost on how I should begin to add this extra option to allow for the filtering of data based on what the user enters.

If someone could point me in the correct direction, I would be ever so thankful!

ConsoleView.cs

```<code>class ConsoleView
{
    public int ShowMenu()
    {
        Console.WriteLine("_________Menu________");
        Console.WriteLine("1) Add Orders");
        Console.WriteLine("2) See all orders");
        Console.WriteLine("3) Filter Orders");
        Console.WriteLine("4) exit");
        Console.WriteLine("______________________");
        Console.WriteLine("Please enter a selection (1-4):");

        return Convert.ToInt32(Console.ReadLine());
    }

    public Order AddOrder()
    {
        Console.WriteLine("What is the name of the product?");
        string name = Console.ReadLine();
        Console.WriteLine("What is the amount paid for the product?");
        double value = Convert.ToDouble(Console.ReadLine());

        return new Order(name, value);
    }

    public void DisplayAllOrders(Order[] orders)
    {
        Console.WriteLine("___________ORDERS_____________");
        for (int i = 0; i< orders.Length; i++)
        {

            Console.WriteLine("Product Name: " + orders[i].GetOrders() + " - Amount Paid - " + orders[i].GetAmount());
        }
        Console.WriteLine("______________________________");
    }

    public void FilterOrder(Order filter)
    {
        Console.WriteLine("What numerical value would you like the information to be greater than?");
        double Value = Convert.ToInt32(Console.ReadLine());

    }

}
</code>```

Order.cs

```<code>class Order
{

    private string orderName;
    private double orderAmount;

    public Order(string ProductName, double Price)
    {
        SetName(ProductName);
        SetAmount(Price);
    }

    public void SetName(string name)
    {
        orderName = name;
    }

    public string GetOrders()
    {
        return orderName;
    }

    public void SetAmount(double value)
    {
        orderAmount = value;
    }

    public double GetAmount()
    {
        return orderAmount;
    }

    public static void FilterPrices(double userNum)
    {
        int largeNum = priceArray[0];
    }
}
</code>```

OrderManager.cs

```<code>class OrderManager
{
    private List<Order> orders;

    public OrderManager()
    {
        orders = new List<Order>();
    }

    public void AddOrder(Order order)
    {
        orders.Add(order);

    }

   public void setAmount(Order amount)
    {
        orders.Add(amount);
    }

    public Order[] GetOrder()
    {
        return orders.ToArray();
    }
}
</code>```

Program.cs

```<code>static void Main(string[] args)
{
    ConsoleView view = new ConsoleView();
    OrderManager model = new OrderManager();
    int userSelection;

    do
    {
        userSelection = view.ShowMenu();
        if (userSelection == 1)
        {
            //Add orders

            model.AddOrder(view.AddOrder());
        }

        else if (userSelection == 2)
        {
            //Display Orders

            view.DisplayAllOrders(model.GetOrder());
        }
        else if (userSelection == 3)
        {
            //Filter Orders
            model.FilterOrder
        }
    }
    while (userSelection != 4);
</code>```

答:
try this:</p>

```<code>public void FilterOrder(Order filter)
{
    Console.WriteLine("What numerical value would you like the information to be greater than?");
    double Value = Convert.ToInt32(Console.ReadLine());
    for (int i = 0; i< orders.Length; i++)
    {
       if(orders.get(i).GetAmount()>Value){
           //print orders.get(i) here
        }

    }

}
</code>```

Body:
Question

After finishing this product order manager, I was tasked with adding a feature which lets the user enter a double value, which once entered, will only show the products with prices greater than the chosen value.

I am lost on how I should begin to add this extra option to allow for the filtering of data based on what the user enters.

If someone could point me in the correct direction, I would be ever so thankful!

ConsoleView.cs

class ConsoleView
{
    public int ShowMenu()
    {
        Console.WriteLine("_________Menu________");
        Console.WriteLine("1) Add Orders");
        Console.WriteLine("2) See all orders");
        Console.WriteLine("3) Filter Orders");
        Console.WriteLine("4) exit");
        Console.WriteLine("______________________");
        Console.WriteLine("Please enter a selection (1-4):");

        return Convert.ToInt32(Console.ReadLine());
    }

    public Order AddOrder()
    {
        Console.WriteLine("What is the name of the product?");
        string name = Console.ReadLine();
        Console.WriteLine("What is the amount paid for the product?");
        double value = Convert.ToDouble(Console.ReadLine());

        return new Order(name, value);
    }

    public void DisplayAllOrders(Order[] orders)
    {
        Console.WriteLine("___________ORDERS_____________");
        for (int i = 0; i< orders.Length; i++)
        {

            Console.WriteLine("Product Name: " + orders[i].GetOrders() + " - Amount Paid - " + orders[i].GetAmount());
        }
        Console.WriteLine("______________________________");
    }

    public void FilterOrder(Order filter)
    {
        Console.WriteLine("What numerical value would you like the information to be greater than?");
        double Value = Convert.ToInt32(Console.ReadLine());

    }

}

Order.cs

class Order
{

    private string orderName;
    private double orderAmount;

    public Order(string ProductName, double Price)
    {
        SetName(ProductName);
        SetAmount(Price);
    }

    public void SetName(string name)
    {
        orderName = name;
    }

    public string GetOrders()
    {
        return orderName;
    }

    public void SetAmount(double value)
    {
        orderAmount = value;
    }

    public double GetAmount()
    {
        return orderAmount;
    }

    public static void FilterPrices(double userNum)
    {
        int largeNum = priceArray[0];
    }
}

OrderManager.cs

class OrderManager
{
    private List<Order> orders;

    public OrderManager()
    {
        orders = new List<Order>();
    }

    public void AddOrder(Order order)
    {
        orders.Add(order);

    }

   public void setAmount(Order amount)
    {
        orders.Add(amount);
    }

    public Order[] GetOrder()
    {
        return orders.ToArray();
    }
}

Program.cs

static void Main(string[] args)
{
    ConsoleView view = new ConsoleView();
    OrderManager model = new OrderManager();
    int userSelection;

    do
    {
        userSelection = view.ShowMenu();
        if (userSelection == 1)
        {
            //Add orders

            model.AddOrder(view.AddOrder());
        }

        else if (userSelection == 2)
        {
            //Display Orders

            view.DisplayAllOrders(model.GetOrder());
        }
        else if (userSelection == 3)
        {
            //Filter Orders
            model.FilterOrder
        }
    }
    while (userSelection != 4);

Body:
try this:

public void FilterOrder(Order filter)
{
    Console.WriteLine("What numerical value would you like the information to be greater than?");
    double Value = Convert.ToInt32(Console.ReadLine());
    for (int i = 0; i< orders.Length; i++)
    {
       if(orders.get(i).GetAmount()>Value){
           //print orders.get(i) here
        }

    }

}


问:
Function that transforms a list in a list of dictionary
I have to make a function whose purpose is taking in parameter a list.

Such as this one :

```<code>['music', ' extension=mp3', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', 'games', ' name_contains=SC2,Wesnoth', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']
</code>```

And return a list similar to this :

```<code>data_config = [{'music' : {'extension':'mp3'}}, {'reports/INFOB131': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB131', 'max_size':100000}}, {'reports/INFOB132': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB132', 'max_size':100000}}]
</code>```

So I made that function :

```<code>def my_function(list_in_question, my_config_list =[], prev_list = []):
    """ """
    enumerated_list = list(enumerate(list_in_question))

    if not '=' in enumerated_list[0][1]:
        main_key = enumerated_list[0][1]# référencé avant assignement
        pre_dict = {main_key : {}}

        for i in enumerated_list[1:]:

            if '=' in i[1] :
                splitted = i[1].split('=')
                prev_list.append({splitted[0] : splitted[1]})

            elif not '=' in i[1] and i[1] != main_key:
                for j in prev_list:
                    pre_dict[main_key].update(j)

                my_config_list.append(pre_dict)

                return my_function(list_in_question[i[0]:])

            elif not '=' in i[1] and i[1] == main_key and main_key!= enumerated_list[0][1]:
                return my_config_list
    else:
        print("The format of the file containig the data in not adequate !")
</code>```

But I don't understand why when I execute it this way :

```<code>new_lines = ['music', ' extension=mp3', '', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', '', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', '', 'games', ' name_contains=SC2,Wesnoth', '', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', '', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']

my_function(new_lines)
</code>```

I end up with this output...

```<code>None
</code>```

I would be very grateful if someone could help me,

Thank you !

PS : If anyone have an idea of how I could do without loop and do it in a recursive way, it would be awesome !

Everyone... Thank you !!! You really hepled me, all your answers are awesome, I have some issues to understand some parts so I'll be annoying just a little longer with some questions of you code. Anyway, thank you for the time you took to help me, you were all more than great help !!!

答:
You need to traverse the list one time. The pattern is this:

Start an empty list (let's call it new_list)

You find an element in the original list (original_list).

If it does not contain '=', you create a new dictionary in the new_list

If it contains the '=' sign, split the element into k and v (before and after the '='), and in the last entry in the new_list, for the only key, you add a key-value pair

```<code>def parse_list(original_list):
    new_list=[]

    for element in original_list:
        if not '=' in element:
            new_list.append({element:{}})
        else:
            k,w=element.split('=')
            new_list[-1][new_list[-1].keys()[0]][k]=w
    return new_list

new_lines = ['music', ' extension=mp3', '', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', '', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', '', 'games', ' name_contains=SC2,Wesnoth', '', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', '', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']

parse_list(new_lines)
</code>```

Now I should explain the line before the return statement:

new_list[-1] is the dictionary corresponding to the last entry without an equal sign that was found in the original_list. After the first pass through the loop,

new_list=[{'music': {}}]

during the second pass

new_list[-1]={'music': {}}

new_list[-1].keys()=['music']

new_list[-1].keys()[0]='music'

new_list[-1][new_list[-1].keys()[0]]={}

now you just update this dictionary with the parsed k,w pair

Body:
I have to make a function whose purpose is taking in parameter a list.

Such as this one :

['music', ' extension=mp3', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', 'games', ' name_contains=SC2,Wesnoth', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']

And return a list similar to this :

data_config = [{'music' : {'extension':'mp3'}}, {'reports/INFOB131': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB131', 'max_size':100000}}, {'reports/INFOB132': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB132', 'max_size':100000}}]

So I made that function :

def my_function(list_in_question, my_config_list =[], prev_list = []):
    """ """
    enumerated_list = list(enumerate(list_in_question))

    if not '=' in enumerated_list[0][1]:
        main_key = enumerated_list[0][1]# référencé avant assignement
        pre_dict = {main_key : {}}

        for i in enumerated_list[1:]:

            if '=' in i[1] :
                splitted = i[1].split('=')
                prev_list.append({splitted[0] : splitted[1]})

            elif not '=' in i[1] and i[1] != main_key:
                for j in prev_list:
                    pre_dict[main_key].update(j)

                my_config_list.append(pre_dict)

                return my_function(list_in_question[i[0]:])

            elif not '=' in i[1] and i[1] == main_key and main_key!= enumerated_list[0][1]:
                return my_config_list
    else:
        print("The format of the file containig the data in not adequate !")

But I don't understand why when I execute it this way :

new_lines = ['music', ' extension=mp3', '', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', '', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', '', 'games', ' name_contains=SC2,Wesnoth', '', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', '', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']

my_function(new_lines)

I end up with this output...

None

I would be very grateful if someone could help me,

Thank you !

PS : If anyone have an idea of how I could do without loop and do it in a recursive way, it would be awesome !

Everyone... Thank you !!! You really hepled me, all your answers are awesome, I have some issues to understand some parts so I'll be annoying just a little longer with some questions of you code. Anyway, thank you for the time you took to help me, you were all more than great help !!!

Body:
You need to traverse the list one time. The pattern is this:

Start an empty list (let's call it new_list)

You find an element in the original list (original_list).

If it does not contain '=', you create a new dictionary in the new_list

If it contains the '=' sign, split the element into k and v (before and after the '='), and in the last entry in the new_list, for the only key, you add a key-value pair

def parse_list(original_list):
    new_list=[]

    for element in original_list:
        if not '=' in element:
            new_list.append({element:{}})
        else:
            k,w=element.split('=')
            new_list[-1][new_list[-1].keys()[0]][k]=w
    return new_list

new_lines = ['music', ' extension=mp3', '', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', '', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', '', 'games', ' name_contains=SC2,Wesnoth', '', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', '', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']

parse_list(new_lines)

Now I should explain the line before the return statement:

new_list[-1] is the dictionary corresponding to the last entry without an equal sign that was found in the original_list. After the first pass through the loop,

new_list=[{'music': {}}]

during the second pass

new_list[-1]={'music': {}}

new_list[-1].keys()=['music']

new_list[-1].keys()[0]='music'

new_list[-1][new_list[-1].keys()[0]]={}

now you just update this dictionary with the parsed k,w pair


问:
Google sample BluetoothAdvertisements not detecting advertisements
I have a BLE wearable (running on Tizen 3.0) sending out BLE advertisements. The advertisements get immediately detected by the Nordic nRF Android App.

However, the BluetoothAdvertisements Google sample app detects none.

In ScannerFragment.buildScanFilters(), I did set the filters to see all BLE devices around.

The platform is Android 8.1.0 on Google Pixel.

Any suggestions will be greatly appreciated.

]
]

答: Solution: request the location permissions during runtime</p>


问:
Disable "Break Mode" page in VS2015
Recently migrated from VS2010 to 2015.  Now when I pause a running app to work on it, I get this very annoying "Break Mode" page with "The application is in break mode".  Well, no shoot Sherlock, I pressed pause.  I know its in break mode.  The page is annoying and takes me away from the code I was going to work on completely unnecessarily.

I didn't get this annoying page in 2010.  I may have some setting switched back then on 2010 but too long to remember.

Is there a way to disable this silly break mode page in VS2015?

答:
I had this annoying problem, too and did not realise, that i turned the Exception Settings to "Break on all exceptions". Then there where some Exceptions in external Code, where the debugger stopped, but I could not see the code, as it was in a Framework. Pretty annoying.

To reset Exception Settings in VS2017:

```<code>ctrl+al+e -> right click on the opening window -> reset to defaults
</code>```

Maybe this helps someone =)

Title: Disable "Break Mode" page in VS2015

Body:
I had this annoying problem, too and did not realise, that i turned the Exception Settings to "Break on all exceptions". Then there where some Exceptions in external Code, where the debugger stopped, but I could not see the code, as it was in a Framework. Pretty annoying.

To reset Exception Settings in VS2017:

ctrl+al+e -> right click on the opening window -> reset to defaults

Maybe this helps someone =)


问:
How can I change the position of Bootstrap 4 popovers?
I'm trying to align Bootstrap 4 popovers on the left or right side of their parent button. I know that I could achieve it by using "offset", but that would mean I'd have to set a different offset value for each button as those are never the same width.

Is there some way to utilize popper.js (which BS is using for positioning) to achieve that alignment, instead of always centering the popover?

For reference, this is the result I'm looking for

答:
After messing around with it for a while I figured out I can achieve what I want by using the offset since it does not only accept pixel values, but also % relative to the parent object.

So I'm just doing:

```<code>data-offset="-50%"
</code>```

Body:
After messing around with it for a while I figured out I can achieve what I want by using the offset since it does not only accept pixel values, but also % relative to the parent object.

So I'm just doing:

data-offset="-50%"


问:
Overflow: scroll not working in a specific column grid with Bootstrap 4
I have 3 columns in my main tag (). The first column has a table with many rows. I want that column to be vertically scrollable while staying stretched between the header and the footer.
I added in my css :

```<code>#please-scroll{
  height: calc(100% - 110px); overflow-y: scroll
}
</code>```

But it doesn't work.

Here is my code :

html {
  height: 100%;
  font-family: sans-serif;
  background: #1F1F1F !important; }

body {
  font-family: sans-serif;
  background-color: #1F1F1F;
  height: 100%; }

.container {
  min-height: calc(100% - 110px) !important;
  margin: 0 auto -33px;
  width: 100%; }

body > .container {
  padding: 60px 15px 0; }

.nav-item .nav-link span {
  border-radius: 10px;
  border: 2px solid;
  padding: 3px;
  font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif;
  font-size: 12px; }

#please-scroll{
  height: calc(100% - 110px); overflow-y: scroll
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<!-- Latest compiled and minified Bootstrap CSS -->
<head>
    <title>My Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

</head>
<body style="overflow-y:hidden;">
<header>
    <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse fixed-top" style="border-bottom: 1px solid #353738">
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

            My Logo

    </nav>
</header>

<!-- Begin page content -->

<main role="main" class="container" >
    <div class="row " style=" min-height: 100vh;">
        <div class="col-sm-12 col-md-3 " id="please-scroll" style="background: #292b2c; border-right: 1px solid #353738; ">
            <table style=" color: #636c72;">
                <thead>
                <tr>
                    <th>Firstname</th>
                    <th>Lastname</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td>John</td>
                    <td>Doe</td>
                </tr>
                <tr>
                    <td>Mary</td>
                    <td>Moe</td>
                </tr>
                <tr>
                    <td>July</td>
                    <td>Dooley</td>
                </tr>
                <tr>
                    <td>John</td>
                    <td>Doe</td>
                </tr>
                <tr>
                    <td>Mary</td>
                    <td>Moe</td>
                </tr>
                <tr>
                    <td>July</td>
                    <td>Dooley</td>
                </tr>  <tr>
                    <td>John</td>
                    <td>Doe</td>
                </tr>
                <tr>
                    <td>Mary</td>
                    <td>Moe</td>
                </tr>
                <tr>
                    <td>July</td>
                    <td>Dooley</td>
                </tr>  <tr>
                    <td>John</td>
                    <td>Doe</td>
                </tr>
                <tr>
                    <td>Mary</td>
                    <td>Moe</td>
                </tr>
                <tr>
                    <td>July</td>
                    <td>Dooley</td>
                </tr>  <tr>
                    <td>John</td>
                    <td>Doe</td>
                </tr>
                <tr>
                    <td>Mary</td>
                    <td>Moe</td>
                </tr>
                <tr>
                    <td>July</td>
                    <td>Dooley</td>
                </tr>  <tr>
                    <td>John</td>
                    <td>Doe</td>
                </tr>
                <tr>
                    <td>Mary</td>
                    <td>Moe</td>
                </tr>
                <tr>
                    <td>July</td>
                    <td>Dooley</td>
                </tr>  <tr>
                    <td>John</td>
                    <td>Doe</td>
                </tr>
                <tr>
                    <td>Mary</td>
                    <td>Moe</td>
                </tr>
                <tr>
                    <td>July</td>
                    <td>Dooley12</td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="col-sm-12 col-md-5" style=" min-height: 100vh;">col</div>
        <div class="col-sm-12 col-md-4" style=" min-height: 100vh;">col</div>
    </div>
</main>

<footer style="">

    <nav class="navbar navbar-toggleable-md navbar-inverse fixed-bottom bg-inverse" style="height: 10%; border-top: 1px solid #353738 ">

    </nav>
</footer>

<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script><!-- Initialize Bootstrap functionality -->
<script>
    // Initialize tooltip component
    $(function () {
        $('[data-toggle="tooltip"]').tooltip()
    })

    // Initialize popover component
    $(function () {
        $('[data-toggle="popover"]').popover()
    })
</script>
</body>
</html></code>```

Please help!

答:
Try replacing CSS for #please-scroll::</p>

```<code>#please-scroll{
  height: calc(100vh - 110px);
  overflow-y: scroll;
}
</code>```

Body:
I have 3 columns in my main tag (). The first column has a table with many rows. I want that column to be vertically scrollable while staying stretched between the header and the footer.
I added in my css :

#please-scroll{
  height: calc(100% - 110px); overflow-y: scroll
}

But it doesn't work.

Here is my code :

html {
  height: 100%;
  font-family: sans-serif;
  background: #1F1F1F !important; }

body {
  font-family: sans-serif;
  background-color: #1F1F1F;
  height: 100%; }

.container {
  min-height: calc(100% - 110px) !important;
  margin: 0 auto -33px;
  width: 100%; }

body > .container {
  padding: 60px 15px 0; }

.nav-item .nav-link span {
  border-radius: 10px;
  border: 2px solid;
  padding: 3px;
  font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif;
  font-size: 12px; }

#please-scroll{
  height: calc(100% - 110px); overflow-y: scroll
}

<!DOCTYPE html>

    <title>My Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

        </button>

            My Logo

                    Firstname
                    Lastname

                    John
                    Doe

                    Mary
                    Moe

                    July
                    Dooley

                    John
                    Doe

                    Mary
                    Moe

                    July
                    Dooley

                    John
                    Doe

                    Mary
                    Moe

                    July
                    Dooley

                    John
                    Doe

                    Mary
                    Moe

                    July
                    Dooley

                    John
                    Doe

                    Mary
                    Moe

                    July
                    Dooley

                    John
                    Doe

                    Mary
                    Moe

                    July
                    Dooley

                    John
                    Doe

                    Mary
                    Moe

                    July
                    Dooley12

col

col

Please help!

Body:
Try replacing CSS for #please-scroll::

#please-scroll{
  height: calc(100vh - 110px);
  overflow-y: scroll;
}


问:
Meteor change database at run time
I have three database i.e, main_db it is default load database. I want load database after login.
Database are:-

main_db

->user_collection

psm_2017_db

->abc_collection

->xyz_collection

psm_2018_db

->abc_collection

->xyz_collection

Here is my project structure

here is my login script.

```<code>client
 |->login
  |->login.js

            Template.login.rendered = function(){
            SessionStore.set("login_user",false);
            };
            Template.login.events({
                'submit #formLogin': function (event, target){
                    event.preventDefault();
                    var email = target.find('#loginEmail').value;
                    var password = target.find('#loginPassword').value;
                    // console.log(email +" "+password);
                    Meteor.loginWithPassword(email, password, function(err){

                        if(err){
                        console.log(err);
                            alert("Invalid Login!");
                        }
                        else {
                        SessionStore.set("login_user",true);
                            console.log('successfully')
                            Router.go("/dashboard")
                        }
                    });
                }
            });

            Template.layout.helpers({
            "isLoggedin": function () {
                return SessionStore.get("login_user");
            }
            });
</code>```

here is my load collection file

```<code>lib
 |->collection.js

     abcCollection=new Mongo.Collection("abc_collection");
     xyzCollection=new Mongo.Collection("xyz_collection");
</code>```

答:
You can connect to multiple dbs using the below approach.

```<code>var database = new MongoInternals.RemoteCollectionDriver("<<mongo url>>");
MyCollection = new Mongo.Collection("collection_name", { _driver: database });
</code>```

<<mongo_url>> is your standard mongodb url.
Eg. mongodb://127.0.0.1:27017/database_name

Now, in your specific scenario, main_db contains the user collection (I'm under the assumption that this is pertaining to meteor user collection). You need to have this loaded at all times. You can't have it load after login since user information - which is required for logging in resides in that db!

Once you take care of the above, connecting to the remaining two dbs can be done on login as below:

/lib/dbconnection.js (this will be common to both server and clinet)

```<code>Meteor.methods({
    loadDB: function(){

        if(Meteor.userId()){ // if a user has logged in

            var database = new MongoInternals.RemoteCollectionDriver("<<mongo url>>");
            MyCollection = new Mongo.Collection("collection_name", { _driver: database });

        }

    }
})
Meteor.call("loadDB");
</code>```

loadDB will get called each time a user logs in. But I fear that it will be run each time any user logs in. In order to avoid it being re-initialized for each user login, you might want to do a check on  whether database or myCollection already exists.

Title: Meteor change database at run time

Body:
I have three database i.e, main_db it is default load database. I want load database after login.
Database are:-

main_db

->user_collection

psm_2017_db

->abc_collection

->xyz_collection

psm_2018_db

->abc_collection

->xyz_collection

Here is my project structure

here is my login script.

client
 |->login
  |->login.js

            Template.login.rendered = function(){
            SessionStore.set("login_user",false);
            };
            Template.login.events({
                'submit #formLogin': function (event, target){
                    event.preventDefault();
                    var email = target.find('#loginEmail').value;
                    var password = target.find('#loginPassword').value;
                    // console.log(email +" "+password);
                    Meteor.loginWithPassword(email, password, function(err){

                        if(err){
                        console.log(err);
                            alert("Invalid Login!");
                        }
                        else {
                        SessionStore.set("login_user",true);
                            console.log('successfully')
                            Router.go("/dashboard")
                        }
                    });
                }
            });

            Template.layout.helpers({
            "isLoggedin": function () {
                return SessionStore.get("login_user");
            }
            });

here is my load collection file

lib
 |->collection.js

     abcCollection=new Mongo.Collection("abc_collection");
     xyzCollection=new Mongo.Collection("xyz_collection");

Body:
You can connect to multiple dbs using the below approach.

var database = new MongoInternals.RemoteCollectionDriver("<<mongo url>>");
MyCollection = new Mongo.Collection("collection_name", { _driver: database });

<<mongo_url>> is your standard mongodb url.
Eg. mongodb://127.0.0.1:27017/database_name

Now, in your specific scenario, main_db contains the user collection (I'm under the assumption that this is pertaining to meteor user collection). You need to have this loaded at all times. You can't have it load after login since user information - which is required for logging in resides in that db!

Once you take care of the above, connecting to the remaining two dbs can be done on login as below:

/lib/dbconnection.js (this will be common to both server and clinet)

Meteor.methods({
    loadDB: function(){

        if(Meteor.userId()){ // if a user has logged in

            var database = new MongoInternals.RemoteCollectionDriver("<<mongo url>>");
            MyCollection = new Mongo.Collection("collection_name", { _driver: database });

        }

    }
})
Meteor.call("loadDB");

loadDB will get called each time a user logs in. But I fear that it will be run each time any user logs in. In order to avoid it being re-initialized for each user login, you might want to do a check on  whether database or myCollection already exists.


问:
Vuejs warning: infinite update loop in a component render function
working through my first project in vue js.
Here, looping through different tabs and show correct content for each tab when clicked on.

https://codepen.io/anon/pen/vWPMGq?editors=1010

problem here is with line
this.cardData = $(".card-content").html(this.coinInfo[this.activeTabName]);
but I'm not sure how to fix this.

答:
You shouldn't be mixing jquery and Vue if it's not 100% necessary.

Here a simple way to do it:

https://jsfiddle.net/gmmujLs4/2/

HTML

```<code><div id="root">
    <div class="navbar-start" v-for="tab in tabs">
        <a class="navbar-item" href="#" @click="activeTabName = tab.name">{{tab.name}}</a>
    </div>
    <div class="card-content">
        {{ coinInfo[activeTabName] }}
    </div>
</div>
</code>```

Vue instance

```<code>new Vue({
    el: '#root',
    data: {
        activeTabName: 'Description',
        tabs: [
            {
                name: 'Description',
            },
            {
                name: 'Features',
            },
            {
                name: 'Technology',
            }
        ],
        coinInfo: {
            Description:'DescriptionContent',
            Features:'FeaturesContent',
            Technology:'TechnologyContent'
        }
    }
 })
</code>```

coinInfo could be passed by properties instead of beeing declared as data.

Body:
You shouldn't be mixing jquery and Vue if it's not 100% necessary.

Here a simple way to do it:

https://jsfiddle.net/gmmujLs4/2/

HTML

<div id="root">
    <div class="navbar-start" v-for="tab in tabs">
        <a class="navbar-item" href="#" @click="activeTabName = tab.name">{{tab.name}}</a>
    </div>
    <div class="card-content">
        {{ coinInfo[activeTabName] }}
    </div>
</div>

Vue instance

new Vue({
    el: '#root',
    data: {
        activeTabName: 'Description',
        tabs: [
            {
                name: 'Description',
            },
            {
                name: 'Features',
            },
            {
                name: 'Technology',
            }
        ],
        coinInfo: {
            Description:'DescriptionContent',
            Features:'FeaturesContent',
            Technology:'TechnologyContent'
        }
    }
 })

coinInfo could be passed by properties instead of beeing declared as data.


问:
Implementing logical negation with only bitwise operators (except !)
~ & ^ | + << >> are the only operations I can use

Before I continue, this is a homework question, I've been stuck on this for a really long time.

My original approach: I thought that !x could be done with two's complement and doing something with it's additive inverse.   I know that an xor is probably in here but I'm really at a loss how to approach this.

For the record: I also cannot use conditionals, loops, ==, etc, only the functions (bitwise) I mentioned above.

For example:

```<code>!0 = 1
!1 = 0
!anything besides 0 = 0
</code>```

Body:
~ & ^ | + << >> are the only operations I can use

Before I continue, this is a homework question, I've been stuck on this for a really long time.

My original approach: I thought that !x could be done with two's complement and doing something with it's additive inverse.   I know that an xor is probably in here but I'm really at a loss how to approach this.

For the record: I also cannot use conditionals, loops, ==, etc, only the functions (bitwise) I mentioned above.

For example:

!0 = 1
!1 = 0
!anything besides 0 = 0

Body:
Assuming e.g. an 8-bit unsigned type:

~(((x >> 0) & 1)
| ((x >> 1) & 1)
| ((x >> 2) & 1)
...
| ((x >> 7) & 1)) & 1


问:
How to get last executed query Yii
How to get Last executed query after  model save, update, delete in yii.

i.e:

```<code>$model->save();
</code>```

like $this->db->last_query(); in CI

Thanks

答: The simplest way to show last executed query is to make an sql error in that query! :p Give an invalid column name in query, then Yii error reporting will show that query as error, but you can see that query.</p>

Title: How to get last executed query Yii

Body:
How to get Last executed query after  model save, update, delete in yii.

i.e:

$model->save();

like $this->db->last_query(); in CI

Thanks


问:
C2386: 'void_t': a symbol with this name already exists in the current scope
I'm working on a Qt project which is intended to be built on Windows and on Linux. As a build system I use CMake with GCC 5.4 on Ubuntu 16.04 and with Visual Studio 2017 on Windows 10. Because the currently used standard is c++14 but I wanted to use the convenience type std::void_t I defined it as follows:

#if __cplusplus >= 201703L
#include <type_traits>
#else
namespace std {
template<typename... Ts> struct make_void { typedef void type; };
template<typename... Ts> using void_t = typename make_void<Ts...>::type;
}
#endif
```

<p>The definition above is working fine if I build the project under Linux with the mentioned compiler, but when I try to build it under Windows I receive the following error messages:</p>

<pre class="lang-none prettyprint-override"><code>C2386: 'void_t': a symbol with this name already exists in the current scope
U1077: 'C:\PROGRA~2\MICROS~4\2017\ENTERP~1\VC\Tools\MSVC\1411~1.255\bin\HostX64\x64\cl.exe' : return code '0x2'
U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\bin\HostX64\x64\nmake.exe"' : return code '0x2'
U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\bin\HostX64\x64\nmake.exe"' : return code '0x2'
</code>```

The top-level CMake file sets the C++ standard as follows:

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
```

I don't understand why does Visual Studio 2017 complain for the std::void_t when the standard is set to c++14. Is this a normal behaviour and I expect it incorrectly that polluting the std namespace in the shown way won't cause errors? How can I overcome these errors produced by the Visual Studio 2017?

Edit: I just noticed that relying on the value of predefined macro __cplusplus may cause unexpected results. This question also aims to the __cplusplus macro.

答:
The CMAKE_CXX_STANDARD option currently has limited effect on Visual Studio.

Unlike gcc or clang, which offer the -std command line switches for specifying the requested version of the Standard, Visual C++ used to always give you all the latest features at once. Only with the 2015 version (Update 3) did they introduce a /std option that is intended to provide an opt-in mechanism for newer language features.

Unfortunately, this is not as mature yet as the gcc or clang equivalents, so you might still get features that you would not have expected.

Body:
I'm working on a Qt project which is intended to be built on Windows and on Linux. As a build system I use CMake with GCC 5.4 on Ubuntu 16.04 and with Visual Studio 2017 on Windows 10. Because the currently used standard is c++14 but I wanted to use the convenience type std::void_t I defined it as follows:

#if __cplusplus >= 201703L
#include <type_traits>
#else
namespace std {
template<typename... Ts> struct make_void { typedef void type; };
template<typename... Ts> using void_t = typename make_void<Ts...>::type;
}
#endif

The definition above is working fine if I build the project under Linux with the mentioned compiler, but when I try to build it under Windows I receive the following error messages:

C2386: 'void_t': a symbol with this name already exists in the current scope
U1077: 'C:\PROGRA~2\MICROS~4\2017\ENTERP~1\VC\Tools\MSVC\1411~1.255\bin\HostX64\x64\cl.exe' : return code '0x2'
U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\bin\HostX64\x64\nmake.exe"' : return code '0x2'
U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\bin\HostX64\x64\nmake.exe"' : return code '0x2'

The top-level CMake file sets the C++ standard as follows:

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

I don't understand why does Visual Studio 2017 complain for the std::void_t when the standard is set to c++14. Is this a normal behaviour and I expect it incorrectly that polluting the std namespace in the shown way won't cause errors? How can I overcome these errors produced by the Visual Studio 2017?

Edit: I just noticed that relying on the value of predefined macro __cplusplus may cause unexpected results. This question also aims to the __cplusplus macro.


问:
How to get Kubernetes UI in localmachine?
I have a kubernetes cluster running in azure on 3 centos7 machines. I'm treating those machines as a bare-metal cluster to do some test. I'm using kubeadm for spinning the cluster. Now my question is how can I see the kubernetes UI in my localmachine for the cluster running in azure private n/w. I have the cluster running and nodes registered which I can see in centos7 terminal by running "kubectl get-nodes".

Any insights would be helpful, please shed some light on how to get that work.

Thx,
Arun

答:
You have a cluster up and running.Now if you want to access the kubernetes-dashboard which is part of kube-system namespaces.Apply following commands to access the dashboard.

```<code>kubectl get pods -n kube-system
</code>```

You will copy the name of the pod of kubernetes-dashboard and replace it with the following command

```<code> kubectl -n kube-system port-forward NAME-OF-k8s-Dashboard-POD 9090:9090
</code>```

It will create TCP-Proxy and you can access it on http://localhost:9090

There is another way to access the dashboard

you can use following command

```<code>kubectl proxy --port=8001
</code>```

Now you can access it on
 http://localhost:8001/ui

Body:
You have a cluster up and running.Now if you want to access the kubernetes-dashboard which is part of kube-system namespaces.Apply following commands to access the dashboard.

kubectl get pods -n kube-system

You will copy the name of the pod of kubernetes-dashboard and replace it with the following command

 kubectl -n kube-system port-forward NAME-OF-k8s-Dashboard-POD 9090:9090

It will create TCP-Proxy and you can access it on http://localhost:9090

There is another way to access the dashboard

you can use following command

kubectl proxy --port=8001

Now you can access it on
 http://localhost:8001/ui


问:
AS 2.0 dynamic Text in Movieclip
I'm using ActionScript 2.0 and I do not have control of dynamic text inside movie clips. I have a movie clip named 'Glass' and dynamic text named 'Glass_ID'
I want Glass_ID Value become Glass_ID01 when clicked the button named 'btn' but it doesn's work
how to i'm solve it?

```<code>on(press){this.Glass.Glass_ID.text ="Glass_ID01"}
</code>```

答:
If "Glass" is not inside the button this won't work, you must set the correct path, eg.

```<code>on(press){_level0.Glass.Glass_ID.text ="Glass_ID01"}
</code>```

or from the timeline:

```<code>btn.onPress = function(){
   _level0.Glass.Glass_ID.text ="Glass_ID01"
}
</code>```

(of course, you should change that _level0 with _root or a container movieclip, whatever applies to your situation).

Disclaimer: last time I used Flash it was 2011!   :-)

Title: AS 2.0 dynamic Text in Movieclip

Body:
I'm using ActionScript 2.0 and I do not have control of dynamic text inside movie clips. I have a movie clip named 'Glass' and dynamic text named 'Glass_ID'
I want Glass_ID Value become Glass_ID01 when clicked the button named 'btn' but it doesn's work
how to i'm solve it?

on(press){this.Glass.Glass_ID.text ="Glass_ID01"}

Body:
If "Glass" is not inside the button this won't work, you must set the correct path, eg.

on(press){_level0.Glass.Glass_ID.text ="Glass_ID01"}

or from the timeline:

btn.onPress = function(){
   _level0.Glass.Glass_ID.text ="Glass_ID01"
}

(of course, you should change that _level0 with _root or a container movieclip, whatever applies to your situation).

Disclaimer: last time I used Flash it was 2011!   :-)


问:
Convert Object To Byte Array without Serialization nor Padding
It seems easy but I can't see it easy at all. My question is I have a struct and I need to convert it to byte stream without any additional bytes for types nor padding nor metadata. Assume I have a struct

```<code>[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
    public ushort a;
    public uint b;
    public uint c;
    public ushort d;
}
</code>```

Remark: I can't change the pack here to 1(Project constrains), so using the following solution won't work as there's a padding added

```<code>int size = Marshal.SizeOf(typeof(T));
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
</code>```

Also Remark: I can't use Binary format serialization as there's a metadata added.  All what I want simply if a=1 b=2 c=3 d=4 to get binary format in a GENERIC WAY as

```<code>    arr {byte[12]}  byte[]
    [0]  1  byte
    [1]  0  byte
    [2]  2  byte
    [3]  0  byte
    [4]  0  byte
    [5]  0  byte
    [6]  3  byte
    [7]  0  byte
    [8]  0  byte
    [9]  0  byte
    [10] 4  byte
    [11] 0  byte
</code>```

Any help?

答:
You can use Explicit layout to define exactly how you want the array to be formed:

```<code>    [StructLayout(LayoutKind.Explicit)]
    public struct MyStruct
    {
        [FieldOffset(0)]
        public ushort a;
        [FieldOffset(2)]
        public uint b;
        [FieldOffset(6)]
        public uint c;
        [FieldOffset(10)]
        public ushort d;
    }
</code>```

But of course its not at all generic

Body:
It seems easy but I can't see it easy at all. My question is I have a struct and I need to convert it to byte stream without any additional bytes for types nor padding nor metadata. Assume I have a struct

[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
    public ushort a;
    public uint b;
    public uint c;
    public ushort d;
}

Remark: I can't change the pack here to 1(Project constrains), so using the following solution won't work as there's a padding added

int size = Marshal.SizeOf(typeof(T));
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);

Also Remark: I can't use Binary format serialization as there's a metadata added.  All what I want simply if a=1 b=2 c=3 d=4 to get binary format in a GENERIC WAY as

    arr {byte[12]}  byte[]
    [0]  1  byte
    [1]  0  byte
    [2]  2  byte
    [3]  0  byte
    [4]  0  byte
    [5]  0  byte
    [6]  3  byte
    [7]  0  byte
    [8]  0  byte
    [9]  0  byte
    [10] 4  byte
    [11] 0  byte

Any help?

Body:
You can use Explicit layout to define exactly how you want the array to be formed:

    [StructLayout(LayoutKind.Explicit)]
    public struct MyStruct
    {
        [FieldOffset(0)]
        public ushort a;
        [FieldOffset(2)]
        public uint b;
        [FieldOffset(6)]
        public uint c;
        [FieldOffset(10)]
        public ushort d;
    }

But of course its not at all generic


问:
cq5/aem url rewriting or mapping dispatcher and apache web server
I am new to cq5/aem url re-writing with selectors. I have the following scenarios to achieve. Could you please help me how to do it.

I need to request an URL such as

```<code>http://localhost:4502/batteries/toyota/corolla/2011/LE/
</code>```

which should convert to

```<code>http://localhost:4502/content/myprojectroot/project1/en/batteries/search-results.toyota.corolla.2011.LE.html
</code>```

using apache web server/dispatcher configuration and cq5/aem (etc/map). Please help me how to achieve this.

答:
Use Rewrite rule as below on your Vhost:

```<code>RewriteRule ^/batteries/toyota/corolla/2011/LE/ /content/myprojectroot/project1/en/batteries/search-results.toyota.corolla.2011.LE.html [R=301,L]
</code>```

Body:
I am new to cq5/aem url re-writing with selectors. I have the following scenarios to achieve. Could you please help me how to do it.

I need to request an URL such as

http://localhost:4502/batteries/toyota/corolla/2011/LE/

which should convert to

http://localhost:4502/content/myprojectroot/project1/en/batteries/search-results.toyota.corolla.2011.LE.html

using apache web server/dispatcher configuration and cq5/aem (etc/map). Please help me how to achieve this.

Body:
Use Rewrite rule as below on your Vhost:

RewriteRule ^/batteries/toyota/corolla/2011/LE/ /content/myprojectroot/project1/en/batteries/search-results.toyota.corolla.2011.LE.html [R=301,L]


问:
Tracing Variables in AS3 is not working
```<code>var a:Number;
var b:Number;

a + b = 17;

trace ("A: "a"       B: "b);
</code>```

Why does this not work? Is there somthing about tracing multiple pieces of information in  the same trace statement in AS3?

答:
In ActionScript 3, the trace method can take many parameters. But they must be comma seperated like any method call. So you could use:</p>

```<code>trace ("A:", a, "B:", b);
</code>```

Title: Tracing Variables in AS3 is not working

Body:
var a:Number;
var b:Number;

a + b = 17;

trace ("A: "a"       B: "b);

Why does this not work? Is there somthing about tracing multiple pieces of information in  the same trace statement in AS3?

Body:
In ActionScript 3, the trace method can take many parameters. But they must be comma seperated like any method call. So you could use:

trace ("A:", a, "B:", b);


问:
PHP Regex replace all instances of a character in similar strings
I have a file that contains a collection strings. All of the strings begin with the same set of characters and end with the same character. I need to find all of the strings that match a certain pattern, and then remove particular characters from them before saving the file. Each string looks like this:

```<code>Data_*: " ... "
</code>```

where Data_ is the same for each string, the asterisk is an incrementing integer that is either two or three digits, and the colon and the double quotation marks are the same for each string. The ... is completely different in every string and it's the part of each I need to work with. I need to remove all double quotation marks from the ... , preserving the enclosing double quotation marks. I don't need to replace them, just remove them.

So for example, I need this...

```<code>Data_83: "He said, "Yes!" to the question"
</code>```

to become this...

```<code>Data_83: "He said, Yes! to the question"
</code>```

I am familiar with PHP and would like to use this. I know how to do something like...

```<code><?php
$filename = 'path/to/file';
$content = file_get_contents($filename);
$new_content = str_replace('"', '', $content);
file_put_contents($filename, $new_content);
</code>```

And I'm pretty sure a regular expression will be what I'm wanting to use to find the strings and remove the extra double quotation marks. But I'm very new to regular expressions and need some help here.

EDIT:

I should have mentioned, the file is a PHP file containing an object. It looks a bit like this:

```<code><?php
$thing = {
    Data_83: "He said, "Yes!" to the question",
    Data_84: "Another string with "unwanted" quotes"
}
</code>```

答:
Not as elegant but you could create a UDF:

```<code>function RemoveNestedQuotes($string)
{
    $firstPart = explode(":", $string)[0];
    preg_match('/"(.*)"/', $string, $matches, PREG_OFFSET_CAPTURE);
    $tmpString = $matches[1][0];
    return $firstPart . ': "' . preg_replace('/"/', '', $tmpString) . '"';
}
</code>```

example:

```<code>$string = 'Data_83: "He said, "Yes!" to the question"';

echo RemoveNestedQuotes($string);

// Data_83: "He said, Yes! to the question"
</code>```

Body:
I have a file that contains a collection strings. All of the strings begin with the same set of characters and end with the same character. I need to find all of the strings that match a certain pattern, and then remove particular characters from them before saving the file. Each string looks like this:

Data_*: " ... "

where Data_ is the same for each string, the asterisk is an incrementing integer that is either two or three digits, and the colon and the double quotation marks are the same for each string. The ... is completely different in every string and it's the part of each I need to work with. I need to remove all double quotation marks from the ... , preserving the enclosing double quotation marks. I don't need to replace them, just remove them.

So for example, I need this...

Data_83: "He said, "Yes!" to the question"

to become this...

Data_83: "He said, Yes! to the question"

I am familiar with PHP and would like to use this. I know how to do something like...

<?php
$filename = 'path/to/file';
$content = file_get_contents($filename);
$new_content = str_replace('"', '', $content);
file_put_contents($filename, $new_content);

And I'm pretty sure a regular expression will be what I'm wanting to use to find the strings and remove the extra double quotation marks. But I'm very new to regular expressions and need some help here.

EDIT:

I should have mentioned, the file is a PHP file containing an object. It looks a bit like this:

<?php
$thing = {
    Data_83: "He said, "Yes!" to the question",
    Data_84: "Another string with "unwanted" quotes"
}

Body:
Not as elegant but you could create a UDF:

function RemoveNestedQuotes($string)
{
    $firstPart = explode(":", $string)[0];
    preg_match('/"(.*)"/', $string, $matches, PREG_OFFSET_CAPTURE);
    $tmpString = $matches[1][0];
    return $firstPart . ': "' . preg_replace('/"/', '', $tmpString) . '"';
}

example:

$string = 'Data_83: "He said, "Yes!" to the question"';

echo RemoveNestedQuotes($string);

// Data_83: "He said, Yes! to the question"


问:
cordovaActivity.appView DownloadListener err
appView is cordovaActivity.appVeiw
DownloadListener is webkit.DownloadListener
I am also using Crosswalk in scenario.

```<code>DownloadListener dl = new DownloadListener() {
  public void onDownloadStart(String url, String userAgent,
  String contentDisposition, String mimetype,
  long contentLength) {
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
    finish();
  }
};
appView.setDownloadListener(dl);
</code>```

it give err while compile

```<code>sample.java:###:  error: cannot find symbol
[javac]         appView.setDownloadListener(dl);
[javac]                     ^
[javac]   symbol:   method setDownloadListener(DownloadListener)
[javac]   location: variable appView of type CordovaWebView
[javac] Note: Some input files use or override a deprecated API.
[javac] Note: Recompile with -Xlint:deprecation for details.
[javac] 1 error
</code>```

Any idea how to resolve this issue?

答:
This code works in cordova 6+</p>

```<code>SystemWebView wv = (SystemWebView) appView.getView();
wv.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
                                 String contentDisposition, String mimetype,
                                 long contentLength) {

        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
        finish();
    }
});
</code>```

Body:
appView is cordovaActivity.appVeiw
DownloadListener is webkit.DownloadListener
I am also using Crosswalk in scenario.

DownloadListener dl = new DownloadListener() {
  public void onDownloadStart(String url, String userAgent,
  String contentDisposition, String mimetype,
  long contentLength) {
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
    finish();
  }
};
appView.setDownloadListener(dl);

it give err while compile

sample.java:###:  error: cannot find symbol
[javac]         appView.setDownloadListener(dl);
[javac]                     ^
[javac]   symbol:   method setDownloadListener(DownloadListener)
[javac]   location: variable appView of type CordovaWebView
[javac] Note: Some input files use or override a deprecated API.
[javac] Note: Recompile with -Xlint:deprecation for details.
[javac] 1 error

Any idea how to resolve this issue?

Body:
This code works in cordova 6+

SystemWebView wv = (SystemWebView) appView.getView();
wv.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
                                 String contentDisposition, String mimetype,
                                 long contentLength) {

        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
        finish();
    }
});


问:
How to make multiple PivotItems visible in Excel VBA
I have a Pivot table in sheet "Main". In PivotField "Report Filter" I have "Country Code" which contain 200 countries. I want to Make visible more than 1 countries from that filter using InputBox.

The problem is I need to choose minimum one country or ALL in filter manually and run this program. I can't get the correct data by doing this.
I need to deselect all the countries and then I need to run.

My Code

```<code>Sub Addcountries()

Dim ws As Worksheet
Dim str1 As Variant
Dim Data As Variant
Dim pf As PivotField
Dim target As PivotTable

Set ws = Sheets("Main")
str1 = Application.InputBox("Enter the Country - comma separated")

If str1 = False Then
    MsgBox "Please Enter one Country", , "Filter Country"
    Exit Sub
Else
    If InStr(1, str1, ",") > 0 Then
        Data = Split(str1, ",")
        For i = LBound(Data) To UBound(Data)
            ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems(Data(i)).Visible = True
        Next i
    Else
        ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems(str1).Visible = True
    End If
End If

End Sub
</code>```

答:
In order for your filter to work you need to give False Visible values to the Pivot Items you don't want to see as well as True Values to the one's you do so that you have set all the Pivot Items to True or False.

Here is some code to give you an idea;

```<code>Sub Addcountries()
    Dim ws As Worksheet
    Dim str1 As Variant
    Dim Data() As Variant
    Dim pf As PivotField
    Dim target As PivotTable
    Dim PivotItem As Object
    Dim ShowMe As Boolean

    Set ws = Sheets("Main")
    str1 = Application.InputBox("Enter the Country - comma separated")

    If str1 = False Then
        MsgBox "Please Enter one Country", , "Filter Country"
        Exit Sub
    Else
        If InStr(1, str1, ",") > 0 Then
            Data = Split(str1, ",")
        Else
            'Make Single Item Array
            ReDim Data(1)
            Data(0) = str1
        End If
        For Each PivotItem In ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems
            'Default Visibility Is False
            ShowMe = False
            For i = LBound(Data) To UBound(Data)
                'Loop Through Each Item In Data To See If You Should ShowMe
                ShowMe = (PivotItem.Name = Data(i))
                If ShowMe Then
                    'Quit Early If You ShowMe
                    Exit For
                End If
            Next i
            PivotItem.Visible = ShowMe
        Next PivotItem
    End If

End Sub
</code>```

Body:
I have a Pivot table in sheet "Main". In PivotField "Report Filter" I have "Country Code" which contain 200 countries. I want to Make visible more than 1 countries from that filter using InputBox.

The problem is I need to choose minimum one country or ALL in filter manually and run this program. I can't get the correct data by doing this.
I need to deselect all the countries and then I need to run.

My Code

Sub Addcountries()

Dim ws As Worksheet
Dim str1 As Variant
Dim Data As Variant
Dim pf As PivotField
Dim target As PivotTable

Set ws = Sheets("Main")
str1 = Application.InputBox("Enter the Country - comma separated")

If str1 = False Then
    MsgBox "Please Enter one Country", , "Filter Country"
    Exit Sub
Else
    If InStr(1, str1, ",") > 0 Then
        Data = Split(str1, ",")
        For i = LBound(Data) To UBound(Data)
            ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems(Data(i)).Visible = True
        Next i
    Else
        ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems(str1).Visible = True
    End If
End If

End Sub

Body:
In order for your filter to work you need to give False Visible values to the Pivot Items you don't want to see as well as True Values to the one's you do so that you have set all the Pivot Items to True or False.

Here is some code to give you an idea;

Sub Addcountries()
    Dim ws As Worksheet
    Dim str1 As Variant
    Dim Data() As Variant
    Dim pf As PivotField
    Dim target As PivotTable
    Dim PivotItem As Object
    Dim ShowMe As Boolean

    Set ws = Sheets("Main")
    str1 = Application.InputBox("Enter the Country - comma separated")

    If str1 = False Then
        MsgBox "Please Enter one Country", , "Filter Country"
        Exit Sub
    Else
        If InStr(1, str1, ",") > 0 Then
            Data = Split(str1, ",")
        Else
            'Make Single Item Array
            ReDim Data(1)
            Data(0) = str1
        End If
        For Each PivotItem In ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems
            'Default Visibility Is False
            ShowMe = False
            For i = LBound(Data) To UBound(Data)
                'Loop Through Each Item In Data To See If You Should ShowMe
                ShowMe = (PivotItem.Name = Data(i))
                If ShowMe Then
                    'Quit Early If You ShowMe
                    Exit For
                End If
            Next i
            PivotItem.Visible = ShowMe
        Next PivotItem
    End If

End Sub


问:
Copy text of single cell to clipboard
My CurrentCellValue is always null.

I want to mark a row but also if I choose to copy (Ctrl+C) a cell I want that value to be copied, now I get the whole row.

<dxg:GridControl
    Name="GridControl"
    ColumnsSource="{Binding Columns}"
    ItemsSource="{Binding Orders}"
    ColumnGeneratorTemplate="{StaticResource ColumnTemplate}"
    AutoGenerateColumns="None"
    ColumnGeneratorStyle="{StaticResource CommonColumnStyle}"
    SelectedItems="{Binding SelectedOrders}"
    SelectionMode="Row"
    CustomSummary="GridControl_OnCustomSum"
    SelectionChanged="GridControl_OnSelectionChanged"
    CopyingToClipboard="GridControl_OnCopyingToClipboard">
```

<pre class="lang-cs prettyprint-override"><code>private void GridControl_OnCopyingToClipboard(object sender, CopyingToClipboardEventArgs e)
{
    Clipboard.Clear();
    Clipboard.SetText(GetRowData());
    e.Handled = true;
}

private string GetRowData()
{
    return GridControl.CurrentCellValue.ToString();
}
</code>```

SOLUTION:

 <dxg:TableView Name="GridTableView" NavigationStyle="Cell" />
```

Now I have a value in CurrentCellValue

答:
If there's only one cell that you may wish to copy text from:

You can add "SelectedItem" Binding to your GridControl, and in "GridControl_OnCopyingToClipboard" try to find inside the selectedItem the relevant text that you want to copy.

If there're several cells in a row that you may wish to copy from them, and it really matters which one you clicked on inside same row, then you might want to reconsider this line:
SelectionMode="Row"... And change "Row" to "Cell", then again add "SelectedItem" Binding as I mentioned above, and get the text from it

Title: Copy text of single cell to clipboard

Body:
My CurrentCellValue is always null.

I want to mark a row but also if I choose to copy (Ctrl+C) a cell I want that value to be copied, now I get the whole row.

<dxg:GridControl
    Name="GridControl"
    ColumnsSource="{Binding Columns}"
    ItemsSource="{Binding Orders}"
    ColumnGeneratorTemplate="{StaticResource ColumnTemplate}"
    AutoGenerateColumns="None"
    ColumnGeneratorStyle="{StaticResource CommonColumnStyle}"
    SelectedItems="{Binding SelectedOrders}"
    SelectionMode="Row"
    CustomSummary="GridControl_OnCustomSum"
    SelectionChanged="GridControl_OnSelectionChanged"
    CopyingToClipboard="GridControl_OnCopyingToClipboard">

private void GridControl_OnCopyingToClipboard(object sender, CopyingToClipboardEventArgs e)
{
    Clipboard.Clear();
    Clipboard.SetText(GetRowData());
    e.Handled = true;
}

private string GetRowData()
{
    return GridControl.CurrentCellValue.ToString();
}

SOLUTION:

 <dxg:TableView Name="GridTableView" NavigationStyle="Cell" />

Now I have a value in CurrentCellValue


问:
UPDATE record if present; else INSERT in Oracle
Is there any Oracle function that indicate the existence of a record, or any other useful technique to achieve this?

EDIT: using the MERGE statement I did:

```<code>MERGE
 INTO  lims_min.mytab src
 USING lims_min.mytab tgt
    ON (    src.col1 = tgt.col1
        AND tgt.col1 = p_val1
        AND src.col2 = tgt.col2
        AND tgt.col2 = p_val2
       )

 WHEN MATCHED
 THEN
 UPDATE
  SET tgt.col3=p_val3,
      tgt.col4=p_val4

 WHEN NOT MATCHED
 THEN
 INSERT  (col1, col2, col3, col4)
 VALUES  (val1, val2, val2, val4);
</code>```

I get the error saying that col3 is invalid identifier. No typos, and it is existing column.p_val1, p_val2, p_val3 and p_val4 are string parameters that are passed to the stored procedure. i am thinking that the issue may lie in these params, perhaps they should be placed inside a WHERE statement?
Any ideas?

答:
You are looking for merge in Oracle.

```<code>MERGE
       INTO  target_table tgt
      USING source_table src
         ON  ( src.object_id = tgt.object_id ) //The key to check if the record exists
       WHEN MATCHED // if exists
       THEN
     UPDATE
        SET   tgt.object_name = src.object_name //update it
        ,     tgt.object_type = src.object_type
       WHEN NOT MATCHED                         // if not exists
       THEN
     INSERT ( tgt.object_id                    //then insert
            , tgt.object_name
            , tgt.object_type )
     VALUES ( src.object_id
            , src.object_name
            , src.object_type );
</code>```

Body:
Is there any Oracle function that indicate the existence of a record, or any other useful technique to achieve this?

EDIT: using the MERGE statement I did:

MERGE
 INTO  lims_min.mytab src
 USING lims_min.mytab tgt
    ON (    src.col1 = tgt.col1
        AND tgt.col1 = p_val1
        AND src.col2 = tgt.col2
        AND tgt.col2 = p_val2
       )

 WHEN MATCHED
 THEN
 UPDATE
  SET tgt.col3=p_val3,
      tgt.col4=p_val4

 WHEN NOT MATCHED
 THEN
 INSERT  (col1, col2, col3, col4)
 VALUES  (val1, val2, val2, val4);

I get the error saying that col3 is invalid identifier. No typos, and it is existing column.p_val1, p_val2, p_val3 and p_val4 are string parameters that are passed to the stored procedure. i am thinking that the issue may lie in these params, perhaps they should be placed inside a WHERE statement?
Any ideas?

Body:
You are looking for merge in Oracle.

MERGE
       INTO  target_table tgt
      USING source_table src
         ON  ( src.object_id = tgt.object_id ) //The key to check if the record exists
       WHEN MATCHED // if exists
       THEN
     UPDATE
        SET   tgt.object_name = src.object_name //update it
        ,     tgt.object_type = src.object_type
       WHEN NOT MATCHED                         // if not exists
       THEN
     INSERT ( tgt.object_id                    //then insert
            , tgt.object_name
            , tgt.object_type )
     VALUES ( src.object_id
            , src.object_name
            , src.object_type );


问:
In process web server in UWP app to receive JSON messages
I have a question, I have been following this post:

IoT core background webserver

to build my background webserver. However, this post along with most that I read are just a headless background service. In my case, I do have a main app with a UI as well that the user can view and interact with. So, I am not headless, I want the app to start and show the UI when the device starts up. But, I also want a web server running in the background at all times (from within the app) to listen for JSON messages to be posted. For example, if I have text on the UI that I want to change by sending a JSON message to the device/app.

I understand that this is typically referred to as an in-process web server. So, I took most of the link above to implement the web server class and then from my MainPage.xaml.cs code behind, I did this to instantiate the web server class on another thread to listen for messages:

```<code>    private async void StartServer()
    {
        var webServer = new WebServer();

        await ThreadPool.RunAsync((workItem) =>
        {
            webServer.Start();
        });
    }
</code>```

Is this the right way to start the web server in a background thread? As I read the code (and be easy on me, as I am still learning all of this stuff), it seems that the web service will start in the thread pool but then stop after it receives one message. Is that right or will it continue to run indefinitely (or as long as the app is running)?

Thanks!

答:
Yes,it is a right way to start your web server in a background thread in headed UWP Application.In the thread pool,the web service will not stop after it receives messages,because the object of WebServer is not disposed.

Firstly, please refer to the Object Lifetime in .Net Framework.This topic is also about the life cycle of an object. The webServer object will not be disposed until the application exits.

Secondly, HTTP 1.1 implementa persistent connections.In the code you referred,each connection will be closed after web server responses to the client(web browser). So a separate TCP connection will be established to fetch each request in this web server.

var header = $"HTTP/1.1 200 OK\r\nContent-Length: {bodyStream.Length}\r\nConnection: close\r\n\r\n";

Body:
I have a question, I have been following this post:

IoT core background webserver

to build my background webserver. However, this post along with most that I read are just a headless background service. In my case, I do have a main app with a UI as well that the user can view and interact with. So, I am not headless, I want the app to start and show the UI when the device starts up. But, I also want a web server running in the background at all times (from within the app) to listen for JSON messages to be posted. For example, if I have text on the UI that I want to change by sending a JSON message to the device/app.

I understand that this is typically referred to as an in-process web server. So, I took most of the link above to implement the web server class and then from my MainPage.xaml.cs code behind, I did this to instantiate the web server class on another thread to listen for messages:

    private async void StartServer()
    {
        var webServer = new WebServer();

        await ThreadPool.RunAsync((workItem) =>
        {
            webServer.Start();
        });
    }

Is this the right way to start the web server in a background thread? As I read the code (and be easy on me, as I am still learning all of this stuff), it seems that the web service will start in the thread pool but then stop after it receives one message. Is that right or will it continue to run indefinitely (or as long as the app is running)?

Thanks!


问:
MySQL concat multiple row under one ID
I have a MySQL table called mst_order_details and it has column (order no) and it can be same order no it more time.

Each order number have related technique column I want to concat technique column according to order no

mst_order_details table :

```<code>order no   Technique
-------------------------
1           heat_seal
1           laser_cut
1           oil_filter
2           diamond cut
2           diamond cut
</code>```

Output should be like this :

```<code>order no    Technique
---------------------------------------------
 1          heat_seal/laser_cut/ oil_filter
 2          diamond cut
</code>```

答:
You can use GROUP_CONCAT:</p>

```<code>SELECT `order no`, GROUP_CONCAT(DISTINCT `Technique` SEPARATOR '/') FROM mst_order_details GROUP BY `order no`;
</code>```

Title: MySQL concat multiple row under one ID

Body:
I have a MySQL table called mst_order_details and it has column (order no) and it can be same order no it more time.

Each order number have related technique column I want to concat technique column according to order no

mst_order_details table :

order no   Technique
-------------------------
1           heat_seal
1           laser_cut
1           oil_filter
2           diamond cut
2           diamond cut

Output should be like this :

order no    Technique
---------------------------------------------
 1          heat_seal/laser_cut/ oil_filter
 2          diamond cut

Body:
You can use GROUP_CONCAT:

SELECT `order no`, GROUP_CONCAT(DISTINCT `Technique` SEPARATOR '/') FROM mst_order_details GROUP BY `order no`;