问:
ImageView diplaying in one activity but not in aonther
I have an android app with 2 activities: activity_main and activity_login.

On top of my activities I have a logo. It is showing up fine in activity_main but not in the activity_login.

The strange this is they both use similar layout and similar code.

Here is my activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".app.MainActivity"
    android:background="@drawable/background_1">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/logo"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="36dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Sign a File"
        android:layout_marginTop="53dp"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.502" />

    <Button
        android:id="@+id/button2"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Button"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="30dp"
        app:layout_constraintTop_toBottomOf="@+id/button4"
        app:layout_constraintHorizontal_bias="0.502" />

    <Button
        android:id="@+id/button3"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Button"
        android:layout_marginTop="34dp"
        app:layout_constraintTop_toBottomOf="@+id/button1"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.502" />

    <Button
        android:id="@+id/button4"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Button"
        android:layout_marginTop="31dp"
        app:layout_constraintTop_toBottomOf="@+id/button3"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintVertical_bias="0.043"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

And, here is my activity_login.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".login.LoginActivity"
    android:background="@drawable/background_1">

     <ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/logo"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="36dp" />

     <EditText
        android:id="@+id/usernameTextField"
        android:layout_width="291dp"
        android:layout_height="63dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="53dp"
        android:background="@color/editTextBackground"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Username"
        android:textColor="#000000"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <EditText
        android:id="@+id/passwordTextField"
        android:layout_width="291dp"
        android:layout_height="63dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="0dp"
        android:background="@color/editTextBackground"
        android:ems="10"
        android:inputType="textPassword"
        android:text="Password"
        android:textColor="#000000"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/usernameTextField" />

    <Button
        android:id="@+id/button"
        android:onClick="loginButtonClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="66dp"
        android:background="@color/editTextBackground"
        android:text="Log In"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/passwordTextField"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp" />

</android.support.constraint.ConstraintLayout>
</code>```

In the design view of the activity_login it's displaying the image fine. But, when I run a test on emulator/phone it just doesn't show.

I tried removing all the other views from login_activity and still got the same problem. I also tried making a new activity xml with the same ConstarintLayout where I just add logo as imageView, and when I run the app the logo is not showing up.

And, that same logo using the same imageView in constraintLayout works fine in my activity_main

UPDATE: Why the downvote?

UPDATE2: As adviced by rafsanahmad007 this works:

instead of:

app:srcCompat="@drawable/logo" use:

android:src="@drawable/logo"

But, it still doesn't explain why it was working using app:srcCompat in one activity and not the other one.

答:
instead of:

```<code>app:srcCompat="@drawable/logo"
</code>```

use:

```<code>android:src="@drawable/logo"
</code>```

Here is a good answer to know about the difference.

it is a very common mistake. But i would suggest to use android:src as it is more safe in all appcompat versions.

If you are using vector drawable in your app ,then you can go for app:srcCompat . But you need to check the compatibility in gradle.

Body:
I have an android app with 2 activities: activity_main and activity_login.

On top of my activities I have a logo. It is showing up fine in activity_main but not in the activity_login.

The strange this is they both use similar layout and similar code.

Here is my activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".app.MainActivity"
    android:background="@drawable/background_1">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/logo"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="36dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Sign a File"
        android:layout_marginTop="53dp"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.502" />

    <Button
        android:id="@+id/button2"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Button"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="30dp"
        app:layout_constraintTop_toBottomOf="@+id/button4"
        app:layout_constraintHorizontal_bias="0.502" />

    <Button
        android:id="@+id/button3"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Button"
        android:layout_marginTop="34dp"
        app:layout_constraintTop_toBottomOf="@+id/button1"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.502" />

    <Button
        android:id="@+id/button4"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Button"
        android:layout_marginTop="31dp"
        app:layout_constraintTop_toBottomOf="@+id/button3"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintVertical_bias="0.043"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent" />

</android.support.constraint.ConstraintLayout>

And, here is my activity_login.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".login.LoginActivity"
    android:background="@drawable/background_1">

     <ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/logo"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="36dp" />

     <EditText
        android:id="@+id/usernameTextField"
        android:layout_width="291dp"
        android:layout_height="63dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="53dp"
        android:background="@color/editTextBackground"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Username"
        android:textColor="#000000"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <EditText
        android:id="@+id/passwordTextField"
        android:layout_width="291dp"
        android:layout_height="63dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="0dp"
        android:background="@color/editTextBackground"
        android:ems="10"
        android:inputType="textPassword"
        android:text="Password"
        android:textColor="#000000"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/usernameTextField" />

    <Button
        android:id="@+id/button"
        android:onClick="loginButtonClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="66dp"
        android:background="@color/editTextBackground"
        android:text="Log In"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/passwordTextField"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp" />

</android.support.constraint.ConstraintLayout>

In the design view of the activity_login it's displaying the image fine. But, when I run a test on emulator/phone it just doesn't show.

I tried removing all the other views from login_activity and still got the same problem. I also tried making a new activity xml with the same ConstarintLayout where I just add logo as imageView, and when I run the app the logo is not showing up.

And, that same logo using the same imageView in constraintLayout works fine in my activity_main

UPDATE: Why the downvote?

UPDATE2: As adviced by rafsanahmad007 this works:

instead of:

app:srcCompat="@drawable/logo" use:

android:src="@drawable/logo"

But, it still doesn't explain why it was working using app:srcCompat in one activity and not the other one.

Body:
instead of:

app:srcCompat="@drawable/logo"

use:

android:src="@drawable/logo"

Here is a good answer to know about the difference.

it is a very common mistake. But i would suggest to use android:src as it is more safe in all appcompat versions.

If you are using vector drawable in your app ,then you can go for app:srcCompat . But you need to check the compatibility in gradle.


来源: stackexchange

问:
Visual Studio 2017 HRESULT: 0x80070005 / E_ACCESSDENIED on project creation
I'm running Visual Studio 2017, version 15.0.0+26228.9

When I'm trying to create a new project via File > New > Project... in Visual Studio 2017, I'm receiving the following error message and the project is not created:

Access denied (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Don't mind the german message text in the screenshot:

This happens for every project template I use (e.g. C# WPF, VB WPF, C# Console App...).

If I try to create a project via the quick search box on the starting page of visual studio, VS just crashes instantly with no exception message at all:

Has anybody else ran into this issue and might know how to fix it?

答:
I had the same error.
I solved it by following the procedure :

Shutdown all instances of Visual Studio

Delete    %LocalAppData%\Microsoft\VisualStudio\15.0_f4938f75\privateregistry.bin    file (the ID after 15.0_ may be different per machines)

Start VS as    normal user

all credit for this should go to https://developercommunity.visualstudio.com/content/problem/31188/access-denied-error-1.html

ContentLicense: CC BY-SA 3.0


问:
Perl - Pipe command into another
Quick question,

Is there a way to pipe a command into another command via perl like you can in the *Nix command line?

For example:

free -m | grep Mem

How would I be able to do the "piping" in Perl?

答:
You can invoke the command exactly like that:

```<code>system("free -m | grep Mem");
</code>```

From the documentation:

If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is /bin/sh -c on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to execvp , which is more efficient.

You can do the same with other methods for invoking external commands, like open:

```<code>open my $fh, "-|", "free -m | grep Mem" or croak "failed to run pipeline";
# and now read from $fh as usual
</code>```

ContentLicense: CC BY-SA 2.5

Title: Perl - Pipe command into another

Body:
You can invoke the command exactly like that:

system("free -m | grep Mem");

From the documentation:

If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is /bin/sh -c on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to execvp , which is more efficient.

You can do the same with other methods for invoking external commands, like open:

open my $fh, "-|", "free -m | grep Mem" or croak "failed to run pipeline";
# and now read from $fh as usual


问:
Slow Mysql Inner joins with multiple OR
I'm helping a friend with an e-commerce site. He has options for users to select different colours, styles, use and type of the products he's selling. The query the adds the following to the query:

```<code>INNER JOIN tbl_coloursProducts col ON ( p.product_id = col.productID AND (col.colourID = 2 OR col.colourID = 3 OR col.colourID = 5 OR col.colourID = 8 OR col.colourID = 10))
INNER JOIN tbl_useProducts tbluse ON ( p.product_id = tbluse.productID AND (tbluse.useID = 15 OR tbluse.useID = 16 OR tbluse.useID = 17 OR tbluse.useID = 18))
INNER JOIN tbl_styleProducts style ON ( p.product_id = style.productID AND (style.styleID = 39 OR style.styleID = 44))
INNER JOIN tbl_typeProducts type ON ( p.product_id = type.productID AND (type.typeID = 46 OR type.typeID = 48 OR type.typeID = 50))
</code>```

The query loads fast enough when only a few options are selecting, but some users are selecting multiple or each which is causing the query to run in excess of 30 seconds and timing out.

Without altering the table structure is there a better way to optimise the query?

This is the full query:

```<code>SELECT *,
       p.product_id,
       Coalesce((SELECT p2sp.price
                 FROM   ab_product_specials p2sp
                 WHERE  p2sp.product_id = p.product_id
                        AND p2sp.customer_group_id = '1'
                        AND ( ( p2sp.date_start = '0000-00-00'
                                 OR p2sp.date_start < Now() )
                              AND ( p2sp.date_end = '0000-00-00'
                                     OR p2sp.date_end > Now() ) )
                 ORDER  BY p2sp.priority ASC,
                           p2sp.price ASC
                 LIMIT  1), p.price) AS final_price,
       pd.name                       AS name,
       m.name                        AS manufacturer,
       ss.name                       AS stock,
       (SELECT Avg(r.rating)
        FROM   ab_reviews r
        WHERE  p.product_id = r.product_id
        GROUP  BY r.product_id)      AS rating,
       (SELECT Count(rw.review_id)
        FROM   ab_reviews rw
        WHERE  p.product_id = rw.product_id
        GROUP  BY rw.product_id)     AS review
