问:
java.lang.ClassCastException: org.springframework.orm.hibernate5.SessionHolder cannot be cast to org.springframework.orm.jpa.EntityManagerHolder
There have been similar questions in the past, but no real resolution.

I'm converting a Hibernate Web app to be JPA-enabled. There is only 1 DAO class so far, and it's already giving the following error after conversion to JPA.

Note: We are not using Spring-Boot, so prior answers don't apply in our case.

```<code>java.lang.ClassCastException: org.springframework.orm.hibernate5.SessionHolder cannot be cast to org.springframework.orm.jpa.EntityManagerHolder
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.doGetTransactionalEntityManager(EntityManagerFactoryUtils.java:221)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:255)
    at com.sun.proxy.$Proxy42.createQuery(Unknown Source)
    at gov.nih.nci.cbiit.scimgmt.idp.dao.LookupDao.findById(LookupDao.java:52)
    at gov.nih.nci.cbiit.scimgmt.idp.dao.LookupDao$$FastClassBySpringCGLIB$$7b0b6cbb.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:651)
    at gov.nih.nci.cbiit.scimgmt.idp.dao.LookupDao$$EnhancerBySpringCGLIB$$1cd8b9dd.findById(<generated>)
    at gov.nih.nci.cbiit.scimgmt.idp.service.impl.LookupServiceImpl.findById(LookupServiceImpl.java:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
</code>```

Converted JPA-enabled DAO class, just 1 method:

```<code>public class LookupDao {

    private final Logger log = LogManager.getLogger(getClass());

    @PersistenceContext
    private EntityManager entityManager;

    public LookupT findById(long id) throws Exception {

        log.info("Entered: LookupDao.findById(), id = " + id);

        // Pre-JPA (pre-conversion; note: commented out. No Hibernate Session conflicts)
        // -------
        /*
        log.info("getting lookup id="+id);
        return sessionFactory.getCurrentSession().get(LookupT.class, id);
        */

        // New JPA Approach (converted)
        // ----------------
        CriteriaBuilder crbuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<LookupT> crquery = crbuilder.createQuery(LookupT.class);

        Root<LookupT> root = crquery.from(LookupT.class);
        crquery.where(
                    (crbuilder.equal(root.get("id"), id))
                );

        Query q = entityManager.createQuery(crquery);
        return (LookupT)q.getSingleResult();
    }
</code>```

Libraries:

spring-aop-4.3.2.RELEASE.jar

spring-beans-4.3.2.RELEASE.jar

spring-context-4.3.2.RELEASE.jar

spring-core-4.3.2.RELEASE.jar

spring-jdbc-4.3.2.RELEASE.jar

spring-web-4.3.2.RELEASE.jar

hibernate-commons-annotations-5.0.1.Final.jar

hibernate-core-5.2.1.Final.jar

hibernate-jpa-2.1-api-1.0.0.Final.jar

Anything else that may be helpful to debug this?

I've confirmed:

No mixing between Hibernate Session and EntityManager, only 1 DAO
with 1 method using the EntityManager, everything else is commented
out.

Not using Spring-Boot

Prior questions on this subject:
Spring 4 + Hibernate 5 = org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate5.SessionHolder

ClassCastException: org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate5.SessionHolder

答:
SOLVED

Our applicationContext.xml had the following bean definition

```<code><bean id="transactionManager"
    class="org.springframework.orm.hibernate5.HibernateTransactionManager"
    p:sessionFactory-ref="sessionFactory" />
</code>```

which had to be replaced with

```<code>    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceXmlLocation" value="/META-INF/persistence.xml" />
</bean>
</code>```

Also, put persistence.xml into the location specified there, META-INF/persistence.

So the key point is that the JpaTransactionManager has to replace the HibernateTransactionManager, and the beans approprioately configured.

Body:
There have been similar questions in the past, but no real resolution.

I'm converting a Hibernate Web app to be JPA-enabled. There is only 1 DAO class so far, and it's already giving the following error after conversion to JPA.

Note: We are not using Spring-Boot, so prior answers don't apply in our case.

java.lang.ClassCastException: org.springframework.orm.hibernate5.SessionHolder cannot be cast to org.springframework.orm.jpa.EntityManagerHolder
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.doGetTransactionalEntityManager(EntityManagerFactoryUtils.java:221)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:255)
    at com.sun.proxy.$Proxy42.createQuery(Unknown Source)
    at gov.nih.nci.cbiit.scimgmt.idp.dao.LookupDao.findById(LookupDao.java:52)
    at gov.nih.nci.cbiit.scimgmt.idp.dao.LookupDao$$FastClassBySpringCGLIB$$7b0b6cbb.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:651)
    at gov.nih.nci.cbiit.scimgmt.idp.dao.LookupDao$$EnhancerBySpringCGLIB$$1cd8b9dd.findById(<generated>)
    at gov.nih.nci.cbiit.scimgmt.idp.service.impl.LookupServiceImpl.findById(LookupServiceImpl.java:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)

Converted JPA-enabled DAO class, just 1 method:

public class LookupDao {

    private final Logger log = LogManager.getLogger(getClass());

    @PersistenceContext
    private EntityManager entityManager;

    public LookupT findById(long id) throws Exception {

        log.info("Entered: LookupDao.findById(), id = " + id);

        // Pre-JPA (pre-conversion; note: commented out. No Hibernate Session conflicts)
        // -------
        /*
        log.info("getting lookup id="+id);
        return sessionFactory.getCurrentSession().get(LookupT.class, id);
        */

        // New JPA Approach (converted)
        // ----------------
        CriteriaBuilder crbuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<LookupT> crquery = crbuilder.createQuery(LookupT.class);

        Root<LookupT> root = crquery.from(LookupT.class);
        crquery.where(
                    (crbuilder.equal(root.get("id"), id))
                );

        Query q = entityManager.createQuery(crquery);
        return (LookupT)q.getSingleResult();
    }

Libraries:

spring-aop-4.3.2.RELEASE.jar

spring-beans-4.3.2.RELEASE.jar

spring-context-4.3.2.RELEASE.jar

spring-core-4.3.2.RELEASE.jar

spring-jdbc-4.3.2.RELEASE.jar

spring-web-4.3.2.RELEASE.jar

hibernate-commons-annotations-5.0.1.Final.jar

hibernate-core-5.2.1.Final.jar

hibernate-jpa-2.1-api-1.0.0.Final.jar

Anything else that may be helpful to debug this?

I've confirmed:

No mixing between Hibernate Session and EntityManager, only 1 DAO
with 1 method using the EntityManager, everything else is commented
out.

Not using Spring-Boot

Prior questions on this subject:
Spring 4 + Hibernate 5 = org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate5.SessionHolder

ClassCastException: org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate5.SessionHolder

Body:
SOLVED

Our applicationContext.xml had the following bean definition

<bean id="transactionManager"
    class="org.springframework.orm.hibernate5.HibernateTransactionManager"
    p:sessionFactory-ref="sessionFactory" />

which had to be replaced with

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceXmlLocation" value="/META-INF/persistence.xml" />
</bean>

Also, put persistence.xml into the location specified there, META-INF/persistence.

So the key point is that the JpaTransactionManager has to replace the HibernateTransactionManager, and the beans approprioately configured.


来源: stackexchange

问:
Play video from local file using Adobe AIR
I'd like to play videos, as well as display images and possibly other flash content using adobe air, and reading from the local file system. I've been searching APIs and I have not yet been able to connect the dots.

I know of flash.filesystem.File and flash.filesystem.FileStream and have experimented with loading and reading files. I believe I can load images this way but haven't tried.

As for video:

mx.controls.VideoDisplay
- seems to accept a file:// URI for source, but I can't get it to work.

flash.media.Video
- accepts a NetStream or can load video directly from a video input, can't seem to find a way to reference a local file

Can anyone help me out here? I specifically want to load and play video directly off the local disk, not from a web server or a streaming file server... assume no network connectivity.

Slightly related question: Loading a video from the local file system… (but my question does not involve a web browser)

答:
Try adding "-use-network=false" to your Flex compiler settings.  This will give you access to load local resources, which could be the source of the problem; the sandboxing rules are somewhat sensitive, so if you're sure you won't need network connectivity, tweaking this setting might relax things a bit.

Also ran across this, which might be related as well:

http://soenkerohde.com/2008/06/playing-local-files-with-air/

In my case, though, just briefly testing, both of the following work in debug and release builds, without modifying the compiler setting, in case it's just the literals you're using to reference the FLVs:

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:VideoDisplay source="D:\Data\Projects\Flex 3\AirLocalVideo\bin-debug\NightSky.flv" />
</mx:WindowedApplication>

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:VideoDisplay source="file://D:/Data/Projects/Flex 3/AirLocalVideo/bin-debug/NightSky.flv" />
</mx:WindowedApplication>
</code>```

... so I guess it's maybe difficult to diagnose without a bit more information.  Hope this helps -- I'll keep an eye on the comments if you want to share a bit more info.

OwnerDisplayName: tweakt

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: tweakt

Body:
Try adding "-use-network=false" to your Flex compiler settings.  This will give you access to load local resources, which could be the source of the problem; the sandboxing rules are somewhat sensitive, so if you're sure you won't need network connectivity, tweaking this setting might relax things a bit.

Also ran across this, which might be related as well:

http://soenkerohde.com/2008/06/playing-local-files-with-air/

In my case, though, just briefly testing, both of the following work in debug and release builds, without modifying the compiler setting, in case it's just the literals you're using to reference the FLVs:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:VideoDisplay source="D:\Data\Projects\Flex 3\AirLocalVideo\bin-debug\NightSky.flv" />
</mx:WindowedApplication>

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:VideoDisplay source="file://D:/Data/Projects/Flex 3/AirLocalVideo/bin-debug/NightSky.flv" />
</mx:WindowedApplication>

... so I guess it's maybe difficult to diagnose without a bit more information.  Hope this helps -- I'll keep an eye on the comments if you want to share a bit more info.

OwnerDisplayName: Christian Nunciato

LastEditorDisplayName: Christian Nunciato


问:
C++ -- Win32 API, GUI stuff
I've been messing with Win32 API for abit, and I've got a question regarding the GUI functions.

How does one handle user input that is not managed through popup windows? I've been reading http://www.winprog.org/ but right when the interesting features comes -- lesson9 -- it becomes more abstract and I'm not sure how to do it.
Basically what I am after is the user to write input in two windows and then press a button to send a message that the content of the input is to be processed.
I think the input windows would be some EDIT-class windows and the input BUTTON-class but that's about it.

Any ideas? I'm sure it's simple, it's just makes me want to rip my hair of in native code :p

Cheers

答:
You're correct, you want and EDIT control which is more commonly known as a TextBox and a BUTTON class which is a command button.

To get the the input the Button will send a WM_COMMAND message to its parent window with a BN_CLICKED in the wParam high word. You can identify the particular button from the hWnd you get in that message.

After that you'll need to post a WM_GETTEXT to the edit control to retrieve the users input.

This is all from memory so I highly recommend looking up the msdn pages before you code.

Title: C++ -- Win32 API, GUI stuff

ContentLicense: CC BY-SA 3.0


问:
How to replace an entire cell with NaN on pandas DataFrame
I want to replace the entire cell that contains the word as circled in the picture with blanks or NaN. However when I try to replace for example '1.25 Dividend' it turned out as '1.25 NaN'. I want to return the whole cell as 'NaN'. Any idea how to work on this?

答:
Option 1

Use a regular expression in your replace

```<code>df.replace('^.*Dividend.*$', np.nan, regex=True)
</code>```

From comments

(Using regex=True) means that it will interpret the problem as a regular expression one.  You still need an appropriate pattern.  The '^' says to start at the beginning of the string.  '^.*' matches all characters from the beginning of the string.  '$' says to end the match with the end of the string.  '.*$' matches all characters up to the end of the string.  Finally, '^.*Dividend.*$' matches all characters from the beginning, has 'Dividend' somewhere in the middle, then any characters after it.  Then replace this whole thing with np.nan

Consider the dataframe df

```<code>df = pd.DataFrame([[1, '2 Dividend'], [3, 4], [5, '6 Dividend']])
df

