问:
Jump to activity from Android preference activity
I have an Android app with a PreferenceActivity, and one of the Preference entries launches one of my own activities (the "About" screen). The entry looks like this:

```<code><PreferenceScreen android:title="@string/about.Title">
    <intent ... />
</PreferenceScreen>
</code>```

Also (and this is important), I use Gradle and a .debug application ID suffix for my debug builds. I install both the Play Store version and the debug version on my phone.

The question is: What kind of intent to use above? I know of two options, neither of which work:

Use an android:action intent with my own action string, and register that action string in my manifest with <intent-filter>.

If I use android:exported="false" in the manifest, then the activity fails to load on Android 7.1 when both apps are installed. (I get "Complete action using ... No apps can perform this action".) It works fine if only one is installed (either).

If I use android:exported="true", then not only am I exporting an internal Activity, but when I tap the preference, two instances of the activity are pushed on the stack (one for each app). If I install only one of the two apps, then only one instance shows up.

Use the android:targetPackage and android:androidClass approach, but then I don't know what to use for the package, since it's different for the release and debug versions (because of the suffix). One solution is to have a copy of the preferences.xml file in the debug resource folder with only the package changed, but this is bug-prone.

I was using option #1.1 for years but it recently broke on my phone, and I suspect the 7.1 update is to blame. I've never had cross-talk between these two installed apps before!

This has to be a pretty common pattern! Any ideas?

答:
Please follow this steps:

After you add preferences using

```<code>addPreferencesFromResource(R.xml.preferences);
</code>```

find your preference that you want to set onClick and define it by casting like

```<code>Preference pref = (Preference) findPreference("pref");
</code>```

Then you can easily set its onClick using:

```<code>pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        startActivity(new Intent(CurrentActivity.this, NextActivity.class));
        return true;
    }
});
</code>```

Body:
I have an Android app with a PreferenceActivity, and one of the Preference entries launches one of my own activities (the "About" screen). The entry looks like this:

<PreferenceScreen android:title="@string/about.Title">
    <intent ... />
</PreferenceScreen>

Also (and this is important), I use Gradle and a .debug application ID suffix for my debug builds. I install both the Play Store version and the debug version on my phone.

The question is: What kind of intent to use above? I know of two options, neither of which work:

Use an android:action intent with my own action string, and register that action string in my manifest with <intent-filter>.

If I use android:exported="false" in the manifest, then the activity fails to load on Android 7.1 when both apps are installed. (I get "Complete action using ... No apps can perform this action".) It works fine if only one is installed (either).

If I use android:exported="true", then not only am I exporting an internal Activity, but when I tap the preference, two instances of the activity are pushed on the stack (one for each app). If I install only one of the two apps, then only one instance shows up.

Use the android:targetPackage and android:androidClass approach, but then I don't know what to use for the package, since it's different for the release and debug versions (because of the suffix). One solution is to have a copy of the preferences.xml file in the debug resource folder with only the package changed, but this is bug-prone.

I was using option #1.1 for years but it recently broke on my phone, and I suspect the 7.1 update is to blame. I've never had cross-talk between these two installed apps before!

This has to be a pretty common pattern! Any ideas?

Body:
Please follow this steps:

After you add preferences using

addPreferencesFromResource(R.xml.preferences);

find your preference that you want to set onClick and define it by casting like

Preference pref = (Preference) findPreference("pref");

Then you can easily set its onClick using:

pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        startActivity(new Intent(CurrentActivity.this, NextActivity.class));
        return true;
    }
});


来源: stackexchange

问:
Magento - Multi Select Category Attribute not saving
I'm using Magento Community 1.9.0.0.

I have programmatically created a custom category attribute which is a multi select. The attribute can be seen in my admin category section. When i select any values - whether it's one or more and press save i get a successful saved message but the values never save.

I then also tried an extension which creates category attributes. This had the same issue. When i contacted support they said

Category entity does not support multi selection so this type of attribute will not work with category.

Is this true? Can multi select not work on category attributes on CE-1.9?

Here is the code i was using to create it programmatically:

```<code>require_once('app/Mage.php');
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$installer = new Mage_Sales_Model_Mysql4_Setup;
$attribute  = array(
    'type' => 'text',
    'label'=> 'Room Type',
    'input' => 'multiselect',
    'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
    'visible' => true,
    'required' => false,
    'user_defined' => true,
    'default' => "",
    'group' => "General Information",
    'option' => array (
        'value' => array(
            'kitchen' => array('Kitchen'),
            'bedroom' => array('Bedroom'),
            'bathroom' => array('Bathroom'),
            'loft' => array('Loft'),
            'basement' => array('Basement'),
            'lounge' => array('Lounge')
        )
    )

);
$installer->addAttribute('catalog_category', 'room_type', $attribute);
$installer->endSetup();
</code>```

答:
@Rian is right, multi-select values are sent as an array, which can't be processed. However, we don't have to use observer. Instead, we should add a backend model for the attribute.
Add the following line to your attribute data array when creating it.

```<code>'backend' => 'your_module/category_attribute_backend_related',
</code>```

In your backend model (Your_Module_Model_Category_Attribute_Backend_Related), you should have the following functions to help the selected options be saved or loaded correctly.

```<code>public function beforeSave($object) {
    $attributeCode = $this->getAttribute()->getName();
    if ($attributeCode == 'room_type') {
        $data = $object->getData($attributeCode);
        if (!is_array($data)) {
            $data = array();
        }
        $object->setData($attributeCode, join(',', $data));
    }
    if (is_null($object->getData($attributeCode))) {
        $object->setData($attributeCode, false);
    }
    return $this;
}

public function afterLoad($object) {
    $attributeCode = $this->getAttribute()->getName();
    if ($attributeCode == 'room_type') {
        $data = $object->getData($attributeCode);
        if ($data) {
            $object->setData($attributeCode, explode(',', $data));
        }
    }
    return $this;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using Magento Community 1.9.0.0.

I have programmatically created a custom category attribute which is a multi select. The attribute can be seen in my admin category section. When i select any values - whether it's one or more and press save i get a successful saved message but the values never save.

I then also tried an extension which creates category attributes. This had the same issue. When i contacted support they said

Category entity does not support multi selection so this type of attribute will not work with category.

Is this true? Can multi select not work on category attributes on CE-1.9?

Here is the code i was using to create it programmatically:

require_once('app/Mage.php');
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$installer = new Mage_Sales_Model_Mysql4_Setup;
$attribute  = array(
    'type' => 'text',
    'label'=> 'Room Type',
    'input' => 'multiselect',
    'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
    'visible' => true,
    'required' => false,
    'user_defined' => true,
    'default' => "",
    'group' => "General Information",
    'option' => array (
        'value' => array(
            'kitchen' => array('Kitchen'),
            'bedroom' => array('Bedroom'),
            'bathroom' => array('Bathroom'),
            'loft' => array('Loft'),
            'basement' => array('Basement'),
            'lounge' => array('Lounge')
        )
    )

);
$installer->addAttribute('catalog_category', 'room_type', $attribute);
$installer->endSetup();

Body:
@Rian is right, multi-select values are sent as an array, which can't be processed. However, we don't have to use observer. Instead, we should add a backend model for the attribute.
Add the following line to your attribute data array when creating it.

'backend' => 'your_module/category_attribute_backend_related',

In your backend model (Your_Module_Model_Category_Attribute_Backend_Related), you should have the following functions to help the selected options be saved or loaded correctly.

public function beforeSave($object) {
    $attributeCode = $this->getAttribute()->getName();
    if ($attributeCode == 'room_type') {
        $data = $object->getData($attributeCode);
        if (!is_array($data)) {
            $data = array();
        }
        $object->setData($attributeCode, join(',', $data));
    }
    if (is_null($object->getData($attributeCode))) {
        $object->setData($attributeCode, false);
    }
    return $this;
}

public function afterLoad($object) {
    $attributeCode = $this->getAttribute()->getName();
    if ($attributeCode == 'room_type') {
        $data = $object->getData($attributeCode);
        if ($data) {
            $object->setData($attributeCode, explode(',', $data));
        }
    }
    return $this;
}


问:
Mongodb schema design
I'm confused, what is the best format for the following case:

```<code>Name: Pretty nice hot dog
Stock: 10
Weight: 0.1 grams
Price: 2 dollars

Name: An ordinary dumbbell
Stock: 5
Weight: 4 kilograms
Price: 667.98 yens
</code>```

This:

```<code>db.item.save ({"_id" : 1, "name" : "Pretty nice hot dog", "stock" : 10, "weight" : {"value" : 0.1, "unit" : "gram"}, "price" : {"value" : 2, "unit" : "dollar"}})
db.item.save ({"_id" : 2, "name" : "An ordinary dumbbell", "stock" : 5, "weight" : {"value" : 4, "unit" : "kilogram"}, "price" : {"value" : 667.98, "unit" : "yen"}})
</code>```

Or this:

```<code>db.unit.save ({"_id" : 1, "name" : "dollar"})
db.unit.save ({"_id" : 2, "name" : "yen"})
db.unit.save ({"_id" : 4, "name" : "gram"})
db.unit.save ({"_id" : 5, "name" : "kilogram"})

