问:
Access to singleton instance fails with derived class
I have a database wrapper code like this (pseudo code):

```<code>class MyDBWrapper<objecttype> : Singleton
{
    private DBDriver _Driver

    Driver => Instance._Driver;

    ... tons of static functionality here referencing the driver
}
</code>```

and then I can create custom databases from it:

```<code>class ObjectA_DB : MyDBWrapper<ObjectA_Type>
{
    ... all my calls using the static functionalities of the base class
}
</code>```

this works very well...

Now, comes a different scenario:

I have a generic object: BaseObject
and a bunch of derived objects: ObjectA, ObjectB, etc

and they all require the same database code, so I did that:

```<code>class MyGenericDB<T> : MyDBWrapper<T> where T : BaseObject
{
    .. common functionality
}
</code>```

and then instantiated the type specific classes like this:

```<code>class MyTypeA_DB : MyGenericDB<ObjectA_Type>
class MyTypeB_DB : MyGenericDB<ObjectB_Type>
</code>```

and this compiles properly, however the singleton code is causing problem when I try to access the instance
as it seems like it's recursing. Visual studio is unable to give a proper error as to what happens, but it hangs then crashes, so I am guessing a stack overflow.

The singleton code is here:

```<code>public abstract class Singleton<T> where T : class
{
    private static readonly Lazy<T> _Instance = new Lazy<T>(CreateInstanceOfT, LazyThreadSafetyMode.PublicationOnly);
    protected static T Instance => _Instance.Value;
    private static T CreateInstanceOfT()
    {
        return Activator.CreateInstance(typeof(T), true) as T;
    }
}
</code>```

Did I miss anything obvious?

答:
Not that used to this version of generics as my main work is in unity, and they update their core every decade, but I am pretty sure that you need your instance to be public to be allowed to read it.

When I write this, I traditionally create a private static instance of the passed type, and follow that up with a public static access function that creates that type if it does not yet exist.

A good full example for my own main engine can be found here:
http://wiki.unity3d.com/index.php/Singleton.

Body:
I have a database wrapper code like this (pseudo code):

class MyDBWrapper<objecttype> : Singleton
{
    private DBDriver _Driver

    Driver => Instance._Driver;

    ... tons of static functionality here referencing the driver
}

and then I can create custom databases from it:

class ObjectA_DB : MyDBWrapper<ObjectA_Type>
{
    ... all my calls using the static functionalities of the base class
}

this works very well...

Now, comes a different scenario:

I have a generic object: BaseObject
and a bunch of derived objects: ObjectA, ObjectB, etc

and they all require the same database code, so I did that:

class MyGenericDB<T> : MyDBWrapper<T> where T : BaseObject
{
    .. common functionality
}

and then instantiated the type specific classes like this:

class MyTypeA_DB : MyGenericDB<ObjectA_Type>
class MyTypeB_DB : MyGenericDB<ObjectB_Type>

and this compiles properly, however the singleton code is causing problem when I try to access the instance
as it seems like it's recursing. Visual studio is unable to give a proper error as to what happens, but it hangs then crashes, so I am guessing a stack overflow.

The singleton code is here:

public abstract class Singleton<T> where T : class
{
    private static readonly Lazy<T> _Instance = new Lazy<T>(CreateInstanceOfT, LazyThreadSafetyMode.PublicationOnly);
    protected static T Instance => _Instance.Value;
    private static T CreateInstanceOfT()
    {
        return Activator.CreateInstance(typeof(T), true) as T;
    }
}

Did I miss anything obvious?


来源: stackexchange

问:
AEM::Dispatcher issue
I have configured dispatcher on my local on AEM and now trying the URL http://www.mywebapp.com (this entry is made in hosts file too). Here is the error that I am getting

```<code>[Tue Mar 10 12:25:43 2015] [D] [7268(496)] Found farm website for www.mywebapp.com
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] checking [/]
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] request URL has no extension: /
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] cache-action for [/]: NONE
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] Filter rejects: GET / HTTP/1.1
[Tue Mar 10 12:25:43 2015] [I] [7268(496)] "GET /" - - 1ms
</code>```

Here is the dispatcher.any file. I am not sure what filter is exactly blocking the request:

```<code># Each farm configures a set of load balanced renders (i.e. remote servers)
/farms
  {
  # First farm entry
  /website
    {
    # Request headers that should be forwarded to the remote server.
    /clientheaders
      {
      # Forward all request headers that are end-to-end. If you want
      # to forward a specific set of headers, you'll have to list
      # them here.
      "*"
      }

    # Hostname globbing for farm selection (virtual domain addressing)
    /virtualhosts
      {
      # Entries will be compared against the "Host" request header
      # and an optional request URL prefix.
      #
      # Examples:
      #
      #   www.company.com
      #   intranet.*
      #   myhost:8888/mysite
      "*"
      }

    # The load will be balanced among these render instances
    /renders
      {
      /rend01
        {
        # Hostname or IP of the render
        /hostname "127.0.0.1"
        # Port of the render
        /port "4503"
        # Connect timeout in milliseconds, 0 to wait indefinitely
        # /timeout "0"
        }
      }

    # The filter section defines the requests that should be handled by the dispatcher.
    # The globs will be compared against the request line, e.g. "GET /index.html HTTP/1.1".
    /filter
      {
      # Deny everything first and then allow specific entries
      /0001 { /type "deny"  /glob "*" }

      # Open consoles
#     /0011 { /type "allow" /glob "* /admin/*"  }  # allow servlet engine admin
#     /0012 { /type "allow" /glob "* /crx/*"    }  # allow content repository
#     /0013 { /type "allow" /glob "* /system/*" }  # allow OSGi console

      # Allow non-public content directories
#     /0021 { /type "allow" /glob "* /apps/*"   }  # allow apps access
#     /0022 { /type "allow" /glob "* /bin/*"    }
      /0023 { /type "allow" /glob "* /content*" }  # disable this rule to allow mapped content only

#     /0024 { /type "allow" /glob "* /libs/*"   }
#     /0025 { /type "deny"  /glob "* /libs/shindig/proxy*" } # if you enable /libs close access to proxy

#     /0026 { /type "allow" /glob "* /home/*"   }
#     /0027 { /type "allow" /glob "* /tmp/*"    }
#     /0028 { /type "allow" /glob "* /var/*"    }

      # Enable specific mime types in non-public content directories
      /0041 { /type "allow" /glob "* *.css *"   }  # enable css
      /0042 { /type "allow" /glob "* *.gif *"   }  # enable gifs
      /0043 { /type "allow" /glob "* *.ico *"   }  # enable icos
      /0044 { /type "allow" /glob "* *.js *"    }  # enable javascript
      /0045 { /type "allow" /glob "* *.png *"   }  # enable png
      /0046 { /type "allow" /glob "* *.swf *"   }  # enable flash
      /0047 { /type "allow" /glob "* *.html *"   }  # enable flash

      # Enable features
      /0061 { /type "allow" /glob "POST /content/[.]*.form.html" }  # allow POSTs to form selectors under content
      /0062 { /type "allow" /glob "* /libs/cq/personalization/*"  }  # enable personalization

      # Deny content grabbing
      /0081 { /type "deny"  /glob "GET *.infinity.json*" }
      /0082 { /type "deny"  /glob "GET *.tidy.json*"     }
      /0083 { /type "deny"  /glob "GET *.sysview.xml*"   }
      /0084 { /type "deny"  /glob "GET *.docview.json*"  }
      /0085 { /type "deny"  /glob "GET *.docview.xml*"  }

      /0086 { /type "deny"  /glob "GET *.*[0-9].json*" }
#     /0087 { /type "allow" /glob "GET *.1.json*" }          # allow one-level json requests

      # Deny query
      /0090 { /type "deny"  /glob "* *.query.json*" }
      }

    # The cache section regulates what responses will be cached and where.
    /cache
      {
      # The docroot must be equal to the document root of the webserver. The
      # dispatcher will store files relative to this directory and subsequent
      # requests may be "declined" by the dispatcher, allowing the webserver
      # to deliver them just like static files.
      /docroot "C:/Apache2.2/htdocs"

      # Sets the level upto which files named ".stat" will be created in the
      # document root of the webserver. When an activation request for some
      # page is received, only files within the same subtree are affected
      # by the invalidation.
      /statfileslevel "3"

      # Flag indicating whether to cache responses to requests that contain
      # authorization information.
      /allowAuthorized "1"

      # Flag indicating whether the dispatcher should serve stale content if
      # no remote server is available.
      #/serveStaleOnError "0"

      # The rules section defines what responses should be cached based on
      # the requested URL. Please note that only the following requests can
      # lead to cacheable responses:
      #
      # - HTTP method is GET
      # - URL has an extension
      # - Request has no query string
      # - Request has no "Authorization" header (unless allowAuthorized is 1)
      /rules
        {
        /0000
          {
          # the globbing pattern to be compared against the url
          # example: *             -> everything
          #        : /foo/bar.*    -> only the /foo/bar documents
          #        : /foo/bar/*    -> all pages below /foo/bar
          #        : /foo/bar[./]* -> all pages below and /foo/bar itself
          #        : *.html        -> all .html files
          /glob "*"
          /type "allow"
          }
        }

      # The invalidate section defines the pages that are "invalidated" after
      # any activation. Please note that the activated page itself and all
      # related documents are flushed on an modification. For example: if the
      # page /foo/bar is activated, all /foo/bar.* files are removed from the
      # cache.
      /invalidate
        {
        /0000
          {
          /glob "*"
          /type "deny"
          }
        /0001
          {
          # Consider all HTML files stale after an activation.
          /glob "*.html"
          /type "allow"
          }
        }

      # The allowedClients section restricts the client IP addresses that are
      # allowed to issue activation requests.
      /allowedClients
        {
        # Uncomment the following to restrict activation requests to originate
        # from "localhost" only.
        #
        #/0000
        #  {
        #  /glob "*"
        #  /type "deny"
        #  }
        #/0001
        #  {
        #  /glob "127.0.0.1"
        #  /type "allow"
        #  }
        }
      }

    # The statistics sections dictates how the load should be balanced among the
    # renders according to the media-type.
    /statistics
      {
      /categories
        {
        /html
          {
          /glob "*.html"
          }
        /others
          {
          /glob "*"
          }
        }
      }
    }
  }
</code>```