   0           1
0  1  2 Dividend
1  3           4
2  5  6 Dividend
</code>```

then the proposed solution yields

```<code>   0    1
0  1  NaN
1  3  4.0
2  5  NaN
</code>```

Option 2

Another alternative is to use pd.DataFrame.mask in conjunction with a applymap.

If I pass a lambda to applymap that identifies if any cell has 'Dividend' in it.

```<code>df.mask(df.applymap(lambda s: 'Dividend' in s if isinstance(s, str) else False))

   0    1
0  1  NaN
1  3    4
2  5  NaN
</code>```

Option 3

Similar in concept but using stack/unstack + pd.Series.str.contains

```<code>df.mask(df.stack().astype(str).str.contains('Dividend').unstack())

   0    1
0  1  NaN
1  3    4
2  5  NaN
</code>```

Body:
Option 1

Use a regular expression in your replace

df.replace('^.*Dividend.*$', np.nan, regex=True)

From comments

(Using regex=True) means that it will interpret the problem as a regular expression one.  You still need an appropriate pattern.  The '^' says to start at the beginning of the string.  '^.*' matches all characters from the beginning of the string.  '$' says to end the match with the end of the string.  '.*$' matches all characters up to the end of the string.  Finally, '^.*Dividend.*$' matches all characters from the beginning, has 'Dividend' somewhere in the middle, then any characters after it.  Then replace this whole thing with np.nan

Consider the dataframe df

df = pd.DataFrame([[1, '2 Dividend'], [3, 4], [5, '6 Dividend']])
df

   0           1
0  1  2 Dividend
1  3           4
2  5  6 Dividend

then the proposed solution yields

   0    1
0  1  NaN
1  3  4.0
2  5  NaN

Option 2

Another alternative is to use pd.DataFrame.mask in conjunction with a applymap.

If I pass a lambda to applymap that identifies if any cell has 'Dividend' in it.

df.mask(df.applymap(lambda s: 'Dividend' in s if isinstance(s, str) else False))

   0    1
0  1  NaN
1  3    4
2  5  NaN

Option 3

Similar in concept but using stack/unstack + pd.Series.str.contains

df.mask(df.stack().astype(str).str.contains('Dividend').unstack())

   0    1
0  1  NaN
1  3    4
2  5  NaN


问:
Writing a prepared statement to retrieve data from table (fatal error)
I have a table called candidates with some fields. The table contains a column named "keypass" which is the same for all users and is set as default. Using prepared statement I'm trying to first capture the value for key pass (which is the same for this example) and compare it to the user input.

the connection

```<code><?php
$dbServerName = "localhost";
$dbUserName = "root";
$dbPassword = "";
$dbName = "candidateDB";
$conn = mysqli_connect($dbServerName,$dbUserName,$dbPassword,$dbName);
</code>```

here is my code:

```<code>$stm_keypass = $conn ->prepare ("SELECT * FROM candidates WHERE keypass = ?");
$stm_keypass -> bind_param("s", $keypass);
$sql_keypass = $stm_keypass->execute();
</code>```

when I run the script I get this error "Fatal error: Call to a member function bind_param() on a non-object" what is the issue? thanks

table here

答: "Fatal error: Call to a member function bind_param() on a non-object" here would mean your $stm_keypass was likely not created properly, and is thus not an object. Check out the docs on how to handle error detection of prepared statements and go from there.

Body:
I have a table called candidates with some fields. The table contains a column named "keypass" which is the same for all users and is set as default. Using prepared statement I'm trying to first capture the value for key pass (which is the same for this example) and compare it to the user input.

the connection

<?php
$dbServerName = "localhost";
$dbUserName = "root";
$dbPassword = "";
$dbName = "candidateDB";
$conn = mysqli_connect($dbServerName,$dbUserName,$dbPassword,$dbName);

here is my code:

$stm_keypass = $conn ->prepare ("SELECT * FROM candidates WHERE keypass = ?");
$stm_keypass -> bind_param("s", $keypass);
$sql_keypass = $stm_keypass->execute();

when I run the script I get this error "Fatal error: Call to a member function bind_param() on a non-object" what is the issue? thanks

table here


问:
Any way to share data between Polymer components?
Currently I have two Polymer components that share a great amount of data. You can see here:

```<code><polymer-component1
      series="{{series}}"
      stackhelper={{stackhelper}}
      stack={{stack}}
      controls={{controls}}
      camera={{camera}}
      threed={{threed}}
      scene={{scene}}
      renderer={{renderer}}>
</polymer-component1>
<polymer-component2
      stackhelper=[[stackhelper]]
      stack={{stack}}
      controls={{controls}}
      camera={{camera}}
      threed={{threed}}
      scene={{scene}}
      renderer={{renderer}}
      guiobjects={{guiobjects}}>
</polymer-component2>
</code>```

This is working fine right now but whats the best practice about sharing data? Any way to share all the properties between two components?

答:
In Polymer 2 one element can just inherit the properties by extending it.

```<code>class MyElementSubclass extends MyElement {...}
</code>```

Or you create an element with just the properties both need and then both components extend the parent. You can find this here scroll down to Extending an existing element

Body:
Currently I have two Polymer components that share a great amount of data. You can see here:

<polymer-component1
      series="{{series}}"
      stackhelper={{stackhelper}}
      stack={{stack}}
      controls={{controls}}
      camera={{camera}}
      threed={{threed}}
      scene={{scene}}
      renderer={{renderer}}>
</polymer-component1>
<polymer-component2
      stackhelper=[[stackhelper]]
      stack={{stack}}
      controls={{controls}}
      camera={{camera}}
      threed={{threed}}
      scene={{scene}}
      renderer={{renderer}}
      guiobjects={{guiobjects}}>
</polymer-component2>

This is working fine right now but whats the best practice about sharing data? Any way to share all the properties between two components?

Body:
In Polymer 2 one element can just inherit the properties by extending it.

class MyElementSubclass extends MyElement {...}

Or you create an element with just the properties both need and then both components extend the parent. You can find this here scroll down to Extending an existing element


问:
Non-ASCII character '\xc5' breaking python script
My node.js server outputs the following array:

```<code>["Daniel Guillen","Sarah Tremaine Milam","Karen Ann"...."Chris Doyle","Katie Gould"]
</code>```

I'm trying to convert it to a csv file using a python script but when I declare the array in my .py file I get the following error:

```<code>SyntaxError: Non-ASCII character '\xc5' in file toCSV.py
</code>```

The array consists of people's names from Facebook so someone somewhere has a weird character in their name. It is too long to manually search.

How do you recommend working around this problem or finding the offending character? Iterating through the array in javascript before handing to python is also an option.

答:
You can use codecs (you'll have to import it) to read utf8 (non-ascii) characters. Like so:

```<code>csvfile = codecs.open(outputFileName+".csv", 'w+', 'utf8')
</code>```

That would be for writing to an output file. If you want to read in a file, just change the 'w+' to 'r'.
For individual strings, you can also use the method "string".encode('utf8')
This fixes the issue if it's being read from another file. If you have it in the file you're running, you need to set the encoding by putting

```<code># -*- coding: utf-8 -*-
</code>```

at top of file

Body:
My node.js server outputs the following array:

["Daniel Guillen","Sarah Tremaine Milam","Karen Ann"...."Chris Doyle","Katie Gould"]

I'm trying to convert it to a csv file using a python script but when I declare the array in my .py file I get the following error:

SyntaxError: Non-ASCII character '\xc5' in file toCSV.py

The array consists of people's names from Facebook so someone somewhere has a weird character in their name. It is too long to manually search.

How do you recommend working around this problem or finding the offending character? Iterating through the array in javascript before handing to python is also an option.

Body:
You can use codecs (you'll have to import it) to read utf8 (non-ascii) characters. Like so:

csvfile = codecs.open(outputFileName+".csv", 'w+', 'utf8')

That would be for writing to an output file. If you want to read in a file, just change the 'w+' to 'r'.
For individual strings, you can also use the method "string".encode('utf8')
This fixes the issue if it's being read from another file. If you have it in the file you're running, you need to set the encoding by putting

# -*- coding: utf-8 -*-

at top of file


问:
Laravel Passport oauth/authorize returns basic auth
I try to create oauth2 server on Laravel Passport and test it from third-party application. Oauth server use Laravel, and client use Yii framework. I am unable to modify the client front end and I created a route /api/oauth/login which forwards the request to oauth server:

```<code>public function actionOauthLogin()
{
   $query = http_build_query([
       'client_id' => '12',
       'client_secret' => '',
       'redirect_uri' => 'http://client.loc/api/oauth/callback',
       'response_type' => 'code',
       'scope' => '',
   ]);
   return $this->redirect('http://oauth-server.loc/oauth/authorize?' . $query);
}
</code>```

This method handling /api/oauth/callback route:

```<code>public function actionOauthCallback()
{
    $http = new Client();
    $response = $http->post('http://oauth-server.loc/oauth/token', [
        'form_params' => [
            'grant_type' => 'authorization_code',
            'client_id' => '3',
            'client_secret' => 'TJDyfygkuga45rtyfj8&65567Yhhgjjjj',
            'redirect_uri' => 'http://client.loc/api/oauth/callback',
            'code' => Yii::app()->request->getParamFromRequest('code'),
        ],
    ]);
    return json_decode((string) $response->getBody(), true);
 }
</code>```

All realized like in documentation. But when I open /api/oauth/login, forwarding redirection to oauth-server.loc/oauth/authorize?{params} and I see a http basic auth window. Wtf? Nginx has no such settings. Somebody knows what I'm doing wrong? Help me please.

答: Ensure that the 'redirect_uri' => 'http://client.loc/api/oauth/callback' is the same as as the redirect url that is saved in oauth_clients table with the matching client_id

Body:
I try to create oauth2 server on Laravel Passport and test it from third-party application. Oauth server use Laravel, and client use Yii framework. I am unable to modify the client front end and I created a route /api/oauth/login which forwards the request to oauth server:

public function actionOauthLogin()
{
   $query = http_build_query([
       'client_id' => '12',
       'client_secret' => '',
       'redirect_uri' => 'http://client.loc/api/oauth/callback',
       'response_type' => 'code',
       'scope' => '',
   ]);
   return $this->redirect('http://oauth-server.loc/oauth/authorize?' . $query);
}

This method handling /api/oauth/callback route:

public function actionOauthCallback()
{
    $http = new Client();
    $response = $http->post('http://oauth-server.loc/oauth/token', [
        'form_params' => [
            'grant_type' => 'authorization_code',
            'client_id' => '3',
            'client_secret' => 'TJDyfygkuga45rtyfj8&65567Yhhgjjjj',
            'redirect_uri' => 'http://client.loc/api/oauth/callback',
            'code' => Yii::app()->request->getParamFromRequest('code'),
        ],
    ]);
    return json_decode((string) $response->getBody(), true);
 }

All realized like in documentation. But when I open /api/oauth/login, forwarding redirection to oauth-server.loc/oauth/authorize?{params} and I see a http basic auth window. Wtf? Nginx has no such settings. Somebody knows what I'm doing wrong? Help me please.


问:
Background not covering full page
My background image is not covering the full page when I type in my nav bar. I have set the background width and height to 100%, which I thought would solve the problem.

https://jsfiddle.net/oefu0rmk/

CSS

```<code> #intro {
    background: #151515 url(../img/b1.jpg) no-repeat center bottom;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: 650px;
    background-attachment: fixed;
    width: 100%;
    height: 100%;
    min-height: 720px;
    display: table;
    position: relative;
    text-align: center;
}