FROM   ab_products p
       LEFT JOIN ab_product_descriptions pd
              ON ( p.product_id = pd.product_id
                   AND pd.language_id = '1' )
       LEFT JOIN ab_products_to_stores p2s
              ON ( p.product_id = p2s.product_id )
       LEFT JOIN ab_manufacturers m
              ON ( p.manufacturer_id = m.manufacturer_id )
       LEFT JOIN ab_stock_statuses ss
              ON ( p.stock_status_id = ss.stock_status_id
                   AND ss.language_id = '1' )
       LEFT JOIN ab_products_to_categories p2c
              ON ( p.product_id = p2c.product_id )
       INNER JOIN tbl_coloursproducts col
               ON ( p.product_id = col.productid
                    AND ( col.colourid = 2
                           OR col.colourid = 3
                           OR col.colourid = 5
                           OR col.colourid = 8
                           OR col.colourid = 10 ) )
       INNER JOIN tbl_useproducts tbluse
               ON ( p.product_id = tbluse.productid
                    AND ( tbluse.useid = 15
                           OR tbluse.useid = 16
                           OR tbluse.useid = 17
                           OR tbluse.useid = 18 ) )
       INNER JOIN tbl_styleproducts style
               ON ( p.product_id = style.productid
                    AND ( style.styleid = 39
                           OR style.styleid = 44 ) )
       INNER JOIN tbl_typeproducts type
               ON ( p.product_id = type.productid
                    AND ( type.typeid = 46
                           OR type.typeid = 48
                           OR type.typeid = 50 ) )
WHERE  p.status = '1'
       AND p.date_available <= Now()
       AND p2s.store_id = 0
       AND p2c.category_id = 131
GROUP  BY p.product_id
ORDER  BY p.product_id DESC
LIMIT  0, 8
</code>```

Without the custom bits the query runs fine.

答:
Looking at that query, not sure the ORs are the problem themselves (although you could possibly make the code more compact by using and IN clause for each one). Rather I suspect that selecting more and more options results in more rows being returned. And this is causing problems with the sub queries in the SELECT clause.

Can you try the query with the sub queries removed from the SELECT clause and see the effect that has.

You can remove the sub queries quite easily.

```<code>SELECT *,
       p.product_id,
       Coalesce(sub1.price, p.price) AS final_price,
       pd.name                       AS name,
       m.name                        AS manufacturer,
       ss.name                       AS stock,
       sub0.rating,
       sub0.review
FROM   ab_products p
INNER JOIN
(
    SELECT r.product_id,
            Avg(r.rating)  AS rating,
            Count(rw.review_id) AS review
    FROM   ab_reviews r
    GROUP  BY r.product_id
) sub0
ON p.product_id = sub0.product_id
LEFT OUTER JOIN
(
    SELECT p2sp.product_id,
            SUBSTRING_INDEX(GROUP_CONCAT(p2sp.price ORDER  BY p2sp.priority ASC, p2sp.price ASC ), ',', 1) AS price
    FROM   ab_product_specials p2sp
    WHERE  p2sp.customer_group_id = '1'
    AND ( p2sp.date_start = '0000-00-00' OR p2sp.date_start < NOW() )
    AND ( p2sp.date_end = '0000-00-00' OR p2sp.date_end > NOW() )
    GROUP BY p2sp.product_id
) sub1
ON p.product_id = sub1.product_id
       LEFT JOIN ab_product_descriptions pd
              ON ( p.product_id = pd.product_id
                   AND pd.language_id = '1' )
       LEFT JOIN ab_products_to_stores p2s
              ON ( p.product_id = p2s.product_id )
       LEFT JOIN ab_manufacturers m
              ON ( p.manufacturer_id = m.manufacturer_id )
       LEFT JOIN ab_stock_statuses ss
              ON ( p.stock_status_id = ss.stock_status_id
                   AND ss.language_id = '1' )
       LEFT JOIN ab_products_to_categories p2c
              ON ( p.product_id = p2c.product_id )
       INNER JOIN tbl_coloursproducts col
               ON ( p.product_id = col.productid
                    AND ( col.colourid = 2
                           OR col.colourid = 3
                           OR col.colourid = 5
                           OR col.colourid = 8
                           OR col.colourid = 10 ) )
       INNER JOIN tbl_useproducts tbluse
               ON ( p.product_id = tbluse.productid
                    AND ( tbluse.useid = 15
                           OR tbluse.useid = 16
                           OR tbluse.useid = 17
                           OR tbluse.useid = 18 ) )
       INNER JOIN tbl_styleproducts style
               ON ( p.product_id = style.productid
                    AND ( style.styleid = 39
                           OR style.styleid = 44 ) )
       INNER JOIN tbl_typeproducts type
               ON ( p.product_id = type.productid
                    AND ( type.typeid = 46
                           OR type.typeid = 48
                           OR type.typeid = 50 ) )
WHERE  p.status = '1'
       AND p.date_available <= Now()
       AND p2s.store_id = 0
       AND p2c.category_id = 131