答:
There are two ways we can resolve it.

1, In filter section add the below rule.
  /0001 { /type "allow"  /glob "*" }

2, normally in real time projects we have content under /content/xyz.html, for this kind of scenario we add below rules.

```<code>`/0001 { /type "deny"  /glob "*" }`
`/0001 { /type "allow"  /glob "/content/*" }`
</code>```

Add a rewrite rule which any thing after URL redirect to /content/xyz.html.

RewriteRule ^/(.*) /content/mywebapp/$1 [R=301, L]

keep adding deny and allow rules as per the project requirements.

ContentLicense: CC BY-SA 3.0

Title: AEM::Dispatcher issue

Body:
I have configured dispatcher on my local on AEM and now trying the URL http://www.mywebapp.com (this entry is made in hosts file too). Here is the error that I am getting

[Tue Mar 10 12:25:43 2015] [D] [7268(496)] Found farm website for www.mywebapp.com
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] checking [/]
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] request URL has no extension: /
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] cache-action for [/]: NONE
[Tue Mar 10 12:25:43 2015] [D] [7268(496)] Filter rejects: GET / HTTP/1.1
[Tue Mar 10 12:25:43 2015] [I] [7268(496)] "GET /" - - 1ms

Here is the dispatcher.any file. I am not sure what filter is exactly blocking the request:

# Each farm configures a set of load balanced renders (i.e. remote servers)
/farms
  {
  # First farm entry
  /website
    {
    # Request headers that should be forwarded to the remote server.
    /clientheaders
      {
      # Forward all request headers that are end-to-end. If you want
      # to forward a specific set of headers, you'll have to list
      # them here.
      "*"
      }

    # Hostname globbing for farm selection (virtual domain addressing)
    /virtualhosts
      {
      # Entries will be compared against the "Host" request header
      # and an optional request URL prefix.
      #
      # Examples:
      #
      #   www.company.com
      #   intranet.*
      #   myhost:8888/mysite
      "*"
      }

    # The load will be balanced among these render instances
    /renders
      {
      /rend01
        {
        # Hostname or IP of the render
        /hostname "127.0.0.1"
        # Port of the render
        /port "4503"
        # Connect timeout in milliseconds, 0 to wait indefinitely
        # /timeout "0"
        }
      }

    # The filter section defines the requests that should be handled by the dispatcher.
    # The globs will be compared against the request line, e.g. "GET /index.html HTTP/1.1".
    /filter
      {
      # Deny everything first and then allow specific entries
      /0001 { /type "deny"  /glob "*" }

      # Open consoles
#     /0011 { /type "allow" /glob "* /admin/*"  }  # allow servlet engine admin
#     /0012 { /type "allow" /glob "* /crx/*"    }  # allow content repository
#     /0013 { /type "allow" /glob "* /system/*" }  # allow OSGi console

      # Allow non-public content directories
#     /0021 { /type "allow" /glob "* /apps/*"   }  # allow apps access
#     /0022 { /type "allow" /glob "* /bin/*"    }
      /0023 { /type "allow" /glob "* /content*" }  # disable this rule to allow mapped content only

#     /0024 { /type "allow" /glob "* /libs/*"   }
#     /0025 { /type "deny"  /glob "* /libs/shindig/proxy*" } # if you enable /libs close access to proxy

#     /0026 { /type "allow" /glob "* /home/*"   }
#     /0027 { /type "allow" /glob "* /tmp/*"    }
#     /0028 { /type "allow" /glob "* /var/*"    }

      # Enable specific mime types in non-public content directories
      /0041 { /type "allow" /glob "* *.css *"   }  # enable css
      /0042 { /type "allow" /glob "* *.gif *"   }  # enable gifs
      /0043 { /type "allow" /glob "* *.ico *"   }  # enable icos
      /0044 { /type "allow" /glob "* *.js *"    }  # enable javascript
      /0045 { /type "allow" /glob "* *.png *"   }  # enable png
      /0046 { /type "allow" /glob "* *.swf *"   }  # enable flash
      /0047 { /type "allow" /glob "* *.html *"   }  # enable flash

      # Enable features
      /0061 { /type "allow" /glob "POST /content/[.]*.form.html" }  # allow POSTs to form selectors under content
      /0062 { /type "allow" /glob "* /libs/cq/personalization/*"  }  # enable personalization

      # Deny content grabbing
      /0081 { /type "deny"  /glob "GET *.infinity.json*" }
      /0082 { /type "deny"  /glob "GET *.tidy.json*"     }
      /0083 { /type "deny"  /glob "GET *.sysview.xml*"   }
      /0084 { /type "deny"  /glob "GET *.docview.json*"  }
      /0085 { /type "deny"  /glob "GET *.docview.xml*"  }

      /0086 { /type "deny"  /glob "GET *.*[0-9].json*" }
#     /0087 { /type "allow" /glob "GET *.1.json*" }          # allow one-level json requests

      # Deny query
      /0090 { /type "deny"  /glob "* *.query.json*" }
      }

    # The cache section regulates what responses will be cached and where.
    /cache
      {
      # The docroot must be equal to the document root of the webserver. The
      # dispatcher will store files relative to this directory and subsequent
      # requests may be "declined" by the dispatcher, allowing the webserver
      # to deliver them just like static files.
      /docroot "C:/Apache2.2/htdocs"

      # Sets the level upto which files named ".stat" will be created in the
      # document root of the webserver. When an activation request for some
      # page is received, only files within the same subtree are affected
      # by the invalidation.
      /statfileslevel "3"

      # Flag indicating whether to cache responses to requests that contain
      # authorization information.
      /allowAuthorized "1"

      # Flag indicating whether the dispatcher should serve stale content if
      # no remote server is available.
      #/serveStaleOnError "0"

      # The rules section defines what responses should be cached based on
      # the requested URL. Please note that only the following requests can
      # lead to cacheable responses:
      #
      # - HTTP method is GET
      # - URL has an extension
      # - Request has no query string
      # - Request has no "Authorization" header (unless allowAuthorized is 1)
      /rules
        {
        /0000
          {
          # the globbing pattern to be compared against the url
          # example: *             -> everything
          #        : /foo/bar.*    -> only the /foo/bar documents
          #        : /foo/bar/*    -> all pages below /foo/bar
          #        : /foo/bar[./]* -> all pages below and /foo/bar itself
          #        : *.html        -> all .html files
          /glob "*"
          /type "allow"
          }
        }

      # The invalidate section defines the pages that are "invalidated" after
      # any activation. Please note that the activated page itself and all
      # related documents are flushed on an modification. For example: if the
      # page /foo/bar is activated, all /foo/bar.* files are removed from the
      # cache.
      /invalidate
        {
        /0000
          {
          /glob "*"
          /type "deny"
          }
        /0001
          {
          # Consider all HTML files stale after an activation.
          /glob "*.html"
          /type "allow"
          }
        }

      # The allowedClients section restricts the client IP addresses that are
      # allowed to issue activation requests.
      /allowedClients
        {
        # Uncomment the following to restrict activation requests to originate
        # from "localhost" only.
        #
        #/0000
        #  {
        #  /glob "*"
        #  /type "deny"
        #  }
        #/0001
        #  {
        #  /glob "127.0.0.1"
        #  /type "allow"
        #  }
        }
      }

    # The statistics sections dictates how the load should be balanced among the
    # renders according to the media-type.
    /statistics
      {
      /categories
        {
        /html
          {
          /glob "*.html"
          }
        /others
          {
          /glob "*"
          }
        }
      }
    }
  }

Body:
There are two ways we can resolve it.

1, In filter section add the below rule.
  /0001 { /type "allow"  /glob "*" }

2, normally in real time projects we have content under /content/xyz.html, for this kind of scenario we add below rules.

`/0001 { /type "deny"  /glob "*" }`
`/0001 { /type "allow"  /glob "/content/*" }`

Add a rewrite rule which any thing after URL redirect to /content/xyz.html.

RewriteRule ^/(.*) /content/mywebapp/$1 [R=301, L]

keep adding deny and allow rules as per the project requirements.


问:
Use Results of CTE to Update Another Table
I have the following CTE that does what I want it to do.

```<code>;WITH numbering AS
(
    SELECT SrcID, AsOfDate, PID,
           dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
    FROM   RAW_DATA
)
SELECT SrcID,
       MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
       MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
       MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
       MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
FROM   numbering
GROUP BY SrcID
</code>```

I need to use that, as well as the AsOfDate and PID, but I don’t want to display these in the CTE, as that throws off populating PID1, PID2, PID3, and PID4 . . . all of which is correct now.  I do need the SrcID and AsOfDate to do an update to another table, named ‘RAW_DATA’.  How can I run the CTE to generate the specific data set that I need, and then do an update to the RAW_DATA table, based on joins between SrcID and AsOfDate?

I think it should be something like this:

```<code>    ;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,
               dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )
    SELECT SrcID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    FROM   numbering
    GROUP BY SrcID

INSERT INTO RAW_DATA(SrcID, AsOfDate, PID, PID1, PID2, PID3, PID4)
Select *
FROM         RAW_DATA INNER JOIN numbering
             ON RAW_DATA.SrcID = numbering.SrcID
             AND RAW_DATA.AsofDate = numbering.AsofDate
</code>```

However, that throws this error: Invalid object name 'numbering'.  I am on SQL Server 2008.

Update

Modifying my original post just a bit here.

Jeffrey, I'm testing your solution:

```<code>--drop table Count_Unique_PID
;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,PID1,PID2,PID3,PID4,
               dense_rank() OVER (PARTITION BY AsOfDate, SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )

    SELECT SrcID,AsOfDate, PID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    INTO Count_Unique_PID
    FROM   numbering
    GROUP BY SrcID,AsOfDate, PID

    SELECT SrcID,
           AsOfDate,
           PID,
           PID1,
           PID2,
           PID3,
           PID4
    FROM   Count_Unique_PID
    GROUP BY SrcID,AsOfDate, PID,PID1,PID2,PID3,PID4

UPDATE    RAW_DATA
SET              PID1 = B.PID1,
                 PID2 = B.PID2,
                 PID3 = B.PID3,
                 PID4 = B.PID4
FROM         RAW_DATA AS A INNER JOIN Count_Unique_PID  As B
             ON A.SrcID = B.SrcID
             AND A.AsofDate = B.AsofDate
</code>```

This runs, but it blows up my rows from 357,518 to 724,150.  The number of records should stay the same; it should remain 357,518 after the Update is done...something is still not quite right here.  Maybe I am missing a Group By somewhere, or something like that.  I don't see what the actual problem is.  Any additional thoughts on this?

答:
You need encapsulate your query as a second cte:

sintaxis is

```<code>WITH cte1 as (
   SELECT ...
), cte2  as (
   SELECT *
   FROM cte1
   .....
)
INSERT INTO table_name
SELECT *
FROM cte2
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following CTE that does what I want it to do.

;WITH numbering AS
(
    SELECT SrcID, AsOfDate, PID,
           dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
    FROM   RAW_DATA
)
SELECT SrcID,
       MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
       MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
       MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
       MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
FROM   numbering
GROUP BY SrcID

I need to use that, as well as the AsOfDate and PID, but I don’t want to display these in the CTE, as that throws off populating PID1, PID2, PID3, and PID4 . . . all of which is correct now.  I do need the SrcID and AsOfDate to do an update to another table, named ‘RAW_DATA’.  How can I run the CTE to generate the specific data set that I need, and then do an update to the RAW_DATA table, based on joins between SrcID and AsOfDate?

I think it should be something like this:

    ;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,
               dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )
    SELECT SrcID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    FROM   numbering
    GROUP BY SrcID

INSERT INTO RAW_DATA(SrcID, AsOfDate, PID, PID1, PID2, PID3, PID4)
Select *
FROM         RAW_DATA INNER JOIN numbering
             ON RAW_DATA.SrcID = numbering.SrcID
             AND RAW_DATA.AsofDate = numbering.AsofDate

However, that throws this error: Invalid object name 'numbering'.  I am on SQL Server 2008.

Update

Modifying my original post just a bit here.

Jeffrey, I'm testing your solution:

--drop table Count_Unique_PID
;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,PID1,PID2,PID3,PID4,
               dense_rank() OVER (PARTITION BY AsOfDate, SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )

    SELECT SrcID,AsOfDate, PID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    INTO Count_Unique_PID
    FROM   numbering
    GROUP BY SrcID,AsOfDate, PID

    SELECT SrcID,
           AsOfDate,
           PID,
           PID1,
           PID2,
           PID3,
           PID4
    FROM   Count_Unique_PID
    GROUP BY SrcID,AsOfDate, PID,PID1,PID2,PID3,PID4

UPDATE    RAW_DATA
SET              PID1 = B.PID1,
                 PID2 = B.PID2,
                 PID3 = B.PID3,
                 PID4 = B.PID4
FROM         RAW_DATA AS A INNER JOIN Count_Unique_PID  As B
             ON A.SrcID = B.SrcID
             AND A.AsofDate = B.AsofDate

This runs, but it blows up my rows from 357,518 to 724,150.  The number of records should stay the same; it should remain 357,518 after the Update is done...something is still not quite right here.  Maybe I am missing a Group By somewhere, or something like that.  I don't see what the actual problem is.  Any additional thoughts on this?

Body:
You need encapsulate your query as a second cte:

sintaxis is

WITH cte1 as (
   SELECT ...
), cte2  as (
   SELECT *
   FROM cte1
   .....
)
INSERT INTO table_name
SELECT *
FROM cte2


问:
How to rotate views to portrait mode?
I have an application whose orientation is hard coded to landscape in the Manifest file.
When the user presses options/menu on the application, the application launches a gridview/listview (depending on the option clicked). This works very well in the landscape mode.
However, I run into problems if I want to change the UI when the user views the application in portrait mode.
No matter what the mode the phone is in, the UIs are always displayed in landscape. (Because of the setting in the Manifest file).
I tried doing a rotate animation (90 degrees), but that causes problems. For the list view, the scrolling does not work properly after the animation, and for the grid view, the clicks on the grid view elements correspond to the older layout (landscape) and not the newer one (after rotate animation).
Has anyone encountered this problem before? Any suggestions would be most welcome. </p>

答:
Try using the setRequestedOrientation method on your activity:

```<code>activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to rotate views to portrait mode?

Body:
Try using the setRequestedOrientation method on your activity:

activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


问:
Returning more than one output in C extensions?
Python allows to return more than one result using commas as separating value.

When developing a CPython extension written in C language, is it possible to obtain the same result? How?

I'm developing a CPython extension that replaces an existing Python code to do some tests on performance and I will prefer to have the same interface to not change the existing code base.

I'm using Python 3.6.

答:
Yes, you can create a tuple with PyTuple_New, populate it and return it. The callee will be able to unpack the result as usual.

Python returns multiple values by using containers. A single object is returned that is unpacked. Comma separated means tuple; in square brackets, on the other hand, a list is created. See How does Python return multiple values from a function for more on this.

If you'd like an example of how one might do this in C you can take a look at the implementation of str.partition or array.buffer_info (or any tuple returning built-in method).


问:
device validation layer vulkan

Hello, I'm beginning with vulkan API, I'm trying to show Validation layers.
But the problem is I only have access to one device validation layer : "VK_LAYER_NV_optimus"

```<code>{//Enumerating Device Verification Layers
    uint32_t layer_count = 0;
    vkEnumerateDeviceLayerProperties(_gpu, &layer_count, nullptr);
    std::vector<VkLayerProperties> layer_property_list(layer_count);
    vkEnumerateDeviceLayerProperties(_gpu, &layer_count, layer_property_list.data());
    std::cout << "Device Layers : \n";
    for (auto &i : layer_property_list) {
        std::cout << "  " << i.layerName << "\t\t | " << i.description << std::endl;
    }
    std::cout << std::endl;
}
</code>```

In the tutorial i'm following the guys have way more layers whose "VK_LAYER_LUNARG_standard_validation" he is using.

here you can see what the guy got.

I though maybe the tutorial isn't up to date but i can't find anything related to this topic.

thanks for helping :)

答:
Consider using vkEnumerateInstanceLayerProperties.

Device layers were deprecated in Vulkan some time ago, essentially making all layers instance layers.  In this case, the Optimus layer is probably being registered as both an instance and a device layer, which is allowed and is why it shows up when you list the device layers.

If that does not help, you may have an installation problem that is preventing you from seeing the layers.  Consider running vulkaninfo or via to help troubleshoot the problem.

Finally, not all layers are validation layers.  When you enumerate the layers, you'll find layers that perform other functions, as seen in the screenshot you provided.

Title: device validation layer vulkan

Body:
Hello, I'm beginning with vulkan API, I'm trying to show Validation layers.
But the problem is I only have access to one device validation layer : "VK_LAYER_NV_optimus"

{//Enumerating Device Verification Layers
    uint32_t layer_count = 0;
    vkEnumerateDeviceLayerProperties(_gpu, &layer_count, nullptr);
    std::vector<VkLayerProperties> layer_property_list(layer_count);
    vkEnumerateDeviceLayerProperties(_gpu, &layer_count, layer_property_list.data());
    std::cout << "Device Layers : \n";
    for (auto &i : layer_property_list) {
        std::cout << "  " << i.layerName << "\t\t | " << i.description << std::endl;
    }
    std::cout << std::endl;
}

In the tutorial i'm following the guys have way more layers whose "VK_LAYER_LUNARG_standard_validation" he is using.

here you can see what the guy got.

I though maybe the tutorial isn't up to date but i can't find anything related to this topic.

thanks for helping :)


问:
Building API Call 'Authorization' header MVC5
Before I ask the question, I would like to point out that I have already been through the API Documentation at www.developer.intuit.com, and I have also done a search on Stack Overflow.  I mention this because I want to avoid any responses that include "why don't you read the Documentation or do a search".  As far as I can tell, this isn't actually addressed in the documentation.

I am attempting to call the API using an HttpClient object, and the only thing I am missing are the details concerning how exactly to construct the Authorization header.

This is the block of code that builds and handles the API call:

```<code>string jsonString = JsonConvert.SerializeObject(customer, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
var httpResponse = new HttpResponseMessage();
    using (var client = new HttpClient()) {
        client.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8");
        client.DefaultRequestHeaders.Add("ContentType", "application/json;charset=UTF-8");
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppController.access_token);
        httpResponse = await client.PostAsync(uri, httpContent);
    }
</code>```

I have made the change suggested by Coder1409, and reflected that change in the code block above.  I am still getting an error, but the error number has changed.

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2017-12-04T07:57:11.131-08:00">
    <Fault type="AuthenticationFault">
        <Error code="100">
        <Message>General Authentication Error</Message>
        <Detail>AuthenticationErrorGeneral: Internal Server Error , statusCode: 500</Detail>
        </Error>
    </Fault>