.intro-overlay{
    position:absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background: #111111;
    opacity: .85
}
</code>```

HTML

```<code><nav>
    <a href="#about">about me</a>
    <a href="#my parents">about my parents</a>
    <a href="#hobbies">My hobbies</a>
    </nav>

<body>

    <section id="intro">
        <div class="intro-overlay"></div>
            <div class="intro-content">
                <h5>Oh, hi there! My name is Tatsu</h5>
                <h1> (Tah-T-Su)</h1>
                <a class="button stroke smoothscroll" href="#about" title="about me button">find out more about me</a>
</div>
</code>```

答:
Try this

```<code>   html {
           background: url(xyz.jpg) no-repeat center center fixed;
          -webkit-background-size: cover;
           -moz-background-size: cover;
           -o-background-size: cover;
          background-size: cover;
        }
    body
      {
         background:none;
      }
</code>```

This will definitely work.

Title: Background not covering full page

Body:
My background image is not covering the full page when I type in my nav bar. I have set the background width and height to 100%, which I thought would solve the problem.

https://jsfiddle.net/oefu0rmk/

CSS

 #intro {
    background: #151515 url(../img/b1.jpg) no-repeat center bottom;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: 650px;
    background-attachment: fixed;
    width: 100%;
    height: 100%;
    min-height: 720px;
    display: table;
    position: relative;
    text-align: center;
}

.intro-overlay{
    position:absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background: #111111;
    opacity: .85
}

HTML

    about me
    about my parents
    My hobbies

Oh, hi there! My name is Tatsu

 (Tah-T-Su)

                find out more about me

Body:
Try this

   html {
           background: url(xyz.jpg) no-repeat center center fixed;
          -webkit-background-size: cover;
           -moz-background-size: cover;
           -o-background-size: cover;
          background-size: cover;
        }
    body
      {
         background:none;
      }

This will definitely work.


问:
Geocoding things from the database?
I am kind of new to Geocoding.  What I want to do is pull a bunch of names of places from the DB, and display them as markers on the page.  And then allow people to choose different options which would force another db query, which would place a number of new markers on the page.

Is that possible?  It seems like relatively simple functionality, but since I am not good at JSON, it is giving me a hard time.

Thanks,
Alex

答:
There are lots of ways to geocode and really you need to give more information!

For example, in an offline environment, MapPoint is a pretty good solution (costs about $200/300 license). It can be made to work on a webserver but isn't usually worth the effort.

For a web server, then I would look at a web service. These are usually limited for free use, or pay for heavier (or commercial) use. Your question is too wide to give specifics, but look at the web services provided by Bing Maps, Google Maps, Yahoo (yes they're still around), and OpenStreetMaps-based.  bing Maps and Google Maps look like they'll be around for a long time - but might cost, depending on your application. OpenStreetMaps promises to have the widest coverage (including non NAm/EUR countries), but probably doesn't have the coverage of the others, yet.

Title: Geocoding things from the database?


问:
request file not working in asp.net
i need to request file from fileupload that is created in html. my question is quite simple how do i do this?
i know there is this option : HttpPostedFile File = Request.Files["imagem"]; but when i try to do that my File returns NULL.
I dont know what am i doing wrong, but even this simple code example is not working and i dont know why .

```<code><body>
    <form id="form1" runat="server">
    <div>
    protected void Button1_Click(object sender, EventArgs e)
        {
            HttpPostedFile File = Request.Files["imagem"];
      if ( File != null)
     Response.Write("Sucesso");
    }
   </form>
</body>
</code>```

and here is my aspx code example :

```<code>  <input type="file" name="image"  class="image-upload" /></div>
 <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</code>```

can any one explain what am i doing wrong ? thank you

答:
I'd recommend going with the asp.net file upload control:

```<code><asp:FileUpload ID="pictureUpload" class="form-control input-sm input-spacing" runat="server" />
</code>```

You can create these dynamically

```<code>FileUpload OneUpload = new FileUpload();
OneUpload.ID = "Upload" + MyIdNumber;
UploadsDiv.Controls.Add(OneUpload);
</code>```

Then to access the file, you have:

```<code>pictureUpload.SaveAs(FilePathAndName);
</code>```

You can also access different properties of the posted file...

```<code>pictureUpload.PostedFile.FileName
pictureUpload.PostedFile.ContentLength
pictureUpload.PostedFile.ContentType
</code>```

Title: request file not working in asp.net

Body:
i need to request file from fileupload that is created in html. my question is quite simple how do i do this?
i know there is this option : HttpPostedFile File = Request.Files["imagem"]; but when i try to do that my File returns NULL.
I dont know what am i doing wrong, but even this simple code example is not working and i dont know why .

    <form id="form1" runat="server">

    protected void Button1_Click(object sender, EventArgs e)
        {
            HttpPostedFile File = Request.Files["imagem"];
      if ( File != null)
     Response.Write("Sucesso");
    }
   </form>

and here is my aspx code example :

  <input type="file" name="image"  class="image-upload" />

 <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

can any one explain what am i doing wrong ? thank you

Body:
I'd recommend going with the asp.net file upload control:

<asp:FileUpload ID="pictureUpload" class="form-control input-sm input-spacing" runat="server" />

You can create these dynamically

FileUpload OneUpload = new FileUpload();
OneUpload.ID = "Upload" + MyIdNumber;
UploadsDiv.Controls.Add(OneUpload);

Then to access the file, you have:

pictureUpload.SaveAs(FilePathAndName);

You can also access different properties of the posted file...

pictureUpload.PostedFile.FileName
pictureUpload.PostedFile.ContentLength
pictureUpload.PostedFile.ContentType


问:
Compare list of strings in two different files vb.net
I have two different .txt files (requested_description.txt and all_description.txt).

In all_description.txt I have a list of strings, something like this:

all_description.txt

John is a policeman

  Mike is a doctor

  Barbara is a model

  etc...

In other file (requested_description.txt) I will search names from the first file (all_description.txt)

requested_description.txt

John

  Michael

  Ivan

  Donald

  Barbara

  etc...

I want to find if the strings (names) from requested_description.txt are the same in all_description.txt

Then I want to show results in output, for example:

John > John is a policeman

Barbara > Barbara is a model

For now I have only this sort of code, I want to use sort method, first to sort ascending then use for each... so I'm a little stuck here:

```<code>  Dim i As Integer = 0
  Dim ReadAllDescrpt As String() =File.ReadAllLines("all_description.txt")
  Dim RqstDescription As String()= File.ReadAllLines("rqst_description.txt")

  Dim allDescrpt As New List(Of String())
  allDescrpt.Sort()
  For Each descrpt In ReadAllDescrpt
     Console.WriteLine(ReadAllDescrpt)
  Next
  Console.WriteLine()
</code>```

答:
Here is a simple example on sort and check the string array line by line.</p>

```<code>Dim ReadAllDescrpt As String() = File.ReadAllLines("all_description.txt")
Dim RqstDescription As String() = File.ReadAllLines("requested_description.txt")
Array.Sort(RqstDescription)
For i As Integer = 0 To RqstDescription.Length - 1
    For j As Integer = 0 To ReadAllDescrpt.Length - 1
        If ReadAllDescrpt(j).Contains(RqstDescription(i)) Then
            Console.WriteLine(RqstDescription(i) & " > " & ReadAllDescrpt(j))
        End If
    Next