GROUP  BY p.product_id
ORDER  BY p.product_id DESC
LIMIT  0, 8
</code>```

As an aside, when you read from ab_product_specials you are checking for the date_start and date_end to be 0000-00-00 (ie, dates), but also comparing them with NOW() which returns a date / time field. Are those fields date or date / time fields?

Title: Slow Mysql Inner joins with multiple OR

Body:
I'm helping a friend with an e-commerce site. He has options for users to select different colours, styles, use and type of the products he's selling. The query the adds the following to the query:

INNER JOIN tbl_coloursProducts col ON ( p.product_id = col.productID AND (col.colourID = 2 OR col.colourID = 3 OR col.colourID = 5 OR col.colourID = 8 OR col.colourID = 10))
INNER JOIN tbl_useProducts tbluse ON ( p.product_id = tbluse.productID AND (tbluse.useID = 15 OR tbluse.useID = 16 OR tbluse.useID = 17 OR tbluse.useID = 18))
INNER JOIN tbl_styleProducts style ON ( p.product_id = style.productID AND (style.styleID = 39 OR style.styleID = 44))
INNER JOIN tbl_typeProducts type ON ( p.product_id = type.productID AND (type.typeID = 46 OR type.typeID = 48 OR type.typeID = 50))

The query loads fast enough when only a few options are selecting, but some users are selecting multiple or each which is causing the query to run in excess of 30 seconds and timing out.

Without altering the table structure is there a better way to optimise the query?

This is the full query:

SELECT *,
       p.product_id,
       Coalesce((SELECT p2sp.price
                 FROM   ab_product_specials p2sp
                 WHERE  p2sp.product_id = p.product_id
                        AND p2sp.customer_group_id = '1'
                        AND ( ( p2sp.date_start = '0000-00-00'
                                 OR p2sp.date_start < Now() )
                              AND ( p2sp.date_end = '0000-00-00'
                                     OR p2sp.date_end > Now() ) )
                 ORDER  BY p2sp.priority ASC,
                           p2sp.price ASC
                 LIMIT  1), p.price) AS final_price,
       pd.name                       AS name,
       m.name                        AS manufacturer,
       ss.name                       AS stock,
       (SELECT Avg(r.rating)
        FROM   ab_reviews r
        WHERE  p.product_id = r.product_id
        GROUP  BY r.product_id)      AS rating,
       (SELECT Count(rw.review_id)
        FROM   ab_reviews rw
        WHERE  p.product_id = rw.product_id
        GROUP  BY rw.product_id)     AS review
FROM   ab_products p
       LEFT JOIN ab_product_descriptions pd
              ON ( p.product_id = pd.product_id
                   AND pd.language_id = '1' )
       LEFT JOIN ab_products_to_stores p2s
              ON ( p.product_id = p2s.product_id )
       LEFT JOIN ab_manufacturers m
              ON ( p.manufacturer_id = m.manufacturer_id )
       LEFT JOIN ab_stock_statuses ss
              ON ( p.stock_status_id = ss.stock_status_id
                   AND ss.language_id = '1' )
       LEFT JOIN ab_products_to_categories p2c
              ON ( p.product_id = p2c.product_id )
       INNER JOIN tbl_coloursproducts col
               ON ( p.product_id = col.productid
                    AND ( col.colourid = 2
                           OR col.colourid = 3
                           OR col.colourid = 5
                           OR col.colourid = 8
                           OR col.colourid = 10 ) )
       INNER JOIN tbl_useproducts tbluse
               ON ( p.product_id = tbluse.productid
                    AND ( tbluse.useid = 15
                           OR tbluse.useid = 16
                           OR tbluse.useid = 17
                           OR tbluse.useid = 18 ) )
       INNER JOIN tbl_styleproducts style
               ON ( p.product_id = style.productid
                    AND ( style.styleid = 39
                           OR style.styleid = 44 ) )
       INNER JOIN tbl_typeproducts type
               ON ( p.product_id = type.productid
                    AND ( type.typeid = 46
                           OR type.typeid = 48
                           OR type.typeid = 50 ) )
WHERE  p.status = '1'
       AND p.date_available <= Now()
       AND p2s.store_id = 0
       AND p2c.category_id = 131
GROUP  BY p.product_id
ORDER  BY p.product_id DESC
LIMIT  0, 8

Without the custom bits the query runs fine.

Body:
Looking at that query, not sure the ORs are the problem themselves (although you could possibly make the code more compact by using and IN clause for each one). Rather I suspect that selecting more and more options results in more rows being returned. And this is causing problems with the sub queries in the SELECT clause.

Can you try the query with the sub queries removed from the SELECT clause and see the effect that has.

You can remove the sub queries quite easily.

SELECT *,
       p.product_id,
       Coalesce(sub1.price, p.price) AS final_price,
       pd.name                       AS name,
       m.name                        AS manufacturer,
       ss.name                       AS stock,
       sub0.rating,
       sub0.review
FROM   ab_products p
INNER JOIN
(
    SELECT r.product_id,
            Avg(r.rating)  AS rating,
            Count(rw.review_id) AS review
    FROM   ab_reviews r
    GROUP  BY r.product_id
) sub0
ON p.product_id = sub0.product_id
LEFT OUTER JOIN
(
    SELECT p2sp.product_id,
            SUBSTRING_INDEX(GROUP_CONCAT(p2sp.price ORDER  BY p2sp.priority ASC, p2sp.price ASC ), ',', 1) AS price
    FROM   ab_product_specials p2sp
    WHERE  p2sp.customer_group_id = '1'
    AND ( p2sp.date_start = '0000-00-00' OR p2sp.date_start < NOW() )
    AND ( p2sp.date_end = '0000-00-00' OR p2sp.date_end > NOW() )
    GROUP BY p2sp.product_id
) sub1
ON p.product_id = sub1.product_id
       LEFT JOIN ab_product_descriptions pd
              ON ( p.product_id = pd.product_id
                   AND pd.language_id = '1' )
       LEFT JOIN ab_products_to_stores p2s
              ON ( p.product_id = p2s.product_id )
       LEFT JOIN ab_manufacturers m
              ON ( p.manufacturer_id = m.manufacturer_id )
       LEFT JOIN ab_stock_statuses ss
              ON ( p.stock_status_id = ss.stock_status_id
                   AND ss.language_id = '1' )
       LEFT JOIN ab_products_to_categories p2c
              ON ( p.product_id = p2c.product_id )
       INNER JOIN tbl_coloursproducts col
               ON ( p.product_id = col.productid
                    AND ( col.colourid = 2
                           OR col.colourid = 3
                           OR col.colourid = 5
                           OR col.colourid = 8
                           OR col.colourid = 10 ) )
       INNER JOIN tbl_useproducts tbluse
               ON ( p.product_id = tbluse.productid
                    AND ( tbluse.useid = 15
                           OR tbluse.useid = 16
                           OR tbluse.useid = 17
                           OR tbluse.useid = 18 ) )
       INNER JOIN tbl_styleproducts style
               ON ( p.product_id = style.productid
                    AND ( style.styleid = 39
                           OR style.styleid = 44 ) )
       INNER JOIN tbl_typeproducts type
               ON ( p.product_id = type.productid
                    AND ( type.typeid = 46
                           OR type.typeid = 48
                           OR type.typeid = 50 ) )
WHERE  p.status = '1'
       AND p.date_available <= Now()
       AND p2s.store_id = 0
       AND p2c.category_id = 131
GROUP  BY p.product_id
ORDER  BY p.product_id DESC
LIMIT  0, 8

As an aside, when you read from ab_product_specials you are checking for the date_start and date_end to be 0000-00-00 (ie, dates), but also comparing them with NOW() which returns a date / time field. Are those fields date or date / time fields?


问:
convert to PDF from html or svg, which one is best?
I am going to work on some project where i need to create PDF of some sections in webpage...

Its completely in decision phase what should do for it...

So i have found that we can convert HTML to PDF using some js OR other lib which work at server end...same i found for SVG images...

But confusion is like some time info found as HTML to PDF is good idea whereas few says SVG to PDF will be good for you to maintain Quality etc...

So I wan views with experience that which is best way to go with?

答:
If you need to create a PDF of a webpage then you'll have to convert from HTML to PDF.  You cannot convert from SVG to PDF because simply you don't have the SVG - which is a vectorial image format - to start with.  Then the question is not whichever it's the best, it's which is the most appropriate for your use case.

Note that HTML describes the structure of a document, not its style (this can be done via CSS) and hence not the way it appears.


问:
Angular2 click event not working
I'm facing an issue with an angular2 click event, it's not launching a simple console.log or an alert.

Here I post my component template:

```<code><div class="col-md-4">
<div *ngFor="let phone of phones">
{{phone.text}}
</div>
<input class="form-control" type="text" [(ngModel)]="phone"/>
<button class="btn btn-primary" (click)="console.log('clicked');" type="button">Call</button>
</div>
</code>```

When I click the button, there is nothing in the console.

I tried to execute a component function, with no luck as well.

I'm doing it the same way than here:
http://learnangular2.com/events/

Do you guys need more files? I just don't understand why this is not working

Thank you so much,
Daniel

Edit:

Ok so now I'm doing it like this:

Template:

```<code><div class="col-md-4">
<div *ngFor="let phone of phones">
    {{phone.text}}
</div>
<input class="form-control" type="text" [(ngModel)]="phone"/>
<button class="btn btn-primary" (click)="callPhone();" type="button">Call</button>
</div>
</code>```

And my ts file component:

```<code>import {Component, OnInit, OnDestroy} from '@angular/core';
import {FormControl} from '@angular/forms';
import {CallService} from '../call.service';

@Component({
moduleId: module.id,
selector: 'app-call-formular',
templateUrl: './call-formular.component.html',
styleUrls: ['./call-formular.component.css'],
providers: [CallService]
})
export class CallFormularComponent implements OnInit, OnDestroy {

phones = [];
connection;
phone;

constructor(private callService: CallService) {
}

callPhone(): any {
    console.log('callPhone executed.');
}

ngOnInit() {
    this.connection = this.callService.getPhones().subscribe(phone =>
{
        this.phones.push(phone);
    });
}

ngOnDestroy() {
    this.connection.unsubscribe();
}

}
</code>```

And still not launching my click event

答:
You should do it in the ts file

```<code>(click)="myFunc();"
</code>```

and inside the .ts file

```<code>myFunc():any{
  console.log('clicked');
}
</code>```

Title: Angular2 click event not working

Body:
I'm facing an issue with an angular2 click event, it's not launching a simple console.log or an alert.

Here I post my component template:

{{phone.text}}

<input class="form-control" type="text" [(ngModel)]="phone"/>
<button class="btn btn-primary" (click)="console.log('clicked');" type="button">Call</button>

When I click the button, there is nothing in the console.

I tried to execute a component function, with no luck as well.

I'm doing it the same way than here:
http://learnangular2.com/events/

Do you guys need more files? I just don't understand why this is not working

Thank you so much,
Daniel

Edit:

Ok so now I'm doing it like this:

Template:

    {{phone.text}}

<input class="form-control" type="text" [(ngModel)]="phone"/>
<button class="btn btn-primary" (click)="callPhone();" type="button">Call</button>

And my ts file component:

import {Component, OnInit, OnDestroy} from '@angular/core';
import {FormControl} from '@angular/forms';
import {CallService} from '../call.service';

@Component({
moduleId: module.id,
selector: 'app-call-formular',
templateUrl: './call-formular.component.html',
styleUrls: ['./call-formular.component.css'],
providers: [CallService]
})
export class CallFormularComponent implements OnInit, OnDestroy {

phones = [];
connection;
phone;

constructor(private callService: CallService) {
}

callPhone(): any {
    console.log('callPhone executed.');
}

ngOnInit() {
    this.connection = this.callService.getPhones().subscribe(phone =>
{
        this.phones.push(phone);
    });
}

ngOnDestroy() {
    this.connection.unsubscribe();
}

}

And still not launching my click event

Body:
You should do it in the ts file

(click)="myFunc();"

and inside the .ts file

myFunc():any{
  console.log('clicked');
}


问:
Javassist insturmenter
I am new to Java and Javassist. I would like to add a logger before each read-access on one of my primitive variables in certain methods. After some research I came up with this code:

```<code>try {
method.instrument(
        new ExprEditor() {
            public void edit(FieldAccess fa) throws CannotCompileException {
                CtField field = null;
                CtClass fieldType = null;
                try {
                    field = fa.getField();
                    fieldType = field.getType();
                } catch (NotFoundException e) {
                    e.printStackTrace();
                }
                if (fa.isReader() && field != null && fieldType.isPrimitive()){
                    System.out.println("Primitive found: " + field.getName());

                    //ToDo: call method before variable access
                    fa.replace("{ $_ = $proceed($$); }");
                }
            }
        }
    );
} catch (CannotCompileException e) {
    e.printStackTrace();
}
</code>```

Is there a way to call a (logger) method before the variable is accessed, or do I have to solve this in a different way? What's the best way to achieve this by using Javassist?

Hope someone can help me :)

答: You can use normal logger object to call the logger methods. But make sure to give the jar class path in the manifest file.</p>

Title: Javassist insturmenter

Body:
I am new to Java and Javassist. I would like to add a logger before each read-access on one of my primitive variables in certain methods. After some research I came up with this code:

try {
method.instrument(
        new ExprEditor() {
            public void edit(FieldAccess fa) throws CannotCompileException {
                CtField field = null;
                CtClass fieldType = null;
                try {
                    field = fa.getField();
                    fieldType = field.getType();
                } catch (NotFoundException e) {
                    e.printStackTrace();
                }
                if (fa.isReader() && field != null && fieldType.isPrimitive()){
                    System.out.println("Primitive found: " + field.getName());

                    //ToDo: call method before variable access
                    fa.replace("{ $_ = $proceed($$); }");
                }
            }
        }
    );
} catch (CannotCompileException e) {
    e.printStackTrace();
}

Is there a way to call a (logger) method before the variable is accessed, or do I have to solve this in a different way? What's the best way to achieve this by using Javassist?

Hope someone can help me :)


问:
How do I know when a copy job is done?
I'm using

```<code>File.Copy(source, dest);
</code>```

I need to know when this copy job is done processing so that it can move on to another task.

Is there any callback function I could use in this particular case?

答:
Here is some code to do what you need...cause I'm awesome that way :-)</p>

```<code>dim FileCopyDelegate as new Delegate = addressof File.Copy