</IntuitResponse>
</code>```

答:
Think you should change this line </p>

```<code> client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth2", AppController.access_token);
</code>```

<p>to this </p>

```<code> client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppController.access_token);
</code>```

Body:
Before I ask the question, I would like to point out that I have already been through the API Documentation at www.developer.intuit.com, and I have also done a search on Stack Overflow.  I mention this because I want to avoid any responses that include "why don't you read the Documentation or do a search".  As far as I can tell, this isn't actually addressed in the documentation.

I am attempting to call the API using an HttpClient object, and the only thing I am missing are the details concerning how exactly to construct the Authorization header.

This is the block of code that builds and handles the API call:

string jsonString = JsonConvert.SerializeObject(customer, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
var httpResponse = new HttpResponseMessage();
    using (var client = new HttpClient()) {
        client.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8");
        client.DefaultRequestHeaders.Add("ContentType", "application/json;charset=UTF-8");
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppController.access_token);
        httpResponse = await client.PostAsync(uri, httpContent);
    }

I have made the change suggested by Coder1409, and reflected that change in the code block above.  I am still getting an error, but the error number has changed.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2017-12-04T07:57:11.131-08:00">
    <Fault type="AuthenticationFault">
        <Error code="100">
        <Message>General Authentication Error</Message>
        <Detail>AuthenticationErrorGeneral: Internal Server Error , statusCode: 500</Detail>
        </Error>
    </Fault>
</IntuitResponse>

Body:
Think you should change this line

 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth2", AppController.access_token);

to this

 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppController.access_token);


问:
bing map- 2 pushpins same co-ordinate workaround?
I have multiple locations that I show on the bing map via pushpins at specific lat/long co-ordinates. There's a situation where 2 pushpins have the same co-ordinates and both are stacked on top of each other. So the user cannot click or see the pushpin below. Please suggest workarounds or any ideas.</p>

答:
The general approach is to display some sort of cluster icon to let the user see that there is more than one location represented by that pushpin, and then present a disambiguation box when the user clicks/hovers on the pushpin to let them choose which location they want to select.
This is the same approach as you would use to cluster pushpin data on the map - aggregating several distinct items of data into a single cluster unit.</p>


问:
What type of database is suited for realtime aggregated operations on millions of rows
I need to store 15-30 millions of rows of data. Most of the queries will be group by operations (aggregations). I'm currently using Teradata as the database backend. But the response time is not real-time (some queries are taking about 30 seconds). I was looking into Cassandra as a substitute but in some documentation, I found that if there are group by operations, then Cassandra is not the best option.

What database would be most suited for my use case given that a maximum of 100 users will use the application at a time (along with data updates happening in parallel)? Any traditional RDBMS can handle this kind of requirements?

Any help would be appreciated. Thanks in advance.

答: Cassandra itself is not so good for aggregation, consider Cassandra + Storm/Spark</p>


问:
Recover lost Umbraco Forms files from App_Plugins
Suddenly the files inside the folder App_Plugins/UmbracoForms have vanished and I cannot seem to recover them. The files include UmbracoForms.config, version, installed as well as the most important form data inside the Data folder.

Checking the file/folder history it seems that the files were last modified by the Application Pool user identity, meaning the website deleted it's own files.

Why would this happen and how is it possible to recover these files?

答:
I've never come across Forms/Umbraco deleting anything out of the App_Plugins folder without a user uninstalling the plugin in the back office.

Is it possible that someone has done a publish via VS or similar that's cleared the folder and replaced it?

In terms of getting the files back, if they've been deleted, you should in theory be able to recover them from your hosting company's back-ups (assuming the site is being regularly backed up).


问:
Strange URL in the WordPress theme causing error when the site loads
I am facing a problem i.e.,  the site is taking more than usual time to load and showing an error when I inspected the page.

I tried searching for the link through the source code of the page, but I wasn’t able to locate where that link is actually present.
I don’t know where from this URL came, but I want to remove it, as it is not letting the page to load properly and fast.
Please tell me how to eliminate this error.
Details -

URL - reportingall
Theme - Newspaper 8.5
Demo Module Installed - Gadgets
CMS - WordPress

I can provide more information, if required.
Thanks and have a nice day.

答:
It looks like the page is trying to load image 52.jpg with the HTTP protocol instead of the HTTPS protocol your website is using. It seems your theme is trying to set your header to have a background image of 52.jpg, if you can change the path to be HTTPS instead of HTTP that should correct that issue. I know wordpress has plugins that can achieve this, or you can try to contact the creator of the theme if you don't have access to change the path.

If you're looking to just remove the code, you can try and find:

background-image:url(http://192.168.0.120/wp_011_gadgets/wp-content/uploads/2017/03/52.jpg)

In your theme files and remove that, but if the theme is updated it will likely revert back and need to reapplied to each time you update the theme.

Hope this helps.


问:
django messages for a successfully delete,add or edit item
I have started using django messages for creating items.
It works great for creating adding a new item.

but.. I want to have functions for each action -
delete,create,edit ( I have different buttons for each)
I have only post function.. it really confuse me when I try to create a message that the item has been deleted successfuly.. how can I know a delete was submitted and not post? since everything goes through post function.

The PostEdit and Delete don't have the "request" that it requires for messages.

So for now I h ave only messages.succuess that runs everytime I create a server.
I want to have a different message for delete, edit, create and same for errors.

Does anyone have a clue?

index.html -

```<code>{% if messages %}
    <ul class="messages">
        {% for message in messages %}
        <div class="alert alert-success alert-dismissible fade show" role="alert">
                <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
        {% endfor %}
    </ul>
    {% endif %}
</code>```

views.py -

```<code># Create your views here.

from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.shortcuts import render, redirect
from django.template import RequestContext
from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView
from DevOpsWeb.forms import HomeForm
from DevOpsWeb.models import serverlist
from django.core.urlresolvers import reverse_lazy
from simple_search import search_filter
from django.db.models import Q
from django.contrib import messages

class HomeView(TemplateView):

    template_name = 'serverlist.html'

    def get(self, request):

        form = HomeForm()
        query = request.GET.get("q")
        posts = serverlist.objects.all()

        forms = {}

        if query:
            posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query))
        else:
            posts = serverlist.objects.all()
        for post in posts:
            forms[post.id] = HomeForm(instance=post)
        args = {'form' : form,'forms': forms, 'posts' : posts}

        return render(request, self.template_name, args)

    def post(self,request):
        form = HomeForm(request.POST)
        posts = serverlist.objects.all()
        forms = {}

        if form.is_valid(): # Checks if validation of the forms passed
            post = form.save(commit=False)
            post.save()
            messages.success(request,'{0} has been added successfully!'.format(post.ServerName))

            return redirect('serverlist')
        messages.error(request,'Servername is required, please refresh the page and try again.')
        for post in posts:
            forms[post.id] = HomeForm(instance=post)
        args = {'form' : form, 'forms': forms, 'posts' : posts}

        return render(request, self.template_name,args)

class PostDelete(DeleteView):
    model = serverlist
    success_url = reverse_lazy('serverlist')

class PostEdit(UpdateView):
    template_name = 'serverlist.html'
    model = serverlist
    form_class = HomeForm
    #messages.success(request,"The server has been edited successfully")
    #fields = ['ServerName','Owner','Project','Description','IP','ILO','Rack','Status']

    success_url = reverse_lazy('serverlist')
</code>```

答:
```<code>class PostEdit(UpdateView):
    template_name = 'serverlist.html'
    model = serverlist
    form_class = HomeForm
    #messages.success(request,"The server has been edited successfully")
</code>```

You can't call messages.success in the class definition like that. The call has to go in a method like post or form_valid.

The messages framework has a SuccessMessageMixin which you might find useful. You add the mixin to each view, and set success_message:

```<code>class PostDelete(SuccessMessageMixin, DeleteView):
    model = serverlist
    success_url = reverse_lazy('serverlist')
    success_message = "Object deleted"
</code>```

See the docs on adding messages to class-based views for more info.

Body:
I have started using django messages for creating items.
It works great for creating adding a new item.

but.. I want to have functions for each action -
delete,create,edit ( I have different buttons for each)
I have only post function.. it really confuse me when I try to create a message that the item has been deleted successfuly.. how can I know a delete was submitted and not post? since everything goes through post function.

The PostEdit and Delete don't have the "request" that it requires for messages.

So for now I h ave only messages.succuess that runs everytime I create a server.
I want to have a different message for delete, edit, create and same for errors.

Does anyone have a clue?

index.html -

{% if messages %}

        {% for message in messages %}

{{ message }}

                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    ×
                </button>

        {% endfor %}

    {% endif %}

views.py -

# Create your views here.

from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.shortcuts import render, redirect
from django.template import RequestContext
from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView
from DevOpsWeb.forms import HomeForm
from DevOpsWeb.models import serverlist
from django.core.urlresolvers import reverse_lazy
from simple_search import search_filter
from django.db.models import Q
from django.contrib import messages

class HomeView(TemplateView):

    template_name = 'serverlist.html'

    def get(self, request):

        form = HomeForm()
        query = request.GET.get("q")
        posts = serverlist.objects.all()

        forms = {}

        if query:
            posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query))
        else:
            posts = serverlist.objects.all()
        for post in posts:
            forms[post.id] = HomeForm(instance=post)
        args = {'form' : form,'forms': forms, 'posts' : posts}

        return render(request, self.template_name, args)

    def post(self,request):
        form = HomeForm(request.POST)
        posts = serverlist.objects.all()
        forms = {}

        if form.is_valid(): # Checks if validation of the forms passed
            post = form.save(commit=False)
            post.save()
            messages.success(request,'{0} has been added successfully!'.format(post.ServerName))

            return redirect('serverlist')
        messages.error(request,'Servername is required, please refresh the page and try again.')
        for post in posts:
            forms[post.id] = HomeForm(instance=post)
        args = {'form' : form, 'forms': forms, 'posts' : posts}

        return render(request, self.template_name,args)

class PostDelete(DeleteView):
    model = serverlist
    success_url = reverse_lazy('serverlist')

class PostEdit(UpdateView):
    template_name = 'serverlist.html'
    model = serverlist
    form_class = HomeForm
    #messages.success(request,"The server has been edited successfully")
    #fields = ['ServerName','Owner','Project','Description','IP','ILO','Rack','Status']

    success_url = reverse_lazy('serverlist')

Body:
class PostEdit(UpdateView):
    template_name = 'serverlist.html'
    model = serverlist
    form_class = HomeForm
    #messages.success(request,"The server has been edited successfully")

You can't call messages.success in the class definition like that. The call has to go in a method like post or form_valid.

The messages framework has a SuccessMessageMixin which you might find useful. You add the mixin to each view, and set success_message:

class PostDelete(SuccessMessageMixin, DeleteView):
    model = serverlist
    success_url = reverse_lazy('serverlist')
    success_message = "Object deleted"

See the docs on adding messages to class-based views for more info.


问:
How do I Spring enable a Tomcat valve
I wrote a Tomcat valve and configured it in server.xml.
So far so good. However, I want one of the valve's data members to be a Spring managed bean.
So, how can I make the valve also be Spring managed so that I can have Spring's IoC inject that dependency into the valve?</p>

答:
Valves aren't associated with an application, while spring contexts are. So you can't have a spring-managed bean in a Valve.

You can, of course, instantiate the spring context in the Valve constructor, and use context.autowireBean(this) there, but this will be a separate spring context, not one from any of the contexts available.

Technically, you have access to the contexts from the Valve, but afaik it is from the request, so you can obtain the ApplicationContext for each servlet context, and from there - get a reference to a bean, but that sounds odd.

Title: How do I Spring enable a Tomcat valve


问:
Cannot access protected symbol?
I'm getting

cannot access protected symbol TParent.Test

for following code:

In Unit1:

```<code>TParent = class
protected
  function Test: TParent;