Next
</code>```

Body:
I have two different .txt files (requested_description.txt and all_description.txt).

In all_description.txt I have a list of strings, something like this:

all_description.txt

John is a policeman

  Mike is a doctor

  Barbara is a model

  etc...

In other file (requested_description.txt) I will search names from the first file (all_description.txt)

requested_description.txt

John

  Michael

  Ivan

  Donald

  Barbara

  etc...

I want to find if the strings (names) from requested_description.txt are the same in all_description.txt

Then I want to show results in output, for example:

John > John is a policeman

Barbara > Barbara is a model

For now I have only this sort of code, I want to use sort method, first to sort ascending then use for each... so I'm a little stuck here:

  Dim i As Integer = 0
  Dim ReadAllDescrpt As String() =File.ReadAllLines("all_description.txt")
  Dim RqstDescription As String()= File.ReadAllLines("rqst_description.txt")

  Dim allDescrpt As New List(Of String())
  allDescrpt.Sort()
  For Each descrpt In ReadAllDescrpt
     Console.WriteLine(ReadAllDescrpt)
  Next
  Console.WriteLine()

Body:
Here is a simple example on sort and check the string array line by line.

Dim ReadAllDescrpt As String() = File.ReadAllLines("all_description.txt")
Dim RqstDescription As String() = File.ReadAllLines("requested_description.txt")
Array.Sort(RqstDescription)
For i As Integer = 0 To RqstDescription.Length - 1
    For j As Integer = 0 To ReadAllDescrpt.Length - 1
        If ReadAllDescrpt(j).Contains(RqstDescription(i)) Then
            Console.WriteLine(RqstDescription(i) & " > " & ReadAllDescrpt(j))
        End If
    Next
Next


问:
How would I implement Arrays into this code
I've been a lurker of this site and now I need help with implementing arrays into this code. I'm not sure how to add the code into here so here's </p>

```<code>#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
//Named constants – residential customers
const double RES_BILL_PROC_FEES = 4.50;
const double RES_BASIC_SERV_COST = 20.50;
const double RES_COST_PREM_CHANNEL = 7.50;
//Named constants – business customers
const double BUS_BILL_PROC_FEES = 15.00;
const double BUS_BASIC_SERV_COST = 75.00;
const double BUS_BASIC_CONN_COST = 5.00;
const double BUS_COST_PREM_CHANNEL = 50.00;
int main()
{
    //Variable declaration
    int accountNumber;
    char customerType;
    int numOfPremChannels;
    int numOfBasicServConn;
    double amountDue;
    int rescount = 0, buscount = 0;
    double ressum = 0.00, bussum = 0.00;
    double resavg, busavg;
    ifstream fin;
    ofstream fout;
    //open input file
    fin.open("custin.txt", ios::in);
    if (fin.fail()) {
        cout << "Unable to open file " << endl;
        exit(0);
    }

    //open ouput file
    fout.open("custout.txt", ios::out);
    fout << fixed << showpoint;
    fout << setprecision(2);
    fout << "This program computes a cable "
         << "bill." << endl;
    //read from input file
    while (!fin.eof()) {
        //read customer type from file
        fin >> customerType;
        //read account number from file
        fin >> accountNumber;

        //If customer type is residential
        if (customerType == 'r' || customerType == 'R') {
            //read number of prem channels from file
            fin >> numOfPremChannels;
            amountDue = RES_BILL_PROC_FEES + RES_BASIC_SERV_COST + numOfPremChannels * RES_COST_PREM_CHANNEL;

            //write into output file
            fout << "Account number: " << accountNumber << endl;
            fout << "Amount due: $" << amountDue << endl
                 << endl;
            //compute running average of residential cusomer's amount due
            rescount += 1;
            ressum += amountDue;
            resavg = ressum / rescount;
        }

        //If customer type is business
        else if (customerType == 'b' || customerType == 'B') {
            //read number of service connection from file
            fin >> numOfBasicSevConn;

            //read number of prem channels from file
            fin >> numOfPremChannels;
            if (numOfBasicServConn <= 10)
                amountDue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + numOfPremChannels * BUS_COST_PREM_CHANNEL;
            else
                amountDue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + (numOfBasicServConn - 10) * BUS_BASIC_CONN_COST + numOfPremChannels * BUS_COST_PREM_CHANNEL;
            fout << "Account number: " << accountNumber << endl; //Step 7f
            fout << "Amount due: $" << amountDue << endl
                 << endl; //Step 7f

            //compute running average of business cusomer's amount due
            buscount += 1;
            bussum += amountDue;
            busavg = bussum / buscount;
        }
        else
            fout << "Invalid customer type.in " << accountNumber << endl; //Step 8
    }
    fout << endl
         << "Average Due for residential Customer " << resavg << endl;
    fout << endl
         << "Average Due for Business Customer " << busavg << endl;
    fin.close();
    fout.close();
    return 0;
}
</code>```

答: There are two ways to add arrays in C++. The first way is to specify the type of the array (int, double, float, char, string) and then specify the length of the array and type all the values until you get to the length. For example int arr[5] = {1, 2, 3, 4, 5}; For the other way you don't need to specify the length so that means you can put as many elements in the array as you like but you still need the data type and variable name like int arr[] = {1, 2, 3, 5, 8, 13, 21, 34};. Remember though in programming we start counting from 0.

Body:
I've been a lurker of this site and now I need help with implementing arrays into this code. I'm not sure how to add the code into here so here's

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
//Named constants – residential customers
const double RES_BILL_PROC_FEES = 4.50;
const double RES_BASIC_SERV_COST = 20.50;
const double RES_COST_PREM_CHANNEL = 7.50;
//Named constants – business customers
const double BUS_BILL_PROC_FEES = 15.00;
const double BUS_BASIC_SERV_COST = 75.00;
const double BUS_BASIC_CONN_COST = 5.00;
const double BUS_COST_PREM_CHANNEL = 50.00;
int main()
{
    //Variable declaration
    int accountNumber;
    char customerType;
    int numOfPremChannels;
    int numOfBasicServConn;
    double amountDue;
    int rescount = 0, buscount = 0;
    double ressum = 0.00, bussum = 0.00;
    double resavg, busavg;
    ifstream fin;
    ofstream fout;
    //open input file
    fin.open("custin.txt", ios::in);
    if (fin.fail()) {
        cout << "Unable to open file " << endl;
        exit(0);
    }

    //open ouput file
    fout.open("custout.txt", ios::out);
    fout << fixed << showpoint;
    fout << setprecision(2);
    fout << "This program computes a cable "
         << "bill." << endl;
    //read from input file
    while (!fin.eof()) {
        //read customer type from file
        fin >> customerType;
        //read account number from file
        fin >> accountNumber;

        //If customer type is residential
        if (customerType == 'r' || customerType == 'R') {
            //read number of prem channels from file
            fin >> numOfPremChannels;
            amountDue = RES_BILL_PROC_FEES + RES_BASIC_SERV_COST + numOfPremChannels * RES_COST_PREM_CHANNEL;

            //write into output file
            fout << "Account number: " << accountNumber << endl;
            fout << "Amount due: $" << amountDue << endl
                 << endl;
            //compute running average of residential cusomer's amount due
            rescount += 1;
            ressum += amountDue;
            resavg = ressum / rescount;
        }

        //If customer type is business
        else if (customerType == 'b' || customerType == 'B') {
            //read number of service connection from file
            fin >> numOfBasicSevConn;

            //read number of prem channels from file
            fin >> numOfPremChannels;
            if (numOfBasicServConn <= 10)
                amountDue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + numOfPremChannels * BUS_COST_PREM_CHANNEL;
            else
                amountDue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + (numOfBasicServConn - 10) * BUS_BASIC_CONN_COST + numOfPremChannels * BUS_COST_PREM_CHANNEL;
            fout << "Account number: " << accountNumber << endl; //Step 7f
            fout << "Amount due: $" << amountDue << endl
                 << endl; //Step 7f

            //compute running average of business cusomer's amount due
            buscount += 1;
            bussum += amountDue;
            busavg = bussum / buscount;
        }
        else
            fout << "Invalid customer type.in " << accountNumber << endl; //Step 8
    }
    fout << endl
         << "Average Due for residential Customer " << resavg << endl;
    fout << endl
         << "Average Due for Business Customer " << busavg << endl;
    fin.close();
    fout.close();
    return 0;
}


问:
How to retrieve SF actor service name programmatically?
Is there a way to programmatically retrieve the DefaultService Name attribute from ServiceManifest.xml inside other services? Example: actor's service name inside a Web API service. I am trying to avoid hard-coding anything.</p>

答:
I don't know how to avoid hard-coding of application type name and other things but you can try something like this in your controller

```<code>[HttpGet("{id:int}")]
public async Task<srting> Get(int id)
{
    var fabricClient = new FabricClient();
    string applicationTypeName = "ApplicationTypeName";
    string applicationVersion = "1.0.0";
    string actorServiceManifestName = "Actor1Pkg";
    var appManifest = await fabricClient.ServiceManager.GetServiceManifestAsync(applicationTypeName, applicationVersion, actorServiceManifestName);

    var document = XDocument.Parse(appManifest);
    ...
    // TODO: Get DefaultService Name attribute from simple XML
}
</code>```

You will get an xml, then find the desired attribute

Body:
I don't know how to avoid hard-coding of application type name and other things but you can try something like this in your controller

[HttpGet("{id:int}")]
public async Task<srting> Get(int id)
{
    var fabricClient = new FabricClient();
    string applicationTypeName = "ApplicationTypeName";
    string applicationVersion = "1.0.0";
    string actorServiceManifestName = "Actor1Pkg";
    var appManifest = await fabricClient.ServiceManager.GetServiceManifestAsync(applicationTypeName, applicationVersion, actorServiceManifestName);

    var document = XDocument.Parse(appManifest);
    ...
    // TODO: Get DefaultService Name attribute from simple XML
}

You will get an xml, then find the desired attribute


问:
transition timing function doesn't work
First problem it's doesn't work transition timing function(always work as transition timing function: linear,
second problem I wanna set up two setting for transition timing function

Setting in case reducing window size easy out

Setting in case increasing window size 'linear`

Any how fix it?

/*====== Ignore section __start ======*/

* {
  margin:0;
  padding:0;
}

html, body {
  height: 100%;
}

body {
  background-color: #eee;
}

.wrapper {
  height: 100%;
  display: table;
  width: 100%;
  text-align: center;
  border-collapse: collapse;
}

header {
  box-sizing: border-box;
  display: table-row;
  height: 50px;
  background-color: #eee;
  border-bottom: 1px solid #999;
}

main {
  height: 100%;
  display: table;
  width: 800px;
  margin: 0 auto;
  background-color: #fff;
  padding-bottom: 50px;
}

section {
  display: table-cell;
}
/*====== Ignore section __end ======*/

aside {
  display: table-cell;
  box-sizing: border-box;
  border-left: 1px solid #ccc;
  width: 300px;
  box-shadow: -15px 0 0 rgba(51, 51, 51, .5);

  /*__transition*/
  transition-timing-function: ease-out;
  opacity: 1;
  transition: all 2s;
}

/*====== Ignore section __start ======*/
footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  box-sizing: border-box;
  border-top: 1px solid #999;
  display: table-row;
  height: 50px;
  background-color: #eee;
}