db.item.save ({"_id" : 1, "name" : "Pretty nice hot dog", "stock" : 10, "weight" : {"value" : 0.1, "unit" : [new DBRef ("unit", 4)]}, "price" : [new DBRef ("unit", 1)]})
db.item.save ({"_id" : 2, "name" : "An ordinary dumbbell", "stock" : 5, "weight" : {"value" : 4, "unit" : [new DBRef ("unit", 5)]}, "price" : [new DBRef ("unit", 2)]})
</code>```

The values of the field "unit" is immutable, I don't know if I should put it in a separate collection.

Thanks

答: Read Schema Design from MongoDb docs. This is exactly your case.</p>

ContentLicense: CC BY-SA 2.5

Title: Mongodb schema design

Body:
I'm confused, what is the best format for the following case:

Name: Pretty nice hot dog
Stock: 10
Weight: 0.1 grams
Price: 2 dollars

Name: An ordinary dumbbell
Stock: 5
Weight: 4 kilograms
Price: 667.98 yens

This:

db.item.save ({"_id" : 1, "name" : "Pretty nice hot dog", "stock" : 10, "weight" : {"value" : 0.1, "unit" : "gram"}, "price" : {"value" : 2, "unit" : "dollar"}})
db.item.save ({"_id" : 2, "name" : "An ordinary dumbbell", "stock" : 5, "weight" : {"value" : 4, "unit" : "kilogram"}, "price" : {"value" : 667.98, "unit" : "yen"}})

Or this:

db.unit.save ({"_id" : 1, "name" : "dollar"})
db.unit.save ({"_id" : 2, "name" : "yen"})
db.unit.save ({"_id" : 4, "name" : "gram"})
db.unit.save ({"_id" : 5, "name" : "kilogram"})

db.item.save ({"_id" : 1, "name" : "Pretty nice hot dog", "stock" : 10, "weight" : {"value" : 0.1, "unit" : [new DBRef ("unit", 4)]}, "price" : [new DBRef ("unit", 1)]})
db.item.save ({"_id" : 2, "name" : "An ordinary dumbbell", "stock" : 5, "weight" : {"value" : 4, "unit" : [new DBRef ("unit", 5)]}, "price" : [new DBRef ("unit", 2)]})

The values of the field "unit" is immutable, I don't know if I should put it in a separate collection.

Thanks


问:
The dot product of int32 and float32 produces float64 in Theano
When I compile the function

```<code>x = theano.tensor.imatrix('x')
y = theano.tensor.fmatrix('y')
z = x.dot(y)
f = theano.function([x, y], z)
</code>```

the resulting output is a float64, even when x is of type int32 and y is of type float32. When I compute the same operation where x is a Theano fmatrix of type float32, the resulting matrix is a float32. Why is the smaller bit size not preserved in the former case? In other words, why is the dot product of an int32 and a float32 equal to a float64 instead of float32 in Theano?

I'm using Theano version 0.9.0

答:
In general, it is assumed that you want to keep whatever precision you start out with. int32 has 31 significand bits, float32 has 24 significand bits and 8 exponent bits. Thus staying at either may cause reduced precision, and float64 is chosen, with its 53 significand bits. </p>

<p>You can also configure theano not to use float64 by default. </p>

Body:
When I compile the function

x = theano.tensor.imatrix('x')
y = theano.tensor.fmatrix('y')
z = x.dot(y)
f = theano.function([x, y], z)

the resulting output is a float64, even when x is of type int32 and y is of type float32. When I compute the same operation where x is a Theano fmatrix of type float32, the resulting matrix is a float32. Why is the smaller bit size not preserved in the former case? In other words, why is the dot product of an int32 and a float32 equal to a float64 instead of float32 in Theano?

I'm using Theano version 0.9.0

Body:
In general, it is assumed that you want to keep whatever precision you start out with. int32 has 31 significand bits, float32 has 24 significand bits and 8 exponent bits. Thus staying at either may cause reduced precision, and float64 is chosen, with its 53 significand bits.

You can also configure theano not to use float64 by default.


问:
Liferay JSF service builder configuration error
Am newbie to Liferay. I have created one JSF portlet and added the service builder to it. Using this link Generate a Persistence Framework. After configure a service builder i have generated the source using service builder. But am getting following exception when build service of project.

```<code> Exception in thread "main" java.lang.IllegalArgumentException: No entity column exist with column database name guestbookId for entity Guestbook
 [echo]     at com.liferay.portal.tools.service.builder.ServiceBuilder._getEntityColumnByColumnDBName(ServiceBuilder.java:4242)
 [echo]     at com.liferay.portal.tools.service.builder.ServiceBuilder._getColumnLengths(ServiceBuilder.java:3857)
 [echo]     at com.liferay.portal.tools.service.builder.ServiceBuilder._createSQLIndexes(ServiceBuilder.java:3355)
 [echo]     at com.liferay.portal.tools.service.builder.ServiceBuilder.<init>(ServiceBuilder.java:796)
 [echo]     at com.liferay.portal.tools.service.builder.ServiceBuilder.main(ServiceBuilder.java:216)
 [echo]     -Dservice.tpl.spring_xml_session=com/liferay/portal/tools/service/builder/dependencies/spring_xml_session.ftl
 [echo] Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0
[mkdir] Created dir: D:\liferay\liferay-plugins-sdk-7.0\portlets\jsfguestbook-portlet\docroot\WEB-INF\service-classes
 [copy] Copied 9 empty directories to 9 empty directories under D:\liferay\liferay-plugins-sdk-7.0\portlets\jsfguestbook-portlet\docroot\WEB-INF\service-classes
[javac] Compiling 38 source files to D:\liferay\liferay-plugins-sdk-7.0\portlets\jsfguestbook-portlet\docroot\WEB-INF\service-classes
[javac] Note: Some input files use or override a deprecated API.
[javac] Note: Recompile with -Xlint:deprecation for details.
[javac] Note: Some input files use unchecked or unsafe operations.
[javac] Note: Recompile with -Xlint:unchecked for details.
  [jar] Building jar: D:\liferay\liferay-plugins-sdk-7.0\portlets\jsfguestbook-portlet\docroot\WEB-INF\lib\jsfguestbook-portlet-service.jar
[delete] Deleting directory D:\liferay\liferay-plugins-sdk-7.0\portlets\jsfguestbook-portlet\docroot\WEB-INF\service-classes
BUILD SUCCESSFUL
Total time: 8 seconds
</code>```

Also after built the service i have added the code as per article. I got no method is configured for following code.

```<code>public Guestbook getFirstGuestbookByName(long groupId, String name) throws SystemException {
    Guestbook guestbook = null;

    List<Guestbook> guestbooks = guestbookPersistence.findByName(groupId, name); // This method is not exist.
    if (guestbooks != null && guestbooks.size() > 0) {
        guestbook = guestbooks.get(0);
    }

    return guestbook;
}
</code>```

My service.xml configuration is follows

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 7.0.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_7_0_0.dtd">
<service-builder package-path="com.liferay.docs.guestbook">
<author>muthuvignesh.k</author>
<namespace>GB</namespace>
<entity name="Guestbook" local-service="true" uuid="true">

    <!-- PK fields -->

    <column name="guestbookId" type="long" primary="true"></column>

    <!-- Group instance -->

    <column name="groupId" type="long"></column>

    <!-- Audit fields -->

    <column name="companyId" type="long"></column>
    <column name="userId" type="long"></column>
    <column name="userName" type="String"></column>
    <column name="createDate" type="Date"></column>
    <column name="modifiedDate" type="Date"></column>
    <column name="name" type="String"></column>
    <finder name="GroupId" return-type="Collection">
        <finder-column name="groupId"></finder-column>
    </finder>
</entity>
<entity name="Entry" local-service="true" uuid="true">

    <!-- PK fields -->

    <column name="entryId" type="long" primary="true"></column>

    <!-- Group instance -->

    <column name="groupId" type="long"></column>

    <!-- Audit fields -->

    <column name="companyId" type="long"></column>
    <column name="userId" type="long"></column>
    <column name="userName" type="String"></column>
    <column name="createDate" type="Date"></column>
    <column name="modifiedDate" type="Date"></column>
    <column name="name" type="String"></column>
    <column name="email" type="String"></column>
    <column name="message" type="String"></column>
    <column name="guestbookId" type="long"></column>
    <finder name="G_G" return-type="Collection">
        <finder-column name="groupId"></finder-column>
        <finder-column name="guestbookId"></finder-column>
    </finder>
</entity>
<exceptions>
    <exception>GuestbookName</exception>
    <exception>EntryName</exception>
    <exception>EntryMessage</exception>
    <exception>EntryEmail</exception>
</exceptions>
</code>```

Since i have using Liferay 7.0 for this. How to overcome this.

答:
Service Builder

The issue appears to be in your service builder.

1.What stands out the most is your malformed XML.  You need to close the  tag.

 2.Secondly in your Java code you are trying to access a finder that doesn't exist.  The only finder you have defined in your hibernate file is groupId.  It would look something like

```<code>     return guestbookPersistence.findByGroupId(groupId);
</code>```

3.To create a groupid and name find it would look similar to your entry finder.

```<code>    <finder name="G_N" return-type="Collection">
        <finder-column name="groupId"></finder-column>
        <finder-column name="name"></finder-column>
    </finder>
</code>```

and your java code

```<code>return guestbookPersistence.findByG_N(groupId, name);
</code>```

service.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 7.0.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_7_0_0.dtd">
<service-builder package-path="com.latham.data">
    <author>muthuvignesh.k</author>
    <namespace>GB</namespace>
    <entity name="Guestbook" local-service="true" uuid="true">

        <!-- PK fields -->

        <column name="guestbookId" type="long" primary="true"></column>

        <!-- Group instance -->

        <column name="groupId" type="long"></column>

        <!-- Audit fields -->

        <column name="companyId" type="long"></column>
        <column name="userId" type="long"></column>
        <column name="userName" type="String"></column>
        <column name="createDate" type="Date"></column>
        <column name="modifiedDate" type="Date"></column>
        <column name="name" type="String"></column>
        <finder name="GroupId" return-type="Collection">
            <finder-column name="groupId"></finder-column>
        </finder>
        <finder name="G_N" return-type="Collection">
            <finder-column name="groupId"></finder-column>
            <finder-column name="name"></finder-column>
        </finder>
    </entity>

    <entity name="Entry" local-service="true" uuid="true">

        <!-- PK fields -->

        <column name="entryId" type="long" primary="true"></column>

        <!-- Group instance -->

        <column name="groupId" type="long"></column>

        <!-- Audit fields -->

        <column name="companyId" type="long"></column>
        <column name="userId" type="long"></column>
        <column name="userName" type="String"></column>
        <column name="createDate" type="Date"></column>
        <column name="modifiedDate" type="Date"></column>
        <column name="name" type="String"></column>
        <column name="email" type="String"></column>
        <column name="message" type="String"></column>
        <column name="guestbookId" type="long"></column>
        <finder name="G_G" return-type="Collection">
            <finder-column name="groupId"></finder-column>
            <finder-column name="guestbookId"></finder-column>
        </finder>
    </entity>
    <exceptions>
        <exception>GuestbookName</exception>
        <exception>EntryName</exception>
        <exception>EntryMessage</exception>
        <exception>EntryEmail</exception>
    </exceptions>