end;

implementation

function TParent.Test: TParent;
begin
  Result := Self
end;
</code>```

In Unit2:

```<code>uses Unit1;

type

TChild = class(TParent)
end;

implementation

var c: TChild;
begin
  c := TChild.Create;
  c.Test.Test
end;
</code>```

Shouldn't the return value be accessible to TChild?

```<code>c.Test;
c.Test
</code>```

works, of course.

答:
The return value is accessible to TChild, but what you are trying to do is access it through a TParent within the TChild which is subtly different.

Think of it this way.

c.Test is a TParent, yes?

Now imagine that you had a TParent defined like this

```<code>var
  c: TChild;
  p: TParent
begin
  c := TChild.Create;
  p := c.Test;
  p.Test;
end;
</code>```

which is exactly equivalent to your code. Should p be able to access Test? No, because it is protected (and in a different unit).

Title: Cannot access protected symbol?

Body:
I'm getting

cannot access protected symbol TParent.Test

for following code:

In Unit1:

TParent = class
protected
  function Test: TParent;
end;

implementation

function TParent.Test: TParent;
begin
  Result := Self
end;

In Unit2:

uses Unit1;

type

TChild = class(TParent)
end;

implementation

var c: TChild;
begin
  c := TChild.Create;
  c.Test.Test
end;

Shouldn't the return value be accessible to TChild?

c.Test;
c.Test

works, of course.

Body:
The return value is accessible to TChild, but what you are trying to do is access it through a TParent within the TChild which is subtly different.

Think of it this way.

c.Test is a TParent, yes?

Now imagine that you had a TParent defined like this

var
  c: TChild;
  p: TParent
begin
  c := TChild.Create;
  p := c.Test;
  p.Test;
end;

which is exactly equivalent to your code. Should p be able to access Test? No, because it is protected (and in a different unit).


问:
Why do some websites have styles that aren't assigned to elements when I inspect the markup?
I found something really weird to me on Github:

body.impress-on-applepie #applepie-image,
body.impress-on-applepie-pro #applepie-image,
body.impress-on-applepie-con #applepie-image,
body.impress-on-conclusion #applepie-image,
body.impress-on-overview #applepie-image {
    opacity: 0.7;
    transition:  opacity 2s;
}
```

<pre class="lang-html prettyprint-override"><code><body class="impress-not-supported">
...
</body>
</code>```

As you can see,  only has the class impress-not-supported, so why are there so many other classes in the stylesheet which do not exist or aren't declared in HTML, and how do these styles work?

(these selectors are start from line 197 in presentation.css file.)

答:
Classes declared in CSS can be used (and probably are) with JS events. The body's classname is changed dynamically by JS.

The default class has no special styles, it's the same as the class attribute won't be there.

and how do these body.xxx work?

It works the same way as any class on other HTML elements.

Body:
I found something really weird to me on Github:

body.impress-on-applepie #applepie-image,
body.impress-on-applepie-pro #applepie-image,
body.impress-on-applepie-con #applepie-image,
body.impress-on-conclusion #applepie-image,
body.impress-on-overview #applepie-image {
    opacity: 0.7;
    transition:  opacity 2s;
}

...

As you can see,  only has the class impress-not-supported, so why are there so many other classes in the stylesheet which do not exist or aren't declared in HTML, and how do these styles work?

(these selectors are start from line 197 in presentation.css file.)


问:
Php change fatal error format

I would like to try to change the formatting of fatal error but I can only modify the values of message, file and line.

I would expect to be able to change the css and the html of the message.

Thanks in advance.

答: Fatal errors in PHP are catchable, so you can make your own exception handler or even use a third party package like https://github.com/filp/whoops</p>

Title: Php change fatal error format


答:
They are body classes controlled using Javascript potentially to add feature or browser detection. After they can be targetted with CSS.

Modernizer is an example of a service that uses them:
http://html5doctor.com/using-modernizr-to-detect-html5-features-and-provide-fallbacks/

Title: Why do some websites have styles that aren't assigned to elements when I inspect the markup?


答:
There is a CSS rule on your page which as a selector has .td-search-background and which contains a background-image setting whose URL is linked to a server with the IP address 192.168.0.120 . The image is called "52.jpg".

This looks like a local address - maybe even your own computer - which wasn't converted when you moved the WP installation from the test server to the performance server.

A comment above these CSS rules says  . So you should either search for settings in your theme where the server address is defined, or you should search for CSS files/settings created by your theme which contain this rule and change the URL there.

Title: Strange URL in the WordPress theme causing error when the site loads

Body:
I am facing a problem i.e.,  the site is taking more than usual time to load and showing an error when I inspected the page.

I tried searching for the link through the source code of the page, but I wasn’t able to locate where that link is actually present.
I don’t know where from this URL came, but I want to remove it, as it is not letting the page to load properly and fast.
Please tell me how to eliminate this error.
Details -

URL - reportingall
Theme - Newspaper 8.5
Demo Module Installed - Gadgets
CMS - WordPress

I can provide more information, if required.
Thanks and have a nice day.

Body:
There is a CSS rule on your page which as a selector has .td-search-background and which contains a background-image setting whose URL is linked to a server with the IP address 192.168.0.120 . The image is called "52.jpg".

This looks like a local address - maybe even your own computer - which wasn't converted when you moved the WP installation from the test server to the performance server.

A comment above these CSS rules says <!-- Header style compiled by theme --> . So you should either search for settings in your theme where the server address is defined, or you should search for CSS files/settings created by your theme which contain this rule and change the URL there.


问:
How to make something happen ONLY when clicking in an exact coordinate
I just wanted to know how I could make something on a canvas change clicking ONLY on a specific area of the canvas.

Let's say my canvas is of width 400px and height 400px, and I am drawing a face.
If I click on an eye, I want it to change. Let's say the eye is in the coordinates (drawn with .arc()) (135,70,15,0,Math.PI*2,true).

How can I make it so that when I click anywhere inside said eye, and nowhere else, something happens?

Thanks a lot!!

答:
You need to implement hit testing.

Keep track of your drawn objects in a Scene Graph - a kind of DOM that contains objects and their positions.

When you click somewhere you need to compare the position of the click with the the positions of your objects.

If the click point lies within the area of a drawn object, you consider that a hit.

That or just ahead and use a canvas library that keeps such a Scene Graph for you, such as Paper.js or Fabric.js - both libraries allow for hit-testing as well.


问:
JSTL gt compare is not working
I'm not sure why this snip is not working,
trying to set the length value then check if it's greater than 1 to display delete link.

```<code><c:set var="test" value="${fn:length(planInfoList)}"/>
    ${test} <!-- here the vale is 2 -->

    <c:if test="${test gt 1}  " >
        <a  href="deletePlanInfo.do?planInfoId=${planInfo.planInfoId }">
<img src="remove.png" />Delete</a>

</c:if>
</code>```

the value of the set is 2, but still not displaying the  link, what Am I doing wrong?

答:
Try removing spaces in test attribute:

```<code><c:if test="${test gt 1}  " ></c:if>
                        ^
                   remove here
</code>```

Title: JSTL gt compare is not working

Body:
I'm not sure why this snip is not working,
trying to set the length value then check if it's greater than 1 to display delete link.

<c:set var="test" value="${fn:length(planInfoList)}"/>
    ${test}

    <c:if test="${test gt 1}  " >

Delete

</c:if>

the value of the set is 2, but still not displaying the  link, what Am I doing wrong?

Body:
Try removing spaces in test attribute:

<c:if test="${test gt 1}  " ></c:if>
                        ^
                   remove here


答:
Override the delete method in the deleteview for changing the message type:

```<code>class PostDelete(SuccessMessageMixin, DeleteView):
    model = serverlist
    success_url = reverse_lazy('serverlist')
    success_message = "Object deleted"
    def delete(self, request, *args, **kwargs):
        messages.warning(self.request, self.success_message)
        return super(PostDelete, self).delete(request, *args, **kwargs)
</code>```

You can do the same by overriding the update method for UpdateView.

Title: django messages for a successfully delete,add or edit item

Body:
Override the delete method in the deleteview for changing the message type:

class PostDelete(SuccessMessageMixin, DeleteView):
    model = serverlist
    success_url = reverse_lazy('serverlist')
    success_message = "Object deleted"
    def delete(self, request, *args, **kwargs):
        messages.warning(self.request, self.success_message)
        return super(PostDelete, self).delete(request, *args, **kwargs)

You can do the same by overriding the update method for UpdateView.


问:
Keras : history not accessible for loss or accuracy

I am training a CNN in Keras with Tensorflow backend,

mod1=gmodel.fit(images, train_labels,
      batch_size=100,
      epochs=2,
      verbose=1,
      validation_data=(test_images, test_labels))
```

<p>and at every epoch I can see printed in the output the accuracy and loss (until here everything seems ok).</p>

<pre class="lang-python prettyprint-override"><code>Epoch 1/10
1203/1203 [==============================] - 190s - loss: 0.7600 - acc: 0.5628
- val_loss: 0.5592 - val_acc: 0.6933
Epoch 2/10
1203/1203 [==============================] - 187s - loss: 0.5490 - acc: 0.6933
- val_loss: 0.4589 - val_acc: 0.7930
Epoch 3/10
....
</code>```

At the end, I want to plot the validation loss so in previous projects I have accessed the validation loss via

mod1.history['val_loss']
```