@media screen and (max-width: 800px) {

  main {
    width: 100%;
  }
}
/*====== Ignore section __end ======*/

@media screen and (max-width: 700px) {

  aside {
    box-shadow: -15px 0 0 rgba(51, 51, 51, 0);
    opacity: 0;
    width: 0;
    border: 0px solid transparent;
    font-size: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>
  <div class="wrapper">
    <header>HEADER</header>
    <main>
      <section>SECTION</section>
      <aside>ASIDE</aside>
    </main>
    <footer>FOOTER</footer>
  </div>
</body>
</html></code>```

答:
First issue is that you're overriding the timing function when you place the transition property below it. Try this:

```<code>opacity: 1;
transition: all 2s;
transition-timing-function: ease-out;
</code>```

As far as using different transition timing function based on wether window is growing or shrinking, I do not believe that is possible in just CSS. You would likely need to write an event handler for window which captures that then add a class to  which your CSS can use to know if window is shrinking or growing.

Title: transition timing function doesn't work

Body:
First problem it's doesn't work transition timing function(always work as transition timing function: linear,
second problem I wanna set up two setting for transition timing function

Setting in case reducing window size easy out

Setting in case increasing window size 'linear`

Any how fix it?

/*====== Ignore section __start ======*/

* {
  margin:0;
  padding:0;
}

html, body {
  height: 100%;
}

body {
  background-color: #eee;
}

.wrapper {
  height: 100%;
  display: table;
  width: 100%;
  text-align: center;
  border-collapse: collapse;
}

header {
  box-sizing: border-box;
  display: table-row;
  height: 50px;
  background-color: #eee;
  border-bottom: 1px solid #999;
}

main {
  height: 100%;
  display: table;
  width: 800px;
  margin: 0 auto;
  background-color: #fff;
  padding-bottom: 50px;
}

section {
  display: table-cell;
}
/*====== Ignore section __end ======*/

aside {
  display: table-cell;
  box-sizing: border-box;
  border-left: 1px solid #ccc;
  width: 300px;
  box-shadow: -15px 0 0 rgba(51, 51, 51, .5);

  /*__transition*/
  transition-timing-function: ease-out;
  opacity: 1;
  transition: all 2s;
}

/*====== Ignore section __start ======*/
footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  box-sizing: border-box;
  border-top: 1px solid #999;
  display: table-row;
  height: 50px;
  background-color: #eee;
}

@media screen and (max-width: 800px) {

  main {
    width: 100%;
  }
}
/*====== Ignore section __end ======*/

@media screen and (max-width: 700px) {

  aside {
    box-shadow: -15px 0 0 rgba(51, 51, 51, 0);
    opacity: 0;
    width: 0;
    border: 0px solid transparent;
    font-size: 0;
  }
}

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>

    HEADER

SECTION

      ASIDE

    FOOTER

Body:
First issue is that you're overriding the timing function when you place the transition property below it. Try this:

opacity: 1;
transition: all 2s;
transition-timing-function: ease-out;

As far as using different transition timing function based on wether window is growing or shrinking, I do not believe that is possible in just CSS. You would likely need to write an event handler for window which captures that then add a class to  which your CSS can use to know if window is shrinking or growing.


问:
Populate table in twig with for loop
I want to populate my table in twig with a for loop and some if statement.

```<code>{% for user in users %}
      <td>
      {% if user.planningday == 1 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
      <td>
      {% if user.planningday == 2 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
      <td>
      {% if user.planningday == 3 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
      <td>
      {% if user.planningday == 4 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
      <td>
      {% if user.planningday == 5 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
{% endfor %}
</code>```

But that's not working and i dont know why.
Example :
 I try to populate my planning with 2 user. The first user select the day 5 so friday, the second user select the day 1 so monday. In my planning, first user have his name displaying on the friday , the second one is displaying after the friday  and not on the monday . Thanks for your help.

答:
The problem is you loop all the user, thus creating a calendar for all the users. If you want to group the users into one table try this aproach

```<code>{% for i in 1..5 %}
    {% set assigned_user = '' %}
    {% for user in users if user.planningday == i %}
        {% set assigned_user = user %}
    {% endfor %}
    <td>{{user.name}} {{user.lastname}}</td>
{% endfor %}
</code>```

twigfiddle

Title: Populate table in twig with for loop

Body:
I want to populate my table in twig with a for loop and some if statement.

{% for user in users %}

      {% if user.planningday == 1 %}
          {{user.name}} {{user.lastname}}
      {% endif %}

      {% if user.planningday == 2 %}
          {{user.name}} {{user.lastname}}
      {% endif %}

      {% if user.planningday == 3 %}
          {{user.name}} {{user.lastname}}
      {% endif %}

      {% if user.planningday == 4 %}
          {{user.name}} {{user.lastname}}
      {% endif %}

      {% if user.planningday == 5 %}
          {{user.name}} {{user.lastname}}
      {% endif %}

{% endfor %}

But that's not working and i dont know why.
Example :
 I try to populate my planning with 2 user. The first user select the day 5 so friday, the second user select the day 1 so monday. In my planning, first user have his name displaying on the friday , the second one is displaying after the friday  and not on the monday . Thanks for your help.

Body:
The problem is you loop all the user, thus creating a calendar for all the users. If you want to group the users into one table try this aproach

{% for i in 1..5 %}
    {% set assigned_user = '' %}
    {% for user in users if user.planningday == i %}
        {% set assigned_user = user %}
    {% endfor %}
    <td>{{user.name}} {{user.lastname}}</td>
{% endfor %}

twigfiddle


问:
.htaccess Accept no php extension, but don't force it
I built a website, and now want to remove the .php off of the filenames. That said, I have a ton of code and forms, and when I put foo.php, it redirects to foo, and then removes all the POST data.

Is there a way that

example.com/foo.php and

example.com/foo

will go to the same place? In other words, accept if the user took off the .php, but don't redirect if it's there.

Thanks for all of the help!

答:
Just remove your redirect rule and enable MultiViews option to allow extension-less URLs:

```<code>Options +MultiViews
</code>```

Body:
Just remove your redirect rule and enable MultiViews option to allow extension-less URLs:

Options +MultiViews


问:
How to keep white space as
I have xml element as following.

```<code><requestBody type="String"><![CDATA[Today, the XXXXXXXX XXXXXXXXXX XXXX (#XXXXXXX) Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Thanks,

XXXXXXXXXX
Test Administrator

XXXXXXXX XXXXXXXXXX XXXX
#### Address
CITY, ST  12345
Direct:  123-123-1234
Main Office:   123-123-1234
Fax:   123-123-1234
E-mail:   XXXXXXXXXX

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book, please visit www.WEBADDRESS.com<http://www.WEBADDRESS.com>.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.]]>
</requestBody>
</code>```

When I apply <xsl:value-of select="/requestBody"/> it is removing all white spaces in this element and printing a concatenated string as:

```<code>Today, the XXXXXXXX XXXXXXXXXX XXXX (#XXXXXXX) Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. Thanks, XXXXXXXXXX Test Administrator XXXXXXXX XXXXXXXXXX XXXX #### Address CITY, ST 12345 Direct: 123-123-1234 Main Office: 123-123-1234 Fax: 123-123-1234 E-mail: XXXXXXXXXX Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book, please visit www.WEBADDRESS.com<http://www.WEBADDRESS.com>. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</code>```

Can somebody tell me how to get the element content as-is without removing white spaces?

Thank you in advance.

答:
@Harishfysx, as John Bollinger notes in the comments, it is unclear if you are describing the actual file output, or the rendering in a browser -- since you include the xhtml tag, we (the readers) must assume that you're potentially talking about browser on-screen rendering, which does ignore whitespace in some important ways.

If you are talking about the file output, either your code or your XSL processor is doing something funny.  If I apply the following template:

```<code><xsl:template match="requestBody">
    <xsl:value-of select="."/>
</xsl:template>
</code>```

... I get the following output:

```<code><?xml version="1.0" encoding="UTF-8"?>Today, the XXXXXXXX XXXXXXXXXX XXXX (#XXXXXXX) Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Thanks,

XXXXXXXXXX
Test Administrator

XXXXXXXX XXXXXXXXXX XXXX
#### Address
CITY, ST  12345
Direct:  123-123-1234
Main Office:   123-123-1234
Fax:   123-123-1234
E-mail:   XXXXXXXXXX

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book, please visit www.WEBADDRESS.com<http://www.WEBADDRESS.com>.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</code>```

You'll note that all whitespace is preserved.

You'll also note that there's that pesky XML header, <?xml version="1.0" encoding="UTF-8"?>, and that the tag-ish link marker <http://www.WEBADDRESS.com> in your source is output in escaped format as <http://www.WEBADDRESS.com>.  Both of these can be fixed by adding the following before the template:

```<code><xsl:output method="text"/>
</code>```

Since I can quite easily produce output with whitespace preserved, I must assume that your problem is not the XSL, and instead that your browser is displaying this text in the default browser mode, which collapses each and every whitespace string (multiple instances of space, tab, newline) into a single space character.

As John suggests, use a ``` element, or use CSS that defines a style of whitespace:pre;, if you want strict layout where lines run off the right end of the screen, or whitespace:pre-wrap;, if you want to keep the whitespace but have the browser wrap lines that are too long to display within the margins.

Title: How to keep white space as

Body:
I have xml element as following.

<requestBody type="String"><![CDATA[Today, the XXXXXXXX XXXXXXXXXX XXXX (#XXXXXXX) Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Thanks,

XXXXXXXXXX
Test Administrator

XXXXXXXX XXXXXXXXXX XXXX
#### Address
CITY, ST  12345
Direct:  123-123-1234
Main Office:   123-123-1234
Fax:   123-123-1234
E-mail:   XXXXXXXXXX

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book, please visit www.WEBADDRESS.com<http://www.WEBADDRESS.com>.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.]]>
</requestBody>

When I apply <xsl:value-of select="/requestBody"/> it is removing all white spaces in this element and printing a concatenated string as:

Today, the XXXXXXXX XXXXXXXXXX XXXX (#XXXXXXX) Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. Thanks, XXXXXXXXXX Test Administrator XXXXXXXX XXXXXXXXXX XXXX #### Address CITY, ST 12345 Direct: 123-123-1234 Main Office: 123-123-1234 Fax: 123-123-1234 E-mail: XXXXXXXXXX Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book, please visit www.WEBADDRESS.com<http://www.WEBADDRESS.com>. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Can somebody tell me how to get the element content as-is without removing white spaces?

Thank you in advance.

Body:
@Harishfysx, as John Bollinger notes in the comments, it is unclear if you are describing the actual file output, or the rendering in a browser -- since you include the xhtml tag, we (the readers) must assume that you're potentially talking about browser on-screen rendering, which does ignore whitespace in some important ways.

If you are talking about the file output, either your code or your XSL processor is doing something funny.  If I apply the following template:

<xsl:template match="requestBody">
    <xsl:value-of select="."/>
</xsl:template>

... I get the following output:

<?xml version="1.0" encoding="UTF-8"?>Today, the XXXXXXXX XXXXXXXXXX XXXX (#XXXXXXX) Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Thanks,

XXXXXXXXXX
Test Administrator

XXXXXXXX XXXXXXXXXX XXXX
#### Address
CITY, ST  12345
Direct:  123-123-1234
Main Office:   123-123-1234
Fax:   123-123-1234
E-mail:   XXXXXXXXXX

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book, please visit www.WEBADDRESS.com&lt;http://www.WEBADDRESS.com&gt;.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

You'll note that all whitespace is preserved.

You'll also note that there's that pesky XML header, <?xml version="1.0" encoding="UTF-8"?>, and that the tag-ish link marker <http://www.WEBADDRESS.com> in your source is output in escaped format as &lt;http://www.WEBADDRESS.com&gt;.  Both of these can be fixed by adding the following before the template:

<xsl:output method="text"/>

Since I can quite easily produce output with whitespace preserved, I must assume that your problem is not the XSL, and instead that your browser is displaying this text in the default browser mode, which collapses each and every whitespace string (multiple instances of space, tab, newline) into a single space character.

As John suggests, use a <pre> element, or use CSS that defines a style of whitespace:pre;, if you want strict layout where lines run off the right end of the screen, or whitespace:pre-wrap;, if you want to keep the whitespace but have the browser wrap lines that are too long to display within the margins.


问:
Getting AJAX data in Laravel
I'm pulling my hair out here. I cannot access data submitted through an Ajax request in Laravel. I've tried using formData and just plain objects. Every time I just see a default Request object in Laravel and not the data I've submitted.

Here's my JS (TypeScript):

```<code>$('#save-section-order').on('click', function(e){
   e.preventDefault();

   let $this = $(this);
   let data = [];

   const order = $('#sortable').sortable('serialize');
   const project_id = $this.data('id');
   const url = "/admin/save-new-order";
   const csrfToken = $this.data('csrf');

   $.ajax({
       url: url,
       type: 'POST',
       data: {
           order: order,
           project_id: project_id
       },
       contentType: false,
       processData: false,
       headers: {
           'X-CSRF-TOKEN': csrfToken,
           'X-HTTP-Method-Override': 'PATCH'
       },
       success: function( msg ) {
           if ( msg.status === 'success' ) {
               $this.parent().parent().fadeOut();
           }
       },
       error: function( data ) {
           if ( data.status !== 200 ) {
               $this.parent().parent().css('background-color', '#f2dede');
           }
       }
   });
});
</code>```

Here's my web route:

Route::patch('/admin/save-new-order', 'Admin\ProjectsController@saveSectionsOrder');

Here's my ProjectsController:

```<code>public function saveSectionsOrder(Request $request) {

    dd($request);

}
</code>```

The output is always a generic Request object and I cannot retrieve the data I submitted through $request->order or $request->input('order').

I know I'm missing something really obvious, but I just can't see what.

答:
For receiving data from request object you must use

```<code>$request->all()
</code>```

This command will get you array of passed data. Or you can access directly by name:

```<code>$request->input('order')
</code>```

Title: Getting AJAX data in Laravel

Body:
I'm pulling my hair out here. I cannot access data submitted through an Ajax request in Laravel. I've tried using formData and just plain objects. Every time I just see a default Request object in Laravel and not the data I've submitted.

Here's my JS (TypeScript):

$('#save-section-order').on('click', function(e){
   e.preventDefault();

   let $this = $(this);
   let data = [];

   const order = $('#sortable').sortable('serialize');
   const project_id = $this.data('id');
   const url = "/admin/save-new-order";
   const csrfToken = $this.data('csrf');

   $.ajax({
       url: url,
       type: 'POST',
       data: {
           order: order,
           project_id: project_id
       },
       contentType: false,
       processData: false,
       headers: {
           'X-CSRF-TOKEN': csrfToken,
           'X-HTTP-Method-Override': 'PATCH'
       },
       success: function( msg ) {
           if ( msg.status === 'success' ) {
               $this.parent().parent().fadeOut();
           }
       },
       error: function( data ) {
           if ( data.status !== 200 ) {
               $this.parent().parent().css('background-color', '#f2dede');
           }
       }
   });
});

Here's my web route:

Route::patch('/admin/save-new-order', 'Admin\ProjectsController@saveSectionsOrder');

Here's my ProjectsController:

public function saveSectionsOrder(Request $request) {

    dd($request);

}

The output is always a generic Request object and I cannot retrieve the data I submitted through $request->order or $request->input('order').

I know I'm missing something really obvious, but I just can't see what.

Body:
For receiving data from request object you must use

$request->all()

This command will get you array of passed data. Or you can access directly by name:

$request->input('order')


问:
is it possible to append figures to Matplotlib's PdfPages?
I want to save 2 figures created at different parts of a script into a PDF using PdfPages, is it possible to append them to the pdf?

Example:

```<code>fig = plt.figure()
ax = fig_zoom.add_subplot(111)
ax.plot(range(10), range(10), 'b')

with PdfPages(pdffilepath) as pdf:
    pdf.savefig(fig)

fig1 = plt.figure()
ax = fig_zoom.add_subplot(111)
ax.plot(range(10), range(2, 12), 'r')

with PdfPages(pdffilepath) as pdf:
    pdf.savefig(fig1)
</code>```

答:
I think that Prashanth's answer can be generalized a bit better, for instance by incorporating it in a for loop, and avoiding the creation of multiple figures, which can generate memory leaks.</p>

```<code>import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

# create a PdfPages object
pdf = PdfPages('out.pdf')

# define here the dimension of your figure
fig = plt.figure()

for color in ['blue', 'red']:
    plt.plot(range(10), range(10), color)

    # save the current figure
    pdf.savefig(fig)

    # destroy the current figure
    # saves memory as opposed to create a new figure
    plt.clf()

# remember to close the object to ensure writing multiple plots
pdf.close()
</code>```

Body:
I want to save 2 figures created at different parts of a script into a PDF using PdfPages, is it possible to append them to the pdf?

Example:

fig = plt.figure()
ax = fig_zoom.add_subplot(111)
ax.plot(range(10), range(10), 'b')

with PdfPages(pdffilepath) as pdf:
    pdf.savefig(fig)

fig1 = plt.figure()
ax = fig_zoom.add_subplot(111)
ax.plot(range(10), range(2, 12), 'r')

with PdfPages(pdffilepath) as pdf:
    pdf.savefig(fig1)

Body:
I think that Prashanth's answer can be generalized a bit better, for instance by incorporating it in a for loop, and avoiding the creation of multiple figures, which can generate memory leaks.

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

# create a PdfPages object
pdf = PdfPages('out.pdf')

# define here the dimension of your figure
fig = plt.figure()

for color in ['blue', 'red']:
    plt.plot(range(10), range(10), color)

    # save the current figure
    pdf.savefig(fig)

    # destroy the current figure
    # saves memory as opposed to create a new figure
    plt.clf()

# remember to close the object to ensure writing multiple plots
pdf.close()


问:
What is the simplest way for an app to communicate with a website in asp.net?
I have a desktop application.
Users register to use it.
When they register, I need to make sure their email address is unique.
So I need to send a request to a website that keeps a list of all email addresses and returns the results.

What is the simplest, quickest way to do this is ASP.NET?

I could do this:

Send a webrequest:

```<code>http://www.site.com/validate.aspx?email=a@a.a
</code>```

And the aspx returns xml:

```<code><response>Valid</response>
</code>```

There are a few other simple tasks like this.
There is no need for heavy security or the need to make the system particularly robust due to high demand.

I have used web services before but that seems like too much overhead for this simple task.

Is there an elegant API that wraps up this communication system as it must be very common.

答: Actually, I'd go with something like what you described. It works for me unless you need something else. And I've seen a number of online services work exactly this way.</p>

Body:
I have a desktop application.
Users register to use it.
When they register, I need to make sure their email address is unique.
So I need to send a request to a website that keeps a list of all email addresses and returns the results.

What is the simplest, quickest way to do this is ASP.NET?

I could do this:

Send a webrequest:

http://www.site.com/validate.aspx?email=a@a.a

And the aspx returns xml:

<response>Valid</response>

There are a few other simple tasks like this.
There is no need for heavy security or the need to make the system particularly robust due to high demand.

I have used web services before but that seems like too much overhead for this simple task.

Is there an elegant API that wraps up this communication system as it must be very common.


答:
You're overriding transition-timing-function value with the transition shorthand.

Either merge the two together:

```<code>aside {
    ...
    transition: all 2s ease-out;
}
</code>```

Or change the order of your declarations:

```<code>aside {
    ...
    transition: all 2s;
    transition-timing-function: ease-out;
}
</code>```

Title: transition timing function doesn't work

Body:
You're overriding transition-timing-function value with the transition shorthand.

Either merge the two together:

aside {
    ...
    transition: all 2s ease-out;
}

Or change the order of your declarations:

aside {
    ...
    transition: all 2s;
    transition-timing-function: ease-out;
}


问:
Android O : Broadcast Limitations PHONE_STATE alternative solution
I have been using android.intent.action.PHONE_STATE for receiving the call state and show the user a dialog once after the call ends to log the call or not?. As from Android O we have to remove the implicit broadcasts from the manifest I need an alternate solution to this where I can listen to the phone call state when when the application is not active. I don't want to use job scheduler as it will kill the user experience. Can anyone suggest me an alternate solution.     </p>

答: You need to register a broadcast receiver in a foreground service or use the job scheduler.</p>


问:
What to do about 'discard' in Purescript do-notation?
Having a problem with some of the examples in the Learn Purescript by Example book. Specifically this code from section 9.3:

```<code>main :: Eff (canvas :: CANVAS) Unit
main = void $ unsafePartial do
  Just canvas <- getCanvasElementById "canvas"
  ctx <- getContext2D canvas

  setFillStyle "#0000FF" ctx -- this's line 16 referred to in the error message

  fillPath ctx $ rect ctx
    { x: 250.0
    , y: 250.0
    , w: 100.0
    , h: 100.0
    }
</code>```

gives the following error:

in module Example.Rectangle
  at src\Example\Rectangle.purs line 16, column 3 - line 16, column 29

A result of type

Context2D

was implicitly discarded in a do notation block.
   You can use _ <- ... to explicitly discard the result.

while applying a function discard
   of type Discard t0 => Bind t1 => t1 t0 -> (t0 -> t1 t2) -> t1 t2
   to argument (setFillStyle "#0000FF") ctx
  while inferring the type of discard ((setFillStyle "#0000FF") ctx)
  in value declaration main

where t0 is an unknown type
       t2 is an unknown type
       t1 is an unknown type

See https://github.com/purescript/documentation/blob/master/errors/NoInstanceFound.md for more information,

The suggested error doesn't help and I can't work out what "discard" acctualy does. I also noticed a similar problem with, for example, the "simulate" function from section 8.17. If I try the suggestion of assigning using "_ <- " more random seeming errors crop up.

(This is using PSCi 0.11.5)

答:
It is no more allowed to implicitly discard a value in a do block.

You can:
- ignore the value explicitly: _ <- setFillStyle....
- or if the return value is Unit (e.g. Eff fx Unit) you can simply import "discard" from "Prelude"

Body:
Having a problem with some of the examples in the Learn Purescript by Example book. Specifically this code from section 9.3:

main :: Eff (canvas :: CANVAS) Unit
main = void $ unsafePartial do
  Just canvas <- getCanvasElementById "canvas"
  ctx <- getContext2D canvas

  setFillStyle "#0000FF" ctx -- this's line 16 referred to in the error message

  fillPath ctx $ rect ctx
    { x: 250.0
    , y: 250.0
    , w: 100.0
    , h: 100.0
    }

gives the following error:

in module Example.Rectangle
  at src\Example\Rectangle.purs line 16, column 3 - line 16, column 29

A result of type

Context2D

was implicitly discarded in a do notation block.
   You can use _ <- ... to explicitly discard the result.

while applying a function discard
   of type Discard t0 => Bind t1 => t1 t0 -> (t0 -> t1 t2) -> t1 t2
   to argument (setFillStyle "#0000FF") ctx
  while inferring the type of discard ((setFillStyle "#0000FF") ctx)
  in value declaration main

where t0 is an unknown type
       t2 is an unknown type
       t1 is an unknown type

See https://github.com/purescript/documentation/blob/master/errors/NoInstanceFound.md for more information,

The suggested error doesn't help and I can't work out what "discard" acctualy does. I also noticed a similar problem with, for example, the "simulate" function from section 8.17. If I try the suggestion of assigning using "_ <- " more random seeming errors crop up.

(This is using PSCi 0.11.5)


问:
BC30456: 'Checked' is not a member of 'checkbox'
I have a gridView control with a checkBox TemplateField. I am trying to delete records from the gridvie based on the checked checkbox control but keep getting the error

BC30456: 'Checked' is not a member of 'checkbox'.

below is my button_click subroutine which should do the delete.

```<code>Protected Sub DeleteSelectedProducts_Click(sender As Object, e As EventArgs) Handles DeleteSelectedProducts.Click
    Try
        Dim atLeastOneRowDeleted As Boolean = False

        For Each row As GridViewRow In GridView1.Rows

            Dim cb As CheckBox = row.FindControl("ProductSelector")
            If cb IsNot Nothing AndAlso cb.Checked Then

                atLeastOneRowDeleted = True

                Dim productID As Integer = _
                    Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)

                DeleteResults.Text &= String.Format( _
                    "This would have deleted ProductID {0}<br />", productID)

            End If
        Next
        DeleteResults.Visible = atLeastOneRowDeleted
    Catch ex As Exception

    End Try

