问:
Sylius Product customized model : fields not showed in form
I started to learn Sylius few days ago. I need an ecommerce module within my Symfony 3 project. So I gonna extend my project with Sylius, I'll just use the Core/Components stack.

I started with the installation of the Sylius ProductBundle (cf. http://docs.sylius.org/en/latest/bundles/SyliusProductBundle/installation.html)

Seems simple but didn't work at first because Composer installed a stable version (0.19) which is not supported anymore... Anyway, I finally installed the sylius/sylius ~1.0@dev package so my composer.json looks like that :

```<code>"minimum-stability" : "dev",
"prefer-stable" : true,
"require" : {
    "php" : "^7.0",
    "sylius/sylius" : "^1.0@beta",
    "friendsofsymfony/user-bundle" : "~2.0@dev",
    "symfony/assetic-bundle" : "^2.8",
    "gedmo/doctrine-extensions" : "^2.4"
},
</code>```

=> First question : is this the right way ???

Then I created a SyliusBundle within my project to decouple the entire Sylius configuration from the rest of my project.

In SyliusBundle/app/config.yml :

```<code>imports:
    - { resource: "@SyliusProductBundle/Resources/config/app/config.yml" }

# Doctrine
stof_doctrine_extensions:
    default_locale: "%locale%"
    orm:
        default:
            tree: true
            sluggable: true
            timestampable: true
            loggable: false
            sortable: true

# Product
sylius_product:
    driver: doctrine/orm
    resources:
        product:
            classes:
                model: OfferBundle\Entity\Offer
                repository: OfferBundle\Entity\OfferRepository
                form: OfferBundle\Form\OfferType
</code>```

I followed the Sylius guideline to customize my Offer model inherited from Sylius Product model (quite simple)

in OfferBundle/Entity/Offer.php :

```<code><?php
namespace OfferBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Sylius\Component\Core\Model\Product as BaseProduct;

/**
 * @ORM\Table(name="offer")
 * @ORM\Entity(repositoryClass="OfferRepository")
 */
class Offer extends BaseProduct
{
</code>```

=> question 2 : sounds good to you ?

Then I customized the form extended my Offer form with the Sylius Product form (cf. http://docs.sylius.org/en/latest/customization/form.html)

in OfferBundle/Form/OfferType.php :

```<code><?php

namespace OfferBundle\Form;

use Symfony\Component\OptionsResolver\OptionsResolver;
use OfferBundle\Entity\Offer;
use Symfony\Component\Form\AbstractType;

class OfferType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(['data_class' => Offer::class]);
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'offer';
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return \Sylius\Bundle\ProductBundle\Form\Type\ProductType::class;
    }
}
</code>```

In OfferBundle/Form/Extension/OfferTypeExtension.php :

```<code><?php

namespace OfferBundle\Form\Extension;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Form\Type\WysiwygType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use OfferBundle\Form\Type\TagsType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use OfferBundle\Entity\Offer;
use MediaBundle\Form\MediaFileType;
use MediaBundle\Form\MediaVideoType;
use CompanyBundle\Entity\Company;
use Tetranz\Select2EntityBundle\Form\Type\Select2EntityType;
use Admin\CompanyBundle\Controller\CompanyController;
use Symfony\Component\Form\AbstractTypeExtension;
use OfferBundle\Form\ContactType;
use OfferBundle\Form\PriceType;
use OfferBundle\Form\OfferType;

final class OfferTypeExtension extends AbstractTypeExtension
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('advantage', WysiwygType::class)
            ->add('ecommerce')
            ->add('enabled')
            ->add('bestseller')
            ->add('company', Select2EntityType::class, [
                'multiple' => false,
                'remote_route' => 'admin_company_company_autocomplete',
                'class' => Company::class,
                'primary_key' => 'id',
                'text_property' => 'name',
                'minimum_input_length' => 0,
                'page_limit' => CompanyController::NB_PER_PAGE,
                'allow_clear' => false,
                'delay' => 250,
                'cache' => false,
                'cache_timeout' => 60000,
                'language' => 'fr',
                'placeholder' => 'form.choose',
                'required' => true,
            ])
            ->add('state', ChoiceType::class, [
                'choices' => Offer::getStates(),
                'placeholder' => 'form.choose',
            ])
...
</code>```

And the form extension is loaded by service.
in OfferBundle/Resources/config/services.yml :

```<code>offer.form.extension.type.offer:
        class: OfferBundle\Form\Extension\OfferTypeExtension
        tags:
            - { name: form.type_extension, extended_type: OfferBundle\Form\OfferType }
</code>```

Question 3 : It works BUT in see that Sylius\Bundle\CoreBundle\Form\Extension\ProductTypeExtension contains additionnal fields like $images, $variantSelectionMethod... But it doesn't appear in my form. So I suppose that a service.yml somewhere is not loaded ?

Hope somebody can help me on that !

答: you may also need to override the template of the form in order to show those added fields. </p>

Body:
I started to learn Sylius few days ago. I need an ecommerce module within my Symfony 3 project. So I gonna extend my project with Sylius, I'll just use the Core/Components stack.

I started with the installation of the Sylius ProductBundle (cf. http://docs.sylius.org/en/latest/bundles/SyliusProductBundle/installation.html)

Seems simple but didn't work at first because Composer installed a stable version (0.19) which is not supported anymore... Anyway, I finally installed the sylius/sylius ~1.0@dev package so my composer.json looks like that :

"minimum-stability" : "dev",
"prefer-stable" : true,
"require" : {
    "php" : "^7.0",
    "sylius/sylius" : "^1.0@beta",
    "friendsofsymfony/user-bundle" : "~2.0@dev",
    "symfony/assetic-bundle" : "^2.8",
    "gedmo/doctrine-extensions" : "^2.4"
},

=> First question : is this the right way ???

Then I created a SyliusBundle within my project to decouple the entire Sylius configuration from the rest of my project.

In SyliusBundle/app/config.yml :

imports:
    - { resource: "@SyliusProductBundle/Resources/config/app/config.yml" }

# Doctrine
stof_doctrine_extensions:
    default_locale: "%locale%"
    orm:
        default:
            tree: true
            sluggable: true
            timestampable: true
            loggable: false
            sortable: true

# Product
sylius_product:
    driver: doctrine/orm
    resources:
        product:
            classes:
                model: OfferBundle\Entity\Offer
                repository: OfferBundle\Entity\OfferRepository
                form: OfferBundle\Form\OfferType

I followed the Sylius guideline to customize my Offer model inherited from Sylius Product model (quite simple)

in OfferBundle/Entity/Offer.php :

<?php
namespace OfferBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Sylius\Component\Core\Model\Product as BaseProduct;

/**
 * @ORM\Table(name="offer")
 * @ORM\Entity(repositoryClass="OfferRepository")
 */
class Offer extends BaseProduct
{

=> question 2 : sounds good to you ?

Then I customized the form extended my Offer form with the Sylius Product form (cf. http://docs.sylius.org/en/latest/customization/form.html)

in OfferBundle/Form/OfferType.php :

<?php

namespace OfferBundle\Form;

use Symfony\Component\OptionsResolver\OptionsResolver;
use OfferBundle\Entity\Offer;
use Symfony\Component\Form\AbstractType;

class OfferType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(['data_class' => Offer::class]);
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'offer';
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return \Sylius\Bundle\ProductBundle\Form\Type\ProductType::class;
    }
}

In OfferBundle/Form/Extension/OfferTypeExtension.php :

<?php

namespace OfferBundle\Form\Extension;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Form\Type\WysiwygType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use OfferBundle\Form\Type\TagsType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use OfferBundle\Entity\Offer;
use MediaBundle\Form\MediaFileType;
use MediaBundle\Form\MediaVideoType;
use CompanyBundle\Entity\Company;
use Tetranz\Select2EntityBundle\Form\Type\Select2EntityType;
use Admin\CompanyBundle\Controller\CompanyController;
use Symfony\Component\Form\AbstractTypeExtension;
use OfferBundle\Form\ContactType;
use OfferBundle\Form\PriceType;
use OfferBundle\Form\OfferType;

final class OfferTypeExtension extends AbstractTypeExtension
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('advantage', WysiwygType::class)
            ->add('ecommerce')
            ->add('enabled')
            ->add('bestseller')
            ->add('company', Select2EntityType::class, [
                'multiple' => false,
                'remote_route' => 'admin_company_company_autocomplete',
                'class' => Company::class,
                'primary_key' => 'id',
                'text_property' => 'name',
                'minimum_input_length' => 0,
                'page_limit' => CompanyController::NB_PER_PAGE,
                'allow_clear' => false,
                'delay' => 250,
                'cache' => false,
                'cache_timeout' => 60000,
                'language' => 'fr',
                'placeholder' => 'form.choose',
                'required' => true,
            ])
            ->add('state', ChoiceType::class, [
                'choices' => Offer::getStates(),
                'placeholder' => 'form.choose',
            ])
...

And the form extension is loaded by service.
in OfferBundle/Resources/config/services.yml :

offer.form.extension.type.offer:
        class: OfferBundle\Form\Extension\OfferTypeExtension
        tags:
            - { name: form.type_extension, extended_type: OfferBundle\Form\OfferType }

Question 3 : It works BUT in see that Sylius\Bundle\CoreBundle\Form\Extension\ProductTypeExtension contains additionnal fields like $images, $variantSelectionMethod... But it doesn't appear in my form. So I suppose that a service.yml somewhere is not loaded ?

Hope somebody can help me on that !


来源: stackexchange

问:
Setting random color for each face in THREEjs results in black object
I am trying to render a geometry with each face colored by a random color.

I iterate through geometry.faces and set a random color for each face. Upon that I create a new material which is added to the mesh. It seems to me that I've set all the necessary flags, but still my object appears pitch black in the scene.

The scene contains two directional lights, as well as ambient light. In case I use THREE.MeshPhongMaterial the object also appears black, but has some reflections from directional light.

Here is the code:

```<code>var geometry = new THREE.Geometry().fromBufferGeometry( object );

for ( var i = 0; i < geometry.faces.length; i ++ ) {

    var face = geometry.faces[ i ];
    face.color.setHex( Math.random() * 0xffffff );
}

var material = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );

var mesh = new THREE.Mesh( geometry, material);
mesh.dynamic = true;
mesh.geometry.colorsNeedUpdate = true;

scene.add( mesh );
</code>```

I am using the latest version of three.js: r84

Does anyone see what I am missing?

答:
Huh! I got it!
We can't just assign color to a face, but we need to assign it to each vertex. Yes, then we have interpolation, which is not really something I want, but at least we can see colors. In case someone knows how to assign color for the face directly without interpolation, I'd be grateful for advice!

This is the new version of the code, just adapt the for loop:

```<code>var faceIndices = [ 'a', 'b', 'c' ];
for ( var i = 0; i < geometry.faces.length; i ++ ) {
    var face  = geometry.faces[ i ];
    for( var j = 0; j < 3; j++ ) {
        color = new THREE.Color( 0xffffff );
        color.setHex( Math.random() * 0xffffff );
        face.vertexColors[ j ] = color;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to render a geometry with each face colored by a random color.

I iterate through geometry.faces and set a random color for each face. Upon that I create a new material which is added to the mesh. It seems to me that I've set all the necessary flags, but still my object appears pitch black in the scene.

The scene contains two directional lights, as well as ambient light. In case I use THREE.MeshPhongMaterial the object also appears black, but has some reflections from directional light.

Here is the code:

var geometry = new THREE.Geometry().fromBufferGeometry( object );

for ( var i = 0; i < geometry.faces.length; i ++ ) {

    var face = geometry.faces[ i ];
    face.color.setHex( Math.random() * 0xffffff );
}

var material = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );

var mesh = new THREE.Mesh( geometry, material);
mesh.dynamic = true;
mesh.geometry.colorsNeedUpdate = true;

scene.add( mesh );

I am using the latest version of three.js: r84

Does anyone see what I am missing?

Body:
Huh! I got it!
We can't just assign color to a face, but we need to assign it to each vertex. Yes, then we have interpolation, which is not really something I want, but at least we can see colors. In case someone knows how to assign color for the face directly without interpolation, I'd be grateful for advice!

This is the new version of the code, just adapt the for loop:

var faceIndices = [ 'a', 'b', 'c' ];
for ( var i = 0; i < geometry.faces.length; i ++ ) {
    var face  = geometry.faces[ i ];
    for( var j = 0; j < 3; j++ ) {
        color = new THREE.Color( 0xffffff );
        color.setHex( Math.random() * 0xffffff );
        face.vertexColors[ j ] = color;
    }
}


问:
Is it possible to disable AJAX in RichFaces?
Is it possible in a Seam/RichFaces page to disable AJAX so requests are sent via regular server-client request, where the entire page is refreshed instead of individual elements? I'm using an a4j:outputPanel and an a4j:commandButton and need to have them not use AJAX in some cases via a toggle button.

Here's a code snippet from the page. Thanks.

```<code><a4j:outputPanel id="output" rendered="#{not empty overtime.overtimeItems}"
    ajaxRendered="true">
  <c:forEach items="#{overtime.overtimeItems}" var="oc">
    <h:outputLabel value="#{oc.dateLabel}"
      style="font-weight:#{(oc.id == 1) ? 'bold' : 'normal'}"
      for="#{oc.overtimeDateId}" />
    <rich:calendar value="#{oc.overtimeDate}"
      requiredMessage="Date 1 is required."
      id="#{oc.overtimeDateId}" datePattern="MM-dd-yyyy"
      required="#{oc.id == 1 ? true : false}" firstWeekDay="0">
      <a4j:support event="onchanged"
         reRender="#{oc.overtimeHoursId}, #{oc.overtimeHoursOutputId}"
         ajaxSingle="true"/>
    </rich:calendar>
    ......

  </c:foreach>
</a4j:outputPanel>

<a4j:commandButton action="#{utilities.sendEmail('/pages/overtime/mail.xhtml')}"
    type="submit" value="Submit"
    reRender="status, valid1, valid2" eventsQueue="foo" status="status"
    onclick="this.disabled=false" id="btnSubmit"
    oncomplete="#{facesContext.maximumSeverity == null ? 'Richfaces.hideModalPanel(\'mpErrors\');' : 'Richfaces.showModalPanel(\'mpErrors\'); this.disabled=false'}"/>
</code>```

答:
Only way to do it is to wrap these ajax components in panelgroups and use the rendered property. You'll basically need to provide conditional rendering and provide non-ajax alternatives of the ajax components.

So you would have something like :

```<code><h:panelGroup rendered="#{someBean.ajaxEnabled}">
    <a4j:commandButton ..... />
</h:panelGroup>

<h:panelGroup rendered="#{!someBean.ajaxEnabled}">
    <h:commandButton ..... />
</h:panelGroup>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is it possible in a Seam/RichFaces page to disable AJAX so requests are sent via regular server-client request, where the entire page is refreshed instead of individual elements? I'm using an a4j:outputPanel and an a4j:commandButton and need to have them not use AJAX in some cases via a toggle button.

Here's a code snippet from the page. Thanks.

<a4j:outputPanel id="output" rendered="#{not empty overtime.overtimeItems}"
    ajaxRendered="true">
  <c:forEach items="#{overtime.overtimeItems}" var="oc">
    <h:outputLabel value="#{oc.dateLabel}"
      style="font-weight:#{(oc.id == 1) ? 'bold' : 'normal'}"
      for="#{oc.overtimeDateId}" />
    <rich:calendar value="#{oc.overtimeDate}"
      requiredMessage="Date 1 is required."
      id="#{oc.overtimeDateId}" datePattern="MM-dd-yyyy"
      required="#{oc.id == 1 ? true : false}" firstWeekDay="0">
      <a4j:support event="onchanged"
         reRender="#{oc.overtimeHoursId}, #{oc.overtimeHoursOutputId}"
         ajaxSingle="true"/>
    </rich:calendar>
    ......

  </c:foreach>
</a4j:outputPanel>

<a4j:commandButton action="#{utilities.sendEmail('/pages/overtime/mail.xhtml')}"
    type="submit" value="Submit"
    reRender="status, valid1, valid2" eventsQueue="foo" status="status"
    onclick="this.disabled=false" id="btnSubmit"
    oncomplete="#{facesContext.maximumSeverity == null ? 'Richfaces.hideModalPanel(\'mpErrors\');' : 'Richfaces.showModalPanel(\'mpErrors\'); this.disabled=false'}"/>

Body:
Only way to do it is to wrap these ajax components in panelgroups and use the rendered property. You'll basically need to provide conditional rendering and provide non-ajax alternatives of the ajax components.

So you would have something like :

<h:panelGroup rendered="#{someBean.ajaxEnabled}">
    <a4j:commandButton ..... />
</h:panelGroup>

<h:panelGroup rendered="#{!someBean.ajaxEnabled}">
    <h:commandButton ..... />
</h:panelGroup>


问:
Go to activity without starting it upon clicking on notification
Following the Android tutorial on Notification https://developer.android.com/guide/topics/ui/notifiers/notifications.html I'm able to display a Notification.
What I do want, which is not explain in the article, is how to go to the activity without starting it.
In fact I have an application with a couple of Activities. As soon as I enter one of those activities, a permanent Notification is shown which only disappears when the user leaves that activity.
If the user then clicks on the Notification while my application is not on screen, I want the activity to be resumed without restarting it. The activity runs a counter. That's why it shouldn't be restarted.

Best regards

答:
I want the activity to be resumed without restarting it. The activity runs a counter. That's why it shouldn't be restarted.

Well, you have to save the counter state during onPause() method and restore it during onResume() method.

How to save the state?

You can save the counter value into SharedPreferences. That will do the magic for you. cheers :)


问:
Displaying the wrong launch image on my app. Tried to replace it in several ways
I have a problem with my app´s launch image. Early on in the development I added a sample image as launch image. Now when the app is ready for release, I can’t change the launch image.

I have tried changing it inside xcode in the project summary, deleting the files from the project file and replacing the files with the new image with the correct name. No luck. It still displays wrong on all devices.

I don’t even have the image in the project anymore.

Is there anyone in here who knows what’s wrong, or have experienced anything like this?

The launch image is for iPhone and iPad, portrait.

答:
For Xamarin users, the only solution I could find to this problem was to do the following:

Remove the app from the device/simulator

Restart the device/simulator

Deploy and run the app

Deleting the app, cleaning the build, deleting the bin and obj directories, and rebuilding, doesn't work. The device/simulator has to be restarted for it to forget the old cached image.

As Steven Fisher points out, this wouldn't happen for a proper install from the App Store, where it 'does a better job of installing'.


问:
c# commandline no error line number
If there is an exception in .NET code and and PDB file is available you normally get the errors with source code line numbers shown in the exception message. This seems to be different in command line executables, where I do not get any line number although a PDB file is available:

Anwendung: MNX.CommandLine.EpkFtpEventhandler.exe Frameworkversion: v4.0.30319 Beschreibung: Der Prozess wurde aufgrund eines Ausnahmefehlers beendet. Ausnahmeinformationen: System.Data.SqlClient.SqlException Stapel: bei System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(System.String, Boolean, Int32, Boolean) bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(System.Threading.Tasks.TaskCompletionSource`1, System.String, Boolean, Int32, Boolean) bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery() bei MNX.DB.WriteLocal(System.String) bei MNX.DB.Write(System.String) bei MNX.CommandLine.EpkFtpEventHandler.Main(System.String[])

Does anyone know why?

答: Try to empty symbol cache by accessing Debug > Options > Debugging > Symbols and clean your solution afterwards.

Title: c# commandline no error line number


问:
Distributed Key/Value Stores that can run on Windows, and have .Net clients?
As the title says, does anyone know of any Distributed Key/Value Stores that can run on Windows, and have .Net clients?

Thank you

Update: Sorry, forgot to add that it needs to be persisted.

答: Membase is a distributed key-value store that supports Windows and has a .NET client (Enyim). </p>


问:
Met undefined reference when use glib in ubuntu
I've searched about this a lot. And tried a lot. Just don't know where I go wrong.

Here is my code, it's very simple:

```<code>#include <glib.h>
int main()
{
    int *ip=g_new(int,1);
    *ip=42;
    return *ip;
}
</code>```

First I try apt-get libglib2.0-dev in my Ubuntu and Mint, when it's done, compile with:

```<code>gcc `pkg-config --cflags --libs glib-2.0` -o main main.c
/tmp/ccYFljQD.o: In function `main':
main.c:(.text+0x13): undefined reference to `g_malloc_n'
collect2: error: ld returned 1 exit status
Makefile:3: recipe for target 'all' failed
make: *** [all] Error 1
</code>```

And the output of pkg-config:

```<code>$ pkg-config --cflags --libs glib-2.0
-I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -lglib-2.0
</code>```

So it's not working, then I try to compile from source and install one by my own.
I've apt-get libffi-dev, autogen and configure, make, make install, that's all okay.

```<code>$ pkg-config --cflags --libs glib-2.0
-I/home/donpope/software/include/glib-2.0 -I/home/donpope/software/lib/glib-2.0/include -L/home/donpope/software/lib -lglib-2.0
</code>```

Yet compile with the same error:

```<code>gcc `pkg-config --cflags --libs glib-2.0` -o main main.c
/tmp/cctR3iEq.o: In function `main':
main.c:(.text+0x13): undefined reference to `g_malloc_n'
collect2: error: ld returned 1 exit status
Makefile:3: recipe for target 'all' failed
make: *** [all] Error 1
</code>```

So I need some help here. Thank you!

Update:
Later I try this in a RedHat with older gcc. And it's just okay.

答:
I have this Makefile in my glib sandbox:

```<code>PKGS=glib-2.0
CFLAGS+=$(shell pkg-config --cflags $(PKGS))
LDFLAGS+=$(shell pkg-config --libs $(PKGS))

%: %.c
    $(CC) $(CFLAGS) $< -o $@ $(LIBS) $(LDFLAGS)

%.o: %.c
    $(CC) $(CFLAGS) $< -c -o $@

%: %.o
    $(CC) $< -o $@ $(LIBS) $(LDFLAGS)
</code>```

Starting from this and tweaking, you should be able to figure out the exact commandline and compile your program.

Also, you should make sure that your PKG_CONFIG_PATH is properly updated to contain the path where you installed glib (typically in PREFIX/lib/pkgconfig).

Body:
I've searched about this a lot. And tried a lot. Just don't know where I go wrong.

Here is my code, it's very simple:

#include <glib.h>
int main()
{
    int *ip=g_new(int,1);
    *ip=42;
    return *ip;
}

First I try apt-get libglib2.0-dev in my Ubuntu and Mint, when it's done, compile with:

gcc `pkg-config --cflags --libs glib-2.0` -o main main.c
/tmp/ccYFljQD.o: In function `main':
main.c:(.text+0x13): undefined reference to `g_malloc_n'
collect2: error: ld returned 1 exit status
Makefile:3: recipe for target 'all' failed
make: *** [all] Error 1

And the output of pkg-config:

$ pkg-config --cflags --libs glib-2.0
-I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -lglib-2.0

So it's not working, then I try to compile from source and install one by my own.
I've apt-get libffi-dev, autogen and configure, make, make install, that's all okay.

$ pkg-config --cflags --libs glib-2.0
-I/home/donpope/software/include/glib-2.0 -I/home/donpope/software/lib/glib-2.0/include -L/home/donpope/software/lib -lglib-2.0

Yet compile with the same error:

gcc `pkg-config --cflags --libs glib-2.0` -o main main.c
/tmp/cctR3iEq.o: In function `main':
main.c:(.text+0x13): undefined reference to `g_malloc_n'
collect2: error: ld returned 1 exit status
Makefile:3: recipe for target 'all' failed
make: *** [all] Error 1

So I need some help here. Thank you!

Update:
Later I try this in a RedHat with older gcc. And it's just okay.

Body:
I have this Makefile in my glib sandbox:

PKGS=glib-2.0
CFLAGS+=$(shell pkg-config --cflags $(PKGS))
LDFLAGS+=$(shell pkg-config --libs $(PKGS))

%: %.c
    $(CC) $(CFLAGS) $< -o $@ $(LIBS) $(LDFLAGS)

%.o: %.c
    $(CC) $(CFLAGS) $< -c -o $@

%: %.o
    $(CC) $< -o $@ $(LIBS) $(LDFLAGS)

Starting from this and tweaking, you should be able to figure out the exact commandline and compile your program.

Also, you should make sure that your PKG_CONFIG_PATH is properly updated to contain the path where you installed glib (typically in PREFIX/lib/pkgconfig).


问:
How to create a moving object from where I clicked
I'm new to processing and I'm trying to create a Space Invaders kind of mechanic where I shoot a bullet from the ship, however I am having trouble trying to make the bullet shoot from the x coordinate where I click and continue going on the X-axis up and away from the ship. I'm attempting to use mouseClicked but I wind up with the bullet either following the mouseX or not moving at all on the Y-axis, any help is appreciated thanks.

Hero theHero;
Bullet theBullet;

void setup(){
  size(300,600);
  theHero = new Hero(color(255,0,0),mouseX,mouseY);
  theBullet = new Bullet(color(255,255,0),300,600,-4);
}

void draw(){
background(255);
theHero.move();
theHero.display();
theBullet.displayb();
theBullet.mouseClicked();
}

class Hero {
 color c;
 float xpos;
 float ypos;

Hero(color tempC,float tempXpos, float tempYpos){
  c = tempC;
  xpos = tempXpos;
  ypos = tempYpos;
}

 void display() {
  stroke(0);
  fill(c);
  rectMode(CENTER);
  rect(xpos, ypos, 20, 10);
}

void move() {
 xpos = mouseX;
 ypos = 580;

 }
}

class Bullet {
color c;
float xpos;
float ypos;
float yspeed;

Bullet(color tempC, float tempXpos, float tempYpos, float tempYspeed) {
  c = tempC;
  xpos = tempXpos;
  ypos = tempYpos;
  yspeed = tempYspeed;
}

void displayb() {
   stroke(0);
   fill(c);
   rectMode(CENTER);
   rect(xpos, ypos, 5, 5);
}

void mouseClicked(){
  xpos = mouseX;
  ypos = ypos + yspeed;
  if (ypos < 0) {
    ypos = 580;
    xpos = mouseX;

  }
}
}
```

答:
Its because you are calling the mouseClicked() method every frame of the draw loop. Constantly changing the xpos of the bullet to the mouseX position. In order to remove theBullet.mouseClicked() from the draw() function.

You also need to create an array of bullet objects. And draw each of them. In the mouseClicked() (which is called everytime a mouse is clicked) create a new Bullet object with the xpos of the current Hero position. This should look  like this.

void mouseClicked(){
    bulletCount++;
    float startX = theHero.xpos;
    bullets[bulletCount] = new Bullet(color(255,0,0),startX,theHero.ypos, -5 /*YSPEED*/);
}
```

<p>In order to create and draw all of the Bullet objects you need an array. This can be created and displayed like so:</p>

<pre class="lang-java prettyprint-override"><code>Hero theHero;
public Bullet[] bullets = new Bullet[10000];
public static int bulletCount = 0;
void setup(){
  size(300,600);
  theHero = new Hero(color(255,0,0),mouseX,mouseY);
}

void draw(){
background(255);
for(int i = 1; i <= bulletCount;i++){
  bullets[i].updatePos();
  bullets[i].displayb();
}
theHero.move();
theHero.display();
}
</code>```

Ive also added a updatePos() to the Bullet object which increments its y position by the y speed every frame. If you want the full code just copy this pastebin: https://pastebin.com/2CpLPTnQ

Body:
Its because you are calling the mouseClicked() method every frame of the draw loop. Constantly changing the xpos of the bullet to the mouseX position. In order to remove theBullet.mouseClicked() from the draw() function.

You also need to create an array of bullet objects. And draw each of them. In the mouseClicked() (which is called everytime a mouse is clicked) create a new Bullet object with the xpos of the current Hero position. This should look  like this.

void mouseClicked(){
    bulletCount++;
    float startX = theHero.xpos;
    bullets[bulletCount] = new Bullet(color(255,0,0),startX,theHero.ypos, -5 /*YSPEED*/);
}

In order to create and draw all of the Bullet objects you need an array. This can be created and displayed like so:

Hero theHero;
public Bullet[] bullets = new Bullet[10000];
public static int bulletCount = 0;
void setup(){
  size(300,600);
  theHero = new Hero(color(255,0,0),mouseX,mouseY);
}

void draw(){
background(255);
for(int i = 1; i <= bulletCount;i++){
  bullets[i].updatePos();
  bullets[i].displayb();
}
theHero.move();
theHero.display();
}

Ive also added a updatePos() to the Bullet object which increments its y position by the y speed every frame. If you want the full code just copy this pastebin: https://pastebin.com/2CpLPTnQ


问:
Query for updating a column in same table from same table
I have to update the authorid column which are matching  (where documentculture = 'en-US'

to matching (where documentculture = 'el-GR' in the same table. which includes a inner join to another table

I written like below which looks wrong:

```<code>  UPDATE t1
  SET t1.authorid = t2.authorid
  FROM wv_blogdata AS t1
  INNER JOIN wv_blogdata AS t2
  ON t1.documentnodeid = t2.documentnodeid
  inner join CMS_Document d
  ON d.BlogDataID = d.DocumentForeignKeyValue
  WHERE t2.DocumentCulture = 'en-US';
</code>```

could you please correct me?

More explanation:

```<code>select authorid from wv_blogdata
inner join CMS_Document
on wv_blogdata.BlogDataID = CMS_Document.DocumentForeignKeyValue
Where DocumentCulture ='el-GR'
</code>```

The author id of above query is different from authorid of below query
which i want to make it synch

```<code>select authorid from wv_blogdata
inner join CMS_Document
on wv_blogdata.BlogDataID = CMS_Document.DocumentForeignKeyValue
Where DocumentCulture ='en-US'
</code>```

答:
As Zohar Peled says in the comments, unless you give sample data, expected results as well as your current DML it's hard to produce an accurate answer to your question.

That being said, in general terms if you can produce a select statement using table aliases that shows both the field to be updated and the field with the new value then you can use it as the basis for a successful UPDATE query.

So if the correct results are shown in this query(your original converted into a SELECT):

```<code>    SELECT t1.authorid AS OldValue, t2.authorid AS NewValue
      FROM wv_blogdata AS t1
INNER JOIN wv_blogdata AS t2
        ON t1.documentnodeid = t2.documentnodeid
INNER JOIN CMS_Document d
        ON d.BlogDataID = d.DocumentForeignKeyValue
     WHERE t2.DocumentCulture = 'en-US';
</code>```

you will get the correct outcome from this query(your original):

```<code>    UPDATE t1
       SET t1.authorid = t2.authorid
      FROM wv_blogdata AS t1
INNER JOIN wv_blogdata AS t2
        ON t1.documentnodeid = t2.documentnodeid
INNER JOIN CMS_Document d
        ON d.BlogDataID = d.DocumentForeignKeyValue
     WHERE t2.DocumentCulture = 'en-US';
</code>```

Remembering of course to test your work for unexpected outcomes and hidden gotchas.

Again without sufficient sample data it's really hard to give you a definitive answer, so include as much detail as possible to help us help you.

Hope this helps you to work it out.

Body:
I have to update the authorid column which are matching  (where documentculture = 'en-US'

to matching (where documentculture = 'el-GR' in the same table. which includes a inner join to another table

I written like below which looks wrong:

  UPDATE t1
  SET t1.authorid = t2.authorid
  FROM wv_blogdata AS t1
  INNER JOIN wv_blogdata AS t2
  ON t1.documentnodeid = t2.documentnodeid
  inner join CMS_Document d
  ON d.BlogDataID = d.DocumentForeignKeyValue
  WHERE t2.DocumentCulture = 'en-US';

could you please correct me?

More explanation:

select authorid from wv_blogdata
inner join CMS_Document
on wv_blogdata.BlogDataID = CMS_Document.DocumentForeignKeyValue
Where DocumentCulture ='el-GR'

The author id of above query is different from authorid of below query
which i want to make it synch

select authorid from wv_blogdata
inner join CMS_Document
on wv_blogdata.BlogDataID = CMS_Document.DocumentForeignKeyValue
Where DocumentCulture ='en-US'

Body:
As Zohar Peled says in the comments, unless you give sample data, expected results as well as your current DML it's hard to produce an accurate answer to your question.

That being said, in general terms if you can produce a select statement using table aliases that shows both the field to be updated and the field with the new value then you can use it as the basis for a successful UPDATE query.

So if the correct results are shown in this query(your original converted into a SELECT):

    SELECT t1.authorid AS OldValue, t2.authorid AS NewValue
      FROM wv_blogdata AS t1
INNER JOIN wv_blogdata AS t2
        ON t1.documentnodeid = t2.documentnodeid
INNER JOIN CMS_Document d
        ON d.BlogDataID = d.DocumentForeignKeyValue
     WHERE t2.DocumentCulture = 'en-US';

you will get the correct outcome from this query(your original):

    UPDATE t1
       SET t1.authorid = t2.authorid
      FROM wv_blogdata AS t1
INNER JOIN wv_blogdata AS t2
        ON t1.documentnodeid = t2.documentnodeid
INNER JOIN CMS_Document d
        ON d.BlogDataID = d.DocumentForeignKeyValue
     WHERE t2.DocumentCulture = 'en-US';

Remembering of course to test your work for unexpected outcomes and hidden gotchas.

Again without sufficient sample data it's really hard to give you a definitive answer, so include as much detail as possible to help us help you.

Hope this helps you to work it out.


问:
Cannot restore scoped Angular 2 packages in Visual Studio 2015
I am using Visual Studio 2015 with an ASP.NET 4.x project. I created an Angular 2 application with a package.json that includes the new Angular 2 RC scoped packages (@angular/common, @angular/core, etc). When I use the right-click restore packages on this package.json file I get in the Output console:

```<code>npm http 404 https://registry.npmjs.org/angular/compiler
npm ERR! 404 Not Found
npm ERR! 404
npm ERR! 404 'angular/compiler' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404 It was specified as a dependency of 'product-management'
</code>```

Any ideas on how to restore these scoped packages in Visual Studio 2015? (I know how to npm install from the command line ... I'd like to know how to do it without using the command line.)

答:
I had similiar issue, despite the fact of correct order in "external web tools".

Try changing the npm version in your package.json file for at least 3.0.0. For me it worked.

Body:
I am using Visual Studio 2015 with an ASP.NET 4.x project. I created an Angular 2 application with a package.json that includes the new Angular 2 RC scoped packages (@angular/common, @angular/core, etc). When I use the right-click restore packages on this package.json file I get in the Output console:

npm http 404 https://registry.npmjs.org/angular/compiler
npm ERR! 404 Not Found
npm ERR! 404
npm ERR! 404 'angular/compiler' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404 It was specified as a dependency of 'product-management'

Any ideas on how to restore these scoped packages in Visual Studio 2015? (I know how to npm install from the command line ... I'd like to know how to do it without using the command line.)


问:
Best way to represent sets of 3 values
Assume that I have 100 sets of 3 values. first value is time, second value is x position and 3rd value is y position. this is going to be the xy position of a point over 100 seconds for example.
I have a PHP background. in PHP I would do it with a 3D associative array like this :

```<code>position["time"]["x"]["y"]
</code>```

so I can access x,y values at a certain time. How would you do this in c#? I think generics like list and dictionary would do that. but I don't know how to implement key values for a 3D set of data.

答:
It looks like you want to access an x/y position at a given time. You might consider a combination of the other answers along with a dictionary.

Define a simple struct which holds x & y positions. It is important that this object is immutable.

```<code>public struct Position
{
    public int X { get; }
    public int Y { get; }

    public Position(int x, int y)
    {
        this.X = x;
        this.Y = y;
    }
}
</code>```

Now you can store these in a dictionary with (perhaps) DateTime as the key.

```<code>Dictionary<DateTime, Position> positions = new Dictionary<DateTime, Position>();
positions.Add(new DateTime(2017,3,29,10,0,0), new Position(10,10));
</code>```

And you can read your position like

```<code>var pos = positions[new DateTime(2017,3,29,10,0,0)];
Console.WriteLine("{0}:{1}",pos.X,pos.Y);
</code>```

A neat little addition to this is that if, for example, you are getting a list of these object you wish to lookup by time you can easily turn them into a dictionary. Say your get a list of these (from other answer):

```<code>public class PositionEntity
{
   public DateTime Time {get;set;}
   public int X {get;set;}
   public int Y {get;set;}
}
</code>```

As a list entities you can do this:

```<code>IEnumerable<PositionEntity> entities = .... loaded from somewhere
var dict = entities.ToDictionary(k => k.Time, v => new Position(v.X,v.Y));
</code>```

Title: Best way to represent sets of 3 values

Body:
Assume that I have 100 sets of 3 values. first value is time, second value is x position and 3rd value is y position. this is going to be the xy position of a point over 100 seconds for example.
I have a PHP background. in PHP I would do it with a 3D associative array like this :

position["time"]["x"]["y"]

so I can access x,y values at a certain time. How would you do this in c#? I think generics like list and dictionary would do that. but I don't know how to implement key values for a 3D set of data.

Body:
It looks like you want to access an x/y position at a given time. You might consider a combination of the other answers along with a dictionary.

Define a simple struct which holds x & y positions. It is important that this object is immutable.

public struct Position
{
    public int X { get; }
    public int Y { get; }

    public Position(int x, int y)
    {
        this.X = x;
        this.Y = y;
    }
}

Now you can store these in a dictionary with (perhaps) DateTime as the key.

Dictionary<DateTime, Position> positions = new Dictionary<DateTime, Position>();
positions.Add(new DateTime(2017,3,29,10,0,0), new Position(10,10));

And you can read your position like

var pos = positions[new DateTime(2017,3,29,10,0,0)];
Console.WriteLine("{0}:{1}",pos.X,pos.Y);

A neat little addition to this is that if, for example, you are getting a list of these object you wish to lookup by time you can easily turn them into a dictionary. Say your get a list of these (from other answer):

public class PositionEntity
{
   public DateTime Time {get;set;}
   public int X {get;set;}
   public int Y {get;set;}
}

As a list entities you can do this:

IEnumerable<PositionEntity> entities = .... loaded from somewhere
var dict = entities.ToDictionary(k => k.Time, v => new Position(v.X,v.Y));


问:
Upon shuffling I get a None object. What is wrong?
I have shuffled the list and assigned it to another variable and when I am trying to print it, it is giving output as None? What is wrong ?

```<code>list1 = [1,2,3,4,5,6]
list2 = shuffle(list1)
print list2
</code>```

答:
Shuffle() function is not accessible directly, so we need to import shuffle module and then we need to call this function using random static object.</p>

```<code>#!/usr/bin/python

import random`
list = [1, 2, 3, 4, 5];
random.shuffle(list)
print "list : ",  list
</code>```

Body:
I have shuffled the list and assigned it to another variable and when I am trying to print it, it is giving output as None? What is wrong ?

list1 = [1,2,3,4,5,6]
list2 = shuffle(list1)
print list2

Body:
Shuffle() function is not accessible directly, so we need to import shuffle module and then we need to call this function using random static object.

#!/usr/bin/python

import random`
list = [1, 2, 3, 4, 5];
random.shuffle(list)
print "list : ",  list


问:
Drupal 7 doesn't upload images styles
I have a drupal 7 hosted on windows azure as web app.

When I upload an image into a content, my original image is stored in the files folder but its corresponding image styles are not stored (example in the thumbnail folder).

I tried this:

Permissions 777/775

Comment the following lines in the htaccess located in the files folder:

#Options None
#Options + FollowSymLinks
```

I have the impression that it is Azure which blocks the writing of the files because the htaccess can be changed only in its own editor and not in my ftp.

答:
Since you deployed your app to Azure Web Apps, Azure would use IIS to host your app, and this is running on Windows Server machines. So htaceess and permissions 777/775 don't work on Azure. Without any error message and how you deploy your Drupal app, it's hard to figure out what's wrong there.

However, I can successfully deploy Drupal 7 with template Acquia Drupal 7 on MySQL from Azure marketplace. I also tested to upload an image into a content and both of original and thumbnail image are stored properly. Maybe you can have a try.

Choose template Acquia Drupal 7 on MySQL to create an Azure Web
App.

Upload image was worked fine.

Title: Drupal 7 doesn't upload images styles

Body:
I have a drupal 7 hosted on windows azure as web app.

When I upload an image into a content, my original image is stored in the files folder but its corresponding image styles are not stored (example in the thumbnail folder).

I tried this:

Permissions 777/775

Comment the following lines in the htaccess located in the files folder:

#Options None
#Options + FollowSymLinks

I have the impression that it is Azure which blocks the writing of the files because the htaccess can be changed only in its own editor and not in my ftp.


问:
How to connect an application to a SQL Server using IP Adress in C#?
My problem is that I have created a SQL Server database but I access it locally, only from my own computer. What I want to do is to connect the app to a server and to save all the data there.

The code I used to connect to the SQL Server database is:

```<code>SqlConnection con = new SqlConnection(@"Data Source=(localdb)\v11.0;AttachDbFilename=C:\Users\donca\Desktop\Memo\Memo\ContNou.mdf;Integrated Security=True");

SqlCommand cmd1 = new SqlCommand("SELECT * FROM [dbo].[Cont] WHERE Nume_utilizator = @Nume_utilizator and Parola = @Parola;", con);

cmd1.Parameters.AddWithValue("@Nume_utilizator", this.Nume_utilizator.Text);
cmd1.Parameters.AddWithValue("@Parola", this.Parola.Text);

cmd1.Connection = con;
con.Open();
</code>```

My question is: how can I change this to connect and access data from a SQL Server and save data there?

答:
Just change the connection string:
    "Data source=ServerName\InstanceName;"

You can use the IP address instead of the servername.
The default instance name is MSSQLSERVER.

Make sure you turn on "Remote connections" on the distant server. You can use Management studio -> Server properties -> connections -> Allow remote connections.

If it dosn't work check that the TCP/IP protocol is activated for you instance.

You can find it in SQl Server Configuration Manager.

Body:
My problem is that I have created a SQL Server database but I access it locally, only from my own computer. What I want to do is to connect the app to a server and to save all the data there.

The code I used to connect to the SQL Server database is:

SqlConnection con = new SqlConnection(@"Data Source=(localdb)\v11.0;AttachDbFilename=C:\Users\donca\Desktop\Memo\Memo\ContNou.mdf;Integrated Security=True");

SqlCommand cmd1 = new SqlCommand("SELECT * FROM [dbo].[Cont] WHERE Nume_utilizator = @Nume_utilizator and Parola = @Parola;", con);

cmd1.Parameters.AddWithValue("@Nume_utilizator", this.Nume_utilizator.Text);
cmd1.Parameters.AddWithValue("@Parola", this.Parola.Text);

cmd1.Connection = con;
con.Open();

My question is: how can I change this to connect and access data from a SQL Server and save data there?


问:
setting up monitoring for integration to external systems from Azure
I have created an Azure Web App which contains a method which brings a file from an external system by calling Soap service. How can I sett up a monitoring on this particular method?</p>

答:
We can use application insights to monitor our web application. We can do that with Azure portal or Visual Studio Tool, more details please refer to the document. Following is the snippet from the document.

Azure Application Insights monitors your live application to help you detect and diagnose performance issues and exceptions. It also helps you discover how your app is used. It works for the Web Apps feature of Azure App Service, as well as apps that are hosted on your own on-premises IIS servers, or on cloud VMs.

We can easily do that with our Azure portal, detail steps are as blow:

Step 1:  Navigate to your Web app in the Azure portal.

Step 2:  Select Application Insights in the Monitoring blade for the service.

Step 3:  Select Create new resource and enter the name.

Step 4:  Select OK

I test with Asp.net MVC project on the azure. The following is my detail steps.

Step 1: Add the Application Insights SDK

Step 2: Update about method and run my app with F5

Step 3: execute the method

Step 4: Check operation details from portal.


答:
You just have to change your connection string. That's all. For an example, if your server name is CORP and the SQL instance name is SQL2012, your connection string will be like this. </p>

```<code>SqlConnection con = new SqlConnection(@"Data Source=CORP\SQL2012;Initial Catalog=ContNou;Integrated Security=True");
</code>```

<p>In case if you cannot find the SQL server by its name, you can use the IP too. </p>

```<code>SqlConnection con = new SqlConnection(@"Data Source=10.4.2.208;Initial Catalog=ContNou;Integrated Security=True");
</code>```

Title: How to connect an application to a SQL Server using IP Adress in C#?

Body:
You just have to change your connection string. That's all. For an example, if your server name is CORP and the SQL instance name is SQL2012, your connection string will be like this.

SqlConnection con = new SqlConnection(@"Data Source=CORP\SQL2012;Initial Catalog=ContNou;Integrated Security=True");

In case if you cannot find the SQL server by its name, you can use the IP too.

SqlConnection con = new SqlConnection(@"Data Source=10.4.2.208;Initial Catalog=ContNou;Integrated Security=True");


问:
spring mvc 3 No mapping found for HTTP request with URI
Error info: No mapping found for HTTP request with URI [/TestSpringWebApp/hello.htm]

Any help would be greatly appreciated!

I am using annotation to map request to controller.
controller code :

```<code>@Controller
@RequestMapping("/hello.htm")
public class HelloController  {
    protected final Log logger = LogFactory.getLog(getClass());

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String now = (new Date()).toString();

        logger.info("Returning hello view with " + now);

        return new ModelAndView("hello", "now", now);
    }
}
</code>```

Dispatcher-servlet.xml as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans ...>

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">indexController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <!--
    The index controller.
    -->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />
   <!-- <bean name="/hello.htm" class="com.kibboko.poprocks.web.HelloController"/>-->
</beans>
</code>```

applicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans ...>

    <!--bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="/WEB-INF/jdbc.properties" />

    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource"
          p:driverClassName="${jdbc.driverClassName}"
          p:url="${jdbc.url}"
          p:username="${jdbc.username}"
          p:password="${jdbc.password}" /-->

    <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->

</beans>

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans ...>

    <!--bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="/WEB-INF/jdbc.properties" />

    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource"
          p:driverClassName="${jdbc.driverClassName}"
          p:url="${jdbc.url}"
          p:username="${jdbc.username}"
          p:password="${jdbc.password}" /-->

    <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->

</beans>
</code>```

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>
</code>```

答:
You also need to add

<mvc:annotation-driven />

to your Dispatcher-servlet.xml file.

Body:
Error info: No mapping found for HTTP request with URI [/TestSpringWebApp/hello.htm]

Any help would be greatly appreciated!

I am using annotation to map request to controller.
controller code :

@Controller
@RequestMapping("/hello.htm")
public class HelloController  {
    protected final Log logger = LogFactory.getLog(getClass());

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String now = (new Date()).toString();

        logger.info("Returning hello view with " + now);

        return new ModelAndView("hello", "now", now);
    }
}

Dispatcher-servlet.xml as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans ...>

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">indexController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />

</beans>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans ...>

</beans>

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans ...>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>


问:
How to add a button in the heading next to php echo string
i am trying to add a button to the heading, but i cant figure that out.
It now looks this way:

The button should be at the light grey part at the right side of the "name". The code i am having now is:

```<code><div class="panel panel-default bg-white nopadding">
          <div class="panel-heading">
            <div class="col-md-4">
                <h3 class="text-uppercase text-faded">
                <?php echo $info['c_name'];?>
                </h3>
            </div>
            <div class="col-md-4">
                <div class="input-group">
                    <div id="addcinfo" class="btn btn-success" name="search1">Redigera</div>
                </div>
            </div>
          </div>
        </div>
</code>```

What do i am doing wrong?

The webpage is: http://109.74.0.128/~sarath/admin
username: Jonathan@inkhousemedia.se
pw: John@123

Go on "Kund" and search for saurav and you will see the error

答:
Use below code: </p>

```<code><div class="panel panel-default bg-white nopadding">
   <div class="panel-heading">
      <h3 class="text-uppercase text-faded" style="float: left;"><?php echo $info['c_name'];?></h3>
        <div class="input-group" style="padding: 5px 0 5px 20px">
          <div name="search1" class="btn btn-success" id="addcinfo" >Redigera</div>
        </div>
   </div>
</div>
</code>```

Body:
i am trying to add a button to the heading, but i cant figure that out.
It now looks this way:

The button should be at the light grey part at the right side of the "name". The code i am having now is:

                <?php echo $info['c_name'];?>

Redigera

What do i am doing wrong?

The webpage is: http://109.74.0.128/~sarath/admin
username: Jonathan@inkhousemedia.se
pw: John@123

Go on "Kund" and search for saurav and you will see the error

Body:
Use below code:

<div class="panel panel-default bg-white nopadding">
   <div class="panel-heading">
      <h3 class="text-uppercase text-faded" style="float: left;"><?php echo $info['c_name'];?></h3>
        <div class="input-group" style="padding: 5px 0 5px 20px">
          <div name="search1" class="btn btn-success" id="addcinfo" >Redigera</div>
        </div>
   </div>
</div>


问:
Invalid identifier when I query in my table
In my table ALI_LEASE_IN, I have a DEF14 field, (sorry about the red frame, choose to DEF16), you can see in my snapshot.

But when I execute the query sql:

```<code>select b.equip_name a2,b.model b3,b.def2 c4,b.def3 d5,
  ALI_LEASE_IN.DEF14 as e6,
  '' f7,
  To_char(b.pre_rent) h9,
  b.start_date k10,
  sup.name j11,
  org.name l12,
  b.memo o13,
  h.bill_date bdate,
  h.pk_group
from ali_lease_in_b b,ali_lease_in h,bd_supplier sup,org_itemorg org
where b.pk_lease_in=h.pk_lease_in
  and h.pk_supplier=sup.pk_supplier
  and b.pk_org=org.pk_itemorg
</code>```

But I got this error below:

```<code>[SQL]select b.equip_name a2,b.model b3,b.def2 c4,b.def3 d5,
ALI_LEASE_IN.DEF14 as e6,
'' f7,
To_char(b.pre_rent) h9,b.start_date k10,sup.name j11,org.name l12, b.memo o13,h.bill_date bdate,h.pk_group
from ali_lease_in_b b,ali_lease_in h,bd_supplier sup,org_itemorg org
where b.pk_lease_in=h.pk_lease_in
and h.pk_supplier=sup.pk_supplier
and b.pk_org=org.pk_itemorg
--and h.pk_org in (parameter('param3'))
                   --     and substr(h.bill_date,1,10) >= parameter('param1')
                    --    and substr(h.bill_date,1,10) <= parameter('param2')
[Err] ORA-00904: "ALI_LEASE_IN"."DEF14": invalid identifier
</code>```

I don't know why, my snapshot shows the DEF14 is exsits in my table.

My environment is :

database is Oracle,
visual software is navicat.

答:
I see your code:

```<code>from ali_lease_in_b b,ali_lease_in h,bd_supplier sup,org_itemorg org
</code>```

this line you get the table ali_lease_in a alias h.

So you should use alias, change the line:

```<code>ALI_LEASE_IN.DEF14 as e6,
</code>```

to :

```<code>h.DEF14 as e6
</code>```

Body:
In my table ALI_LEASE_IN, I have a DEF14 field, (sorry about the red frame, choose to DEF16), you can see in my snapshot.

But when I execute the query sql:

select b.equip_name a2,b.model b3,b.def2 c4,b.def3 d5,
  ALI_LEASE_IN.DEF14 as e6,
  '' f7,
  To_char(b.pre_rent) h9,
  b.start_date k10,
  sup.name j11,
  org.name l12,
  b.memo o13,
  h.bill_date bdate,
  h.pk_group
from ali_lease_in_b b,ali_lease_in h,bd_supplier sup,org_itemorg org
where b.pk_lease_in=h.pk_lease_in
  and h.pk_supplier=sup.pk_supplier
  and b.pk_org=org.pk_itemorg

But I got this error below:

[SQL]select b.equip_name a2,b.model b3,b.def2 c4,b.def3 d5,
ALI_LEASE_IN.DEF14 as e6,
'' f7,
To_char(b.pre_rent) h9,b.start_date k10,sup.name j11,org.name l12, b.memo o13,h.bill_date bdate,h.pk_group
from ali_lease_in_b b,ali_lease_in h,bd_supplier sup,org_itemorg org
where b.pk_lease_in=h.pk_lease_in
and h.pk_supplier=sup.pk_supplier
and b.pk_org=org.pk_itemorg
--and h.pk_org in (parameter('param3'))
                   --     and substr(h.bill_date,1,10) >= parameter('param1')
                    --    and substr(h.bill_date,1,10) <= parameter('param2')
[Err] ORA-00904: "ALI_LEASE_IN"."DEF14": invalid identifier

I don't know why, my snapshot shows the DEF14 is exsits in my table.

My environment is :

database is Oracle,
visual software is navicat.

Body:
I see your code:

from ali_lease_in_b b,ali_lease_in h,bd_supplier sup,org_itemorg org

this line you get the table ali_lease_in a alias h.

So you should use alias, change the line:

ALI_LEASE_IN.DEF14 as e6,

to :

h.DEF14 as e6


问:
Is html title attribute a toolip?
I have question to know the truth. can some one tell me is HTML title attribute a tool tip.
Someone told me it is not a tooltip.
Can anybody describe what is a tool tip?
and HTML title is it or not?
I need the truth pleas.

答:
Html title attribute is not a tool tip. But browsers can display it as a tooltip.

The problem with this is that you no longer control what your website shows. You will depend on whether the browser wants to show it or not.
A tooltip is programmed so you can control the operation, and you can change it, add events, etc ...

Title: Is html title attribute a toolip?


问:
Set new value on attributes in a namespace
I have this xml (it is a part of a more extended one) that I'm parsing using python and lxml

```<code><om:OM_Observation gml:id="observation">
 <gml:description>Wind Speed</gml:description>
 <om:phenomenonTime xlink:href="#phenomenonTime"/>
 <om:resultTime xlink:href="#phenomenonTime"/>
 <om:procedure xlink:href="procedure"/>
 <om:observedProperty xlink:href="WS_5min_avg"/>
 <om:featureOfInterest xlink:href="#FOI"/>
 <om:result xsi:type="gml:MeasureType" uom="m/s">568</om:result>
</om:OM_Observation>
</code>```

I'm able to get the text value within the tags and change its value and update the file data.xml:

```<code>from lxml import etree
data='data.xml'
data_tree = etree.parse(data)
root = data_tree.getroot()
nsmap = {'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xlink': 'http://www.w3.org/1999/xlink',  'gml': 'http://www.opengis.net/gml/3.2',  'om': 'http://www.opengis.net/om/2.0'}

result=data_tree.xpath("//om:OM_Observation/om:result", namespaces=nsmap)
result[0].text="114"
etree.ElementTree(root).write(data, xml_declaration=True, encoding='utf-8', method="xml", pretty_print=True)
</code>```

What I would like to do is to change the value of the attribute and update the xml file.
I'm trying a similar approach but it is not working. I'm able to get the value of the attribute:

```<code> featureOfInterest_attr=tree.xpath("//om:featureOfInterest/@xlink:href", namespaces=nsmap)
</code>```

but if I would like to change its value using:

```<code>tree.xpath("//om:featureOfInterest/@xlink:href",namespaces=nsmap)="#newFOI"
etree.ElementTree(root).write(data, xml_declaration=True,encoding='utf-8', method='xml', pretty_print=True)
</code>```

the new value is not inserted.
What I'm doing wrong?

答:
Your last code snippet has a crucial difference from your successful code. xpath() returns list, so you have to specify which item in the list need to be updated by using index :

```<code>result = tree.xpath("//om:featureOfInterest/@xlink:href",namespaces=nsmap)
result[0] = "#newFOI"
# or
# tree.xpath("//om:featureOfInterest/@xlink:href",namespaces=nsmap)[0] = "#newFOI"
</code>```

Apparently, we can't update attributes that was directly selected using xpath(), since the return value is just a list of string. So in this case result[0] = ... only update value of the first item of the list and doesn't affect the source XML tree at all. We need to get the parent of the attribute instead and then update from there :

```<code>result = tree.xpath("//om:featureOfInterest",namespaces=nsmap)
result[0].attrib['{%s}href' % nsmap['xlink']] = "#newFOI"
</code>```

Body:
I have this xml (it is a part of a more extended one) that I'm parsing using python and lxml

<om:OM_Observation gml:id="observation">
 <gml:description>Wind Speed</gml:description>
 <om:phenomenonTime xlink:href="#phenomenonTime"/>
 <om:resultTime xlink:href="#phenomenonTime"/>
 <om:procedure xlink:href="procedure"/>
 <om:observedProperty xlink:href="WS_5min_avg"/>
 <om:featureOfInterest xlink:href="#FOI"/>
 <om:result xsi:type="gml:MeasureType" uom="m/s">568</om:result>
</om:OM_Observation>

I'm able to get the text value within the tags and change its value and update the file data.xml:

from lxml import etree
data='data.xml'
data_tree = etree.parse(data)
root = data_tree.getroot()
nsmap = {'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xlink': 'http://www.w3.org/1999/xlink',  'gml': 'http://www.opengis.net/gml/3.2',  'om': 'http://www.opengis.net/om/2.0'}

result=data_tree.xpath("//om:OM_Observation/om:result", namespaces=nsmap)
result[0].text="114"
etree.ElementTree(root).write(data, xml_declaration=True, encoding='utf-8', method="xml", pretty_print=True)

What I would like to do is to change the value of the attribute and update the xml file.
I'm trying a similar approach but it is not working. I'm able to get the value of the attribute:

 featureOfInterest_attr=tree.xpath("//om:featureOfInterest/@xlink:href", namespaces=nsmap)

but if I would like to change its value using:

tree.xpath("//om:featureOfInterest/@xlink:href",namespaces=nsmap)="#newFOI"
etree.ElementTree(root).write(data, xml_declaration=True,encoding='utf-8', method='xml', pretty_print=True)

the new value is not inserted.
What I'm doing wrong?

Body:
Your last code snippet has a crucial difference from your successful code. xpath() returns list, so you have to specify which item in the list need to be updated by using index :

result = tree.xpath("//om:featureOfInterest/@xlink:href",namespaces=nsmap)
result[0] = "#newFOI"
# or
# tree.xpath("//om:featureOfInterest/@xlink:href",namespaces=nsmap)[0] = "#newFOI"

Apparently, we can't update attributes that was directly selected using xpath(), since the return value is just a list of string. So in this case result[0] = ... only update value of the first item of the list and doesn't affect the source XML tree at all. We need to get the parent of the attribute instead and then update from there :

result = tree.xpath("//om:featureOfInterest",namespaces=nsmap)
result[0].attrib['{%s}href' % nsmap['xlink']] = "#newFOI"


问:
Using DataFrame.plot to make a chart with subplots -- how to use ax parameter
I can not wrap my head around axes parameter, what it contains and how to use it for making subplots.

Would really appreciate if someone could explain what is going on in the following example

```<code>fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(15, 10))
for idx, feature in enumerate(df.columns[:-1]):
  df.plot(feature, "cnt", subplots=True, kind="scatter", ax=axes[idx / 4, idx % 4])
</code>```

Here is the data (UCI Bike sharing dataset):

Here is the output of the code snippet (a pairwise comparison of features and the end results):

To be more specific, here are the parts that I do understand (at least I think I do)

plt.subplots returns a tuple containing a figure and axes object(s) (link)

enumerate() returns a tuple containing index of a feature and its name(link)

df.plot uses column names to put data on subplots within  fig

Here is what I do not understand

What does axes object contain? Again, based on documentation and this answer I do realize that axes contains "Axis, Tick, Line2D, Text, Polygon, etc." but

what do we address using axes[x,y] ?

why in this example author decided to use [idx / 4, idx % 4] as values?

答:
Concerning the last question about the array indexing as [idx / 4, idx % 4]:

The idea is to loop over all subplots and all dataframe columns at the same time. The problem is that the axes array is two-dimensional while the column array is one-dimensional. One therefore needs to decide over which of those to loop and map the loop index/indizes to the other dimension.

An intuitive way would be to use two loops

```<code>for i in range(axes.shape[0]):
    for j in range(axes.shape[1]):
        df.plot(df.columns[i*axes.shape[0]+j], "cnt", ... , ax=axes[i,j])
</code>```

Here, i*axes.shape[0]+j maps the two dimension of the numpy array to the single dimension of the columns list.

In the example from the question, the loop is over the columns, which means we have to somehow map the one-dimensional index to two dimensions. This is what [idx / 4, idx % 4] does.. or should do. It will only work in python 2. To make it more comprehensible and version save, one should actually use [idx // 4, idx % 4]. The // makes it clear that an integer division is used. So for the first 4 idx values (0,1,2,3), idx // 4 is 0, for the next set of 4 values it's 1 and so on. idx % 4 calculates the index modulo 4. So (0,1,2,3) are mapped to (0,1,2,3), and then (4,5,6,7) are mapped to (0,1,2,3) again, etc.

An alternative solution using a single loop would be to flatten the axes array:

```<code>for idx, feature in enumerate(df.columns[:-1]):
    df.plot(feature, "cnt", ... , ax=axes.flatten()[idx])
</code>```

or maybe most pythonic

```<code>for ax, feature in zip(axes.flatten(), df.columns[:-1]):
    df.plot(feature, "cnt", ... , ax=ax)
</code>```

Body:
I can not wrap my head around axes parameter, what it contains and how to use it for making subplots.

Would really appreciate if someone could explain what is going on in the following example

fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(15, 10))
for idx, feature in enumerate(df.columns[:-1]):
  df.plot(feature, "cnt", subplots=True, kind="scatter", ax=axes[idx / 4, idx % 4])

Here is the data (UCI Bike sharing dataset):

Here is the output of the code snippet (a pairwise comparison of features and the end results):

To be more specific, here are the parts that I do understand (at least I think I do)

plt.subplots returns a tuple containing a figure and axes object(s) (link)

enumerate() returns a tuple containing index of a feature and its name(link)

df.plot uses column names to put data on subplots within  fig

Here is what I do not understand

What does axes object contain? Again, based on documentation and this answer I do realize that axes contains "Axis, Tick, Line2D, Text, Polygon, etc." but

what do we address using axes[x,y] ?

why in this example author decided to use [idx / 4, idx % 4] as values?

Body:
Concerning the last question about the array indexing as [idx / 4, idx % 4]:

The idea is to loop over all subplots and all dataframe columns at the same time. The problem is that the axes array is two-dimensional while the column array is one-dimensional. One therefore needs to decide over which of those to loop and map the loop index/indizes to the other dimension.

An intuitive way would be to use two loops

for i in range(axes.shape[0]):
    for j in range(axes.shape[1]):
        df.plot(df.columns[i*axes.shape[0]+j], "cnt", ... , ax=axes[i,j])

Here, i*axes.shape[0]+j maps the two dimension of the numpy array to the single dimension of the columns list.

In the example from the question, the loop is over the columns, which means we have to somehow map the one-dimensional index to two dimensions. This is what [idx / 4, idx % 4] does.. or should do. It will only work in python 2. To make it more comprehensible and version save, one should actually use [idx // 4, idx % 4]. The // makes it clear that an integer division is used. So for the first 4 idx values (0,1,2,3), idx // 4 is 0, for the next set of 4 values it's 1 and so on. idx % 4 calculates the index modulo 4. So (0,1,2,3) are mapped to (0,1,2,3), and then (4,5,6,7) are mapped to (0,1,2,3) again, etc.

An alternative solution using a single loop would be to flatten the axes array:

for idx, feature in enumerate(df.columns[:-1]):
    df.plot(feature, "cnt", ... , ax=axes.flatten()[idx])

or maybe most pythonic

for ax, feature in zip(axes.flatten(), df.columns[:-1]):
    df.plot(feature, "cnt", ... , ax=ax)


问:
Protractor: Why cucumber steps shows as executed before the actual execution happened
I am new to protractor-cucumber. I am trying to execute below step definition from protractor conf.js.

```<code>this.Given(/^I go to sparqHomePage$/, function (callback) {

  homepage.goToHomePage()
  homepage.login(data[0].UserName,data[0].Password).then(callback);

});

this.Then(/^I create a process$/, function () {

  homepage.clickDesign();
  homepage.clickFlowDesigner();
  console.log(params.flow.procName + ' '+  params.flow.procDesc);
  designPage.createNewProc(params.flow.procName, params.flow.procDesc);

});

this.Then(/^I should see process is saved in db$/, function (callback) {

    var sql = "select * from process where name = ?";
    sql = mysql.format(sql, params.flow.procName);
    console.log(sql);

    dbConn.query(sql, function(err, rows, fields){

        if(!err) {
            procDbObj = rows;
            console.log(rows);
            expect(procDbObj[0].name).to.eventually.equal( params.flow.procName);
            expect(procDbObj[0].description).to.eventually.equal(params.flow.procDesc).and.notify(callback);
        }
    });
});
</code>```

As soon as I start the execution, the console log shows, feature file execution was completed, but the actual execution is not yet completed.

In my 3rd step I am doing some db validation based on the step 1 and step 2 actions. As cucumber trying to execute all the steps before the completion of real execution with browser, my 3rd test is always failing.

How can I make cucumber to wait for step execution is completed before moving to the next step.

答:
You are calling
homepage.goToHomePage() and homepage.login(data[0].UserName,data[0].Password).then(callback);. Are both methods correct promises that are correctly handled? It now looks like it is calling both methods but giving a direct callback before resolving the promise.

As Ross stated, you can also chain the promises, but first be sure the promises are correctly handled

Edit:

As Ross stated, you can also chain the promises, but first be sure the promises are correctly handled.

You can also return the promise in stead of the callback, just use it as this

```<code>this.Given(/^I go to sparqHomePage$/, function () {
  homepage.goToHomePage();
  return homepage.login(data[0].UserName,data[0].Password);
});
</code>```

Body:
I am new to protractor-cucumber. I am trying to execute below step definition from protractor conf.js.

this.Given(/^I go to sparqHomePage$/, function (callback) {

  homepage.goToHomePage()
  homepage.login(data[0].UserName,data[0].Password).then(callback);

});

this.Then(/^I create a process$/, function () {

  homepage.clickDesign();
  homepage.clickFlowDesigner();
  console.log(params.flow.procName + ' '+  params.flow.procDesc);
  designPage.createNewProc(params.flow.procName, params.flow.procDesc);

});

this.Then(/^I should see process is saved in db$/, function (callback) {

    var sql = "select * from process where name = ?";
    sql = mysql.format(sql, params.flow.procName);
    console.log(sql);

    dbConn.query(sql, function(err, rows, fields){

        if(!err) {
            procDbObj = rows;
            console.log(rows);
            expect(procDbObj[0].name).to.eventually.equal( params.flow.procName);
            expect(procDbObj[0].description).to.eventually.equal(params.flow.procDesc).and.notify(callback);
        }
    });
});

As soon as I start the execution, the console log shows, feature file execution was completed, but the actual execution is not yet completed.

In my 3rd step I am doing some db validation based on the step 1 and step 2 actions. As cucumber trying to execute all the steps before the completion of real execution with browser, my 3rd test is always failing.

How can I make cucumber to wait for step execution is completed before moving to the next step.

Body:
You are calling
homepage.goToHomePage() and homepage.login(data[0].UserName,data[0].Password).then(callback);. Are both methods correct promises that are correctly handled? It now looks like it is calling both methods but giving a direct callback before resolving the promise.

As Ross stated, you can also chain the promises, but first be sure the promises are correctly handled

Edit:

As Ross stated, you can also chain the promises, but first be sure the promises are correctly handled.

You can also return the promise in stead of the callback, just use it as this

this.Given(/^I go to sparqHomePage$/, function () {
  homepage.goToHomePage();
  return homepage.login(data[0].UserName,data[0].Password);
});


问:
Check if only certain values exist in a list (Python)
I have the following list:

```<code>A = [x,y,z]
</code>```

and I need help with writing a code in Python that returns True if any combination of x or y or z is in the list, but returns False if any other variables outside of A is in the list.

Example:

```<code>B = [x]  (return True)
B = [l] (return False)
B = [x,z] (return True)
B = [x,y,z,l] (return False)
</code>```

答:
```<code>def b(list_of_b):
    A = ['X', 'Y', 'Z']
    for i in list_of_b:
        if i in A:
            return True
    return False
print(b(['X','Y']))
</code>```

This may help Happy Coding

Body:
I have the following list:

A = [x,y,z]

and I need help with writing a code in Python that returns True if any combination of x or y or z is in the list, but returns False if any other variables outside of A is in the list.

Example:

B = [x]  (return True)
B = [l] (return False)
B = [x,z] (return True)
B = [x,y,z,l] (return False)

Body:
def b(list_of_b):
    A = ['X', 'Y', 'Z']
    for i in list_of_b:
        if i in A:
            return True
    return False
print(b(['X','Y']))

This may help Happy Coding


问:
WPF: change style of progressbar
How can I change the style of a progressbar in WPF?
On Windows 10 it's a straight bar, but in win 7 it's splitted in many small blocks. I want to have the bar straight as on win 10, when the application is used on win 7</p>

答: Progressbar has a property called Style, you could set it to your liking.</p>

Title: WPF: change style of progressbar


问:
Is is possible to hardcode Google API credentials into my Java application?
In the following documentation, there are named points 1-4 how to provide credentials to my application. All of them I dislike, because they are making my application environment dependent.

Is it possible to hardcode credentials into my application, like using some API key or something?

答:
You can add in your environement variable your API KEY:

```<code>export GOOGLE_API_KEY="xxxx"
</code>```

or the JSON containing your credentials:

```<code>export GOOGLE_APPLICATION_CREDENTIALS=/home/toto/tmp/project-name-123456789.json
</code>```

Body:
You can add in your environement variable your API KEY:

export GOOGLE_API_KEY="xxxx"

or the JSON containing your credentials:

export GOOGLE_APPLICATION_CREDENTIALS=/home/toto/tmp/project-name-123456789.json


问:
Django dropped table still exists
Having problems with a model in one of my django apps.

I can make an instance of the model, but when I go to access it, I get an error:

```<code># create and save model instance
user_form = UserSearchForm(user=user)
user_form.save()

# Then later
first_user_form = UserSearchForm.objects.all()[0]

(1146, "Table 'project.app_tablename' doesn't exist")
Request Method: GET
Request URL:    http://10.0.75.1:8000/search/
Django Version: 1.9.5
Exception Type: ProgrammingError
Exception Value:
(1146, "Table 'project.app_tablename' doesn't exist")
Exception Location: /opt/project-venv/lib/python3.4/site-packages/MySQLdb/connections.py in query, line 280
Python Executable:  /opt/project-venv/bin/python
Python Version: 3.4.3
Python Path:
['/opt/project/project',
 '/opt/project-venv/lib64/python34.zip',
 '/opt/project-venv/lib64/python3.4',
 '/opt/project-venv/lib64/python3.4/plat-linux',
 '/opt/project-venv/lib64/python3.4/lib-dynload',
 '/usr/lib64/python3.4',
 '/usr/lib/python3.4',
 '/opt/project-venv/lib/python3.4/site-packages']
Server time:    Tue, 28 Mar 2017 22:50:16 +0000
</code>```

I'm using Django 1.95 and I tried the following from the linked answer (https://stackoverflow.com/a/36565161/2516846):

Delete app migrations folder

Drop all app tables, e.g. DROP TABLE search_usersearchform

Delete all migrations from db: DELETE FROM django_migrations WHERE app = 'search'.

python manage.py makemigrations search

python manage.py migrate

But when I run migrate, it gives error:

```<code>django.db.utils.ProgrammingError: relation "search_usersearchform" already exists
</code>```

Summary: Cannot create model again as relation already exists, yet cannot access model in my app as it says table doesn't exist

Is there a reference to this table/model stored else where which I need to remove? I don't know how the relation can already exist if I dropped the table, deleted migrations folder and removed migrations from db

EDIT

Okay finally got this sorted.

My project had two databases, the 'default' db, using postgres, and the 'secondary' db, using mysql.

When I created a new model in my app, and ran the migration, the table was added to the default db.

This allowed me to create an instance of the new model.

However when I went to access a previously saved instance, I got the error saying the table does not exist.

Turns out it was caused by my apps router.py, which redirected any queries to the 'secondary' db, which of course did not have the table.

To fix this, I added conditionals to the db_for_write and db_for_read methods in  router.py, to route those models to the 'default' db.

答:
make a back up of the models.py, delete the model code from the original models.py, then run:

```<code>python manage.py makemigrations
python manage.py migrate
</code>```

Then simply restore the model code in models.py and run the above commands again.

Title: Django dropped table still exists

Body:
Having problems with a model in one of my django apps.

I can make an instance of the model, but when I go to access it, I get an error:

# create and save model instance
user_form = UserSearchForm(user=user)
user_form.save()

# Then later
first_user_form = UserSearchForm.objects.all()[0]

(1146, "Table 'project.app_tablename' doesn't exist")
Request Method: GET
Request URL:    http://10.0.75.1:8000/search/
Django Version: 1.9.5
Exception Type: ProgrammingError
Exception Value:
(1146, "Table 'project.app_tablename' doesn't exist")
Exception Location: /opt/project-venv/lib/python3.4/site-packages/MySQLdb/connections.py in query, line 280
Python Executable:  /opt/project-venv/bin/python
Python Version: 3.4.3
Python Path:
['/opt/project/project',
 '/opt/project-venv/lib64/python34.zip',
 '/opt/project-venv/lib64/python3.4',
 '/opt/project-venv/lib64/python3.4/plat-linux',
 '/opt/project-venv/lib64/python3.4/lib-dynload',
 '/usr/lib64/python3.4',
 '/usr/lib/python3.4',
 '/opt/project-venv/lib/python3.4/site-packages']
Server time:    Tue, 28 Mar 2017 22:50:16 +0000

I'm using Django 1.95 and I tried the following from the linked answer (https://stackoverflow.com/a/36565161/2516846):

Delete app migrations folder

Drop all app tables, e.g. DROP TABLE search_usersearchform

Delete all migrations from db: DELETE FROM django_migrations WHERE app = 'search'.

python manage.py makemigrations search

python manage.py migrate

But when I run migrate, it gives error:

django.db.utils.ProgrammingError: relation "search_usersearchform" already exists

Summary: Cannot create model again as relation already exists, yet cannot access model in my app as it says table doesn't exist

Is there a reference to this table/model stored else where which I need to remove? I don't know how the relation can already exist if I dropped the table, deleted migrations folder and removed migrations from db

EDIT

Okay finally got this sorted.

My project had two databases, the 'default' db, using postgres, and the 'secondary' db, using mysql.

When I created a new model in my app, and ran the migration, the table was added to the default db.

This allowed me to create an instance of the new model.

However when I went to access a previously saved instance, I got the error saying the table does not exist.

Turns out it was caused by my apps router.py, which redirected any queries to the 'secondary' db, which of course did not have the table.

To fix this, I added conditionals to the db_for_write and db_for_read methods in  router.py, to route those models to the 'default' db.

Body:
make a back up of the models.py, delete the model code from the original models.py, then run:

python manage.py makemigrations
python manage.py migrate

Then simply restore the model code in models.py and run the above commands again.


问:
Bash/Linux if elif else issue
Currently working on my bash skills. I've done a few activites based on if/elif/else given to me to my tutor but can't put my finger on the one below.

Basically I'm tasked with outputting the following based on the input of a grade.
 Less than 40% = Fail 40% to 59% = Pass 60% to 69% = Merit 70% and above = Distinction

It seems to get caught on the first elif, presents the grade as merit for anything below 70 and doesn't check the others, it gives the same result when I change the order too.

```<code>echo "Please enter your grade"
read GRADE
echo

     if [ $GRADE -ge 70 ]; then
         echo "Well done, you got a distinction"

    elif [ $GRADE -ge 60 ] || [ $GRADE -le 69 ]; then
          echo "Well done, you got a merit"
    elif [ $GRADE -ge 40 ] || [ $GRADE -le 59 ]; then
          echo "Well done, you got a pass"
    else
          echo "Unfortunately you failed"
      fi
</code>```

答:
your problem came from the || (or), you need to use && (and). For exemple 65 is greater than 60 AND lesser than 69.</p>

```<code>echo "Please enter your grade"
read GRADE
echo

 if [ $GRADE -ge 70 ]; then
     echo "Well done, you got a distinction"

elif [ $GRADE -ge 60 ] && [ $GRADE -le 69 ]; then
      echo "Well done, you got a merit"
elif [ $GRADE -ge 40 ] && [ $GRADE -le 59 ]; then
      echo "Well done, you got a pass"
else
      echo "Unfortunately you failed"
  fi
</code>```

Title: Bash/Linux if elif else issue

Body:
Currently working on my bash skills. I've done a few activites based on if/elif/else given to me to my tutor but can't put my finger on the one below.

Basically I'm tasked with outputting the following based on the input of a grade.
 Less than 40% = Fail 40% to 59% = Pass 60% to 69% = Merit 70% and above = Distinction

It seems to get caught on the first elif, presents the grade as merit for anything below 70 and doesn't check the others, it gives the same result when I change the order too.

echo "Please enter your grade"
read GRADE
echo

     if [ $GRADE -ge 70 ]; then
         echo "Well done, you got a distinction"

    elif [ $GRADE -ge 60 ] || [ $GRADE -le 69 ]; then
          echo "Well done, you got a merit"
    elif [ $GRADE -ge 40 ] || [ $GRADE -le 59 ]; then
          echo "Well done, you got a pass"
    else
          echo "Unfortunately you failed"
      fi

Body:
your problem came from the || (or), you need to use && (and). For exemple 65 is greater than 60 AND lesser than 69.

echo "Please enter your grade"
read GRADE
echo

 if [ $GRADE -ge 70 ]; then
     echo "Well done, you got a distinction"

elif [ $GRADE -ge 60 ] && [ $GRADE -le 69 ]; then
      echo "Well done, you got a merit"
elif [ $GRADE -ge 40 ] && [ $GRADE -le 59 ]; then
      echo "Well done, you got a pass"
else
      echo "Unfortunately you failed"
  fi


问:
Why my _getch() is not working correctly?
Firstly sorry for my English.
I was trying to make a console game. At the end of the game I wanted to let user choose to continue game or not by selecting yes or no by using arrow keys on keyboard. But it working weirdly right now.  When I pressed the arrow key, the cursor should move but it does it only for a bit and back to selecting "yes". I just really couldn't figure out what is going on here so I wanted to ask somebody who know why is this happening. Please teach me what am I doing wrong.
Thank you.

```<code>void askForRestart() {
bool yesOrNo = true;

system("cls");
cout << "You died." << endl;
cout << "Restart?" << endl;
cout << "> YES" << endl << "  NO";
while (true) {
    int arrowKeycode = 0;

    switch (arrowKeycode = _getch()) {
    case KEY_ENTER:
        break;
    default:
        if (yesOrNo) {
            yesOrNo = false;
            system("cls");
            cout << "You died." << endl;
            cout << "Restart?" << endl;
            cout << "  YES" << endl << "> NO";
            break;
        }
        else {
            yesOrNo = true;
            system("cls");
            cout << "You died." << endl;
            cout << "Restart?" << endl;
            cout << "> YES" << endl << "  NO";
            break;
        }

    }
    cin.clear();
    //cin.ignore(10000, '\n');
}
</code>```

}

答:
Because this is how it works. For ordinary character keys (numeric, alphabetic) it returns the key code. But if you tap arrow or functional key, _getch returns 0, which indicates that you must call _getch again to obtain the actual key code.

MSDN:

When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code.

So you should change your key reading procedure.

Body:
Firstly sorry for my English.
I was trying to make a console game. At the end of the game I wanted to let user choose to continue game or not by selecting yes or no by using arrow keys on keyboard. But it working weirdly right now.  When I pressed the arrow key, the cursor should move but it does it only for a bit and back to selecting "yes". I just really couldn't figure out what is going on here so I wanted to ask somebody who know why is this happening. Please teach me what am I doing wrong.
Thank you.

void askForRestart() {
bool yesOrNo = true;

system("cls");
cout << "You died." << endl;
cout << "Restart?" << endl;
cout << "> YES" << endl << "  NO";
while (true) {
    int arrowKeycode = 0;

    switch (arrowKeycode = _getch()) {
    case KEY_ENTER:
        break;
    default:
        if (yesOrNo) {
            yesOrNo = false;
            system("cls");
            cout << "You died." << endl;
            cout << "Restart?" << endl;
            cout << "  YES" << endl << "> NO";
            break;
        }
        else {
            yesOrNo = true;
            system("cls");
            cout << "You died." << endl;
            cout << "Restart?" << endl;
            cout << "> YES" << endl << "  NO";
            break;
        }

    }
    cin.clear();
    //cin.ignore(10000, '\n');
}

}


问:
Display none at the end of animation
I'm trying to make element dissapear at the end of animation but it doesn't work, can someone explain how to make exit animation with element dissappearing at the end of it?:

```<code>var test = document.getElementById("test");
test.addEventListener("click", displayOpacity);

function displayOpacity(event){
    event.target.style.animation = "changeOpacity 1s linear";
    if(event.target.style.opacity === 0){
        event.target.style.display = "none";
    }
}
</code>```

.container .test {
  text-align: center;
  padding: 100px;
  color: #fff;
  background-color: #00f;
  max-width: 500px;
  -webkit-animation-fill-mode: forwards;
          animation-fill-mode: forwards;
}

@-webkit-keyframes changeOpacity {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
@keyframes changeOpacity {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

Custom Text

```

答:
The animation time is 1 second

```<code>event.target.style.animation = "changeOpacity 1s linear";
</code>```

so just make a timeout

```<code>setTimeout(function(){
    event.target.style.display = "none";
},1000)
</code>```

Title: Display none at the end of animation

Body:
I'm trying to make element dissapear at the end of animation but it doesn't work, can someone explain how to make exit animation with element dissappearing at the end of it?:

var test = document.getElementById("test");
test.addEventListener("click", displayOpacity);

function displayOpacity(event){
    event.target.style.animation = "changeOpacity 1s linear";
    if(event.target.style.opacity === 0){
        event.target.style.display = "none";
    }
}

.container .test {
  text-align: center;
  padding: 100px;
  color: #fff;
  background-color: #00f;
  max-width: 500px;
  -webkit-animation-fill-mode: forwards;
          animation-fill-mode: forwards;
}

@-webkit-keyframes changeOpacity {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
@keyframes changeOpacity {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

Custom Text

Body:
The animation time is 1 second

event.target.style.animation = "changeOpacity 1s linear";

so just make a timeout

setTimeout(function(){
    event.target.style.display = "none";
},1000)


答:
Your issue is because the animation-fill-mode is not being respected as you're overwriting it by setting the animation rule directly on the element itself.

To fix this change your JS code to add a class on the element, and put the animation rule in there, along with the required fill mode:

var test = document.getElementById("test");
test.addEventListener("click", displayOpacity);

function displayOpacity(event) {
    this.classList.add('changeOpacity');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container .test {
    text-align: center;
    padding: 100px;
    color: #fff;
    background-color: #00f;
    max-width: 500px;
}

.changeOpacity {
    animation: changeOpacity 1s linear forwards;
}

@-webkit-keyframes changeOpacity {
    0% {  opacity: 1; }
    100% { opacity: 0; }
}
@-webkit-keyframes changeOpacity {
    0% {  opacity: 1; }
    100% { opacity: 0; }
}
@keyframes changeOpacity {
    0% {  opacity: 1; }
    100% { opacity: 0; }
}</code>```

        Test

```

Title: Display none at the end of animation

Body:
Your issue is because the animation-fill-mode is not being respected as you're overwriting it by setting the animation rule directly on the element itself.

To fix this change your JS code to add a class on the element, and put the animation rule in there, along with the required fill mode:

var test = document.getElementById("test");
test.addEventListener("click", displayOpacity);

function displayOpacity(event) {
    this.classList.add('changeOpacity');
}

.container .test {
    text-align: center;
    padding: 100px;
    color: #fff;
    background-color: #00f;
    max-width: 500px;
}

.changeOpacity {
    animation: changeOpacity 1s linear forwards;
}

@-webkit-keyframes changeOpacity {
    0% {  opacity: 1; }
    100% { opacity: 0; }
}
@-webkit-keyframes changeOpacity {
    0% {  opacity: 1; }
    100% { opacity: 0; }
}
@keyframes changeOpacity {
    0% {  opacity: 1; }
    100% { opacity: 0; }
}

<div class="container">
    <div id="test" class="test">
        Test
    </div>
</div>


问:
how to get from row col notation to A1 notation in xlsxwriter add_series()
I'm not clueless on how to convert row col to A1 notation and use it in add_series() method for charts in XlsxWriter.

Please find below code for reference :

```<code> print "Drawing Simultaneous Busy Cores"
    writer.targetWrite('simultaneous_busy_cores', 'weighted_average', *write_data)
    row = writer.getRow('simultaneous_busy_cores')
    str1_cat = xl_rowcol_to_cell(6, 1, row_abs=True, col_abs=True)
    str2_cat = xl_rowcol_to_cell(6, 8, row_abs=True, col_abs=True)
    str1_val = xl_rowcol_to_cell(row-1, 1, row_abs=True, col_abs=True)
    str2_val = xl_rowcol_to_cell(row-1, 8, row_abs=True, col_abs=True)
    print str1_cat
    print str2_cat
    print str1_val
    print str2_val
    dict_series = {
             'name':       'simultaneous_busy_cores',
             'categories': '=simultaneous_busy_cores!str1_cat:str2_cat',
             'values':     '=simultaneous_busy_cores!str1_val:str2_val',
             'data_labels': {'percentage': True, }
             }
    chart1.add_series(dict_series)
    chart1.set_title({'name': 'simultaneous_busy_cores'})
    chart1.set_style(10)
    target_sheet.insert_chart('K2', chart1, {'x_offset': 25, 'y_offset': 10})
</code>```

Values for str_cat and str_val are :

```<code>Drawing Simultaneous Busy Cores
$B$7
$I$7
$B$24
$I$24
</code>```

Any help is appreciated TIA!

答:
To answer the direct question, you could use string.format() or % to insert the variable values into the string:

```<code>'=simultaneous_busy_cores!%s:%s' % (str1_cat, str2_cat),
</code>```

However, that is more work than is necessary since XlsxWriter already supports a list syntax for categories and values:

```<code>dict_series = {
    'name':       'simultaneous_busy_cores',
    'categories': ['simultaneous_busy_cores', 6, 1, 6, 8],
    'values':     ['simultaneous_busy_cores', row-1, 1, row-1],
    'data_labels': {'percentage': True, }
}
</code>```

See the documentation on add_series() for more details.

Body:
I'm not clueless on how to convert row col to A1 notation and use it in add_series() method for charts in XlsxWriter.

Please find below code for reference :

 print "Drawing Simultaneous Busy Cores"
    writer.targetWrite('simultaneous_busy_cores', 'weighted_average', *write_data)
    row = writer.getRow('simultaneous_busy_cores')
    str1_cat = xl_rowcol_to_cell(6, 1, row_abs=True, col_abs=True)
    str2_cat = xl_rowcol_to_cell(6, 8, row_abs=True, col_abs=True)
    str1_val = xl_rowcol_to_cell(row-1, 1, row_abs=True, col_abs=True)
    str2_val = xl_rowcol_to_cell(row-1, 8, row_abs=True, col_abs=True)
    print str1_cat
    print str2_cat
    print str1_val
    print str2_val
    dict_series = {
             'name':       'simultaneous_busy_cores',
             'categories': '=simultaneous_busy_cores!str1_cat:str2_cat',
             'values':     '=simultaneous_busy_cores!str1_val:str2_val',
             'data_labels': {'percentage': True, }
             }
    chart1.add_series(dict_series)
    chart1.set_title({'name': 'simultaneous_busy_cores'})
    chart1.set_style(10)
    target_sheet.insert_chart('K2', chart1, {'x_offset': 25, 'y_offset': 10})

Values for str_cat and str_val are :

Drawing Simultaneous Busy Cores
$B$7
$I$7
$B$24
$I$24

Any help is appreciated TIA!

Body:
To answer the direct question, you could use string.format() or % to insert the variable values into the string:

'=simultaneous_busy_cores!%s:%s' % (str1_cat, str2_cat),

However, that is more work than is necessary since XlsxWriter already supports a list syntax for categories and values:

dict_series = {
    'name':       'simultaneous_busy_cores',
    'categories': ['simultaneous_busy_cores', 6, 1, 6, 8],
    'values':     ['simultaneous_busy_cores', row-1, 1, row-1],
    'data_labels': {'percentage': True, }
}

See the documentation on add_series() for more details.