<p>but I am getting an error as if <code>.history()</code> was empty.</p>

<pre class="lang-python prettyprint-override"><code>TypeError                                 Traceback (most recent call last)
<ipython-input-23-ecdd306e9232> in <module>()
----> 1 modl.history()
TypeError: 'History' object is not callable
</code>```

EDIT (after answer below): When I try to access the loss, for example:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-34-06fcc6efb374> in <module>()
----> 1 mod1.history['val_loss']

TypeError: 'History' object is not subscriptable
```

I haven't found anything like this problem before, so I am lost as to what could be happening or how to debug.

Any pointers or ideas are greatly appreciated.

答:
Although you say you have called mod1.history['val_loss'], your error message tells a different story - most probably, as Daniel Moller has already commented, you have in fact used something like mod1.history() (i.e. with parentheses). Here is what I get (Python 3.5):

mod1.history()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-67bafe3187cc> in <module>()
----> 1 mod1.history()

TypeError: 'dict' object is not callable
```

<p><code>mod1.history</code> is not a function to be called with <code>()</code>, but a Python dictionary:</p>

<pre class="lang-python prettyprint-override"><code>mod1.history
# result:
{'acc': [0.82374999999999998,
  0.94294999999999995,
  0.95861666666666667,
  ...],
 'loss': [0.62551526172161098,
  0.18810810926556587,
  0.13734668906728426,
  ...],
 'val_loss': [12.05395287322998,
  11.584557554626464,
  10.949809835815429,
  ...]}

mod1.history['val_loss']
# result:
[12.05395287322998,
 11.584557554626464,
 10.949809835815429,
 ...]
</code>```

Body:
I am training a CNN in Keras with Tensorflow backend,

mod1=gmodel.fit(images, train_labels,
      batch_size=100,
      epochs=2,
      verbose=1,
      validation_data=(test_images, test_labels))

and at every epoch I can see printed in the output the accuracy and loss (until here everything seems ok).

Epoch 1/10
1203/1203 [==============================] - 190s - loss: 0.7600 - acc: 0.5628
- val_loss: 0.5592 - val_acc: 0.6933
Epoch 2/10
1203/1203 [==============================] - 187s - loss: 0.5490 - acc: 0.6933
- val_loss: 0.4589 - val_acc: 0.7930
Epoch 3/10
....

At the end, I want to plot the validation loss so in previous projects I have accessed the validation loss via

mod1.history['val_loss']

but I am getting an error as if .history() was empty.

TypeError                                 Traceback (most recent call last)
<ipython-input-23-ecdd306e9232> in <module>()
----> 1 modl.history()
TypeError: 'History' object is not callable

EDIT (after answer below): When I try to access the loss, for example:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-34-06fcc6efb374> in <module>()
----> 1 mod1.history['val_loss']

TypeError: 'History' object is not subscriptable

I haven't found anything like this problem before, so I am lost as to what could be happening or how to debug.

Any pointers or ideas are greatly appreciated.

Body:
Although you say you have called mod1.history['val_loss'], your error message tells a different story - most probably, as Daniel Moller has already commented, you have in fact used something like mod1.history() (i.e. with parentheses). Here is what I get (Python 3.5):

mod1.history()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-67bafe3187cc> in <module>()
----> 1 mod1.history()

TypeError: 'dict' object is not callable

mod1.history is not a function to be called with (), but a Python dictionary:

mod1.history
# result:
{'acc': [0.82374999999999998,
  0.94294999999999995,
  0.95861666666666667,
  ...],
 'loss': [0.62551526172161098,
  0.18810810926556587,
  0.13734668906728426,
  ...],
 'val_loss': [12.05395287322998,
  11.584557554626464,
  10.949809835815429,
  ...]}

mod1.history['val_loss']
# result:
[12.05395287322998,
 11.584557554626464,
 10.949809835815429,
 ...]


问:
Group subscription duration by month and year in mysql
I have a table of subscriptions, storing user id, subscription end date, program id. One user can be subscribed to many programs, but for the scope of the problem the latest date is considered as the end date of the subscription. The goal is to find the number of users whose subscription is ending for each month of each year.  To illustrate it:

```<code>-------------------------------------------
| user_id | program_id |  end_date        |
-------------------------------------------
|    1    |     1      |  2015-12-10      |
|    1    |     2      |  2017-08-27      |
|    2    |     1      |  2017-09-20      |
|    3    |     2      |  2017-10-01      |
|    2    |     3      |  2017-09-18      |
|    5    |     12     |  2017-10-22      |
|    4    |     3      |  2017-10-10      |
|    3    |     8      |  2018-11-15      |
-------------------------------------------
</code>```

Intermediate result show when will the subscription end for each user (only month is needed):

```<code>------------------------------
| user_id |   enddate        |
------------------------------
|    1    |   2017-08        |
|    2    |   2017-09        |
|    3    |   2018-11        |
|    4    |   2017-10        |
|    5    |   2017-10        |
------------------------------
</code>```

This was achieved with the query:

```<code>Select user_id, DATE_FORMAT(max(end_date), '%Y-%m') AS as enddate
From subscription
Group by user_id
Order by end_date desc;
</code>```

The final result must further filter the list, showing only how many users will be left with no subscription in each month, like this:

```<code>------------------------------
| count   |  month, year     |
------------------------------
|    1    |   2017-08        |
|    1    |   2017-09        |
|    2    |   2017-10        |
|    1    |  2018-11         |
------------------------------
</code>```

This is where I am stuck with no mysql ideas. Iterating through the results and counting is out of the question.

答:
You could try arranging the results by the enddate, like this:</p>

```<code>    select count(user_id), DATE_FORMAT(max_end_date, '%Y-%m')as enddate
    from (
        select user_id, max(end_date) as max_end_date
        From subscription
        Group by user_id
    ) n
    group by enddate
    Order by enddate desc;
</code>```

Body:
I have a table of subscriptions, storing user id, subscription end date, program id. One user can be subscribed to many programs, but for the scope of the problem the latest date is considered as the end date of the subscription. The goal is to find the number of users whose subscription is ending for each month of each year.  To illustrate it:

-------------------------------------------
| user_id | program_id |  end_date        |
-------------------------------------------
|    1    |     1      |  2015-12-10      |
|    1    |     2      |  2017-08-27      |
|    2    |     1      |  2017-09-20      |
|    3    |     2      |  2017-10-01      |
|    2    |     3      |  2017-09-18      |
|    5    |     12     |  2017-10-22      |
|    4    |     3      |  2017-10-10      |
|    3    |     8      |  2018-11-15      |
-------------------------------------------

Intermediate result show when will the subscription end for each user (only month is needed):

------------------------------
| user_id |   enddate        |
------------------------------
|    1    |   2017-08        |
|    2    |   2017-09        |
|    3    |   2018-11        |
|    4    |   2017-10        |
|    5    |   2017-10        |
------------------------------

This was achieved with the query:

Select user_id, DATE_FORMAT(max(end_date), '%Y-%m') AS as enddate
From subscription
Group by user_id
Order by end_date desc;

The final result must further filter the list, showing only how many users will be left with no subscription in each month, like this:

------------------------------
| count   |  month, year     |
------------------------------
|    1    |   2017-08        |
|    1    |   2017-09        |
|    2    |   2017-10        |
|    1    |  2018-11         |
------------------------------

This is where I am stuck with no mysql ideas. Iterating through the results and counting is out of the question.

Body:
You could try arranging the results by the enddate, like this:

    select count(user_id), DATE_FORMAT(max_end_date, '%Y-%m')as enddate
    from (
        select user_id, max(end_date) as max_end_date
        From subscription
        Group by user_id
    ) n
    group by enddate
    Order by enddate desc;


问:
getJSON done callback
I have the function bellow called every 5 seconds to get data from the server, which is flask/python. My question is how can I adapt the getjson call to have callback when the data is successfully retrieved.

I know there's .done .fail and so on, but I was wondering if I can keep this structure and just add bellow it, but I don't know the syntax in this particular case, hope this isn't too confusing, thanks for reading, here's the code.

```<code>// get data from the server every getDataFromServerInterval milliseconds
var getDataFromServerInterval = 5000;
function getData(){
  // request timesince table entries from server for user...
  $.getJSON($SCRIPT_ROOT + '/_database', {
    action: "getUserTable_timesince",
    username: $('input[name="username"]').val()
  }, function(data) { // do something with the response data
    timesince_dataBuffer = data;
  });
  return false; // prevent get
}
// get data from the server every getDataFromServerInterval milliseconds
setInterval(getData, getDataFromServerInterval);
</code>```

答:
This is the solution I came up with.

```<code>var timesince_dataBuffer;
function getData(){
  // gets user's entries from sql table
  $.getJSON($SCRIPT_ROOT + '/_database', { // $SCRIPT_ROOT, root to the application
    action: "getUserTable_timesince",
    username: $('input[name="username"]').val()
  }, function(data) { // if a response is sent, this function is called
    timesince_dataBuffer = data;
    updateEntryStruct(); // recreate the structure of each content, buttons etc
  });
  return false;
}
</code>```

I get the data, put in a global variable, call another function which takes that data and re-creates a structure for each object received, this way I don't recreate parts of the structure which are static, most importantly the buttons.

Another function is called every 1 second, which updates the dynamic parts.
(formatted time) passed since
(event name)

Anyway, this is actually my final project in CS50, I started by communicating with the server via form submissions, refreshing the page each time the user pressed a button, then I did it by ajax, but I was sending requests to the server every 2 seconds, and having unresponsive buttons because I would keep re-creating the buttons themselves on a time interval.
And now the page feels responsive and efficient, it's been a great learning experience.

If anyone wants to check out the code, everything is here.
https://github.com/silvermirai/cs50-final-project

It's basically a bunch of random functionality that came to mind.
The application can be found here as of now.
http://ide502-silvermirai.cs50.io:8080/

Title: getJSON done callback