</service-builder>
</code>```

The tutorial you linked to is for Liferay 6.2 but your document definition is  for Liferay 7.  There were some very big changes between 6.2 and 7.  Your code seems to be compatible with both however you should still keep that in mind.

Body:
Am newbie to Liferay. I have created one JSF portlet and added the service builder to it. Using this link Generate a Persistence Framework. After configure a service builder i have generated the source using service builder. But am getting following exception when build service of project.

 Exception in thread "main" java.lang.IllegalArgumentException: No entity column exist with column database name guestbookId for entity Guestbook
 [echo]     at com.liferay.portal.tools.service.builder.ServiceBuilder._getEntityColumnByColumnDBName(ServiceBuilder.java:4242)
 [echo]     at com.liferay.portal.tools.service.builder.ServiceBuilder._getColumnLengths(ServiceBuilder.java:3857)
 [echo]     at com.liferay.portal.tools.service.builder.ServiceBuilder._createSQLIndexes(ServiceBuilder.java:3355)
 [echo]     at com.liferay.portal.tools.service.builder.ServiceBuilder.<init>(ServiceBuilder.java:796)
 [echo]     at com.liferay.portal.tools.service.builder.ServiceBuilder.main(ServiceBuilder.java:216)
 [echo]     -Dservice.tpl.spring_xml_session=com/liferay/portal/tools/service/builder/dependencies/spring_xml_session.ftl
 [echo] Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0
[mkdir] Created dir: D:\liferay\liferay-plugins-sdk-7.0\portlets\jsfguestbook-portlet\docroot\WEB-INF\service-classes
 [copy] Copied 9 empty directories to 9 empty directories under D:\liferay\liferay-plugins-sdk-7.0\portlets\jsfguestbook-portlet\docroot\WEB-INF\service-classes
[javac] Compiling 38 source files to D:\liferay\liferay-plugins-sdk-7.0\portlets\jsfguestbook-portlet\docroot\WEB-INF\service-classes
[javac] Note: Some input files use or override a deprecated API.
[javac] Note: Recompile with -Xlint:deprecation for details.
[javac] Note: Some input files use unchecked or unsafe operations.
[javac] Note: Recompile with -Xlint:unchecked for details.
  [jar] Building jar: D:\liferay\liferay-plugins-sdk-7.0\portlets\jsfguestbook-portlet\docroot\WEB-INF\lib\jsfguestbook-portlet-service.jar
[delete] Deleting directory D:\liferay\liferay-plugins-sdk-7.0\portlets\jsfguestbook-portlet\docroot\WEB-INF\service-classes
BUILD SUCCESSFUL
Total time: 8 seconds

Also after built the service i have added the code as per article. I got no method is configured for following code.

public Guestbook getFirstGuestbookByName(long groupId, String name) throws SystemException {
    Guestbook guestbook = null;

    List<Guestbook> guestbooks = guestbookPersistence.findByName(groupId, name); // This method is not exist.
    if (guestbooks != null && guestbooks.size() > 0) {
        guestbook = guestbooks.get(0);
    }

    return guestbook;
}

My service.xml configuration is follows

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 7.0.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_7_0_0.dtd">
<service-builder package-path="com.liferay.docs.guestbook">
<author>muthuvignesh.k</author>
<namespace>GB</namespace>
<entity name="Guestbook" local-service="true" uuid="true">

    <column name="guestbookId" type="long" primary="true"></column>

    <column name="groupId" type="long"></column>

    <column name="companyId" type="long"></column>
    <column name="userId" type="long"></column>
    <column name="userName" type="String"></column>
    <column name="createDate" type="Date"></column>
    <column name="modifiedDate" type="Date"></column>
    <column name="name" type="String"></column>
    <finder name="GroupId" return-type="Collection">
        <finder-column name="groupId"></finder-column>
    </finder>
</entity>
<entity name="Entry" local-service="true" uuid="true">

    <column name="entryId" type="long" primary="true"></column>

    <column name="groupId" type="long"></column>

    <column name="companyId" type="long"></column>
    <column name="userId" type="long"></column>
    <column name="userName" type="String"></column>
    <column name="createDate" type="Date"></column>
    <column name="modifiedDate" type="Date"></column>
    <column name="name" type="String"></column>
    <column name="email" type="String"></column>
    <column name="message" type="String"></column>
    <column name="guestbookId" type="long"></column>
    <finder name="G_G" return-type="Collection">
        <finder-column name="groupId"></finder-column>
        <finder-column name="guestbookId"></finder-column>
    </finder>
</entity>
<exceptions>
    <exception>GuestbookName</exception>
    <exception>EntryName</exception>
    <exception>EntryMessage</exception>
    <exception>EntryEmail</exception>
</exceptions>

Since i have using Liferay 7.0 for this. How to overcome this.

Body:
Service Builder

The issue appears to be in your service builder.

1.What stands out the most is your malformed XML.  You need to close the  tag.

 2.Secondly in your Java code you are trying to access a finder that doesn't exist.  The only finder you have defined in your hibernate file is groupId.  It would look something like

     return guestbookPersistence.findByGroupId(groupId);

3.To create a groupid and name find it would look similar to your entry finder.

    <finder name="G_N" return-type="Collection">
        <finder-column name="groupId"></finder-column>
        <finder-column name="name"></finder-column>
    </finder>

and your java code

return guestbookPersistence.findByG_N(groupId, name);

service.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 7.0.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_7_0_0.dtd">
<service-builder package-path="com.latham.data">
    <author>muthuvignesh.k</author>
    <namespace>GB</namespace>
    <entity name="Guestbook" local-service="true" uuid="true">

        <!-- PK fields -->

        <column name="guestbookId" type="long" primary="true"></column>

        <!-- Group instance -->

        <column name="groupId" type="long"></column>

        <!-- Audit fields -->

        <column name="companyId" type="long"></column>
        <column name="userId" type="long"></column>
        <column name="userName" type="String"></column>
        <column name="createDate" type="Date"></column>
        <column name="modifiedDate" type="Date"></column>
        <column name="name" type="String"></column>
        <finder name="GroupId" return-type="Collection">
            <finder-column name="groupId"></finder-column>
        </finder>
        <finder name="G_N" return-type="Collection">
            <finder-column name="groupId"></finder-column>
            <finder-column name="name"></finder-column>
        </finder>
    </entity>

    <entity name="Entry" local-service="true" uuid="true">

        <!-- PK fields -->

        <column name="entryId" type="long" primary="true"></column>

        <!-- Group instance -->

        <column name="groupId" type="long"></column>

        <!-- Audit fields -->

        <column name="companyId" type="long"></column>
        <column name="userId" type="long"></column>
        <column name="userName" type="String"></column>
        <column name="createDate" type="Date"></column>
        <column name="modifiedDate" type="Date"></column>
        <column name="name" type="String"></column>
        <column name="email" type="String"></column>
        <column name="message" type="String"></column>
        <column name="guestbookId" type="long"></column>
        <finder name="G_G" return-type="Collection">
            <finder-column name="groupId"></finder-column>
            <finder-column name="guestbookId"></finder-column>
        </finder>
    </entity>
    <exceptions>
        <exception>GuestbookName</exception>
        <exception>EntryName</exception>
        <exception>EntryMessage</exception>
        <exception>EntryEmail</exception>
    </exceptions>
</service-builder>

The tutorial you linked to is for Liferay 6.2 but your document definition is  for Liferay 7.  There were some very big changes between 6.2 and 7.  Your code seems to be compatible with both however you should still keep that in mind.


问:
Vuejs JSX onTouchStart is not recognized
I'm trying to use JSX with Vuejs and currently I try to do this

```<code>export default {
  methods: {
    handleClick: function (e) {
      console.log('clicking: ', e)
    },
    handleTouchStart: function (e) {
      console.log('touching: ', e)
    }
  },
  render (h) {
    return (
      <div
        className="slider"
        onTouchStart={(e) => this.handleTouchStart(e)}
        onClick={(e) => this.handleClick(e)}>
        <h1> Hey there </h1>
      </div>
    )
  }
}
</code>```

The handleTouchStart function is not called, but we can still see handleClick is called while clicking the element. I'm not sure how many Synthetic events are supported in Vue JSX syntax ?

Do we need any other library to let Vue know about touch events ?

答: Hmm, I found that onTouchStart, onTouchMove, onTouchEnd are mapped like onTouchstart, onTouchmove and onTouchend. Not sure why it's like that only first letter after on is capitalized as JSX should support camel case syntax. Anyway replacing with above events, it correctly detects the event names.

Body:
I'm trying to use JSX with Vuejs and currently I try to do this

export default {
  methods: {
    handleClick: function (e) {
      console.log('clicking: ', e)
    },
    handleTouchStart: function (e) {
      console.log('touching: ', e)
    }
  },
  render (h) {
    return (

 this.handleTouchStart(e)}
        onClick={(e) => this.handleClick(e)}>

 Hey there

    )
  }
}

The handleTouchStart function is not called, but we can still see handleClick is called while clicking the element. I'm not sure how many Synthetic events are supported in Vue JSX syntax ?

Do we need any other library to let Vue know about touch events ?


问:
Two Partial Views in One Page?
I tried to use 2 partial views under 1 view/page - first half page for search filters & 2nd half page for table display. Its working also,but the issue is the white color content panel is in fixed size. i.e., if my table got data it comes out of the white color panel.

```<code><section class="content admin_table">
   @RenderBody()
</section>
</code>```

I use above class in Layout. In Index View, I render both Partial views. My code part is below

```<code> @Html.Partial("_view1", Model.Filter)
 @Html.Partial("_view2", Model.Result)
</code>```

My IndexPage

```<code>@model SW.Web.ViewModels.CommonVM
@{
    Layout = "~/Views/Shared/_Layout1.cshtml";
    ViewBag.Title = "Title";
    ViewBag.Header = "Details";
       }
<link href="~/Content2/plugins/datatables/dataTables.bootstrap.css" rel="stylesheet" />

  <!DOCTYPE html>

@section JavaScript{

<Script> .....</script>
<Script> .....</script>
}
@Html.Partial("_view1", Model.Filter)
 @Html.Partial("_view2", Model.Result)