End Sub
</code>```

答:
I'm guessing this is WPF since both the WinForms CheckBox and the ASP.NET CheckBox have a Checked property.

For WPF you gotta use CheckBox.IsChecked:

```<code>If cb IsNot Nothing AndAlso cb.IsChecked Then
</code>```

Body:
I have a gridView control with a checkBox TemplateField. I am trying to delete records from the gridvie based on the checked checkbox control but keep getting the error

BC30456: 'Checked' is not a member of 'checkbox'.

below is my button_click subroutine which should do the delete.

Protected Sub DeleteSelectedProducts_Click(sender As Object, e As EventArgs) Handles DeleteSelectedProducts.Click
    Try
        Dim atLeastOneRowDeleted As Boolean = False

        For Each row As GridViewRow In GridView1.Rows

            Dim cb As CheckBox = row.FindControl("ProductSelector")
            If cb IsNot Nothing AndAlso cb.Checked Then

                atLeastOneRowDeleted = True

                Dim productID As Integer = _
                    Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)

                DeleteResults.Text &= String.Format( _
                    "This would have deleted ProductID {0}
", productID)

            End If
        Next
        DeleteResults.Visible = atLeastOneRowDeleted
    Catch ex As Exception

    End Try

End Sub

Body:
I'm guessing this is WPF since both the WinForms CheckBox and the ASP.NET CheckBox have a Checked property.

For WPF you gotta use CheckBox.IsChecked:

If cb IsNot Nothing AndAlso cb.IsChecked Then


问:
Missing required client configuration options: region
I am trying to check bucket existence on Amazon S3 using below code:

```<code>$credentials = new Aws\Common\Credentials\Credentials($creds['access_key_id'], $creds['secret_access_key']);
$client = Aws\S3\S3Client::factory(array( 'credentials' => $credentials ) );
if( ! $client->doesBucketExist($creds['bucket']) ) {
    throw new Exception("Bucket (" . $creds['bucket'] . ") does not exist.");
}
</code>```

It is working on localhost (wamp) but when I tried this on server it is not working. I am getting following error:

Missing required client configuration options: region: (string) A "region" configuration value is required for the "s3" service (e.g., "us-west-2"). A list of available public regions and endpoints can be found at http://docs.aws.amazon.com/general/latest/gr/rande.html. version: (string) A "version" configuration value is required. Specifying a version constraint ensures that your code will not be affected by a breaking change made to the service. For example, when using Amazon S3, you can lock your API version to "2006-03-01". Your build of the SDK has the following version(s) of "s3": * "2006-03-01" You may provide "latest" to the "version" configuration value to utilize the most recent available API version that your client's API provider can find. Note: Using 'latest' in a production application is not recommended. A list of available API versions can be found on each client's API documentation page: http://docs.aws.amazon.com/aws-sdk-php/v3/api/index.html. If you are unable to load a specific API version, then you may need to update your copy of the SDK.

I don't know why it is not working on server but same code is working on localhost.

答:
Set region explicitly when creating s3 client instead of relying on defaults.</p>

```<code>use Aws\Credentials\Credentials;
use Aws\S3\S3Client;