Body:
I have the function bellow called every 5 seconds to get data from the server, which is flask/python. My question is how can I adapt the getjson call to have callback when the data is successfully retrieved.

I know there's .done .fail and so on, but I was wondering if I can keep this structure and just add bellow it, but I don't know the syntax in this particular case, hope this isn't too confusing, thanks for reading, here's the code.

// get data from the server every getDataFromServerInterval milliseconds
var getDataFromServerInterval = 5000;
function getData(){
  // request timesince table entries from server for user...
  $.getJSON($SCRIPT_ROOT + '/_database', {
    action: "getUserTable_timesince",
    username: $('input[name="username"]').val()
  }, function(data) { // do something with the response data
    timesince_dataBuffer = data;
  });
  return false; // prevent get
}
// get data from the server every getDataFromServerInterval milliseconds
setInterval(getData, getDataFromServerInterval);

Body:
This is the solution I came up with.

var timesince_dataBuffer;
function getData(){
  // gets user's entries from sql table
  $.getJSON($SCRIPT_ROOT + '/_database', { // $SCRIPT_ROOT, root to the application
    action: "getUserTable_timesince",
    username: $('input[name="username"]').val()
  }, function(data) { // if a response is sent, this function is called
    timesince_dataBuffer = data;
    updateEntryStruct(); // recreate the structure of each content, buttons etc
  });
  return false;
}

I get the data, put in a global variable, call another function which takes that data and re-creates a structure for each object received, this way I don't recreate parts of the structure which are static, most importantly the buttons.

Another function is called every 1 second, which updates the dynamic parts.
(formatted time) passed since
(event name)

Anyway, this is actually my final project in CS50, I started by communicating with the server via form submissions, refreshing the page each time the user pressed a button, then I did it by ajax, but I was sending requests to the server every 2 seconds, and having unresponsive buttons because I would keep re-creating the buttons themselves on a time interval.
And now the page feels responsive and efficient, it's been a great learning experience.

If anyone wants to check out the code, everything is here.
https://github.com/silvermirai/cs50-final-project

It's basically a bunch of random functionality that came to mind.
The application can be found here as of now.
http://ide502-silvermirai.cs50.io:8080/


问:
Custom page template for global use , don't showing up in wordpress template dropdown
I searched everywhere and could not find.

Now you are my only hope, please help.

Custom page template for global use , don't showing up in wordpress template dropdown when i create custom floder for the template parts.

My-theme/global_template.php WORK

My-theme/template-parts/global_template.php WORK

My-theme/template-parts/archive/global_template.php DON'T WORK

How can I make folders that inside template-parts that contain templates to appear in page attributes->template?

Here the code inside global_template.php

As you see there is no test template..

答:
Your problem is the depth the function thats get the templates have 1 depth. so you must put the files in the theme root or first sub-folder

The core functions get_post_templates() call get_files() with depth 1 and it pass it on to the function scandir() that scan the directories.

You can add more templates manually like this replace the {$post_type} in the add_filter with the post type that you want to add the templates to. for example page.

```<code>/**
* @param array $post_templates Array of page templates.
* Keys are filenames, values are translated names.
*/
function extend_post_type_templates($post_templates, $this, $post, $post_type) {
    $post_templates['template-parts/archive/global_template.php'] = 'Name for this';
    return $post_templates;
}
add_filter( 'theme_{$post_type}_templates', 'extend_post_type_templates', 10, 4 );
</code>```

Body:
Your problem is the depth the function thats get the templates have 1 depth. so you must put the files in the theme root or first sub-folder

The core functions get_post_templates() call get_files() with depth 1 and it pass it on to the function scandir() that scan the directories.

You can add more templates manually like this replace the {$post_type} in the add_filter with the post type that you want to add the templates to. for example page.

/**
* @param array $post_templates Array of page templates.
* Keys are filenames, values are translated names.
*/
function extend_post_type_templates($post_templates, $this, $post, $post_type) {
    $post_templates['template-parts/archive/global_template.php'] = 'Name for this';
    return $post_templates;
}
add_filter( 'theme_{$post_type}_templates', 'extend_post_type_templates', 10, 4 );


问:
How do you terminate a conversation based on user input evaluation through a webhook (api v2)
Let's say my bot has an ongoing conversation with the user and my webhook asks "Are you done?" and the user responds "Yes".
How do I close the conversation through the webhook?
I suspect it is through followupEventInput but I could not get anything to work.

I am not using a nodeJS library. Coding in C#.

Here is what I tried: I respond with an output context and an event: the event is associated with "End conversation" under the Google Assistant at the bottom of the intent window.

```<code> {
  "fulfillmentText": "OK. The note was recorded.",
  "fulfillmentMessages": [
  {
  "text": {
    "text": [
      "OK. The note was recorded."
    ]
  }
}
],
  "outputContexts": [
{
  "lifespanCount": 2,
  "name": "projects/xxx/agent/sessions/1512399774430/contexts/note-end"
}
],
"followupEventInput": {
"name": "end-event",
"languageCode": "en"
  }
}
</code>```

With the above code, the user never hears "OK. The note was recorded.", the session ends abruptly with Google Home saying "The app is not responding anymore" (or something similar). Works but not acceptable.

If I don't put the followupEvent, the user hears "OK. The note was recorded." but the conversation doesn't end... then I need to rely on the user to close it using another intent, which is what I want to avoid as it would be redundant.

答:
OK. After further investigation, it seems that:

the text of the fulfillment is never sent to the user but it needs to be set to something (" " works), otherwise the user will be told that the app is not responding and that s/he has to try again later.

The context and the event are correct and necessary. The only way (I found) to get the user to hear "OK. The note was recorded." is to include this message as a text response of the intent associated with the event. When set this way, the app closes in an acceptable manner.

Body:
Let's say my bot has an ongoing conversation with the user and my webhook asks "Are you done?" and the user responds "Yes".
How do I close the conversation through the webhook?
I suspect it is through followupEventInput but I could not get anything to work.

I am not using a nodeJS library. Coding in C#.

Here is what I tried: I respond with an output context and an event: the event is associated with "End conversation" under the Google Assistant at the bottom of the intent window.

 {
  "fulfillmentText": "OK. The note was recorded.",
  "fulfillmentMessages": [
  {
  "text": {
    "text": [
      "OK. The note was recorded."
    ]
  }
}
],
  "outputContexts": [
{
  "lifespanCount": 2,
  "name": "projects/xxx/agent/sessions/1512399774430/contexts/note-end"
}
],
"followupEventInput": {
"name": "end-event",
"languageCode": "en"
  }
}

With the above code, the user never hears "OK. The note was recorded.", the session ends abruptly with Google Home saying "The app is not responding anymore" (or something similar). Works but not acceptable.

If I don't put the followupEvent, the user hears "OK. The note was recorded." but the conversation doesn't end... then I need to rely on the user to close it using another intent, which is what I want to avoid as it would be redundant.


问:
Invoking a Lambda function every 5 seconds

My problem

I'd like to invoke an AWS Lambda function every 5 seconds, for some monitoring purposes.

According to the docs,

Rate frequencies of less than one minute are not supported.

What have I tried

STFW.

My Question

Can I autonomously invoke an AWS Lambda function every 5 seconds?

答:
Although I can not recommend this way, but if you really need to execute a Lambda function every 5 seconds, you can try this:

Create a Lambda function A which is executed every minute.

Create a Lambda function B which is triggered every 5 seconds by Lambda function A. (A triggers B, waits 5 seconds, triggers B, waits 5 seconds, ...)

Stop Lambda function A after approximately one minute. (You can read the remaining miliseconds from the context object => if you reach >55 seconds, stop execution)

Please carefully consider if you really need this.


问:
getActivity Not found for PendingIntent
I have the header file for pendingIntent

```<code> Intent i=new Intent();
               PendingIntent pi= new PendingIntent.getActivity(MainActivity.this,0,i,0);
</code>```

This seems to not be working

Here is my whole code

```<code>package com.example.srinabh.notof;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button b;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b=findViewById(R.id.notif);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i=new Intent();
               PendingIntent pi= new PendingIntent.getActivity(MainActivity.this,0,i,0);

                Notification n=new Notification.Builder(MainActivity.this)
                        .setTicker("Ticker Title")
                        .setContentTitle("Content Titlle")
                        .setContentText("Content Text")
                        .setContent(pi)
                        .getNotification();
                n.flags=Notification.FLAG_AUTO_CANCEL;
                NotificationManager nm= (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

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

答:
Remove the new

```<code>  PendingIntent pi= PendingIntent.getActivity(MainActivity.this,0,i,0);
</code>```

From the answer:

getActivity() is a static method of the class PendingIntent and does
  not require an instance of PendingIntent in order to be invoked.

Answer may refer here

Title: getActivity Not found for PendingIntent

Body:
I have the header file for pendingIntent

 Intent i=new Intent();
               PendingIntent pi= new PendingIntent.getActivity(MainActivity.this,0,i,0);

This seems to not be working

Here is my whole code

package com.example.srinabh.notof;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button b;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b=findViewById(R.id.notif);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i=new Intent();
               PendingIntent pi= new PendingIntent.getActivity(MainActivity.this,0,i,0);

                Notification n=new Notification.Builder(MainActivity.this)
                        .setTicker("Ticker Title")
                        .setContentTitle("Content Titlle")
                        .setContentText("Content Text")
                        .setContent(pi)
                        .getNotification();
                n.flags=Notification.FLAG_AUTO_CANCEL;
                NotificationManager nm= (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

            }
        });
    }
}

Body:
Remove the new

  PendingIntent pi= PendingIntent.getActivity(MainActivity.this,0,i,0);

From the answer:

getActivity() is a static method of the class PendingIntent and does
  not require an instance of PendingIntent in order to be invoked.

Answer may refer here


问:
Downloading FTP file using Codeigniter Filepath Error
This is what I have done so far.

Configured Filezilla FTP server on localhost.
And added user: Admin with shared folder C://ftp
there is a file inside that folder 123.jpg

So when I try to Download it using ftp class in Codeigniter;

Unable to download the specified file. Please check your path.

this is the code I'm using to download. FTP successfully connects but fails download due to incorrect file path.

```<code>$this->ftp->download('/123.jpg', 'D:/');
</code>```

What should be changed in the above code?

答:
Solved it !

Seemed that local file path need to have the 'file name' at the end as well.

```<code>$this->ftp->download('/123.jpg', 'D:/blah.jpg');
</code>```

And file would be downloaded to D: renamed as blah.jpg

Body:
This is what I have done so far.

Configured Filezilla FTP server on localhost.
And added user: Admin with shared folder C://ftp
there is a file inside that folder 123.jpg

So when I try to Download it using ftp class in Codeigniter;

Unable to download the specified file. Please check your path.

this is the code I'm using to download. FTP successfully connects but fails download due to incorrect file path.

$this->ftp->download('/123.jpg', 'D:/');

What should be changed in the above code?

Body:
Solved it !

Seemed that local file path need to have the 'file name' at the end as well.

$this->ftp->download('/123.jpg', 'D:/blah.jpg');

And file would be downloaded to D: renamed as blah.jpg


问:
Query post based on month and date

I'm building company intranet on WordPress. I'm trying to get upcoming birthday list (for the next 30 days from current day), the birthdays' value is coming from a custom field with the Ymd format.

This code is returning all birthdays:

```<code>$args = array(
            'post_type' => 'employees',
               'meta_key'  => 'birthday',
               'orderby'   => 'meta_value_num',
               'order'     => 'ASC',
               'compare' => '>=',
               'type' => 'DATE',
            );