</code>```

and My Partial view 1

```<code> @model SW.Web.ViewModels.viewmodel1
     @{
    using (Html.BeginForm("Index", "Details", FormMethod.Post, new { d= Model }))
    {
        @Html.ValidationSummary(true)
  <div>.....Design</div>
}
</code>```

and my partial view 2

```<code> @model IEnumerable<SW.Web.ViewModels.Viewmodel2>
    @{
     <div> Designs for partial view 2</div>

}
</code>```

答:
by controller action

@Html.Action("action1", "Controller", new { id = Model.idOfPart1 })

@Html.Action("action2", "Controller", new { id = Model.idOfPart2 })

by rendering view

@ Html.Render ("ParialView1", Model.model1)

@ Html.Render ("PartialView2", Model.model2)

Title: Two Partial Views in One Page?

Body:
I tried to use 2 partial views under 1 view/page - first half page for search filters & 2nd half page for table display. Its working also,but the issue is the white color content panel is in fixed size. i.e., if my table got data it comes out of the white color panel.

   @RenderBody()

I use above class in Layout. In Index View, I render both Partial views. My code part is below

 @Html.Partial("_view1", Model.Filter)
 @Html.Partial("_view2", Model.Result)

My IndexPage

@model SW.Web.ViewModels.CommonVM
@{
    Layout = "~/Views/Shared/_Layout1.cshtml";
    ViewBag.Title = "Title";
    ViewBag.Header = "Details";
       }
<link href="~/Content2/plugins/datatables/dataTables.bootstrap.css" rel="stylesheet" />

  <!DOCTYPE html>

@section JavaScript{

}
@Html.Partial("_view1", Model.Filter)
 @Html.Partial("_view2", Model.Result)

and My Partial view 1

 @model SW.Web.ViewModels.viewmodel1
     @{
    using (Html.BeginForm("Index", "Details", FormMethod.Post, new { d= Model }))
    {
        @Html.ValidationSummary(true)

.....Design

}

and my partial view 2

 @model IEnumerable<SW.Web.ViewModels.Viewmodel2>
    @{

 Designs for partial view 2

}


问:
How do I manage session and role together in nodejs?
I have session management in my mean stack application, how can I implement role in that session? Any help is appreciated. </p>

答:
Role management can be done multiple ways. Each user is associated with one or more than one role and each role has different permissions.

You need to check those permissions at client side as well as server side while performing any action.

Once user is logged in, you can store roles/permissions in session object for later use at server side. Same way you can pass role/permission to the client immediately after user login. You can store those role/permissions in browser so that you can disable/enable some of the functionalities based on role/permission and keep it in browser till user is logged in.

Suppose admin is changing some role/permission for that user from different session. Then you can use socket on/emit feature to update role/permission in browser and server.


问:
Improving this Scrapy crawler
I've written a web crawler which extracts absolute links from the starting URL, and keeps visiting absolute links within the domain until it stops. Scrapy automatically doesn't follow duplicate links. The crawler works.

```<code>import scrapy

class TestSpider(scrapy.Spider):
    name = 'test_spider'
    start_urls = ['http://homeguide.ph/']
    allowed_domains = ['homeguide.ph']

    # for the initial visit
    def parse(self, response):
        links = response.xpath('//a/@href').extract()
        for link in links:
            if link.find("#") == -1:
                yield scrapy.Request(link, callback=self.parse_link)

    # for subsequent visits
    def parse_link(self, response):
        self.logger.info("Visited %s", response.url)
        links = response.xpath('//a/@href').extract()
        for link in links:
            if link.find("#") == -1: # visit only absolute links
                yield scrapy.Request(link, callback=self.parse_link)
</code>```

I feel like it can be improved, though. I'm not sure how. Is there a way to improve this crawler?

答: 1) You can use CrawlSpider object. It extract all links and follow it automatically. You can check it here</p>

Title: Improving this Scrapy crawler

Body:
I've written a web crawler which extracts absolute links from the starting URL, and keeps visiting absolute links within the domain until it stops. Scrapy automatically doesn't follow duplicate links. The crawler works.

import scrapy

class TestSpider(scrapy.Spider):
    name = 'test_spider'
    start_urls = ['http://homeguide.ph/']
    allowed_domains = ['homeguide.ph']

    # for the initial visit
    def parse(self, response):
        links = response.xpath('//a/@href').extract()
        for link in links:
            if link.find("#") == -1:
                yield scrapy.Request(link, callback=self.parse_link)

    # for subsequent visits
    def parse_link(self, response):
        self.logger.info("Visited %s", response.url)
        links = response.xpath('//a/@href').extract()
        for link in links:
            if link.find("#") == -1: # visit only absolute links
                yield scrapy.Request(link, callback=self.parse_link)

I feel like it can be improved, though. I'm not sure how. Is there a way to improve this crawler?


问:
PHP - get object parent
I have a function that is called like this:

```<code>foo($object->ID);
</code>```

and in the function I need to somehow select $object if $object->ID is passed as a variable.

```<code>function foo($id = NULL){
  if($id != NULL) ... // here I want to get $object
  else ...
}
</code>```

How can I do this?

答:
That is not possible. You are passing a number without any information about its origin. Do this</p>

```<code>foo($object)

function foo($object){
   if($object->ID !== null) ... // work with $object
   else ... // work with ID

}
</code>```

Title: PHP - get object parent

Body:
I have a function that is called like this:

foo($object->ID);

and in the function I need to somehow select $object if $object->ID is passed as a variable.

function foo($id = NULL){
  if($id != NULL) ... // here I want to get $object
  else ...
}

How can I do this?

Body:
That is not possible. You are passing a number without any information about its origin. Do this

foo($object)

function foo($object){
   if($object->ID !== null) ... // work with $object
   else ... // work with ID

}


问:
Why does the movement of my canvas box increase on click?

The Js Fiddle attached draw a box where ever the mouse is clicked. It works as expected for the most part. Except every time a new box is drawn on the canvas it speeds up more and more every time to the point where it's way too fast.

I've console.loged the dx/dy values and they are not increasing in value so it's not that, I don't think.

The dx value is what the position of the box is moving by.

Can any one shed some light?

var canvas = document.getElementById('myCanvas');
    var logger = document.getElementById('logger');
    var ctx = canvas.getContext('2d');
    var x = 0;
    var y = 0;
    var dx = -2;
    var dy = -2;
    var boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
    var boxSize = 20;
    var mousex,
        mousey;

    canvas.addEventListener('click',function(e){
      mousex = e.clientX;
      mousey = e.clientY;
      x = mousex - canvas.offsetLeft-(boxSize/2);
      y = mousey - canvas.offsetTop-(boxSize/2);
      draw();
    });

    function draw(){
      logger.innerHTML = "x: " + x + "y: " + y;
      ctx.clearRect(0,0,canvas.width,canvas.height);
      collistionDetection();
      ctx.beginPath();
      ctx.rect(x,y,boxSize,boxSize);
      ctx.fillStyle=boxColour;
      ctx.fill();
      ctx.closePath();
      x+=dx;
      y+=dy;
      requestAnimationFrame(draw);
    };

    function collistionDetection(){
      if(x<0 || x>canvas.width-boxSize){
        dx = -dx;
        boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
      };
      if(y<canvas.offsetTop-(boxSize/2) || y>canvas.height-boxSize){
        boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
        dy = -dy;
      };
    };```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* { padding: 0; margin: 0; }
    canvas { background: #eee; display: block;
      margin: 0 auto; margin-top:10px;
      }</code>```

<canvas id="myCanvas" width='480' height='320'></canvas>

```

Your help is always much appreciated.

Thanks

moe

答:
Because by each mouse click, you are calling draw once again, and this call, as apparent in your code, is recursive and keeps calling itself. So, by each click, you have a chain of calls to draw.

You can add a boolean to check whether draw has initially been called, and if so, prevent subsequent calls inside your draw function:

```<code>if(!initialized)
{
    requestAnimationFrame(draw);
    initialized = true;
}
</code>```

Body:
The Js Fiddle attached draw a box where ever the mouse is clicked. It works as expected for the most part. Except every time a new box is drawn on the canvas it speeds up more and more every time to the point where it's way too fast.

I've console.loged the dx/dy values and they are not increasing in value so it's not that, I don't think.

The dx value is what the position of the box is moving by.

Can any one shed some light?

var canvas = document.getElementById('myCanvas');
    var logger = document.getElementById('logger');
    var ctx = canvas.getContext('2d');
    var x = 0;
    var y = 0;
    var dx = -2;
    var dy = -2;
    var boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
    var boxSize = 20;
    var mousex,
        mousey;

    canvas.addEventListener('click',function(e){
      mousex = e.clientX;
      mousey = e.clientY;
      x = mousex - canvas.offsetLeft-(boxSize/2);
      y = mousey - canvas.offsetTop-(boxSize/2);
      draw();
    });

    function draw(){
      logger.innerHTML = "x: " + x + "y: " + y;
      ctx.clearRect(0,0,canvas.width,canvas.height);
      collistionDetection();
      ctx.beginPath();
      ctx.rect(x,y,boxSize,boxSize);
      ctx.fillStyle=boxColour;
      ctx.fill();
      ctx.closePath();
      x+=dx;
      y+=dy;
      requestAnimationFrame(draw);
    };

    function collistionDetection(){
      if(x<0 || x>canvas.width-boxSize){
        dx = -dx;
        boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
      };
      if(y<canvas.offsetTop-(boxSize/2) || y>canvas.height-boxSize){
        boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
        dy = -dy;
      };
    };

* { padding: 0; margin: 0; }
    canvas { background: #eee; display: block;
      margin: 0 auto; margin-top:10px;
      }

<canvas id="myCanvas" width='480' height='320'></canvas>

Your help is always much appreciated.

Thanks

moe

Body:
Because by each mouse click, you are calling draw once again, and this call, as apparent in your code, is recursive and keeps calling itself. So, by each click, you have a chain of calls to draw.

You can add a boolean to check whether draw has initially been called, and if so, prevent subsequent calls inside your draw function:

if(!initialized)
{
    requestAnimationFrame(draw);
    initialized = true;
}


问:
ggplot2 with factor variable y axis and removed whitespace
I have a plot like the one below, with a factor variable on the y-axis.

```<code>library(reshape2)
library(ggplot2)

MA <- c("A", "B", "C")

dfr <- data.frame(
  name        = factor(MA, levels = MA),
  start       = 1:3,
  end         = 3:5,
  prozent     = c(1,0.5,0.75)
)
mdfr <- melt(dfr, measure.vars = c("start", "end"))

ggplot(mdfr, aes(value, name)) + geom_line(aes(size = prozent)) + scale_size_area()
</code>```

I want to remove the whitespace (or, in default ggplot2, "greyspace") between the horizontal lines so that they touch each other.

答:
You could do as follows:</p>

```<code>ggplot(mdfr, aes(value, name)) +
  geom_line(aes(size = prozent)) +
  scale_size_area() +
  scale_y_discrete(expand = c(7, 0))
</code>```

Body:
I have a plot like the one below, with a factor variable on the y-axis.

library(reshape2)
library(ggplot2)

MA <- c("A", "B", "C")

dfr <- data.frame(
  name        = factor(MA, levels = MA),
  start       = 1:3,
  end         = 3:5,
  prozent     = c(1,0.5,0.75)
)
mdfr <- melt(dfr, measure.vars = c("start", "end"))

ggplot(mdfr, aes(value, name)) + geom_line(aes(size = prozent)) + scale_size_area()

I want to remove the whitespace (or, in default ggplot2, "greyspace") between the horizontal lines so that they touch each other.

Body:
You could do as follows:

ggplot(mdfr, aes(value, name)) +
  geom_line(aes(size = prozent)) +
  scale_size_area() +
  scale_y_discrete(expand = c(7, 0))


问:
How do you disable viewport zooming on Mobile Safari?
I've tried all three of these to no avail:

```<code><meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;” />

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=false;” />

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;” />
</code>```

each are different values I found recommended by google searching or SO searching, but none of the 'user-scalable=X' values seem to be working

I also tried comma delimiting the values instead of semicolon, no luck. Then I tried ONLY having the user-scalable value present, still no luck.

UPDATE

Got this from Apple's site and it works:

```<code><meta name="viewport" content="width=device-width, user-scalable=no" />
</code>```

it turns out that the problem was the non-standard quotes because I had copied the meta tag from a website that was using them, whoops

答:
This works fine in IOS 10.3.2

```<code>    document.addEventListener('touchmove', function(event) {
        event = event.originalEvent || event;
        if (event.scale !== 1) {
           event.preventDefault();
        }
    }, false);
</code>```

thank you @arthur and @aleclarson

ContentLicense: CC BY-SA 4.0

Body:
I've tried all three of these to no avail:

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;” />

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=false;” />

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;” />

each are different values I found recommended by google searching or SO searching, but none of the 'user-scalable=X' values seem to be working

I also tried comma delimiting the values instead of semicolon, no luck. Then I tried ONLY having the user-scalable value present, still no luck.

UPDATE

Got this from Apple's site and it works:

<meta name="viewport" content="width=device-width, user-scalable=no" />

it turns out that the problem was the non-standard quotes because I had copied the meta tag from a website that was using them, whoops

Body:
This works fine in IOS 10.3.2

    document.addEventListener('touchmove', function(event) {
        event = event.originalEvent || event;
        if (event.scale !== 1) {
           event.preventDefault();
        }
    }, false);

thank you @arthur and @aleclarson


问:
Prevent screen reader from reading aria-label
I have an element with a landmark role (complementary) which requires an aria-label/aria-labelledBy.
This element has several focusable child elements with text in them that needs to be read by a screen reader.

Is there a way to prevent screen readers from reading the aria-label of the parent element, while not preventing the children from being read?

EDIT

for this code:

```<code><div id="parent-element" role="complementary" aria-label="some text" tabindex="0">
    <div id="child-element1" tabindex="0">I'm the first child</div>
    <div id="child-element2" tabindex="0">I'm the second child</div>
</div>
</code>```

Screen readers will read "some text I'm the first child I'm the second child" when focused to the parent-element.

I'm using IBM's "Dynamic Assessment Plugin" for chrome to evaluate my site.

This is the violation that I'm getting: comlementary role must have aria label

More explanation about the violation - https://aat.mybluemix.net/token/ace67f8e-8cad-40b4-be4b-eb02197944bc/6c6a166a-542d-4e1a-8a10-40a4c69e1d1d/doc/w3/help/en-US/idhi_accessibility_check_g1174.html

I don't want it to read the "some text", but I have to use aria-label if I want the site to pass the accessibility evaluation tool.

答:
An element with the complementary role does not require an aria-label/aria-labelledby.

As long as you keep this attribute, it's quite expected that your screenreader would ignore the content and read that attribute.

EDIT: No official specs indicates the obligation of having an aria-label, but when you have multiple complementary landmarks you should have a unique label according to the W3C. Note that the "should" is very important, as this is not a "must" (and quite useless in practice imho)

ARIA Example: Multiple Complementary Landmarks
  When there is more than one complementary landmark on a page, each should have a unique label.

A tool is just a tool and that assessment tools are very imperfect.

Body:
I have an element with a landmark role (complementary) which requires an aria-label/aria-labelledBy.
This element has several focusable child elements with text in them that needs to be read by a screen reader.

Is there a way to prevent screen readers from reading the aria-label of the parent element, while not preventing the children from being read?

EDIT

for this code:

I'm the first child

I'm the second child

Screen readers will read "some text I'm the first child I'm the second child" when focused to the parent-element.

I'm using IBM's "Dynamic Assessment Plugin" for chrome to evaluate my site.

This is the violation that I'm getting: comlementary role must have aria label

More explanation about the violation - https://aat.mybluemix.net/token/ace67f8e-8cad-40b4-be4b-eb02197944bc/6c6a166a-542d-4e1a-8a10-40a4c69e1d1d/doc/w3/help/en-US/idhi_accessibility_check_g1174.html

I don't want it to read the "some text", but I have to use aria-label if I want the site to pass the accessibility evaluation tool.


问:
Setting the application focus to a java-program in Ubuntu/LTSP
We are using LTSP with Thin-Clients. We are using it, to run a Java-Swing-Application. The users should not be able to do anything else, so instead of a Gnome-Session we use a shell-script to start our application.

Nearly everything works perfect but one thing: When the Thin-Client starts, the application starts too but doesn't receive the focus. We have to click once with the mouse inside the application, which is not that good, because the application is designed to be used without a mouse.

I didn't found anything useful, a toFront() on my Main Frame wasn't successful.

Has anyone any better suggestions??

答:
You could try to call requestFocus on your JFrame as soon as it becomes visible:

```<code>JFrame frame = new JFrame();

frame.addComponentListener(new ComponentAdapter() {
        public void componentShown(ComponentEvent e) {
            ((JFrame) e.getSource()).requestFocus();
        }
    });

frame.setVisible(true);
</code>```

Body:
You could try to call requestFocus on your JFrame as soon as it becomes visible:

JFrame frame = new JFrame();

frame.addComponentListener(new ComponentAdapter() {
        public void componentShown(ComponentEvent e) {
            ((JFrame) e.getSource()).requestFocus();
        }
    });

frame.setVisible(true);


问:
AWS ElasticBeanstalk Node Version Conflict
I'll keep it short and simple. We're currently running an ElasticBeanstalk setup with Amazon Linux v2.0.6. This version supports 4.x NodeJS, and 0.12.9 NodeJS. Unfortunately, due to a critical fix that was introduced after 0.12.9, I need to upgrade my node version, but stay on 0.12.x. For those of you who know ELB, it version locks Node to a few specific versions... and it seems that I'm stuck with either my current version of Node, which is unacceptable, or upgrading to the latest Amazon Linux (v4.1.0) which drops support for 0.12.x.

We're going to move past 0.12.x soon, but it's not an option yet. So what are my current choices? Is there a way I'm not seeing to manually select an old Amazon Linux version? If not, is there a way to manually build Node v0.12.18 on my instances and have them default to using that? Or, is there a way to introduce the patch to the current binaries, which would appear to ELB as the same Node version? The change is literally 2 lines of code, but it's absolutely crucial.

Cheers for your help - let me know if you have any questions.

答:
0.12 is EOL. 4.x will be EOL in less than a year. Are you 100% certain you can't move to 4, or even better, 8?

End mandatory version-shaming.

You probably need to use a custom Beanstalk template, that uses an AMI with the Linux and Node versions you need.

Seriously, 8.x is like a new language. It's so nice.


问:
Static final field in a class vs Interface field in java
I need to create a 100 or more static final constants in my application and I can achieve this is following two ways as per my understanding:

Creating a simple java class and create static final field in that

Creating an interface an put all variable in that because all field in an interface is implicitly static final

I have these question in above approach:

Which one is right approach to achieve this?

Which one is memory efficient approach?

Is there any design pattern to achieve this?

答:
You can refer to many books about the topic.

I will quote a good one: "Effective Java"

Item 19: Use interfaces only to define types

The constant interface pattern is a poor use of interfaces. That a
  class uses some constants internally is an implementation detail.
  Implementing a constant interface causes this implementation detail to
  leak into the class’s exported API. It is of no consequence to the
  users of a class that the class implements a constant interface

you can even check where JDK mostly constants are declared..

Math.PI for example is declared in the class Math and not in an interface

and as an exception you can see constants like in the java.io.ObjectStreamConstants but again the Books are there to help:

From effective java again:

There are several constant interfaces in the Java platform libraries...

These interfaces should be
  regarded as anomalies and should not be emulated.


问:
JavaScript keycodes are not working in Firefox
I am using JavaScript keycodes, they are not working in Firefox but working in Chrome and IE. I have debugged the code in front end for Firefox I am getting keycode as 0.

This is my code:

```<code>$scope.Validate = function(event,indexVal){
    if ((event.keyCode > 64 && event.keyCode < 91)|| (event.keyCode > 159 && event.keyCode < 166) || (event.keyCode > 96 && event.keyCode < 123) || (event.keyCode == 165) ||(event.keyCode == 32)
                        || (event.keyCode == 164) || (event.keyCode == 130) || (event.keyCode == 181) || (event.keyCode == 144) || (event.keyCode == 214) ||
                        (event.keyCode == 224) ||(event.keyCode == 233)) {
                }else{
                    event.preventDefault();
                }
}
</code>```

Can you please suggest a way to achieve this functionality in Firefox too.

答:
In Firefox, event.keyCode does not always work, depending on the binding event. You'll have to use event.which. Refer to this post for more info.

```<code>$scope.Validate = function(event,indexVal) {
  var key = event.keyCode || event.which;
  if ((key > 64 && key < 91) ||
    (key > 159 && key < 166) ||
    (key > 96 && key < 123) ||
    (key == 165) ||
    (key == 32) ||
    (key == 37) ||
    (key == 39) ||
    (key == 164) ||
    (key == 130) ||
    (key == 181) ||
    (key == 144) ||
    (key == 214) ||
    (key == 224) ||
    (key == 233)
  ) {
    // Do something.
  } else {
    event.preventDefault();
  }
}
</code>```

Body:
I am using JavaScript keycodes, they are not working in Firefox but working in Chrome and IE. I have debugged the code in front end for Firefox I am getting keycode as 0.

This is my code:

$scope.Validate = function(event,indexVal){
    if ((event.keyCode > 64 && event.keyCode < 91)|| (event.keyCode > 159 && event.keyCode < 166) || (event.keyCode > 96 && event.keyCode < 123) || (event.keyCode == 165) ||(event.keyCode == 32)
                        || (event.keyCode == 164) || (event.keyCode == 130) || (event.keyCode == 181) || (event.keyCode == 144) || (event.keyCode == 214) ||
                        (event.keyCode == 224) ||(event.keyCode == 233)) {
                }else{
                    event.preventDefault();
                }
}

Can you please suggest a way to achieve this functionality in Firefox too.

Body:
In Firefox, event.keyCode does not always work, depending on the binding event. You'll have to use event.which. Refer to this post for more info.

$scope.Validate = function(event,indexVal) {
  var key = event.keyCode || event.which;
  if ((key > 64 && key < 91) ||
    (key > 159 && key < 166) ||
    (key > 96 && key < 123) ||
    (key == 165) ||
    (key == 32) ||
    (key == 37) ||
    (key == 39) ||
    (key == 164) ||
    (key == 130) ||
    (key == 181) ||
    (key == 144) ||
    (key == 214) ||
    (key == 224) ||
    (key == 233)
  ) {
    // Do something.
  } else {
    event.preventDefault();
  }
}


问:
How do I create a stable download link for electron-builder releases?
I'm using electron-builder to package an app for Windows/MacOS & trying to configure auto-update with the electron-publisher-s3 package.

The default naming for the published Windows artifact is ${productName}_Setup_${version}.${ext}, or foo_Setup_1.0.0.exe

This means that the download link, dl.example.com/win/foo_Setup_1.0.0.exe will change each update.

My first guess is to just remove dynamic variables from the artifact naming pattern, but I'm assuming the version # is there for a reason & don't want to break anything.

Is there a way to manage a stable download link, like dl.example.com/win/latest, dl.example.com/win/beta, etc. ?

答:
Currently, there are no ready solutions. You can use Amazon S3 Routing Rules to redirect win/latest to win/foo_Setup_1.0.0.exe (and you need to change this rule after each release).

I suggest you to file issue to electron-builder and someday it will be implemented for you. i.e. electron-builder will automatically create and maintain such rules for you.


问:
Why am I not able to add click event to dynamically inserted element of a list?
I have code shown below for a project where I insert list elements using javascript and for click on each element I have to call a function. However, it does not seem to work.

var c = document.getElementById("content");

c.innerHTML += "
";

for(var j = 0; j<5; j++){

    c.innerHTML += "
some stuff"+j+"
";

    document.getElementById(j).addEventListener("click", function(){ alert('this is test'); }, false);

}
c.innerHTML += "
";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id = "content"> </div></code>```

Why is the click event not being triggered? How can I make this work?

答:
Try understand following magic

var c = document.getElementById("content");

c.innerHTML += "
";

for(var j = 0; j<5; j++){
    c.innerHTML += "
some stuff"+j+"
";
}
c.innerHTML += "
";

setTimeout(function () {
 for(var j = 0; j<5; j++){
    document.getElementById(j).addEventListener("click", function(){ alert('this is test'); }, false);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id = "content"> </div></code>```

Body:
I have code shown below for a project where I insert list elements using javascript and for click on each element I have to call a function. However, it does not seem to work.

var c = document.getElementById("content");

c.innerHTML += "
";

for(var j = 0; j<5; j++){

    c.innerHTML += "
some stuff"+j+"
";

    document.getElementById(j).addEventListener("click", function(){ alert('this is test'); }, false);

}
c.innerHTML += "
";

Why is the click event not being triggered? How can I make this work?

Body:
Try understand following magic

var c = document.getElementById("content");

c.innerHTML += "<ul>";

for(var j = 0; j<5; j++){
    c.innerHTML += "<li id = '" + j +  "'>some stuff"+j+"</li>";
}
c.innerHTML += "</ul>";

setTimeout(function () {
 for(var j = 0; j<5; j++){
    document.getElementById(j).addEventListener("click", function(){ alert('this is test'); }, false);
  }
});

<div id = "content"> </div>


问:
Removing the show method and all of its dependencies
I have an existing entity that has been created by scaffolding. Now I'm realizing that I don't really need to present the show view and thus I'd like to eliminate any methods and pieces that are now unnecessary. Besides the show method created at the object controller for me, which other pieces should I remove? These are the ones I can think of:

The show.html.erb file for the entity

The link_to reference to the object instances at the index.html.erb and edit.html.erb files

The redirect_to calls on the update and create methods at the controller

Is there anything else that I should remove?

答:
You can/should remove:

the show action in the controller

the show.html.erb file

the route to the show action (in routes.rb)

any links or redirects to the show action


问:
Postgresql query problems for nodejs
I am making an app with node.js, using the express framwork, woth postgresql as my database.

I have to insert some values into my database, and some of them have quotes. e.g. Tony's Seafood Restaurant. I cannot insert values like this.

I tried

```<code>name.replace('\'', '\\\'');
</code>```

and also

```<code>name.replace("'", "\'");
</code>```

but no success.

Problem is the postgresql server formats queries before running them. If the query look like this in my code,

```<code>insert into venues values (nextval('venue_venueid_seq'),'"+name+"','"+api+"','"+location+"','"+latitude+"','"+longitude+"','"+category+"','"+category_generalized+"')
</code>```

then postgresql formats it like this (i found it by printing the client.query object)

```<code>insert into venues values (nextval(\'venue_venueid_seq\'),\'Tony\'s Seafood Restaurant\',\'Google Places\',\'18863 California 1, Marshall\',\'38.146777\',\'-122.882987\',\'restaurant,food,establishment\',\'Eatery,Eatery,establishment\')
</code>```

You see postgresql already places slashes before the starting and the ending quotes of my string, so the escape slashes I programatically inserted in the middle of the string are not working.

How can I insert values like this? Please help.

答:
You can also use pg-escape module to handle this case. This module also have some other escaping methods those can be usefull.

Installation

npm install pg-escape

Example

var sql = escape('INSERT INTO %I VALUES(%L)', 'books', "O'Reilly");

console.log(sql);

Title: Postgresql query problems for nodejs

Body:
I am making an app with node.js, using the express framwork, woth postgresql as my database.

I have to insert some values into my database, and some of them have quotes. e.g. Tony's Seafood Restaurant. I cannot insert values like this.

I tried

name.replace('\'', '\\\'');

and also

name.replace("'", "\'");

but no success.

Problem is the postgresql server formats queries before running them. If the query look like this in my code,

insert into venues values (nextval('venue_venueid_seq'),'"+name+"','"+api+"','"+location+"','"+latitude+"','"+longitude+"','"+category+"','"+category_generalized+"')

then postgresql formats it like this (i found it by printing the client.query object)

insert into venues values (nextval(\'venue_venueid_seq\'),\'Tony\'s Seafood Restaurant\',\'Google Places\',\'18863 California 1, Marshall\',\'38.146777\',\'-122.882987\',\'restaurant,food,establishment\',\'Eatery,Eatery,establishment\')

You see postgresql already places slashes before the starting and the ending quotes of my string, so the escape slashes I programatically inserted in the middle of the string are not working.

How can I insert values like this? Please help.


问:
How to set a javascript file in chrome,when ever I open a new window it will automatically get execute?
My js file contains some userid and password.I want to set as a prompt for new tab.</p>

答: You need something like tampermonkey </p>

Body: You need something like tampermonkey


答:
You should:

Remove the show action from the controller

Switch the redirect_tos in create and update to go to the new action

Remove the link_tos from index.html.erb and edit.html.erb

Remove the app/views/entities/show.html.erb

Stop the routes from being generated by changing the resources :entities line in your config/routes.rb file to resources :entities, :except => :show

Title: Removing the show method and all of its dependencies

Body:
I have an existing entity that has been created by scaffolding. Now I'm realizing that I don't really need to present the show view and thus I'd like to eliminate any methods and pieces that are now unnecessary. Besides the show method created at the object controller for me, which other pieces should I remove? These are the ones I can think of:

The show.html.erb file for the entity

The link_to reference to the object instances at the index.html.erb and edit.html.erb files

The redirect_to calls on the update and create methods at the controller

Is there anything else that I should remove?


问:
Is this implementation of an in-place shuffle "uniform?"
Sorry if this question is oddly specific; I wasn't sure where else to ask it, though!

I'm working through some problems, and I've found the Fisher-Yates Shuffle, but I want to know if this first shuffle I thought of is uniform or not? I'm not the greatest with probability.. or math... Ha.

The idea is pretty simple; for as many elements as there are in the array, pick two at random and swap them with each other.

```<code>function inPlaceShuffle(arr) {
    const floor = 0,
          ceil = arr.length - 1;

    let i = arr.length;

    while (i > 0) {
        swap(arr, getRandom(floor, ceil), getRandom(floor, ceil));

        i--;
    }

    return arr;
}

function swap(arr, firstIndex, secondIndex) {
    const temp = arr[firstIndex];
    arr[firstIndex] = arr[secondIndex];
    arr[secondIndex] = temp;
}

function getRandom(floor, ceil) {
    floor = Math.ceil(floor);
    ceil = Math.floor(ceil);
    return Math.floor(Math.random() * (ceil - floor + 1)) + floor;
}
</code>```

答:
Note that every iteration of loop gives n^2 combinations of indexes for change, and n iterations give n^(2n) variants, but this value does not divide n! permutations evenly for n>2, so some permutations will have higher probability than others.

Clear example:

There are 729 results for 6 permutations of  {1,2,3}, 729 / 6 = 121. 5, so probability of permutations varies.

Body:
Sorry if this question is oddly specific; I wasn't sure where else to ask it, though!

I'm working through some problems, and I've found the Fisher-Yates Shuffle, but I want to know if this first shuffle I thought of is uniform or not? I'm not the greatest with probability.. or math... Ha.

The idea is pretty simple; for as many elements as there are in the array, pick two at random and swap them with each other.

function inPlaceShuffle(arr) {
    const floor = 0,
          ceil = arr.length - 1;

    let i = arr.length;

    while (i > 0) {
        swap(arr, getRandom(floor, ceil), getRandom(floor, ceil));

        i--;
    }

    return arr;
}

function swap(arr, firstIndex, secondIndex) {
    const temp = arr[firstIndex];
    arr[firstIndex] = arr[secondIndex];
    arr[secondIndex] = temp;
}

function getRandom(floor, ceil) {
    floor = Math.ceil(floor);
    ceil = Math.floor(ceil);
    return Math.floor(Math.random() * (ceil - floor + 1)) + floor;
}


问:
Unable to center content using margin auto
When the screen size is less than 768px, the 3 boxes are aligned to the left. I'm having a hard time trying to make them appear center.

I managed to center it by setting margin-left to some value however, it isn't responsive afterwards.

Here's the code:

HTML

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<body>
      <div class="row bg_color">
            <div class="col-xs-12 col-sm-4 col-md-4 stats_box">
               <h3>2015/16</h3>
               <hr>
               <ul>
                  <li>The Best FIFA Men's Player 2016</li>
                  <li>FIFA Club World Cup</li>
                  <li>France Football Ballon D'Or 2016</li>
                  <li>UEFA Best Player in Europe</li>
                  <li>UEFA Euro 2016 (Portugal)</li>
                  <li>UEFA Champions League (Real Madrid)</li>
               </ul>
            </div>
            <div class="col-xs-12 col-sm-4 col-md-4 stats_box">
               <h3>2014/15</h3>
               <hr>
               <ul>
                  <li>Pichichi Award</li>
                  <li>European Golden Boot 2015</li>
                  <li>FIFA Ballon D'Or 2014</li>
                  <li>Globe Soccer Best Player of the Year</li>
                  <li>Globe Soccer Fan's Favourite Player Award</li>
                  <li>IFFHS Trophy for Best Striker  on the planet</li>
               </ul>
            </div>
            <div class="col-xs-12 col-sm-4 col-md-4 stats_box">
               <h3>2013/14</h3>
               <hr>
               <ul>
                  <li>Club World Cup</li>
                  <li>BBC Overseas Sports  Personality Award</li>
                  <li>World's Top  Goalscorer 2013</li>
                  <li>Pichichi Award</li>
                  <li>Best Player, Best Forward in La Liga</li>
                  <li>UEFA Best Player in Europe</li>
               </ul>
            </div>
         </div>

</body>
</code>```

CSS:

```<code> .bg_color {
    background: #ECFEAA;
}

.stats_box {
    margin: 20px;
    padding: 20px 40px 40px;
    max-width: 400px;
    text-align: left;
    background: #fff;
    border-bottom: 4px solid #ccc;
    border-radius: 6px;

}

@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin-left: 200px;
  }
}
</code>```

Any possible solution for this? And why isn't margin:0 auto not working here?

Link to the code: CodePen

答:
try this for 768px, it works

```<code>@media only screen and (max-width: 768px) {
 .stats_box {
   width: 100%;
   left:50%;
   transform:translateX(-50%);
 }
}
</code>```

Hope this will help!!

Body:
When the screen size is less than 768px, the 3 boxes are aligned to the left. I'm having a hard time trying to make them appear center.

I managed to center it by setting margin-left to some value however, it isn't responsive afterwards.

Here's the code:

HTML

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

2015/16

The Best FIFA Men's Player 2016

FIFA Club World Cup

France Football Ballon D'Or 2016

UEFA Best Player in Europe

UEFA Euro 2016 (Portugal)

UEFA Champions League (Real Madrid)

2014/15

Pichichi Award

European Golden Boot 2015

FIFA Ballon D'Or 2014

Globe Soccer Best Player of the Year

Globe Soccer Fan's Favourite Player Award

IFFHS Trophy for Best Striker  on the planet

2013/14

Club World Cup

BBC Overseas Sports  Personality Award

World's Top  Goalscorer 2013

Pichichi Award

Best Player, Best Forward in La Liga

UEFA Best Player in Europe

CSS:

 .bg_color {
    background: #ECFEAA;
}

.stats_box {
    margin: 20px;
    padding: 20px 40px 40px;
    max-width: 400px;
    text-align: left;
    background: #fff;
    border-bottom: 4px solid #ccc;
    border-radius: 6px;

}

@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin-left: 200px;
  }
}

Any possible solution for this? And why isn't margin:0 auto not working here?

Link to the code: CodePen

Body:
try this for 768px, it works

@media only screen and (max-width: 768px) {
 .stats_box {
   width: 100%;
   left:50%;
   transform:translateX(-50%);
 }
}

Hope this will help!!


问:
Which attribute replace for “layout_constraintGuide_Percent” at Android-Studio
I used constraint layout Android Studio 2.3.1 with constraint-layout:1.0.0-alpha4 dependency before, but now I am using 'com.android.support.constraint:constraint-layout:1.0.2', layout_constraintGuide_Percent attribute is not exists.

Which attribute replace for layout_constraintGuide_Percent?

my code:

```<code><android.support.constraint.Guideline
    android:id="@+id/guideline_vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_Percent="0.8"
    tools:layout_editor_absoluteX="50dp"
    tools:layout_editor_absoluteY="0dp" />
</code>```

答:
Replace the attribute with this</p>

```<code>app:layout_constraintGuide_percent
</code>```

Body:
I used constraint layout Android Studio 2.3.1 with constraint-layout:1.0.0-alpha4 dependency before, but now I am using 'com.android.support.constraint:constraint-layout:1.0.2', layout_constraintGuide_Percent attribute is not exists.

Which attribute replace for layout_constraintGuide_Percent?

my code:

<android.support.constraint.Guideline
    android:id="@+id/guideline_vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_Percent="0.8"
    tools:layout_editor_absoluteX="50dp"
    tools:layout_editor_absoluteY="0dp" />

Body:
Replace the attribute with this

app:layout_constraintGuide_percent


问:
Streaming input to System.Speech.Recognition.SpeechRecognitionEngine
I am trying to do "streaming" speech recognition in C# from a TCP socket. The problem I am having is that SpeechRecognitionEngine.SetInputToAudioStream() seems to require a Stream of a defined length which can seek. Right now the only way I can think to make this work is to repeatedly run the recognizer on a MemoryStream as more input comes in.

Here's some code to illustrate:

```<code>            SpeechRecognitionEngine appRecognizer = new SpeechRecognitionEngine();

            System.Speech.AudioFormat.SpeechAudioFormatInfo formatInfo = new System.Speech.AudioFormat.SpeechAudioFormatInfo(8000, System.Speech.AudioFormat.AudioBitsPerSample.Sixteen, System.Speech.AudioFormat.AudioChannel.Mono);

            NetworkStream stream = new NetworkStream(socket,true);
            appRecognizer.SetInputToAudioStream(stream, formatInfo);
            // At the line above a "NotSupportedException" complaining that "This stream does not support seek operations."
</code>```

Does anyone know how to get around this? It must support streaming input of some sort, since it works fine with the microphone using SetInputToDefaultAudioDevice().

Thanks, Sean

答:
This is my solution.

```<code>class FakeStreamer : Stream
{
    public bool bExit = false;
    Stream stream;
    TcpClient client;
    public FakeStreamer(TcpClient client)
    {
        this.client = client;
        this.stream = client.GetStream();
        this.stream.ReadTimeout = 100; //100ms
    }
    public override bool CanRead
    {
        get { return stream.CanRead; }
    }

    public override bool CanSeek
    {
        get { return false; }
    }

    public override bool CanWrite
    {
        get { return stream.CanWrite; }
    }

    public override long Length
    {
        get { return -1L; }
    }

    public override long Position
    {
        get { return 0L; }
        set { }
    }
    public override long Seek(long offset, SeekOrigin origin)
    {
        return 0L;
    }

    public override void SetLength(long value)
    {
        stream.SetLength(value);
    }
    public override int Read(byte[] buffer, int offset, int count)
    {
        int len = 0, c = count;
        while (c > 0 && !bExit)
        {
            try
            {
                len = stream.Read(buffer, offset, c);
            }
            catch (Exception e)
            {
                if (e.HResult == -2146232800) // Timeout
                {
                    continue;
                }
                else
                {
                    //Exit read loop
                    break;
                }
            }
            if (!client.Connected || len == 0)
            {
                //Exit read loop
                return 0;
            }
            offset += len;
            c -= len;
        }
        return count;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        stream.Write(buffer,offset,count);
    }

    public override void Close()
    {
        stream.Close();
        base.Close();
    }

    public override void Flush()
    {
        stream.Flush();
    }
}
</code>```

How to Use:

```<code>//client connect in
TcpClient clientSocket = ServerSocket.AcceptTcpClient();
FakeStreamer buffStream = new FakeStreamer(clientSocket);
...
//recognizer init
m_recognizer.SetInputToAudioStream(buffStream , audioFormat);
...
//recognizer end
if (buffStream != null)
    buffStream.bExit = true;
</code>```

Body:
I am trying to do "streaming" speech recognition in C# from a TCP socket. The problem I am having is that SpeechRecognitionEngine.SetInputToAudioStream() seems to require a Stream of a defined length which can seek. Right now the only way I can think to make this work is to repeatedly run the recognizer on a MemoryStream as more input comes in.

Here's some code to illustrate:

            SpeechRecognitionEngine appRecognizer = new SpeechRecognitionEngine();

            System.Speech.AudioFormat.SpeechAudioFormatInfo formatInfo = new System.Speech.AudioFormat.SpeechAudioFormatInfo(8000, System.Speech.AudioFormat.AudioBitsPerSample.Sixteen, System.Speech.AudioFormat.AudioChannel.Mono);

            NetworkStream stream = new NetworkStream(socket,true);
            appRecognizer.SetInputToAudioStream(stream, formatInfo);
            // At the line above a "NotSupportedException" complaining that "This stream does not support seek operations."

Does anyone know how to get around this? It must support streaming input of some sort, since it works fine with the microphone using SetInputToDefaultAudioDevice().

Thanks, Sean

Body:
This is my solution.

class FakeStreamer : Stream
{
    public bool bExit = false;
    Stream stream;
    TcpClient client;
    public FakeStreamer(TcpClient client)
    {
        this.client = client;
        this.stream = client.GetStream();
        this.stream.ReadTimeout = 100; //100ms
    }
    public override bool CanRead
    {
        get { return stream.CanRead; }
    }

    public override bool CanSeek
    {
        get { return false; }
    }

    public override bool CanWrite
    {
        get { return stream.CanWrite; }
    }

    public override long Length
    {
        get { return -1L; }
    }

    public override long Position
    {
        get { return 0L; }
        set { }
    }
    public override long Seek(long offset, SeekOrigin origin)
    {
        return 0L;
    }

    public override void SetLength(long value)
    {
        stream.SetLength(value);
    }
    public override int Read(byte[] buffer, int offset, int count)
    {
        int len = 0, c = count;
        while (c > 0 && !bExit)
        {
            try
            {
                len = stream.Read(buffer, offset, c);
            }
            catch (Exception e)
            {
                if (e.HResult == -2146232800) // Timeout
                {
                    continue;
                }
                else
                {
                    //Exit read loop
                    break;
                }
            }
            if (!client.Connected || len == 0)
            {
                //Exit read loop
                return 0;
            }
            offset += len;
            c -= len;
        }
        return count;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        stream.Write(buffer,offset,count);
    }

    public override void Close()
    {
        stream.Close();
        base.Close();
    }

    public override void Flush()
    {
        stream.Flush();
    }
}

How to Use:

//client connect in
TcpClient clientSocket = ServerSocket.AcceptTcpClient();
FakeStreamer buffStream = new FakeStreamer(clientSocket);
...
//recognizer init
m_recognizer.SetInputToAudioStream(buffStream , audioFormat);
...
//recognizer end
if (buffStream != null)
    buffStream.bExit = true;


问:
"Cannot create infinite type" error in Haskell
I'd like to know why Haskell accepts this

```<code>perms xs = [ x:y | i <- [0..(length xs - 1)], x <- [xs!!i], y <- perms (takeOut i xs)]
</code>```

but won't accept that:

```<code>perms xs = [ x:(perms y) | i <- [0..(length xs - 1)], x <- [xs!!i], y <- (takeOut i xs)]
</code>```

It complains that

[1 of 1] Compiling Main             ( abc.hs, interpreted )

```<code>Occurs check: cannot construct the infinite type: t = [t]
  Expected type: t -> [t]
  Inferred type: [t] -> [[a]]
In the second argument of `(:)', namely `(perms y)'
In the expression: x : (perms y)
</code>```

I can understand what it says, I just cannot is on why the first one is OK and the second one is not!

EDIT: Ah, of course I also have

```<code>perms [] = [[]]
</code>```

at the top.

Thanks

答:
In a list comprehension, x <- ys binds x to each element in ys.  Essentially, you are trying to transform:

```<code>[ f foo | foo <- bar ]
</code>```

Into

```<code>[ f bar ]
</code>```

The phrase

```<code>y <- perms (takeOut i xs)
</code>```

Means "for each permutation y of takeOut i xs".  So the [ x:y | ... ] prepends x to each permutation.

Correspondingly, the phrase

```<code>y <- takeOut i xs
</code>```

Means "for each element y of takeOut i xs".  So the [ x:perms y | ... ] is attempting to find all permutations of the element y (not even a list), and then prepend x to that list of permutations.  The permutations of something is a list of lists, so x must be a list to do this, which it is not.  So, basically, the second one makes no sense.

I can see why you would be thrown off.  Just remember, <- isn't the same as let, it means for each.

Body:
I'd like to know why Haskell accepts this

perms xs = [ x:y | i <- [0..(length xs - 1)], x <- [xs!!i], y <- perms (takeOut i xs)]

but won't accept that:

perms xs = [ x:(perms y) | i <- [0..(length xs - 1)], x <- [xs!!i], y <- (takeOut i xs)]

It complains that

[1 of 1] Compiling Main             ( abc.hs, interpreted )

Occurs check: cannot construct the infinite type: t = [t]
  Expected type: t -> [t]
  Inferred type: [t] -> [[a]]
In the second argument of `(:)', namely `(perms y)'
In the expression: x : (perms y)

I can understand what it says, I just cannot is on why the first one is OK and the second one is not!

EDIT: Ah, of course I also have

perms [] = [[]]

at the top.

Thanks

Body:
In a list comprehension, x <- ys binds x to each element in ys.  Essentially, you are trying to transform:

[ f foo | foo <- bar ]

Into

[ f bar ]

The phrase

y <- perms (takeOut i xs)

Means "for each permutation y of takeOut i xs".  So the [ x:y | ... ] prepends x to each permutation.

Correspondingly, the phrase

y <- takeOut i xs

Means "for each element y of takeOut i xs".  So the [ x:perms y | ... ] is attempting to find all permutations of the element y (not even a list), and then prepend x to that list of permutations.  The permutations of something is a list of lists, so x must be a list to do this, which it is not.  So, basically, the second one makes no sense.

I can see why you would be thrown off.  Just remember, <- isn't the same as let, it means for each.


问:
Chinese translation resulting is question marks (????...)
Long story short, as a test, I am reading data from one cell into a routine that sends non-English words/symbols to Microsoft translator. Upon return, it writes the results in a seperate cell. Unfortunately, because I lack experience when dealing with XMLHTTP, I am banging my head on this one.

That's the plain vanilla short of it. Now here is the long version. I hope I make this clear enough. Forgive me, but remember I am new to this side of VBA...

I'm attempting to leverage a routine that developed by Microsoft and edited by a guy named Patrick O'Beirne, because the way that Microsoft handles tokens has changed supposedly.. Patricks code is here: http://www.sysmod.com/MSTranslator.bas.

Long version...
I am looking to load Chinese data into the routine that uses MSXML2.XMLHTTP to perform a GET on it's way to Microsoft for translation.

This routine works fine on Spanish or French words, but spits out question marks for Chinese Symbols. This may have to do with Chinese symbols being double-byte (?)...

Here is the code. I traced it all the way into the MSHttpRequest function. It looks like it loads the data into oH, but when it comes back  to oH.ResponseText, the symbol change. This is purely a guess on my part.

Anyway, my goal is to send Chinese symbols to Microsoft's translation server and return it in English.

```<code>Function MSHttpRequest(sRequest As String) As String
Dim sURL As String, oH As MSXML2.XMLHTTP, sToken As String

sURL = "http://api.microsofttranslator.com/V2/Http.svc/" & sRequest
sToken = GetAccessToken()
Set oH = CreateObject("MSXML2.XMLHTTP")

oH.Open "GET", sURL, False
oH.setRequestHeader "Authorization", "Bearer " & sToken
oH.send
MSHttpRequest = oH.responseText
Set oH = Nothing
End Function
</code>```

Any help is appreciated.

Thanks,
Steve

答:
Very late to post answer, but this may be it.

You need to change the Language settings in Windows so that VBA can access the language you are working on.

Follow below (except the Registry part) and you should be ok.

How To Display Foreign Characters In Excel VBE

Body:
Long story short, as a test, I am reading data from one cell into a routine that sends non-English words/symbols to Microsoft translator. Upon return, it writes the results in a seperate cell. Unfortunately, because I lack experience when dealing with XMLHTTP, I am banging my head on this one.

That's the plain vanilla short of it. Now here is the long version. I hope I make this clear enough. Forgive me, but remember I am new to this side of VBA...

I'm attempting to leverage a routine that developed by Microsoft and edited by a guy named Patrick O'Beirne, because the way that Microsoft handles tokens has changed supposedly.. Patricks code is here: http://www.sysmod.com/MSTranslator.bas.

Long version...
I am looking to load Chinese data into the routine that uses MSXML2.XMLHTTP to perform a GET on it's way to Microsoft for translation.

This routine works fine on Spanish or French words, but spits out question marks for Chinese Symbols. This may have to do with Chinese symbols being double-byte (?)...

Here is the code. I traced it all the way into the MSHttpRequest function. It looks like it loads the data into oH, but when it comes back  to oH.ResponseText, the symbol change. This is purely a guess on my part.

Anyway, my goal is to send Chinese symbols to Microsoft's translation server and return it in English.

Function MSHttpRequest(sRequest As String) As String
Dim sURL As String, oH As MSXML2.XMLHTTP, sToken As String

sURL = "http://api.microsofttranslator.com/V2/Http.svc/" & sRequest
sToken = GetAccessToken()
Set oH = CreateObject("MSXML2.XMLHTTP")

oH.Open "GET", sURL, False
oH.setRequestHeader "Authorization", "Bearer " & sToken
oH.send
MSHttpRequest = oH.responseText
Set oH = Nothing
End Function

Any help is appreciated.

Thanks,
Steve


问:
opencart admin session not working in localhost. it is redirecting to localhost/admin
I am using Opencart 2.3.0.2, and just installed in localhost and also created a database. during installation i gave username and password for admin. but admin side is not getting.
 when i write ther url localhost/mysitename/admin it is redirecting to localhost/admin..</p>

答:
Please check .htaaccess file in the root folder. Open the file and make change in below line -

RewriteBase /

Change the above line to below code -

```<code>RewriteBase /mysitename
</code>```

In case the above does not work, please check the config.php file in root directory and /admin directory and check the HTTP_SERVER path. If the path is not correct then please correct the path of these files.

Hope it will help. Please feel free to ask in case of any query or issue.

Body:
Please check .htaaccess file in the root folder. Open the file and make change in below line -

RewriteBase /

Change the above line to below code -

RewriteBase /mysitename

In case the above does not work, please check the config.php file in root directory and /admin directory and check the HTTP_SERVER path. If the path is not correct then please correct the path of these files.

Hope it will help. Please feel free to ask in case of any query or issue.


问:
Python shell showing error but cmd is running that program
I am new in python.I am doing addition of two numbers in cmd using input parameter .I am getting output on cmd but  getting Error on python shell.I am using windows 7 and python shell 3.3.2 . so anyone can tell me why my code is not running on python shell ?

code:

```<code>import sys
n=int(sys.argv[1])
m=int(sys.argv[2])
print(n+m)
</code>```

Error:

Traceback (most recent call last):

File "C:/pythonprogram/add.py",  line 4, in

```<code>n=int(sys.argv[1])
</code>```

IndexError: list index out of range

答:
Your program is expecting two command line arguments.
sys.argv is a list of command line arguments. The error IndexError: list index out of range is telling you that you tried to get list item number 2, (with index 1), but the list doesn't have that many values.

You can reproduce that error in the shell:

```<code>>> alist = ['Item 0']
>> print(alist[1])
</code>```

Since alist only has item with index 0 requesting items with higher indexes will cause that error.

Now, to your exact problem. The program is telling you it expected command line arguments, but they were not provided. Provide them!
Run this command:

```<code>python add.py 1 2
</code>```

This will execute the script and pass 1 as the first argument, 2 as the second argument.
In your case the general format is

```<code>python add.py [n] [m]
</code>```

Now at that point you might be (you should be) wondering what sys.argv[0] is then, any why your n number doesn't get assigned to sys.argv[1].
sys.argv[0] is the name of the script running.

Further reading on command line arguments:

http://www.pythonforbeginners.com/system/python-sys-argv

Additional.
You could modify your script to be more descriptive:

```<code>import sys
if len(sys.argv) < 3: #script name + 2 other arguments required
 print("Provide at least two numbers")
else:
 n=int(sys.argv[1])
 m=int(sys.argv[2])
 print(n+m)
</code>```

Body:
I am new in python.I am doing addition of two numbers in cmd using input parameter .I am getting output on cmd but  getting Error on python shell.I am using windows 7 and python shell 3.3.2 . so anyone can tell me why my code is not running on python shell ?

code:

import sys
n=int(sys.argv[1])
m=int(sys.argv[2])
print(n+m)

Error:

Traceback (most recent call last):

File "C:/pythonprogram/add.py",  line 4, in

n=int(sys.argv[1])

IndexError: list index out of range

Body:
Your program is expecting two command line arguments.
sys.argv is a list of command line arguments. The error IndexError: list index out of range is telling you that you tried to get list item number 2, (with index 1), but the list doesn't have that many values.

You can reproduce that error in the shell:

>> alist = ['Item 0']
>> print(alist[1])

Since alist only has item with index 0 requesting items with higher indexes will cause that error.

Now, to your exact problem. The program is telling you it expected command line arguments, but they were not provided. Provide them!
Run this command:

python add.py 1 2

This will execute the script and pass 1 as the first argument, 2 as the second argument.
In your case the general format is

python add.py [n] [m]

Now at that point you might be (you should be) wondering what sys.argv[0] is then, any why your n number doesn't get assigned to sys.argv[1].
sys.argv[0] is the name of the script running.

Further reading on command line arguments:

http://www.pythonforbeginners.com/system/python-sys-argv

Additional.
You could modify your script to be more descriptive:

import sys
if len(sys.argv) < 3: #script name + 2 other arguments required
 print("Provide at least two numbers")
else:
 n=int(sys.argv[1])
 m=int(sys.argv[2])
 print(n+m)


问:
Why isn't my ternary expression working?
I am trying to add and remove some classes depending on window size.

```<code>var windowSizing = function() {
    var $toggleClass;
    var $window = $(window);
    var $iconsContainer = $('.fragments-content > .icons-container');
    ($window.width() > 769) ? $iconsContainer.addClass('mob-only') : $iconsContainer.removeClass('mob-only');
    $window.resize(function(event) {
        ($window.width() > 769) ? $iconsContainer.addClass('mob-only') : $iconsContainer.removeClass('mob-only');
    });
};
</code>```

I am playing with .mob-only and I want to apply it in a ternary operation.

Is there any other way? What am I missing?

答:
var windowSizing = function() {
  var $toggleClass;
  var $window = $(window);
  var $iconsContainer = $('.fragments-content > .icons-container');
  ($window.width() > 500) ? $iconsContainer.addClass('mob-only'): $iconsContainer.removeClass('mob-only');
  $iconsContainer.html($window.width());
  $window.resize(function(event) {
    ($window.width() > 500) ? $iconsContainer.addClass('mob-only'): $iconsContainer.removeClass('mob-only');
    $iconsContainer.html($window.width());

  });
};

$(document).ready(function() {
  windowSizing();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fragments-content">
  <div class="icons-container">Hello</div>
</div></code>```

Your code is fine may be there will be any error in your page please see the code running in fiddle

Body:
I am trying to add and remove some classes depending on window size.

var windowSizing = function() {
    var $toggleClass;
    var $window = $(window);
    var $iconsContainer = $('.fragments-content > .icons-container');
    ($window.width() > 769) ? $iconsContainer.addClass('mob-only') : $iconsContainer.removeClass('mob-only');
    $window.resize(function(event) {
        ($window.width() > 769) ? $iconsContainer.addClass('mob-only') : $iconsContainer.removeClass('mob-only');
    });
};

I am playing with .mob-only and I want to apply it in a ternary operation.

Is there any other way? What am I missing?

Body:
var windowSizing = function() {
  var $toggleClass;
  var $window = $(window);
  var $iconsContainer = $('.fragments-content > .icons-container');
  ($window.width() > 500) ? $iconsContainer.addClass('mob-only'): $iconsContainer.removeClass('mob-only');
  $iconsContainer.html($window.width());
  $window.resize(function(event) {
    ($window.width() > 500) ? $iconsContainer.addClass('mob-only'): $iconsContainer.removeClass('mob-only');
    $iconsContainer.html($window.width());

  });
};

$(document).ready(function() {
  windowSizing();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fragments-content">
  <div class="icons-container">Hello</div>
</div>

Your code is fine may be there will be any error in your page please see the code running in fiddle