dim oListOfParams as new List(of string)

oListOfParams.add(source)
oListOfParams.add(destination)

FileCopyDelegate.begininvoke(oListOfParams, addressof CallBackMethod) 'creates an async thread to do the file copy
</code>```

Title: How do I know when a copy job is done?

Body:
I'm using

File.Copy(source, dest);

I need to know when this copy job is done processing so that it can move on to another task.

Is there any callback function I could use in this particular case?

Body:
Here is some code to do what you need...cause I'm awesome that way :-)

dim FileCopyDelegate as new Delegate = addressof File.Copy

dim oListOfParams as new List(of string)

oListOfParams.add(source)
oListOfParams.add(destination)

FileCopyDelegate.begininvoke(oListOfParams, addressof CallBackMethod) 'creates an async thread to do the file copy


问:
Explanation of test case in the prisoner wall jump program
This would be the general problem statement:

A prisoner escapes from the jail by jumping over N walls each with height of each wall given in an array. He can jump x meters of height, but after every jump he slips y meters due to some uncontrollable factors(wind, slippery wall, etc).

Similar problem statement mentioned here

The programming task given was to debug a function which included four parameters -

```<code>NoOfJumps(int x, int y, int N, int Height[])
</code>```

Number of meters he jumps

Number of meters he slips down the wall

Number of walls

Height of the walls as an array

The first test case was for parameters - (10, 1, 1, {10})

10 being the meters he jumps, 1 meter he slips down, Number of walls being 1, and height of the wall being 10. Now:

effectiveJump = x - y = 9.

So he would have to jump twice to jump over the walls. So, this function should return 2 (total number of jumps required to escape).

There was also another test case for the parameters - (3, 1, 5, {20,5,12,11,3})

3 being the meters he jumps, 1 meter he slips down, Number of walls being 5, and height of the walls given as 20m, 5m, 12m, 11m, 3m. Now:

effectiveJump = x - y = 2.

We were given the output for the above parameter values as 24.

NoOfJumps(3, 1, 5, {20,5,12,11,3})

I can't understand how this output value is obtained. How exactly are the walls arranged?

I can only think of one solution for the corner case, i.e, when the person jumps over the wall

(when (x) > remaining height of the wall),

he should not slip down else I can't obtain the required solution.
For example, in the second test case at first wall, when the person is at 18m height, and he jumps 3m to 21m and doesn't slip down as he has crossed that wall. Next he starts jumping from 21 and not 20. The sequence of jumping would be :

0->2->4->6->8->10->12->14->16->18->21->23->26->28->30->32->34->36->39->41->43->45->47->50->53

Assuming walls at height, 20, 25, 37, 48, 51.

Is this a correct assumption for solving the problem?

答:
You can use this one.

Sample Code

```<code>public static int calculateJumps(int X, int Y, int height[]) {
    int tn=0,n;
    for(int i=0; i<height.length; i++) {
        if(height[i]<=X) {
            tn+=1;
            continue;
        }
        n=((height[i]-X)/(X-Y));
        n+=height[i]-((X-Y)*n)==X?1:2;
        tn+=n;
    }
    return tn;
}
</code>```

You need to pass only X , Y and Array than you can get you output.

Body:
This would be the general problem statement:

A prisoner escapes from the jail by jumping over N walls each with height of each wall given in an array. He can jump x meters of height, but after every jump he slips y meters due to some uncontrollable factors(wind, slippery wall, etc).

Similar problem statement mentioned here

The programming task given was to debug a function which included four parameters -

NoOfJumps(int x, int y, int N, int Height[])

Number of meters he jumps

Number of meters he slips down the wall

Number of walls

Height of the walls as an array

The first test case was for parameters - (10, 1, 1, {10})

10 being the meters he jumps, 1 meter he slips down, Number of walls being 1, and height of the wall being 10. Now:

effectiveJump = x - y = 9.

So he would have to jump twice to jump over the walls. So, this function should return 2 (total number of jumps required to escape).

There was also another test case for the parameters - (3, 1, 5, {20,5,12,11,3})

3 being the meters he jumps, 1 meter he slips down, Number of walls being 5, and height of the walls given as 20m, 5m, 12m, 11m, 3m. Now:

effectiveJump = x - y = 2.

We were given the output for the above parameter values as 24.

NoOfJumps(3, 1, 5, {20,5,12,11,3})

I can't understand how this output value is obtained. How exactly are the walls arranged?

I can only think of one solution for the corner case, i.e, when the person jumps over the wall

(when (x) > remaining height of the wall),

he should not slip down else I can't obtain the required solution.
For example, in the second test case at first wall, when the person is at 18m height, and he jumps 3m to 21m and doesn't slip down as he has crossed that wall. Next he starts jumping from 21 and not 20. The sequence of jumping would be :

0->2->4->6->8->10->12->14->16->18->21->23->26->28->30->32->34->36->39->41->43->45->47->50->53

Assuming walls at height, 20, 25, 37, 48, 51.

Is this a correct assumption for solving the problem?

Body:
You can use this one.

Sample Code

public static int calculateJumps(int X, int Y, int height[]) {
    int tn=0,n;
    for(int i=0; i<height.length; i++) {
        if(height[i]<=X) {
            tn+=1;
            continue;
        }
        n=((height[i]-X)/(X-Y));
        n+=height[i]-((X-Y)*n)==X?1:2;
        tn+=n;
    }
    return tn;
}

You need to pass only X , Y and Array than you can get you output.


问:
How to set the ToolTip in only one control?
I have use the ToolTip with Behavior. So, when click on the control, ToolTip will be appear.

However, when change the disabled of control, this ToolTip is not appeared.
Because, mouse events were not activated. So, i was used the ContentContorl and it can be activate the mouse event when change the disabled.

But, when i have several control in one Grid, i dont know that how to activate the only one control.

```<code><Window.Resources>
    <Style TargetType="ContentControl" >
        <Setter Property="localToolTip:ToolTipTouchScreenBehavior.IsEnabled" Value="True"/>
    </Style>
    <Style TargetType="TextBlock" >
        <Setter Property="localToolTip:ToolTipTouchScreenBehavior.IsEnabled" Value="True"/>
    </Style>
</Window.Resources>

<ContentControl ToolTip="This is ToolTip5 Test.">
            <Grid IsEnabled="False">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="300"/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <TextBlock  HorizontalAlignment="Left" Margin="5" TextWrapping="Wrap" Text="ToolTip Test5"  FontSize="25"
                            ToolTipService.ShowOnDisabled="True" />
                <TextBox Grid.Column="1" Width="200" />

            </Grid>
</ContentControl>

public class ToolTipTouchScreenBehavior : Behavior<FrameworkElement>
{