</code>```

I want to get only upcoming birthdays for one month period.

答:
You need to have your query based until the date you need. So you could do something like:

```<code>$start_date = date('Y-m-d', strtotime('- 1 month')); // or $start_date = date('Y-m-d');
$end_date = date('Y-m-d', strtotime('+ 1 month')); // or '+ 30 days' for example
</code>```

You can use $start_date and $end_date to get a specific date range in your query.

Remember when you use date AND/OR strtotime you can only go up to somewhere in 2038, if im correct. If you want to have dates AFTER 2038 you need to use the new DateTime function. (http://php.net/manual/en/datetime.construct.php)

Title: Query post based on month and date

Body:
I'm building company intranet on WordPress. I'm trying to get upcoming birthday list (for the next 30 days from current day), the birthdays' value is coming from a custom field with the Ymd format.

This code is returning all birthdays:

$args = array(
            'post_type' => 'employees',
               'meta_key'  => 'birthday',
               'orderby'   => 'meta_value_num',
               'order'     => 'ASC',
               'compare' => '>=',
               'type' => 'DATE',
            );

I want to get only upcoming birthdays for one month period.

Body:
You need to have your query based until the date you need. So you could do something like:

$start_date = date('Y-m-d', strtotime('- 1 month')); // or $start_date = date('Y-m-d');
$end_date = date('Y-m-d', strtotime('+ 1 month')); // or '+ 30 days' for example

You can use $start_date and $end_date to get a specific date range in your query.

Remember when you use date AND/OR strtotime you can only go up to somewhere in 2038, if im correct. If you want to have dates AFTER 2038 you need to use the new DateTime function. (http://php.net/manual/en/datetime.construct.php)


问:
Simple usage of Node request not working
I use request lib (https://www.npmjs.com/package/request) for a Node application.

And this simple example doesn't work :

```<code>console.log(' BEGIN ---- ');
request('http://www.google.com', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});
console.log('END ---- ');
</code>```

I only have BEGIN ---- and END ---- messages in my console, but nothing from the get request.

Did I miss something ?

答:
Nodejs behaves asynchronously, which means when you run your script request takes some time to go and fetch data from the provided link but it will take some time to complete this task therefore other code will not wait for it to complete.

You can use callbacks to wait for the result. Below code is an easy solution for your problem.

const request = require('request')

function req(callback){
    console.log(' BEGIN ---- ');
    request('http://www.google.com', function (error, response, body) {
      console.log('error:', error); // Print the error if one occurred
      console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
      console.log('body:', body); // Print the HTML for the Google homepage.
      callback()
    });
}

req(function(){
    console.log('END ---- ');
})```

But for more clean and easy to read code you must learn to use promises or async/await feature in nodejs.

Body:
I use request lib (https://www.npmjs.com/package/request) for a Node application.

And this simple example doesn't work :

console.log(' BEGIN ---- ');
request('http://www.google.com', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});
console.log('END ---- ');

I only have BEGIN ---- and END ---- messages in my console, but nothing from the get request.

Did I miss something ?

Body:
Nodejs behaves asynchronously, which means when you run your script request takes some time to go and fetch data from the provided link but it will take some time to complete this task therefore other code will not wait for it to complete.

You can use callbacks to wait for the result. Below code is an easy solution for your problem.

const request = require('request')

function req(callback){
    console.log(' BEGIN ---- ');
    request('http://www.google.com', function (error, response, body) {
      console.log('error:', error); // Print the error if one occurred
      console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
      console.log('body:', body); // Print the HTML for the Google homepage.
      callback()
    });
}

req(function(){
    console.log('END ---- ');
})

But for more clean and easy to read code you must learn to use promises or async/await feature in nodejs.


答:
```<code>var
  c: TChild;
....
c.Test.Test;
</code>```

The method TParent.Test is protected which means that it is accessible in methods of TParent and methods of classes derived from TParent. And, in addition, it is accessible when called on a reference whose class was defined in the same unit as the calling code.

The documentation says it like this, with my emphasis:

A protected member is visible anywhere in the module where its class is declared and from any descendent class, regardless of the module where the descendent class appears.

The fact that TChild was declared in the unit where you access the protected member is the key to understanding this.

In your example code, in Unit2 when you write c.Test, that call to Test is not made from a method of TParent or a class derived from it. But it is made on a variable of type TChild, which is declared in Unit2, the unit where the call to the method is made. And so it is visible.

However, c.Test is of type TParent. And because TParent is defined in a different unit, Unit1, c.Test.Test does not compile. Likewise this code would not compile in Unit2:

```<code>var
  p: TParent;
....
p.Test;
</code>```

Title: Cannot access protected symbol?

Body:
I'm getting

cannot access protected symbol TParent.Test

for following code:

In Unit1:

TParent = class
protected
  function Test: TParent;
end;

implementation

function TParent.Test: TParent;
begin
  Result := Self
end;

In Unit2:

uses Unit1;

type

TChild = class(TParent)
end;

implementation

var c: TChild;
begin
  c := TChild.Create;
  c.Test.Test
end;

Shouldn't the return value be accessible to TChild?

c.Test;
c.Test

works, of course.

Body:
var
  c: TChild;
....
c.Test.Test;

The method TParent.Test is protected which means that it is accessible in methods of TParent and methods of classes derived from TParent. And, in addition, it is accessible when called on a reference whose class was defined in the same unit as the calling code.

The documentation says it like this, with my emphasis:

A protected member is visible anywhere in the module where its class is declared and from any descendent class, regardless of the module where the descendent class appears.

The fact that TChild was declared in the unit where you access the protected member is the key to understanding this.

In your example code, in Unit2 when you write c.Test, that call to Test is not made from a method of TParent or a class derived from it. But it is made on a variable of type TChild, which is declared in Unit2, the unit where the call to the method is made. And so it is visible.

However, c.Test is of type TParent. And because TParent is defined in a different unit, Unit1, c.Test.Test does not compile. Likewise this code would not compile in Unit2:

var
  p: TParent;
....
p.Test;


问:
Android: How to use tools with include layout
How do I use tools:

```<code>xmlns:tools="http://schemas.android.com/tools"
</code>```

With <include>?

I have a layout A that I use tools to populate all the text fields with test data. And I have layout B that use include to copy layout A in to it. How ever when I do that I do not see the test data of A.

How can I see the test data of A included in B?

*Both layouts have xmlns:tools="http://schemas.android.com/tools, I even pushed it to layout tag.

答: add layout_width and layout_height to the include tag , otherwise you will find it difficult to arrange it in an RelativeLayout

Body:
How do I use tools:

xmlns:tools="http://schemas.android.com/tools"

With <include>?

I have a layout A that I use tools to populate all the text fields with test data. And I have layout B that use include to copy layout A in to it. How ever when I do that I do not see the test data of A.

How can I see the test data of A included in B?

*Both layouts have xmlns:tools="http://schemas.android.com/tools, I even pushed it to layout tag.


问:
Preventing / dealing with double button clicks in angular
In angular we can set up a button to send ajax requests like this in view:

```<code>... ng-click="button-click"
</code>```

and in controller:

```<code>...
$scope.buttonClicked = function() {
   ...
   ...
   // make ajax request
   ...
   ...
}
</code>```

So to prevent a double submit I could set a flag to buttonclicked = true when a button is click and unset it when the ajax callback is finished.  But, even then control is handled back to angular who will updates to the Dom.  That means there is a tiny window where the button could be clicked again before the original button click has completely 100% finished.

It's a small window but can still happen.  Any tips to completely avoid this from happening - client side i.e. without making any updates to server.

Thanks

答:
A simple solution I found and I think is better than other answer here is preventing browser default behavior on mousedown event.

```<code>ng-mousedown="$event.preventDefault();"
</code>```

It does NOT prevent click event but it prevents double-click event :)

Body:
In angular we can set up a button to send ajax requests like this in view:

... ng-click="button-click"

and in controller:

...
$scope.buttonClicked = function() {
   ...
   ...
   // make ajax request
   ...
   ...
}

So to prevent a double submit I could set a flag to buttonclicked = true when a button is click and unset it when the ajax callback is finished.  But, even then control is handled back to angular who will updates to the Dom.  That means there is a tiny window where the button could be clicked again before the original button click has completely 100% finished.

It's a small window but can still happen.  Any tips to completely avoid this from happening - client side i.e. without making any updates to server.

Thanks

Body:
A simple solution I found and I think is better than other answer here is preventing browser default behavior on mousedown event.

ng-mousedown="$event.preventDefault();"

It does NOT prevent click event but it prevents double-click event :)