$result = $stsClient->getSessionToken();

$credentials = new Credentials(
    $result['Credentials']['AccessKeyId'],
    $result['Credentials']['SecretAccessKey'],
    $result['Credentials']['SessionToken']
);

$s3Client = new S3Client([
    'version'     => '2006-03-01',
    'region'      => 'us-west-2',
    'credentials' => $credentials
]);
</code>```

Body:
I am trying to check bucket existence on Amazon S3 using below code:

$credentials = new Aws\Common\Credentials\Credentials($creds['access_key_id'], $creds['secret_access_key']);
$client = Aws\S3\S3Client::factory(array( 'credentials' => $credentials ) );
if( ! $client->doesBucketExist($creds['bucket']) ) {
    throw new Exception("Bucket (" . $creds['bucket'] . ") does not exist.");
}

It is working on localhost (wamp) but when I tried this on server it is not working. I am getting following error:

Missing required client configuration options: region: (string) A "region" configuration value is required for the "s3" service (e.g., "us-west-2"). A list of available public regions and endpoints can be found at http://docs.aws.amazon.com/general/latest/gr/rande.html. version: (string) A "version" configuration value is required. Specifying a version constraint ensures that your code will not be affected by a breaking change made to the service. For example, when using Amazon S3, you can lock your API version to "2006-03-01". Your build of the SDK has the following version(s) of "s3": * "2006-03-01" You may provide "latest" to the "version" configuration value to utilize the most recent available API version that your client's API provider can find. Note: Using 'latest' in a production application is not recommended. A list of available API versions can be found on each client's API documentation page: http://docs.aws.amazon.com/aws-sdk-php/v3/api/index.html. If you are unable to load a specific API version, then you may need to update your copy of the SDK.

I don't know why it is not working on server but same code is working on localhost.

Body:
Set region explicitly when creating s3 client instead of relying on defaults.

use Aws\Credentials\Credentials;
use Aws\S3\S3Client;

$result = $stsClient->getSessionToken();

$credentials = new Credentials(
    $result['Credentials']['AccessKeyId'],
    $result['Credentials']['SecretAccessKey'],
    $result['Credentials']['SessionToken']
);

$s3Client = new S3Client([
    'version'     => '2006-03-01',
    'region'      => 'us-west-2',
    'credentials' => $credentials
]);


问:
Realex HPP request -custom field
I'm trying to send a custom field to realex to use upon successful response. The field in question is a json array.

```<code>[{"InvoiceId":7,"AmountPaid":180,"SucessfulPayment":false}]
</code>```

The problem I face is upon response the array is truncated to [{. I have this working by base 64 encoding the array but feel its a bit heavy and would rather send the raw json. I'm also concerned there may be a character restriction on the field length's which would get eaten up quick. If there's no restriction on length I'll probably go base 64.

Update

Code as requested.

JSON array passed into request object

```<code>[{"InvoiceId":7,"AmountPaid":180,"SucessfulPayment":false}]
</code>```

realex response returning

```<code>[{
</code>```

Code:

```<code><%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="RealexRedirectTestPay.aspx.cs"
Inherits="SmartClubOnline.RedirectTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body onload="document.form.submit();">
    <div class="content">
        <form name="form"
action="https://hpp.sandbox.realexpayments.com/pay" method="post">
        <asp:Literal ID="MERCHANT_ID" runat="server" />
        <asp:Literal ID="SECRET_ID" runat="server" />
        <asp:Literal ID="CLUB_NAME" runat="server" />
        <asp:Literal ID="ORDER_ID" runat="server" />
        <asp:Literal ID="CURRENCY_ID" runat="server" />
        <asp:Literal ID="CURRENCY" runat="server" />
        <asp:Literal ID="AMOUNT" runat="server" />
        <asp:Literal ID="TIMESTAMP" runat="server" />
        <asp:Literal ID="MEMBER_ID" runat="server" />
        <asp:Literal ID="MEMBER_USERNAME" runat="server" />
        <asp:Literal ID="MEMBER_EMAIL" runat="server" />
        <asp:Literal ID="INVOICE_ID" runat="server" />
        <asp:Literal ID="MEMBERPURSEID" runat="server" />
        <asp:Literal ID="SHA1HASH" runat="server" />
        <asp:Literal ID="TempOrderNumber" runat="server" />
        <asp:Literal ID="PromoRow" runat="server" />
        <asp:Literal ID="DELAYEDSETTLEMENTON" runat="server" />
        <asp:Literal ID="CREDITCARD_SHG_AMT" runat="server" />
        <asp:Literal ID="DEBITCARD_SHG_AMT" runat="server" />
        <asp:Literal ID="AUTO_SETTLE_FLAG" runat="server" />
        <asp:Literal ID="MERCHANT_RESPONSE_URL" runat="server" />
        <!--<input type="hidden" name="AUTO_SETTLE_FLAG" value="1" />-->
        <h3>
            Redirecting you to our Payment Provider</h3>
        <p>
            You are being securely redirected to our payment provider...Please Wait...</p>
        <!-- uncomment if you want the user to click a button to continue. Also remove the onload function in the Body tag -->
        <!-- <p><input type="submit" name="submit" value="continue to payment provider" /></p> -->
        </form>
    </div>
</body>
</html>
</code>```

Server side request:

```<code>            MERCHANT_ID.Text = "<input type=\"hidden\" name=\"MERCHANT_ID\"
value=\"" + merchantID + "\" />";
            SECRET_ID.Text = "<input type=\"hidden\" name=\"SECRET_ID\"
value=\"" + sharedSecret + "\" />";
            CLUB_NAME.Text = "<input type=\"hidden\" name=\"CLUB_NAME\"
value=\"" + CLUBNAME + "\" />";
            ORDER_ID.Text = "<input type=\"hidden\" name=\"ORDER_ID\"
value=\"" + orderID + "\" />";
            CURRENCY.Text = "<input type=\"hidden\" name=\"CURRENCY\"
value=\"" + currencyCode + "\" />";
            CURRENCY_ID.Text = "<input type=\"hidden\" name=\"CURRENCY_ID\"
value=\"" + currencyCode + "\" />";
            AMOUNT.Text = "<input type=\"hidden\" name=\"AMOUNT\" value=\""
+ amount + "\" />";
            TIMESTAMP.Text = "<input type=\"hidden\" name=\"TIMESTAMP\"
value=\"" + timestamp + "\" />";
            MEMBER_ID.Text = "<input type=\"hidden\" name=\"MEMBER_ID\"
value=\"" + MEMBERID + "\" />";
            MEMBER_USERNAME.Text = "<input type=\"hidden\"
name=\"MEMBER_USERNAME\" value=\"" + MEMBERUSERNAME + "\" />";
            MEMBER_EMAIL.Text = "<input type=\"hidden\"
name=\"MEMBER_EMAIL\" value=\"" + MEMBEREMAIL + "\" />";
            INVOICE_ID.Text = "<input type=\"hidden\" name=\"INVOICE_ID\"
value=\"" + INVOICEID + "\" />";
            MEMBERPURSEID.Text = "<input type=\"hidden\"
name=\"MEMBERPURSEID\" value=\"" + "0" + "\" />";
            SHA1HASH.Text = "<input type=\"hidden\" name=\"SHA1HASH\"
value=\"" + hash + "\" />";
            AUTO_SETTLE_FLAG.Text = "<input type=\"hidden\"
name=\"AUTO_SETTLE_FLAG\" value=\"" + AUTOSETTLEFLAG + "\" />";
            DELAYEDSETTLEMENTON.Text = "<input type=\"hidden\"
name=\"DELAYEDSETTLEMENTON\" value=\"" + DELAYEDSETTLEFLAG + "\" />";
            CREDITCARD_SHG_AMT.Text = "<input type=\"hidden\"
name=\"CREDITCARD_SHG_AMT\" value=\"" + CREDITCARD_SHG + "\" />";
            DEBITCARD_SHG_AMT.Text = "<input type=\"hidden\"
name=\"DEBITCARD_SHG_AMT\" value=\"" + DEBITCARD_SHG + "\" />";
            MERCHANT_RESPONSE_URL.Text = "<input type=\"hidden\"
name=\"MERCHANT_RESPONSE_URL\" value=\"" + _realexResponseURL + "\" />";
</code>```

Failing code in realex response:

```<code>if (Request.Form["INVOICE_ID"] != null)
   INVOICEID = Request.Form["INVOICE_ID"].ToString();
else
    StaticOps.AddErrorToLog("FORM.INVOICE_ID : ", "VALUE NULL",
"RealexResponse");
</code>```

答:
Apologies for the delay in getting back to you, didn't see the notification of your response. On the POST in, the HPP won't accept the inverted commas and truncates at that point in the string.

Could you try url encoding the string on the way out and decoding when the response comes back? The max length of a custom field on the HPP is 255. Or you could just url encode the inverted commas. Hopefully that suits your needs. Please let me know if not.

Best,

Seán MacDomhnall

Realex Payments

ContentLicense: CC BY-SA 4.0

Title: Realex HPP request -custom field

Body:
I'm trying to send a custom field to realex to use upon successful response. The field in question is a json array.

[{"InvoiceId":7,"AmountPaid":180,"SucessfulPayment":false}]

The problem I face is upon response the array is truncated to [{. I have this working by base 64 encoding the array but feel its a bit heavy and would rather send the raw json. I'm also concerned there may be a character restriction on the field length's which would get eaten up quick. If there's no restriction on length I'll probably go base 64.

Update

Code as requested.

JSON array passed into request object

[{"InvoiceId":7,"AmountPaid":180,"SucessfulPayment":false}]

realex response returning

[{

Code:

<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="RealexRedirectTestPay.aspx.cs"
Inherits="SmartClubOnline.RedirectTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

        <form name="form"
action="https://hpp.sandbox.realexpayments.com/pay" method="post">
        <asp:Literal ID="MERCHANT_ID" runat="server" />
        <asp:Literal ID="SECRET_ID" runat="server" />
        <asp:Literal ID="CLUB_NAME" runat="server" />
        <asp:Literal ID="ORDER_ID" runat="server" />
        <asp:Literal ID="CURRENCY_ID" runat="server" />
        <asp:Literal ID="CURRENCY" runat="server" />
        <asp:Literal ID="AMOUNT" runat="server" />
        <asp:Literal ID="TIMESTAMP" runat="server" />
        <asp:Literal ID="MEMBER_ID" runat="server" />
        <asp:Literal ID="MEMBER_USERNAME" runat="server" />
        <asp:Literal ID="MEMBER_EMAIL" runat="server" />
        <asp:Literal ID="INVOICE_ID" runat="server" />
        <asp:Literal ID="MEMBERPURSEID" runat="server" />
        <asp:Literal ID="SHA1HASH" runat="server" />
        <asp:Literal ID="TempOrderNumber" runat="server" />
        <asp:Literal ID="PromoRow" runat="server" />
        <asp:Literal ID="DELAYEDSETTLEMENTON" runat="server" />
        <asp:Literal ID="CREDITCARD_SHG_AMT" runat="server" />
        <asp:Literal ID="DEBITCARD_SHG_AMT" runat="server" />
        <asp:Literal ID="AUTO_SETTLE_FLAG" runat="server" />
        <asp:Literal ID="MERCHANT_RESPONSE_URL" runat="server" />

            Redirecting you to our Payment Provider

            You are being securely redirected to our payment provider...Please Wait...

        </form>

Server side request:

            MERCHANT_ID.Text = "<input type=\"hidden\" name=\"MERCHANT_ID\"
value=\"" + merchantID + "\" />";
            SECRET_ID.Text = "<input type=\"hidden\" name=\"SECRET_ID\"
value=\"" + sharedSecret + "\" />";
            CLUB_NAME.Text = "<input type=\"hidden\" name=\"CLUB_NAME\"
value=\"" + CLUBNAME + "\" />";
            ORDER_ID.Text = "<input type=\"hidden\" name=\"ORDER_ID\"
value=\"" + orderID + "\" />";
            CURRENCY.Text = "<input type=\"hidden\" name=\"CURRENCY\"
value=\"" + currencyCode + "\" />";
            CURRENCY_ID.Text = "<input type=\"hidden\" name=\"CURRENCY_ID\"
value=\"" + currencyCode + "\" />";
            AMOUNT.Text = "<input type=\"hidden\" name=\"AMOUNT\" value=\""
+ amount + "\" />";
            TIMESTAMP.Text = "<input type=\"hidden\" name=\"TIMESTAMP\"
value=\"" + timestamp + "\" />";
            MEMBER_ID.Text = "<input type=\"hidden\" name=\"MEMBER_ID\"
value=\"" + MEMBERID + "\" />";
            MEMBER_USERNAME.Text = "<input type=\"hidden\"
name=\"MEMBER_USERNAME\" value=\"" + MEMBERUSERNAME + "\" />";
            MEMBER_EMAIL.Text = "<input type=\"hidden\"
name=\"MEMBER_EMAIL\" value=\"" + MEMBEREMAIL + "\" />";
            INVOICE_ID.Text = "<input type=\"hidden\" name=\"INVOICE_ID\"
value=\"" + INVOICEID + "\" />";
            MEMBERPURSEID.Text = "<input type=\"hidden\"
name=\"MEMBERPURSEID\" value=\"" + "0" + "\" />";
            SHA1HASH.Text = "<input type=\"hidden\" name=\"SHA1HASH\"
value=\"" + hash + "\" />";
            AUTO_SETTLE_FLAG.Text = "<input type=\"hidden\"
name=\"AUTO_SETTLE_FLAG\" value=\"" + AUTOSETTLEFLAG + "\" />";
            DELAYEDSETTLEMENTON.Text = "<input type=\"hidden\"
name=\"DELAYEDSETTLEMENTON\" value=\"" + DELAYEDSETTLEFLAG + "\" />";
            CREDITCARD_SHG_AMT.Text = "<input type=\"hidden\"
name=\"CREDITCARD_SHG_AMT\" value=\"" + CREDITCARD_SHG + "\" />";
            DEBITCARD_SHG_AMT.Text = "<input type=\"hidden\"
name=\"DEBITCARD_SHG_AMT\" value=\"" + DEBITCARD_SHG + "\" />";
            MERCHANT_RESPONSE_URL.Text = "<input type=\"hidden\"
name=\"MERCHANT_RESPONSE_URL\" value=\"" + _realexResponseURL + "\" />";

Failing code in realex response:

if (Request.Form["INVOICE_ID"] != null)
   INVOICEID = Request.Form["INVOICE_ID"].ToString();
else
    StaticOps.AddErrorToLog("FORM.INVOICE_ID : ", "VALUE NULL",
"RealexResponse");