    public static DependencyProperty IsEnabledProperty =
        DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),
            typeof(ToolTipTouchScreenBehavior), new FrameworkPropertyMetadata(false, OnIsEnabledChanged));

    public static bool GetIsEnabled(DependencyObject uie)
    {
        return (bool)uie.GetValue(IsEnabledProperty);
    }

    public static void SetIsEnabled(DependencyObject uie, bool value)
    {
        uie.SetValue(IsEnabledProperty, value);
    }

    public static void OnIsEnabledChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs e)
    {

        UIElement uie = dpo as UIElement;

        if (uie != null)
        {

            var behColl = Interaction.GetBehaviors(uie);

            var existingBehavior = behColl.FirstOrDefault(b => b.GetType() ==
                  typeof(ToolTipTouchScreenBehavior)) as ToolTipTouchScreenBehavior;

            if ((bool)e.NewValue == false && existingBehavior != null)
                behColl.Remove(existingBehavior);
            else if ((bool)e.NewValue == true && existingBehavior == null)
                behColl.Add(new ToolTipTouchScreenBehavior());

        }

    }

    Timer timer { get; set; }
    ToolTip toolTip { get; set; }

    protected override void OnAttached()
    {
        base.OnAttached();

        toolTip = new ToolTip();

        timer = new Timer();
        timer.Interval = 5000;
        timer.Elapsed += OnTimerElapsed;

        AssociatedObject.MouseLeave += OnMouseLeave;
        AssociatedObject.MouseLeftButtonUp += OnMouseLeftButtonUp;

    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        AssociatedObject.MouseLeave -= OnMouseLeave;
        AssociatedObject.MouseLeftButtonUp -= OnMouseLeftButtonUp;
    }

    public void OnMouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
    {
        CloseToolTip();
    }

    public void OnMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        try
        {

            //var temp = AssociatedObject.ToolTip;
            //if (((dynamic)sender).ToolTip != null)
            if (AssociatedObject.ToolTip != null)
            {
                if (AssociatedObject.ToolTip is string)
                    toolTip.Content = AssociatedObject.ToolTip;
                else
                    toolTip = (ToolTip)AssociatedObject.ToolTip;

                //Debug.WriteLine("ToolTip Opened: {0}, ToolTip Value: {1}", toolTip.IsOpen, toolTip.ToolTip);

                toolTip.IsOpen = true;
                timer.Start();

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }

    private void CloseToolTip()
    {

        if (timer.Enabled)
        {
            timer.Stop();
        }

        if (toolTip != null)
        {
            toolTip.IsOpen = false;
        }
    }

    private void OnTimerElapsed(object sender, ElapsedEventArgs e)
    {
        Application.Current.Dispatcher.BeginInvoke((Action)CloseToolTip, DispatcherPriority.Send);
    }

}
</code>```

When i have above code, i just want to add the ToolTip for only TextBlock. not TextBox.

How to apply the ToolTip to only one special control?

答:
If your problem is same as mentioned by grek40 then the following is the answer:

If you do want the tooltip to be displayed when the parent control is disabled, you can set the ToolTipService.ShowOnDisabled property to true.
WPF 2000things

Body:
I have use the ToolTip with Behavior. So, when click on the control, ToolTip will be appear.

However, when change the disabled of control, this ToolTip is not appeared.
Because, mouse events were not activated. So, i was used the ContentContorl and it can be activate the mouse event when change the disabled.

But, when i have several control in one Grid, i dont know that how to activate the only one control.

<Window.Resources>

</Window.Resources>

<ContentControl ToolTip="This is ToolTip5 Test.">
            <Grid IsEnabled="False">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="300"/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <TextBlock  HorizontalAlignment="Left" Margin="5" TextWrapping="Wrap" Text="ToolTip Test5"  FontSize="25"
                            ToolTipService.ShowOnDisabled="True" />
                <TextBox Grid.Column="1" Width="200" />

            </Grid>
</ContentControl>

public class ToolTipTouchScreenBehavior : Behavior<FrameworkElement>
{

    public static DependencyProperty IsEnabledProperty =
        DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),
            typeof(ToolTipTouchScreenBehavior), new FrameworkPropertyMetadata(false, OnIsEnabledChanged));

    public static bool GetIsEnabled(DependencyObject uie)
    {
        return (bool)uie.GetValue(IsEnabledProperty);
    }

    public static void SetIsEnabled(DependencyObject uie, bool value)
    {
        uie.SetValue(IsEnabledProperty, value);
    }

    public static void OnIsEnabledChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs e)
    {

        UIElement uie = dpo as UIElement;

        if (uie != null)
        {

            var behColl = Interaction.GetBehaviors(uie);

            var existingBehavior = behColl.FirstOrDefault(b => b.GetType() ==
                  typeof(ToolTipTouchScreenBehavior)) as ToolTipTouchScreenBehavior;

            if ((bool)e.NewValue == false && existingBehavior != null)
                behColl.Remove(existingBehavior);
            else if ((bool)e.NewValue == true && existingBehavior == null)
                behColl.Add(new ToolTipTouchScreenBehavior());

        }

    }

    Timer timer { get; set; }
    ToolTip toolTip { get; set; }

    protected override void OnAttached()
    {
        base.OnAttached();

        toolTip = new ToolTip();

        timer = new Timer();
        timer.Interval = 5000;
        timer.Elapsed += OnTimerElapsed;

        AssociatedObject.MouseLeave += OnMouseLeave;
        AssociatedObject.MouseLeftButtonUp += OnMouseLeftButtonUp;

    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        AssociatedObject.MouseLeave -= OnMouseLeave;
        AssociatedObject.MouseLeftButtonUp -= OnMouseLeftButtonUp;
    }

    public void OnMouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
    {
        CloseToolTip();
    }

    public void OnMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        try
        {

            //var temp = AssociatedObject.ToolTip;
            //if (((dynamic)sender).ToolTip != null)
            if (AssociatedObject.ToolTip != null)
            {
                if (AssociatedObject.ToolTip is string)
                    toolTip.Content = AssociatedObject.ToolTip;
                else
                    toolTip = (ToolTip)AssociatedObject.ToolTip;

                //Debug.WriteLine("ToolTip Opened: {0}, ToolTip Value: {1}", toolTip.IsOpen, toolTip.ToolTip);

                toolTip.IsOpen = true;
                timer.Start();

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }

    private void CloseToolTip()
    {

        if (timer.Enabled)
        {
            timer.Stop();
        }

        if (toolTip != null)
        {
            toolTip.IsOpen = false;
        }
    }

    private void OnTimerElapsed(object sender, ElapsedEventArgs e)
    {
        Application.Current.Dispatcher.BeginInvoke((Action)CloseToolTip, DispatcherPriority.Send);
    }

}

When i have above code, i just want to add the ToolTip for only TextBlock. not TextBox.

How to apply the ToolTip to only one special control?


问:
LINQ - Group by calculated field
Say I have some class like this:

```<code>public class MyClass
{
    public DateTime Date { get; set; }
    public string Code { get; set; }
}
</code>```

And some values like:

```<code>| Date          | Code  |
|------------   |------ |
| 03/04/2017    | 1234  |
| 31/03/2017    | 1234  |
| 29/03/2017    | 1234  |
| 29/03/2017    | 4321  |
| 25/03/2017    | 4321  |
| ...           | ...   |
</code>```

I want to group these by the Code field AND also group by the Date however I want the Date to be grouped by a range. The calculation on this will find the date at the start of the week (Monday of that week) and also the end of the week (Friday of that week) and then give me some results like:

```<code>| 03/04/2017    | 1234  | < week beginning 03/04 and code=1234

| 31/03/2017    | 1234  | < week beginning 27/03 and code=1234
| 29/03/2017    | 1234  |

| 29/03/2017    | 4321  | < week beginning 27/03 and code=4321

| 25/03/2017    | 4321  | < week beginning 20/03 and code=4321
</code>```

I've tried doing a range but I think what I'm doing is pretty useless (StartOfWeek is an extension method from here):

```<code>data.Where(d => d.Date >= d.Date.StartOfWeek(DayOfWeek.Monday) && d.Date <= d.Date.StartOfWeek(DayOfWeek.Monday).AddDays(6));
</code>```

Note: I'm using Entity Framework for my actual project but when I'm doing this I am fetching all the data from the MyClass table and I want to do all the above to filter and group the data appropriately.

答:
I have tried to use week number, so first group by code and then weekOfYear + Year.

```<code>List<MyClass> date = new List<MyClass>
{
    new MyClass { Date = new DateTime(2017,03,04), Code = "1234"},
    new MyClass { Date = new DateTime(2017,03,05), Code = "1234"},
    new MyClass { Date = new DateTime(2017,03,06), Code = "1234"},
    new MyClass { Date = new DateTime(2017,04,04), Code = "1234"},
    new MyClass { Date = new DateTime(2017,04,05), Code = "1234"},
    new MyClass { Date = new DateTime(2017,04,06), Code = "1234"},
    new MyClass { Date = new DateTime(2017,03,06), Code = "12345"},
    new MyClass { Date = new DateTime(2017,04,04), Code = "12345"},
    new MyClass { Date = new DateTime(2017,04,05), Code = "12345"},
    new MyClass { Date = new DateTime(2017,04,06), Code = "12345"}
            };

var groupbydata = date.GroupBy(x => x.Code).ToDictionary(x => x.Key, x => x.GroupBy(y => CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(y.Date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday).ToString() + y.Date.Year.ToString()));
</code>```

Update:

I have changed the

```<code>x => x.GroupBy(y => CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(y.Date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday) + y.Date.Year));
</code>```

to

```<code>x => x.GroupBy(y => CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(y.Date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday).ToString() + y.Date.Year.ToString()));
</code>```

You will get
Dictionary<string, IEnumerable<IGrouping<string, MyClass>>>
the Key of Dictionary is Code and the Value of the Dictionary is grouped data by Week number + Year

Also try to print it out

```<code>    private static void Print(Dictionary<string, IEnumerable<IGrouping<string, MyClass>>> groupbydata)
    {
        foreach (var d1 in groupbydata)
        {
            Debug.WriteLine("Code : " + d1.Key);

            foreach (var d2 in d1.Value)
            {
                Debug.WriteLine("Week number + Year: " + d2.Key);
                foreach (var d3 in d2)
                {
                    Debug.WriteLine("Date : " + d3.Date);
                }
            }
        }
    }
</code>```

And the result is

Code : 1234

Week number + Year: 92017

Date : 3/4/2017 12:00:00 AM

Date : 3/5/2017 12:00:00 AM

Week number + Year: 102017

Date : 3/6/2017 12:00:00 AM

Week number + Year: 142017

Date : 4/4/2017 12:00:00 AM

Date : 4/5/2017 12:00:00 AM

Date : 4/6/2017 12:00:00 AM

Code : 12345

Week number + Year: 102017

Date : 3/6/2017 12:00:00 AM

Week number + Year: 142017

Date : 4/4/2017 12:00:00 AM

Date : 4/5/2017 12:00:00 AM

Date : 4/6/2017 12:00:00 AM

Title: LINQ - Group by calculated field

Body:
Say I have some class like this:

public class MyClass
{
    public DateTime Date { get; set; }
    public string Code { get; set; }
}

And some values like:

| Date          | Code  |
|------------   |------ |
| 03/04/2017    | 1234  |
| 31/03/2017    | 1234  |
| 29/03/2017    | 1234  |
| 29/03/2017    | 4321  |
| 25/03/2017    | 4321  |
| ...           | ...   |

I want to group these by the Code field AND also group by the Date however I want the Date to be grouped by a range. The calculation on this will find the date at the start of the week (Monday of that week) and also the end of the week (Friday of that week) and then give me some results like:

| 03/04/2017    | 1234  | < week beginning 03/04 and code=1234

| 31/03/2017    | 1234  | < week beginning 27/03 and code=1234
| 29/03/2017    | 1234  |

| 29/03/2017    | 4321  | < week beginning 27/03 and code=4321

| 25/03/2017    | 4321  | < week beginning 20/03 and code=4321

I've tried doing a range but I think what I'm doing is pretty useless (StartOfWeek is an extension method from here):

data.Where(d => d.Date >= d.Date.StartOfWeek(DayOfWeek.Monday) && d.Date <= d.Date.StartOfWeek(DayOfWeek.Monday).AddDays(6));

Note: I'm using Entity Framework for my actual project but when I'm doing this I am fetching all the data from the MyClass table and I want to do all the above to filter and group the data appropriately.

Body:
I have tried to use week number, so first group by code and then weekOfYear + Year.

List<MyClass> date = new List<MyClass>
{
    new MyClass { Date = new DateTime(2017,03,04), Code = "1234"},
    new MyClass { Date = new DateTime(2017,03,05), Code = "1234"},
    new MyClass { Date = new DateTime(2017,03,06), Code = "1234"},
    new MyClass { Date = new DateTime(2017,04,04), Code = "1234"},
    new MyClass { Date = new DateTime(2017,04,05), Code = "1234"},
    new MyClass { Date = new DateTime(2017,04,06), Code = "1234"},
    new MyClass { Date = new DateTime(2017,03,06), Code = "12345"},
    new MyClass { Date = new DateTime(2017,04,04), Code = "12345"},
    new MyClass { Date = new DateTime(2017,04,05), Code = "12345"},
    new MyClass { Date = new DateTime(2017,04,06), Code = "12345"}
            };

var groupbydata = date.GroupBy(x => x.Code).ToDictionary(x => x.Key, x => x.GroupBy(y => CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(y.Date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday).ToString() + y.Date.Year.ToString()));

Update:

I have changed the

x => x.GroupBy(y => CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(y.Date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday) + y.Date.Year));

to

x => x.GroupBy(y => CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(y.Date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday).ToString() + y.Date.Year.ToString()));

You will get
Dictionary<string, IEnumerable<IGrouping<string, MyClass>>>
the Key of Dictionary is Code and the Value of the Dictionary is grouped data by Week number + Year

Also try to print it out

    private static void Print(Dictionary<string, IEnumerable<IGrouping<string, MyClass>>> groupbydata)
    {
        foreach (var d1 in groupbydata)
        {
            Debug.WriteLine("Code : " + d1.Key);

            foreach (var d2 in d1.Value)
            {
                Debug.WriteLine("Week number + Year: " + d2.Key);
                foreach (var d3 in d2)
                {
                    Debug.WriteLine("Date : " + d3.Date);
                }
            }
        }
    }

And the result is

Code : 1234

Week number + Year: 92017

Date : 3/4/2017 12:00:00 AM

Date : 3/5/2017 12:00:00 AM

Week number + Year: 102017

Date : 3/6/2017 12:00:00 AM

Week number + Year: 142017

Date : 4/4/2017 12:00:00 AM

Date : 4/5/2017 12:00:00 AM

Date : 4/6/2017 12:00:00 AM

Code : 12345

Week number + Year: 102017

Date : 3/6/2017 12:00:00 AM

Week number + Year: 142017

Date : 4/4/2017 12:00:00 AM

Date : 4/5/2017 12:00:00 AM

Date : 4/6/2017 12:00:00 AM


问:
How to pass selected dropdown value using javascript to Html.ActionLink
I have a LocationCode dropdown:

```<code>@Html.DropDownList("LocationCode", (SelectList)ViewBag.Values, "Search Location...", new { @value = "@ViewBag.LocationCode.ToString()", @class = "form-control btn btn-default dropdown-toggle", name = "LocationCode" })
</code>```

Below is my @Html.ActionLink which calls an Export to Excel function:

```<code>@Html.ActionLink("Export to Excel", "ExportAllVehicleLocationsToExcel", new { id = "ExportAllVehicleLocationsToExcel" })
</code>```

Here is my Javascript attempt which is not working:

```<code>jQuery(function () {
    $("#ExportAllVehicleLocationsToExcel").click(
    function AllVehicleLocationsSearch() {
        $('#LocationCode').val(LocationCode);
        }
    );
});
</code>```

How do I pass the selected LocationCode to the @Html.ActionLink using Javascript?

答:
You need to build a new url based on the selected value

The code for generating the  should be just (never set the value attribute when using the HtmlHelper methods, and your attempt at setting the name attribute fortunately does nothing at all)

```<code>@Html.DropDownList("LocationCode", (SelectList)ViewBag.Values, "Search Location...",
    new { @class = "form-control btn btn-default dropdown-toggle" })
</code>```

and the link can be just

```<code><a href="#" id="export">Export to Excel</a>
</code>```

and then the script will be

```<code>var baseUrl = '@Url.Action("ExportAllVehicleLocationsToExcel")';
$('#export').click(function() {
    location.href = baseUrl + '/' + $('#LocationCode').val();
})
</code>```

Body:
I have a LocationCode dropdown:

@Html.DropDownList("LocationCode", (SelectList)ViewBag.Values, "Search Location...", new { @value = "@ViewBag.LocationCode.ToString()", @class = "form-control btn btn-default dropdown-toggle", name = "LocationCode" })

Below is my @Html.ActionLink which calls an Export to Excel function:

@Html.ActionLink("Export to Excel", "ExportAllVehicleLocationsToExcel", new { id = "ExportAllVehicleLocationsToExcel" })

Here is my Javascript attempt which is not working:

jQuery(function () {
    $("#ExportAllVehicleLocationsToExcel").click(
    function AllVehicleLocationsSearch() {
        $('#LocationCode').val(LocationCode);
        }
    );
});

How do I pass the selected LocationCode to the @Html.ActionLink using Javascript?

Body:
You need to build a new url based on the selected value

The code for generating the  should be just (never set the value attribute when using the HtmlHelper methods, and your attempt at setting the name attribute fortunately does nothing at all)

@Html.DropDownList("LocationCode", (SelectList)ViewBag.Values, "Search Location...",
    new { @class = "form-control btn btn-default dropdown-toggle" })

and the link can be just

<a href="#" id="export">Export to Excel</a>

and then the script will be

var baseUrl = '@Url.Action("ExportAllVehicleLocationsToExcel")';
$('#export').click(function() {
    location.href = baseUrl + '/' + $('#LocationCode').val();
})


问:
What is the best way to implement a RESTful architecture in .NET today?
Before you mention it I am aware that this question has been asked before but not since the launch of WCF4!

So, after a lot of reading I've decided that a RESTful architecture is the way forward to begin a data providing API. Considering the release WCF 4, ASP.NET MVC 2 and WCF REST starter kit, what is the best way to begin implementing a RESTful architecture NOW?

Me:
I am very familiar with ASP.NET MVC so I'd feel quite comfortable there. My knowledge of WCF, however, is lacking.

So WCF4 or ASP.NET MVC? (or something else like the wcf rest starter kit)? Specifically I'm looking for:

Ease of implementation

I know ASP.NET MVC, not WCF. Is WCF worth the learning curve?

Is WCF4 overkill for REST or will ASP.NET MVC falls short at some point?

答: I've used the WCF Rest Service Application Template available in the Visual Studio Extension Manager with a lot of success.  If you are looking to get started fast that is where I would go.</p>


问:
Angular factory function executing only once
I have two modules module-1 and module-2 in my angular application.

In module-1, I have created a factory

```<code>angular.module('ui.campaign.manager').factory('validate',['the',function(the) {
return {
    validateOwner: function(scope) {
        console.log(scope.campaign);
        if(!scope.campaign.owner) {
          scope.view = true;
          scope.errormsg = "Error : Campaign owner is a mandatory field. Please select one from the dropdown menu.";
          return false;
        }
        return true;
    }
};
</code>```

}]);

In module-2, there is a controller where I am calling this function on ng-click

```<code>var campaignApp = angular.module('module-2',[ 'module-1']);

campaignApp.controller('campaignDetailController', function($scope,    validate) {

    scope.submitCampaignPage = function(){
        validate.validateOwner($scope);
    }
});
<input class="btn btn-primary" type="submit" value="Next" name="campdetailsnext" ng-click="submitCampaignPage()">
</code>```

Now, the issue is for the first time when I am clicking on Next button validateOwner function is getting invoked properly while on subsequent clicks submitCampaignPage function is being called but validateOwner function is not getting invoked at all.

Is angular caching the results?

答:
you need to pass the function parameter as $scope not as scope.

Also, make sure to declare scope.campaign as object in controller or factory otherwise there is an exception raised trying to access property of undefined

Demo

angular.module("app",[])
.controller("ctrl",function($scope,validate){
$scope.campaign = {}
  $scope.submitCampaignPage = function(){
    console.log(validate.validateOwner($scope))
 }

}).factory('validate',function() {
  return {
      validateOwner: function(scope) {
          if(!scope.campaign.owner) {
            scope.view = true;
            scope.errormsg = "Error : Campaign owner is a mandatory field. Please select one from the dropdown menu.";
            return false;
          }
          return true;
      }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <input class="btn btn-primary" type="submit" value="Next" name="campdetailsnext" ng-click="submitCampaignPage()">

</div></code>```

Body:
I have two modules module-1 and module-2 in my angular application.

In module-1, I have created a factory

angular.module('ui.campaign.manager').factory('validate',['the',function(the) {
return {
    validateOwner: function(scope) {
        console.log(scope.campaign);
        if(!scope.campaign.owner) {
          scope.view = true;
          scope.errormsg = "Error : Campaign owner is a mandatory field. Please select one from the dropdown menu.";
          return false;
        }
        return true;
    }
};

}]);

In module-2, there is a controller where I am calling this function on ng-click

var campaignApp = angular.module('module-2',[ 'module-1']);

campaignApp.controller('campaignDetailController', function($scope,    validate) {

    scope.submitCampaignPage = function(){
        validate.validateOwner($scope);
    }
});
<input class="btn btn-primary" type="submit" value="Next" name="campdetailsnext" ng-click="submitCampaignPage()">

Now, the issue is for the first time when I am clicking on Next button validateOwner function is getting invoked properly while on subsequent clicks submitCampaignPage function is being called but validateOwner function is not getting invoked at all.

Is angular caching the results?

Body:
you need to pass the function parameter as $scope not as scope.

Also, make sure to declare scope.campaign as object in controller or factory otherwise there is an exception raised trying to access property of undefined

Demo

angular.module("app",[])
.controller("ctrl",function($scope,validate){
$scope.campaign = {}
  $scope.submitCampaignPage = function(){
    console.log(validate.validateOwner($scope))
 }

}).factory('validate',function() {
  return {
      validateOwner: function(scope) {
          if(!scope.campaign.owner) {
            scope.view = true;
            scope.errormsg = "Error : Campaign owner is a mandatory field. Please select one from the dropdown menu.";
            return false;
          }
          return true;
      }
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <input class="btn btn-primary" type="submit" value="Next" name="campdetailsnext" ng-click="submitCampaignPage()">

</div>


问:
one page works but another gets: Uncaught TypeError: Cannot read property 'length' of undefined
I have two webpages with the same table on them so I wrote a script to allow easy modification of both. The script works perfectly on one page but on the other it gets an Uncaught TypeError cannot read property 'length' of undefined on line 18.

```<code>var i, j, dat, lnk, txt;
var pak1, pak3, pak2;

lnk = ''; //Just a long string
lnk += '';

pak1 = ["1 GB","50 kr","30 dagar","",lnk];
pak2 = ["3 GB","100 kr","30 dagar","",lnk];
Pak3 = ["10 GB","200 kr","30 dagar","",lnk];

dat = [pak1, pak2, pak3];

txt = '<table class="table table-striped detail-info"><tbody><tr><td class="title-col"><h5>Data</h5></td>';
txt += '<td><h5>Cost</h5></td><td>Limit</td><td></td><td></td></tr>';

for(i = 0; i < dat.length; i++){
    txt += '<tr>';
    for(j = 0; j < dat[i].length; j++){//Error occurs here
        if(j === 0){
            txt += '<td class="title-col">' + dat[i][j] + '</td>';
        }else{
            txt += '<td>' + dat[i][j] + '</td>';
        }
    }
    txt += '</tr>';
}

txt += '</tbody></table>';

document.getElementById("infoTable").innerHTML = txt;
</code>```

I use the same html on both pages to load the script and they are located in the same folder.

```<code><!-- SCRIPT -->
<div id="infoTable"></div>
<script src="./script/infoTable.js"></script>
<!-- END SCRIPT -->
</code>```

I don't have alot of experience with JavaScript so any help would be greatly appreciated.

答: You have a typo in your example, Pak3 where you want pak3

Body:
I have two webpages with the same table on them so I wrote a script to allow easy modification of both. The script works perfectly on one page but on the other it gets an Uncaught TypeError cannot read property 'length' of undefined on line 18.

var i, j, dat, lnk, txt;
var pak1, pak3, pak2;

lnk = ''; //Just a long string
lnk += '';

pak1 = ["1 GB","50 kr","30 dagar","",lnk];
pak2 = ["3 GB","100 kr","30 dagar","",lnk];
Pak3 = ["10 GB","200 kr","30 dagar","",lnk];

dat = [pak1, pak2, pak3];

txt = '

Data
	';
txt += '
Cost
	Limit
';

for(i = 0; i < dat.length; i++){
    txt += '
';
    for(j = 0; j < dat[i].length; j++){//Error occurs here
        if(j === 0){
            txt += '' + dat[i][j] + '	';
        }else{
            txt += '' + dat[i][j] + '	';
        }
    }
    txt += '
';
}

txt += '

';

document.getElementById("infoTable").innerHTML = txt;

I use the same html on both pages to load the script and they are located in the same folder.

I don't have alot of experience with JavaScript so any help would be greatly appreciated.


问:
image on collapse button
Can I put an image instead the button to collapse and show the text?

<button class="btn btn-info" style="background-color: #60bf3b; color: white;" type="button" data-toggle="collapse" data-target="#fatture">Per D.D.T. e Fatture:</button>

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.

```

Thanks for the help!

答:
If you want the button to have a background, you could try this (fiddle)
Just set

```<code>.btn {
  background: url("https://i.ytimg.com/vi/FhZrU6g9seg/maxresdefault.jpg") no-repeat transparent;
  background-size: cover;
}
</code>```

And make sure you have these 3 included as well:

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</code>```

Unless you just want an image to function as a button, then you can just do this image fiddle

Title: image on collapse button

Body:
Can I put an image instead the button to collapse and show the text?

<button class="btn btn-info" style="background-color: #60bf3b; color: white;" type="button" data-toggle="collapse" data-target="#fatture">Per D.D.T. e Fatture:</button>

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.

Thanks for the help!

Body:
If you want the button to have a background, you could try this (fiddle)
Just set

.btn {
  background: url("https://i.ytimg.com/vi/FhZrU6g9seg/maxresdefault.jpg") no-repeat transparent;
  background-size: cover;
}

And make sure you have these 3 included as well:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Unless you just want an image to function as a button, then you can just do this image fiddle


问:
Importing Sass through npm
Currently in our Sass files we have something like the following:

```<code>@import "../../node_modules/some-module/sass/app";
</code>```

This is bad, because we're not actually sure of the path: it could be ../node_modules, it could be ../../../../../node_modules, because of how npm installs stuff.

Is there a way in Sass that we can search up until we find node_modules? Or even a proper way of including Sass through npm?

答:
If you are looking for a handy answer in 2017 and are using Webpack, this was the easiest I found.

Suppose your module path is like:

```<code>node_modules/some-module/sass/app
</code>```

Then in your main scss file you can use:

```<code>@import "~some-module/sass/app";
</code>```

Tilde operator shall resolve any import as a module.

Title: Importing Sass through npm

Body:
Currently in our Sass files we have something like the following:

@import "../../node_modules/some-module/sass/app";

This is bad, because we're not actually sure of the path: it could be ../node_modules, it could be ../../../../../node_modules, because of how npm installs stuff.

Is there a way in Sass that we can search up until we find node_modules? Or even a proper way of including Sass through npm?

Body:
If you are looking for a handy answer in 2017 and are using Webpack, this was the easiest I found.

Suppose your module path is like:

node_modules/some-module/sass/app

Then in your main scss file you can use:

@import "~some-module/sass/app";

Tilde operator shall resolve any import as a module.


问:
FTP 425 Can't open data connection behind IIS
I need to write an application which connects to a FTP server. This FTP server does not allows passive mode connections. I can connect to the FTP server using Filezilla.

I have developed a C# WCF service which connects to this FTP server, using FTPWebRequest class.
    Here are the basic settings of the FTPWebRequest object:

```<code>ftpreq.Proxy = null;
ftpreq.KeepAlive = true;
ftpreq.UsePassive = false;
</code>```

When I run the WCF service from Visual Studio(Ctrl+F5) it connects to the FTP server and downloads required files without any issues

But when I host the service in my local IIS 7.5, it fails to connect to the FTP server with following error:

The remote server returned an error: (425) Can't open data connection.

After some googling on this problem, I tried playing around the firewall settings, but it was of no use. Not sure if it is related to some IIS security issue or something else.

Any help would be highly appreciated

答:
here is complex solution

step 1
single ftp (non ftps) using two network channels (port and port ranges).
One (tcp:21) for auth, and second, used as data-channel for data.

When configuring ftp on iis, open 21 port for auth and control channel, then in iis control-panel on "FTP Firewall support" specify port range for data (5000-6000) and external ip of network interface married with ftp-server.

step 2
Finally, open tcp:21 in windows firewall and create custon rule, allowing connection on tcp:5000-6000. Restart system (or just restart services).

thats all.

ps. just remember, that ftp on iis using tcp:21 for control/auth and tcp:5000-6000 for data. tcp:5000-6000 may be changes in iis manager 1st, and opened in windows firewall second.

Body:
I need to write an application which connects to a FTP server. This FTP server does not allows passive mode connections. I can connect to the FTP server using Filezilla.

I have developed a C# WCF service which connects to this FTP server, using FTPWebRequest class.
    Here are the basic settings of the FTPWebRequest object:

ftpreq.Proxy = null;
ftpreq.KeepAlive = true;
ftpreq.UsePassive = false;

When I run the WCF service from Visual Studio(Ctrl+F5) it connects to the FTP server and downloads required files without any issues

But when I host the service in my local IIS 7.5, it fails to connect to the FTP server with following error:

The remote server returned an error: (425) Can't open data connection.

After some googling on this problem, I tried playing around the firewall settings, but it was of no use. Not sure if it is related to some IIS security issue or something else.

Any help would be highly appreciated


问:
PDF file printing on client side using javascript
I am trying to print a pdf file on the client side using javascript. My javascript code is as below

```<code>function doit() {
    var win = document.getElementById("pdf");
    var frm = document.getElementById("pdf").contentWindow;
    frm.print();
    win.print();
}
</code>```

The problem is that frm is always null and win does not have a function of print

My pdf element is as below

```<code><iframe id="pdf" name="pdf" src="C:\My_P.pdf"></iframe>
</code>```

I am calling the function from c# as below

```<code>ClientScript.RegisterStartupScript(this.GetType(), "Print", "doit();", true);
</code>```

Really struggling. Please help

答:
Are you being hampered by same origin policy?

In the past I've used:

```<code>window.frames["pdf"].focus();
window.frames["pdf"].print();
</code>```

Body:
I am trying to print a pdf file on the client side using javascript. My javascript code is as below

function doit() {
    var win = document.getElementById("pdf");
    var frm = document.getElementById("pdf").contentWindow;
    frm.print();
    win.print();
}

The problem is that frm is always null and win does not have a function of print

My pdf element is as below

I am calling the function from c# as below

ClientScript.RegisterStartupScript(this.GetType(), "Print", "doit();", true);

Really struggling. Please help

Body:
Are you being hampered by same origin policy?

In the past I've used:

window.frames["pdf"].focus();
window.frames["pdf"].print();


问:
Cannot convert value of type 'UIImage' to expected argument type 'String'
I am lost, is there any alternative?</p>

```<code>let swiftCourse = Course(buttonImage: #imageLiteral(resourceName: "cover_developer"),
                  title: "Become a Developer",
                  instructor: "Duc Tran",
                  featureImage: #imageLiteral(resourceName: "developer"),
                  introductionVideoURL: URL(String: "https://www.youtube.com/watch?v=Inn2K-V3NFI"),
                  description: "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.")
</code>```

答:
The way your class Course is set up, presumably it is expecting a String.

Change the argument in the constructor to simply "cover_developer".

Body:
I am lost, is there any alternative?

let swiftCourse = Course(buttonImage: #imageLiteral(resourceName: "cover_developer"),
                  title: "Become a Developer",
                  instructor: "Duc Tran",
                  featureImage: #imageLiteral(resourceName: "developer"),
                  introductionVideoURL: URL(String: "https://www.youtube.com/watch?v=Inn2K-V3NFI"),
                  description: "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.")


问:
How create GPS Tools?
I try display Google Maps inside my Fragment. The problem is when I run my project I do not see this maps. The additional information is this fragments belongs to Pager View.

This is my sample of code:

```<code>public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        thisContext = inflater.getContext();
        View view = inflater.inflate(R.layout.tab_fragment_2, container, false);
        loadMap();
       // initializeMap();

        locationManager = (LocationManager) thisContext.getSystemService(Context.LOCATION_SERVICE);

        if (ActivityCompat.checkSelfPermission(thisContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(thisContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this);

        return view;

    }

    private void initializeMap() {
        if (map == null) {
            SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
            mapFrag.getMapAsync(this);
        }
    }

    private void loadMap() {
        SupportMapFragment mSupportMapFragment;

        mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        if (mSupportMapFragment == null) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            mSupportMapFragment = SupportMapFragment.newInstance();
            fragmentTransaction.replace(R.id.map, mSupportMapFragment).commit();
        }

        if (mSupportMapFragment != null) {
            mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    if (googleMap != null) {

                        googleMap.getUiSettings().setAllGesturesEnabled(true);

                        // -> marker_latlng // MAKE THIS WHATEVER YOU WANT

                        //CameraPosition cameraPosition = new CameraPosition.Builder().target(marker_latlng).zoom(15.0f).build();
                        // CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
                        // googleMap.moveCamera(cameraUpdate);

                    }

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

答: The best thing so far I know for Fragment is to use MapView instead of MapFragment. I am using MapView inside a Navigation Drawer Fragment and its working fine with all callbacks that I need and PlacesAutoComplete.

Title: How create GPS Tools?

Body:
I try display Google Maps inside my Fragment. The problem is when I run my project I do not see this maps. The additional information is this fragments belongs to Pager View.

This is my sample of code:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        thisContext = inflater.getContext();
        View view = inflater.inflate(R.layout.tab_fragment_2, container, false);
        loadMap();
       // initializeMap();

        locationManager = (LocationManager) thisContext.getSystemService(Context.LOCATION_SERVICE);

        if (ActivityCompat.checkSelfPermission(thisContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(thisContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this);

        return view;

    }

    private void initializeMap() {
        if (map == null) {
            SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
            mapFrag.getMapAsync(this);
        }
    }

    private void loadMap() {
        SupportMapFragment mSupportMapFragment;

        mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        if (mSupportMapFragment == null) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            mSupportMapFragment = SupportMapFragment.newInstance();
            fragmentTransaction.replace(R.id.map, mSupportMapFragment).commit();
        }

        if (mSupportMapFragment != null) {
            mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    if (googleMap != null) {

                        googleMap.getUiSettings().setAllGesturesEnabled(true);

                        // -> marker_latlng // MAKE THIS WHATEVER YOU WANT

                        //CameraPosition cameraPosition = new CameraPosition.Builder().target(marker_latlng).zoom(15.0f).build();
                        // CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
                        // googleMap.moveCamera(cameraUpdate);

                    }

                }
            });
        }
    }


问:
Are reset password links a bad idea?
We have a password reset web application. The application sends out an confirmation code to an alternative e-mail. My manager believes it is not a good idea to include a link to the page were you have to enter the code.

I see his argument. However, the helpdesk has been overwhelmed with users who are confused about the process. I'm assuming this is because many our users browse using only one tab/window and navigate out of our web application to check their e-mail for the confirmation code.

My question: How should we approach this issue? I would like to alleviate helpdesk and, in turn, make the process pain free for our users. Any suggestions?

Clarification

He believes that we are doing the user a disservice by training them to click links from a sender that cannot be verified (in this case, it's an automatic message with a "no-reply" address). This, would in turn, make users more susceptible to phishing attempts which we've had a lot of issues with in our organization.

答:
I think sending links is the standard way of doing it. If a customer is really worried about the integrity of this email account, he better gets that sorted out first.

Essentially you don't gain extra security by not sending the link, but you gain a lot of comfort. Just do it like everyone else - put it in there (time limited).

Title: Are reset password links a bad idea?