问:
Cannot read usernames from file
I am trying to implement a registration panel with username password and email only. I put all the usernames and passwords in a text file "usernames.txt". But my problem is not working properly if user clicks the submit button and the username already exists nothing happens( it should display JOptionPane with text "Username already exists!" ). here is my code :

```<code>submitButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader("usernames.txt"));
            } catch (FileNotFoundException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            try {
                String line = br.readLine();
                StringBuilder sb = new StringBuilder();
                Pattern usernameAndPasswordPattern = Pattern.compile("^(\\S+) (\\S+)$");
                while (line != null) {
                    sb.append(line); //
                    sb.append(System.lineSeparator()); //
                    line = br.readLine();
                }
                String everything = sb.toString();
                Matcher userNameAndPasswordMatcher = usernameAndPasswordPattern.matcher(everything);

                //if username exists!
                while (userNameAndPasswordMatcher.matches()) {
                    String username = userNameAndPasswordMatcher.group(1);
                    String password = userNameAndPasswordMatcher.group(2);

                    if (username.equals(usernameTextField.getText())) {
                        int result = JOptionPane.showConfirmDialog(null, "Username already exists!", "Registration incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                    }
                }

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } finally {
                try {
                    br.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    });
</code>```

Here you can see a pic from my panel

答:
You say that the lines in your file consist of a username AND a password.  Yet you are testing for a match like this:

```<code>boolean matches = Pattern.matches(""+usernameTextField.getText(), line);
</code>```

Problems with the above.

The match verb for a Pattern or Matcher means "it matches the entire string".

The first argument to Pattern.matches(String, String) is supposed to be a regex represented as a string, not just any old string.  Now if your alphabet for user names is suitable restricted, it may work to use the name as a regex.  But it is a bad idea.

Even after changuing the "match" to "find", you could still potentially have the supplied user name match either a password or part of a user name in the file.

Taken out of context (i.e. ignoring point 3), it would be better to do the match like this:

```<code>boolean matches = line.contains(""+usernameTextField.getText());
</code>```

or maybe

```<code>boolean matches = Pattern.find(
    Pattern.quote(""+usernameTextField.getText()), line);
</code>```

However, that still has the problem that you could get false matches; e.g. matches on partial user names ... or even passwords.

Therefore the correct solution would be either to craft a regex that matches on the entire username field in your file, or split the lines into fields  (e.g. String.split and then use String.equals to test the appropriate field against the username that has been provided.

Title: Cannot read usernames from file

Body:
I am trying to implement a registration panel with username password and email only. I put all the usernames and passwords in a text file "usernames.txt". But my problem is not working properly if user clicks the submit button and the username already exists nothing happens( it should display JOptionPane with text "Username already exists!" ). here is my code :

submitButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader("usernames.txt"));
            } catch (FileNotFoundException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            try {
                String line = br.readLine();
                StringBuilder sb = new StringBuilder();
                Pattern usernameAndPasswordPattern = Pattern.compile("^(\\S+) (\\S+)$");
                while (line != null) {
                    sb.append(line); //
                    sb.append(System.lineSeparator()); //
                    line = br.readLine();
                }
                String everything = sb.toString();
                Matcher userNameAndPasswordMatcher = usernameAndPasswordPattern.matcher(everything);

                //if username exists!
                while (userNameAndPasswordMatcher.matches()) {
                    String username = userNameAndPasswordMatcher.group(1);
                    String password = userNameAndPasswordMatcher.group(2);

                    if (username.equals(usernameTextField.getText())) {
                        int result = JOptionPane.showConfirmDialog(null, "Username already exists!", "Registration incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                    }
                }

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } finally {
                try {
                    br.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    });

Here you can see a pic from my panel

Body:
You say that the lines in your file consist of a username AND a password.  Yet you are testing for a match like this:

boolean matches = Pattern.matches(""+usernameTextField.getText(), line);

Problems with the above.

The match verb for a Pattern or Matcher means "it matches the entire string".

The first argument to Pattern.matches(String, String) is supposed to be a regex represented as a string, not just any old string.  Now if your alphabet for user names is suitable restricted, it may work to use the name as a regex.  But it is a bad idea.

Even after changuing the "match" to "find", you could still potentially have the supplied user name match either a password or part of a user name in the file.

Taken out of context (i.e. ignoring point 3), it would be better to do the match like this:

boolean matches = line.contains(""+usernameTextField.getText());

or maybe

boolean matches = Pattern.find(
    Pattern.quote(""+usernameTextField.getText()), line);

However, that still has the problem that you could get false matches; e.g. matches on partial user names ... or even passwords.

Therefore the correct solution would be either to craft a regex that matches on the entire username field in your file, or split the lines into fields  (e.g. String.split and then use String.equals to test the appropriate field against the username that has been provided.


来源: stackexchange

问:
Rspec 3.0 How to mock a method replacing the parameter but with no return value?
I've searched a lot and just cannot figure this out although it seems basic. Here's a way simplified example of what I want to do.

Create a simple method that does something but doesn't return anything, such as:

```<code>class Test
  def test_method(param)
    puts param
  end
  test_method("hello")
end
</code>```

But in my rspec test I need to pass a different parameter, such as "goodbye" instead of "hello."  I know this has to do with stubs and mocks, and I've looking over the documentation but can't figure it out: https://relishapp.com/rspec/rspec-mocks/v/3-0/docs/method-stubs

If I do:

```<code>@test = Test.new
allow(@test).to_receive(:test_method).with("goodbye")
</code>```

it tells me to stub out a default value but I can't figure out how to do it correctly.

Error message:

```<code>received :test_method with unexpected arguments
  expected: ("hello")
  got: ("goodbye")
Please stub a default value first if message might be received with other args as well.
</code>```

I am using rspec 3.0, and calling something like

```<code>@test.stub(:test_method)
</code>```

is not allowed.

答:
How to set a default value that is explained at

and_call_original can configure a default response that can be overriden for specific args

```<code>require 'calculator'

RSpec.describe "and_call_original" do
  it "can be overriden for specific arguments using #with" do
    allow(Calculator).to receive(:add).and_call_original
    allow(Calculator).to receive(:add).with(2, 3).and_return(-5)

    expect(Calculator.add(2, 2)).to eq(4)
    expect(Calculator.add(2, 3)).to eq(-5)
  end
end
</code>```

Source where I came to know about that can be found at https://makandracards.com/makandra/30543-rspec-only-stub-a-method-when-a-particular-argument-is-passed

ContentLicense: CC BY-SA 3.0

Body:
I've searched a lot and just cannot figure this out although it seems basic. Here's a way simplified example of what I want to do.

Create a simple method that does something but doesn't return anything, such as:

class Test
  def test_method(param)
    puts param
  end
  test_method("hello")
end

But in my rspec test I need to pass a different parameter, such as "goodbye" instead of "hello."  I know this has to do with stubs and mocks, and I've looking over the documentation but can't figure it out: https://relishapp.com/rspec/rspec-mocks/v/3-0/docs/method-stubs

If I do:

@test = Test.new
allow(@test).to_receive(:test_method).with("goodbye")

it tells me to stub out a default value but I can't figure out how to do it correctly.

Error message:

received :test_method with unexpected arguments
  expected: ("hello")
  got: ("goodbye")
Please stub a default value first if message might be received with other args as well.

I am using rspec 3.0, and calling something like

@test.stub(:test_method)

is not allowed.

Body:
How to set a default value that is explained at

and_call_original can configure a default response that can be overriden for specific args

require 'calculator'

RSpec.describe "and_call_original" do
  it "can be overriden for specific arguments using #with" do
    allow(Calculator).to receive(:add).and_call_original
    allow(Calculator).to receive(:add).with(2, 3).and_return(-5)

    expect(Calculator.add(2, 2)).to eq(4)
    expect(Calculator.add(2, 3)).to eq(-5)
  end
end

Source where I came to know about that can be found at https://makandracards.com/makandra/30543-rspec-only-stub-a-method-when-a-particular-argument-is-passed


问:
QuantLib installation in Python
Can someone assist with up-to-date instructions for the installation of the QuantLib in Python. I have used the instructions on this link https://vineetv.wordpress.com/2015/07/07/installing-quantlib-python-windows/ and followed the video on this link https://www.youtube.com/watch?v=uWMT78XJFJE
but I keep on getting errors in building the solutions. I am new to programming.</p>

答:
Install Anaconda 4.3.1 (link), then open a Command Prompt as Admin and type:

pip install QuantLib-Python

For me, this only worked on the latest version of Anaconda including Python 3.6, think the QuantLib-Python package was implemented in PIP only very recently.

Title: QuantLib installation in Python


问:
SQL Server Database Management with Continuous Integration
Let's say we have a continuous integration server. When I check in, the post-hook pulls the latest code, runs the tests, packages everything. What is the best way to also automate the database changes?

Ideally, I'd build an installer that could either build a database from scratch or update an existing one using some automated syncing method.

答:
I've recently bumped into an article, that might be of use.

The author explained some of the best continuous integration practices including testing, processing and automation.

Here are some of the key takeaways:

In many shops code is unit tested at the point of commit. For databases, it is preferred running all unit tests at once and in sequence against a QA database, vs development, as a part of the Test step

The test step is a critical part of any CI/CD process. Test scripts, including unit tests themselves, should also be versioned in source control, extracted at the point of the Build step and executed

Pulling data from production is appealing as a quick expedient, but is never a good idea

The best approach is using a tool or script to quickly, repeatedly and reliably create synthetic test data for your transactional tables

Running unit tests to produce manual summary results for human consumption defeats the purpose of automation. We need machine readable results, that can allow an automated process to abort, branch and/or continue.

Running a CI process, which requires 100% of all tests to pass, is akin to not having CI at all, if the workflow pipeline is set up atomically to stop on failure, which it should. To thread the needle, tests should have built in thresholds, that will raise an error based on either the % of tests failing or in some cases, if certain high priority tests fail.

All processes should ultimately produce a Boolean result of pass or fail, but some non-automated processes can easily find their way into your CI workflow pipeline (e.g. unit testing). Software should be plug-n-play into any workflow pipeline, taking known inputs and producing expected outputs – like pass, fail.

CI/CD process should be aborted on failure and a notification email should be immediately sent vs continuing to cycle the pipeline.

The CI process should not cycle again until any errors in the last build are fixed. On failure, the entire team should get the failure notification, including as many details as to what failed as possible.

If a pipeline takes 1 hour, from start to finish, to complete, including all the testing, then all the build intervals should be set to no less than one hour and all new commits should be queued, and applied to the next build.

No plain text passwords should exist in automation scripts

OwnerDisplayName: Pete Michaud

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: recursive


问:
comparing the content of two cells in VBA
I need to compare the content of two cells in macro

RC1=2.0

RC2=2

I am using if(RC1=RC2,"''","x") for this which prints x for the above input but 2.0 and 2 are same, I need it to be '' in this case, please suggest

答:
First and foremost

You are trying to compare two different data types, let's say consider that one is an integer, which does not have decimal values, and the other one a double, with a decimal.

I would suggest you to have a better look at data types in VBA.

Hence we will need to convert the types to one that is the same for both cells with CDbl() to convert them to double. To put it simply, since integers are a simpler form of doubles we will use the more complete type of both.

Code to compare the types

```<code>Sub COMPARING_TYPES()

Dim a As Double, b As Double

' Let's assume the both values are numeric
a = CDbl(Cells(1, 1))
b = CDbl(Cells(2, 1))

If a = b Then
    ' Other code to execute when the values are matching
End If

End Sub
</code>```

This is all considering you want to compare the numbers in a VBA code.

Body:
First and foremost

You are trying to compare two different data types, let's say consider that one is an integer, which does not have decimal values, and the other one a double, with a decimal.

I would suggest you to have a better look at data types in VBA.

Hence we will need to convert the types to one that is the same for both cells with CDbl() to convert them to double. To put it simply, since integers are a simpler form of doubles we will use the more complete type of both.

Code to compare the types

Sub COMPARING_TYPES()

Dim a As Double, b As Double

' Let's assume the both values are numeric
a = CDbl(Cells(1, 1))
b = CDbl(Cells(2, 1))

If a = b Then
    ' Other code to execute when the values are matching
End If

End Sub

This is all considering you want to compare the numbers in a VBA code.


问:
sf2 instance of Doctrine\ORM\PersistentCollection given
I'm new in php and symfony
I use a file service for the upload in symfony 2.8
I got 2 tables One Salon to many Files

I can upload multiple files in my newaction.
The problem happened at the editAction of my SalonController.

I would like to remove the older files in order to add newfiles in my editfiles.html.twig. And I tried a foreach in order to get this array...

Could you help me please ?

Here is the error

Type error: Argument 1 passed to DefaultBundle\Service\FileService::upload() must be an instance of DefaultBundle\Entity\File, instance of Doctrine\ORM\PersistentCollection given, called in /var/www/html/salon-beaute/src/SalonBundle/Controller/SalonController.php on line 131

And the stack trace focused on the line 18 of the fileservice.php

public function upload(File $file = null, $type) {

Here is the my newaction and editaction of my SalonController

```<code>class SalonController extends Controller
</code>```

{
    /**
     * Creates a new salon entity.
     *
     * @Route("/new", name="salon_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $this->denyAccessUnlessGranted('ROLE_SALON');
        $em = $this->getDoctrine()->getManager();
        $salon = new Salon();

```<code>    $options = array('role' => $this->getUser()->getRoles(), 'page' => 'add');

    $form = $this->createForm( 'SalonBundle\Form\SalonType',$salon, $options);
    $user = $this->getUser();
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $uploadService = $this->get('app.file');

        $myFiles = $form->get('file')->getData();

        foreach($myFiles['path'] as $new_file) {

            $file = new File();
            $file->setPath($new_file);
            $file->setSalon($salon);
            $salon->addFile($file);
            $uploadService->upload($file, 'salon');
            $em->persist($file);
        }

        $user->setSalon($salon);
        $salon->setEnable(false);
        $em->persist($user);
        $em->persist($salon);
        $em->flush();

        $this->get('email')->salon($salon);
        return $this->redirectToRoute('salon_show', array('id' => $salon->getId()));
    }
</code>```

```<code>/**
 * Displays a form to edit an existing salon entity.
 *
 * @Route("/edit", name="salon_edit")
 * @Method({"GET", "POST"})
 * @Security("has_role('ROLE_SALON')")
 */
public function editAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $user = $this->getUser();
    $salon = $user->getSalon();
    $deleteForm = $this->createDeleteForm($salon);
</code>```

```<code>    $options = array('role' => $this->getUser()->getRoles(), 'page' => 'edit');

    $editForm = $this->createForm('SalonBundle\Form\SalonType', $salon, $options);

    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {
        // If new file
        $edit_file = $editForm->get('edit_file')->getData();
        if (!is_null($edit_file)) {
            $file_current = $salon->getFiles();
            $salon->getFiles($edit_file);
            if (!$this->get('app.file')->upload($salon->getFiles(), 'salon'))
                $salon->getFiles($file_current);
        }

        foreach($edit_file['path'] as $new_edit_file) {
            $file = new File();
            $file->setPath($new_edit_file);
            $file->setSalon($salon);
            $salon->addFile($file);
            $this->get('app.file')->upload($file);
            $em->persist($file);
        }

        $this->getDoctrine()->getManager()->flush();
        $this->addFlash('success', 'Le partenaire a bien été modifié');
        return $this->redirectToRoute('salon_show');
    }

    return $this->render('@Salon/salon/edit.html.twig', array(
        'salon' => $salon,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

    return $this->render('@Salon/salon/new.html.twig', array(
        'salon' => $salon,
        'form' => $form->createView(),
    ));
}
</code>```

A portion of my SalonType

```<code>    class SalonType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $page = $options['page'];

        $builder
            ->add('name', TextType::class, array(
                'label' => 'Nom du salon'
            ))
            ->add('content', TextareaType::class, array(
                'label' => 'Descriptif'
            ))
            ->add('address_salon', AddressType::class, array(
                'label' => ' '
            ))
        ;

        if($page == 'add') {
            $builder
                ->add('file', FileType::class, array(
                    'label' => 'Vous pouvez téléchargez jusqu\'à 3 images',
                    'required' => false,
                    'mapped' =>false,
                ));
        }

        if($page == 'edit') {
            $builder
                ->add('edit_file', FileType::class, array(
                    'label' => 'Nouveau fichier',
                    'required' => false,
                    'mapped' => false
                ));
        };

    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'SalonBundle\Entity\Salon',
            'role' => null
        ));
        $resolver
            ->setRequired(['page']);
    }

My fileType

    class FileType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
            ->add('path', \Symfony\Component\Form\Extension\Core\Type\FileType::class, array(
                'label' => 'Image',
                'multiple' => true,
            ))
        ;
    }

    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'data_class' => null,
        ));
    }
}

My fileService

    <?php
namespace DefaultBundle\Service;

use DefaultBundle\Entity\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class FileService {
    private $directory_root;
    private $directory_default;

    public function __construct($directory_root, $directory_default) {
        $this->directory_root = $directory_root;
        $this->directory_default = $directory_default;
    }

    public function upload(File $file = null, $type) {
        $path = $this->getDirectory($type);

        if (is_null($file))
            return false;

        // Get file (Class UploadFile)
        $file_uploaded = $file->getPath();

        if ($file_uploaded->getError())
            return false;

        // Move file
        $file_name = md5(uniqid()) . '.' . $file_uploaded->guessExtension();
        $file_uploaded->move($this->directory_root . $path, $file_name);

        // Update object file
        $path .= '/' . $file_name;
        $file->update($file_uploaded, $path);

        return true;
    }

    public function delete(File $file){
        $path = $this->directory_root.$file->getPath();
        if(file_exists($path))
            unlink($path);
    }

    private function getDirectory($type) {
        switch ($type) {
            default:
                return $this->directory_default;
        }
    }
}
</code>```

答:
Your code is kinda messy, by that I mean you have lot of logic in your controller :-)

Just to know which line is the 131 in your controller?

You have an error here (don't know if it's the 131 line)

```<code>if (!$this->get('app.file')->upload($salon->getFiles(), 'salon'))
</code>```

Here you send a collection to upload(), you said it yourself

One Salon to many Files

BUT before trying to hotfix this look at is tutorial here on how to handle multiple file upload.

Also this tutorial has the full demo source code available. The code is quite clear and you should be able to understand it easily.

Edit

If you don't want to rewrite your code you may want to hotfix your code like that

```<code>if (!is_null($edit_file)) {
    $file_current = $salon->getFiles();
    //$salon->getFiles($edit_file); What is the goal of this?
    foreach ($salon->getFiles() as $file) {
        // Note that now we send a single File object not a collection
        if (!$this->get('app.file')->upload($file, 'salon')) {
            $salon->setFiles($file_current); // You want to set the files no?
            break;
        }
    }
}
</code>```

This is 200% ugly, and I'm not even sure if it will work. You should really think about refactoring your code.

Edit 2

The problem you have now is that you are mixing your File object and the UploadedFile object from symfony.

You do $file_uploaded = $file->getPath(); then you have the error

Call to a member function getError() on string

and it's normal because getPath() return a string.

I assume you have look the Uploader Service of the symfony doc. You can see they pass an UploadedFile object which is part of the symfony package, not a custom entity.

If I wanted to do a quick fix, which is definitely not what I recommend, I'll do something like this

```<code>// Your controller (newAction)
foreach($myFiles['path'] as $new_file) {
    // $new_file is an uploadedFile object, this is the file you want to upload
    $file = new File();
    $file->setPath($new_file);
    $file->setSalon($salon);
    $salon->addFile($file);
    $uploadService->upload($file, $new_file, 'salon');
    $em->persist($file);
}

// Your FileService
public function upload(File $file = null, UploadedFile $file_uploaded = null, $type) {
    $path = $this->getDirectory($type);

    if (is_null($file_uploaded) || is_null($file))
        return false;

    // Get file (Class UploadFile), No here you get the file path => a string
    //$file_uploaded = $file->getPath();

    if ($file_uploaded->getError())
        return false;

    //... end of your method
}
</code>```

Body:
I'm new in php and symfony
I use a file service for the upload in symfony 2.8
I got 2 tables One Salon to many Files

I can upload multiple files in my newaction.
The problem happened at the editAction of my SalonController.

I would like to remove the older files in order to add newfiles in my editfiles.html.twig. And I tried a foreach in order to get this array...

Could you help me please ?

Here is the error

Type error: Argument 1 passed to DefaultBundle\Service\FileService::upload() must be an instance of DefaultBundle\Entity\File, instance of Doctrine\ORM\PersistentCollection given, called in /var/www/html/salon-beaute/src/SalonBundle/Controller/SalonController.php on line 131

And the stack trace focused on the line 18 of the fileservice.php

public function upload(File $file = null, $type) {

Here is the my newaction and editaction of my SalonController

class SalonController extends Controller

{
    /**
     * Creates a new salon entity.
     *
     * @Route("/new", name="salon_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $this->denyAccessUnlessGranted('ROLE_SALON');
        $em = $this->getDoctrine()->getManager();
        $salon = new Salon();

    $options = array('role' => $this->getUser()->getRoles(), 'page' => 'add');

    $form = $this->createForm( 'SalonBundle\Form\SalonType',$salon, $options);
    $user = $this->getUser();
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $uploadService = $this->get('app.file');

        $myFiles = $form->get('file')->getData();

        foreach($myFiles['path'] as $new_file) {

            $file = new File();
            $file->setPath($new_file);
            $file->setSalon($salon);
            $salon->addFile($file);
            $uploadService->upload($file, 'salon');
            $em->persist($file);
        }

        $user->setSalon($salon);
        $salon->setEnable(false);
        $em->persist($user);
        $em->persist($salon);
        $em->flush();

        $this->get('email')->salon($salon);
        return $this->redirectToRoute('salon_show', array('id' => $salon->getId()));
    }

/**
 * Displays a form to edit an existing salon entity.
 *
 * @Route("/edit", name="salon_edit")
 * @Method({"GET", "POST"})
 * @Security("has_role('ROLE_SALON')")
 */
public function editAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $user = $this->getUser();
    $salon = $user->getSalon();
    $deleteForm = $this->createDeleteForm($salon);

    $options = array('role' => $this->getUser()->getRoles(), 'page' => 'edit');

    $editForm = $this->createForm('SalonBundle\Form\SalonType', $salon, $options);

    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {
        // If new file
        $edit_file = $editForm->get('edit_file')->getData();
        if (!is_null($edit_file)) {
            $file_current = $salon->getFiles();
            $salon->getFiles($edit_file);
            if (!$this->get('app.file')->upload($salon->getFiles(), 'salon'))
                $salon->getFiles($file_current);
        }

        foreach($edit_file['path'] as $new_edit_file) {
            $file = new File();
            $file->setPath($new_edit_file);
            $file->setSalon($salon);
            $salon->addFile($file);
            $this->get('app.file')->upload($file);
            $em->persist($file);
        }

        $this->getDoctrine()->getManager()->flush();
        $this->addFlash('success', 'Le partenaire a bien été modifié');
        return $this->redirectToRoute('salon_show');
    }

    return $this->render('@Salon/salon/edit.html.twig', array(
        'salon' => $salon,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

    return $this->render('@Salon/salon/new.html.twig', array(
        'salon' => $salon,
        'form' => $form->createView(),
    ));
}

A portion of my SalonType

    class SalonType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $page = $options['page'];

        $builder
            ->add('name', TextType::class, array(
                'label' => 'Nom du salon'
            ))
            ->add('content', TextareaType::class, array(
                'label' => 'Descriptif'
            ))
            ->add('address_salon', AddressType::class, array(
                'label' => ' '
            ))
        ;

        if($page == 'add') {
            $builder
                ->add('file', FileType::class, array(
                    'label' => 'Vous pouvez téléchargez jusqu\'à 3 images',
                    'required' => false,
                    'mapped' =>false,
                ));
        }

        if($page == 'edit') {
            $builder
                ->add('edit_file', FileType::class, array(
                    'label' => 'Nouveau fichier',
                    'required' => false,
                    'mapped' => false
                ));
        };

    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'SalonBundle\Entity\Salon',
            'role' => null
        ));
        $resolver
            ->setRequired(['page']);
    }

My fileType

    class FileType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
            ->add('path', \Symfony\Component\Form\Extension\Core\Type\FileType::class, array(
                'label' => 'Image',
                'multiple' => true,
            ))
        ;
    }

    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'data_class' => null,
        ));
    }
}

My fileService

    <?php
namespace DefaultBundle\Service;

use DefaultBundle\Entity\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class FileService {
    private $directory_root;
    private $directory_default;

    public function __construct($directory_root, $directory_default) {
        $this->directory_root = $directory_root;
        $this->directory_default = $directory_default;
    }

    public function upload(File $file = null, $type) {
        $path = $this->getDirectory($type);

        if (is_null($file))
            return false;

        // Get file (Class UploadFile)
        $file_uploaded = $file->getPath();

        if ($file_uploaded->getError())
            return false;

        // Move file
        $file_name = md5(uniqid()) . '.' . $file_uploaded->guessExtension();
        $file_uploaded->move($this->directory_root . $path, $file_name);

        // Update object file
        $path .= '/' . $file_name;
        $file->update($file_uploaded, $path);

        return true;
    }

    public function delete(File $file){
        $path = $this->directory_root.$file->getPath();
        if(file_exists($path))
            unlink($path);
    }

    private function getDirectory($type) {
        switch ($type) {
            default:
                return $this->directory_default;
        }
    }
}

Body:
Your code is kinda messy, by that I mean you have lot of logic in your controller :-)

Just to know which line is the 131 in your controller?

You have an error here (don't know if it's the 131 line)

if (!$this->get('app.file')->upload($salon->getFiles(), 'salon'))

Here you send a collection to upload(), you said it yourself

One Salon to many Files

BUT before trying to hotfix this look at is tutorial here on how to handle multiple file upload.

Also this tutorial has the full demo source code available. The code is quite clear and you should be able to understand it easily.

Edit

If you don't want to rewrite your code you may want to hotfix your code like that

if (!is_null($edit_file)) {
    $file_current = $salon->getFiles();
    //$salon->getFiles($edit_file); What is the goal of this?
    foreach ($salon->getFiles() as $file) {
        // Note that now we send a single File object not a collection
        if (!$this->get('app.file')->upload($file, 'salon')) {
            $salon->setFiles($file_current); // You want to set the files no?
            break;
        }
    }
}

This is 200% ugly, and I'm not even sure if it will work. You should really think about refactoring your code.

Edit 2

The problem you have now is that you are mixing your File object and the UploadedFile object from symfony.

You do $file_uploaded = $file->getPath(); then you have the error

Call to a member function getError() on string

and it's normal because getPath() return a string.

I assume you have look the Uploader Service of the symfony doc. You can see they pass an UploadedFile object which is part of the symfony package, not a custom entity.

If I wanted to do a quick fix, which is definitely not what I recommend, I'll do something like this

// Your controller (newAction)
foreach($myFiles['path'] as $new_file) {
    // $new_file is an uploadedFile object, this is the file you want to upload
    $file = new File();
    $file->setPath($new_file);
    $file->setSalon($salon);
    $salon->addFile($file);
    $uploadService->upload($file, $new_file, 'salon');
    $em->persist($file);
}

// Your FileService
public function upload(File $file = null, UploadedFile $file_uploaded = null, $type) {
    $path = $this->getDirectory($type);

    if (is_null($file_uploaded) || is_null($file))
        return false;

    // Get file (Class UploadFile), No here you get the file path => a string
    //$file_uploaded = $file->getPath();

    if ($file_uploaded->getError())
        return false;

    //... end of your method
}


问:
How to obtain a more accurate value for RPM
I am trying to build a rev counter using a Hall effect sensor and an Arduino Uno. I'm using Arduino software and I have wrote the following code:

#include <LiquidCrystal.h>

int sensorPin = 2; // hall effect
float revs;
float rpm;
volatile byte rpmcount;
long previousmicros = 0;
long interval = 500000;
LiquidCrystal lcd(12, 11, 6, 5, 4, 3);

void setup()
{
  // setup serial - diagnostics - port
  Serial.begin(115200);
  // setup pins
  pinMode(sensorPin, INPUT);
  // setup interrupt
  attachInterrupt(0, RPM, RISING);
}

void RPM()
{
  rpmcount++;
}

void loop()
{
  unsigned long currentmicros = micros();
  int sensorValue = digitalRead(sensorPin);        // sensor value is read
  if (currentmicros - previousmicros > interval)
  {
    previousmicros = currentmicros;

    detachInterrupt(0);
    revs=10.0/rpmcount;
    rpm =600.0/revs;
    Serial.print("rpmcount : ");
    Serial.print(rpmcount);
    Serial.print("  rpm : ");
    Serial.println(rpm);
    lcd.clear();
    lcd.begin(16, 2);
    lcd.print("RPM = ");
    lcd.setCursor(6,0);
    lcd.print(rpm,0);
    rpmcount=0;
    attachInterrupt(0, RPM, RISING);
  }
}
```

This works and measures the RPM correctly however the value is always a factor of 60. How can I change this so that it will measure the RPM more accurately, to say +-5 RPM? I tried playing about with my revs and rpm formulas but had little success.

答:
Right now you have

```<code>rpm =60.0*rpmcount;
</code>```

You will have to store the count over a longer time and calculate the value from that (or change how often loop is run)

Body:
I am trying to build a rev counter using a Hall effect sensor and an Arduino Uno. I'm using Arduino software and I have wrote the following code:

#include <LiquidCrystal.h>

int sensorPin = 2; // hall effect
float revs;
float rpm;
volatile byte rpmcount;
long previousmicros = 0;
long interval = 500000;
LiquidCrystal lcd(12, 11, 6, 5, 4, 3);

void setup()
{
  // setup serial - diagnostics - port
  Serial.begin(115200);
  // setup pins
  pinMode(sensorPin, INPUT);
  // setup interrupt
  attachInterrupt(0, RPM, RISING);
}

void RPM()
{
  rpmcount++;
}

void loop()
{
  unsigned long currentmicros = micros();
  int sensorValue = digitalRead(sensorPin);        // sensor value is read
  if (currentmicros - previousmicros > interval)
  {
    previousmicros = currentmicros;

    detachInterrupt(0);
    revs=10.0/rpmcount;
    rpm =600.0/revs;
    Serial.print("rpmcount : ");
    Serial.print(rpmcount);
    Serial.print("  rpm : ");
    Serial.println(rpm);
    lcd.clear();
    lcd.begin(16, 2);
    lcd.print("RPM = ");
    lcd.setCursor(6,0);
    lcd.print(rpm,0);
    rpmcount=0;
    attachInterrupt(0, RPM, RISING);
  }
}

This works and measures the RPM correctly however the value is always a factor of 60. How can I change this so that it will measure the RPM more accurately, to say +-5 RPM? I tried playing about with my revs and rpm formulas but had little success.

Body:
Right now you have

rpm =60.0*rpmcount;

You will have to store the count over a longer time and calculate the value from that (or change how often loop is run)


问:
How to iterate a variable length tensor in tensorflow?
I want to build a graph to accept variable size images. So after the last conv layer, I want to iterate through every pixel and feed that vector to softmax layer. And then calculate the mean of them.

It may look like this:

```<code>last_max_pool = tf.nn.max_pool(...)

output = tf.reshape(last_max_pool, [batch_size, None, channels])

results = []
for one_batch in output:
    result = []
    for pixel in one_batch:
        result.append(tf.nn.softmax(tf.matmul(pixel, W_sf) + B_sf))
    result = tf.reduce_mean(result)
    results.append(result)
</code>```

But how to build the graph like this in tensorflow?

答:
I don't think you need for loop, instead you can reshape last_max_pool to [None, channels]

```<code>output = tf.reshape(last_max_pool, [None, channels])
softmax = tf.nn.softmax(tf.matmul(output, W_sf) + B_sf)
final_output = tf.reduce_mean(results)
</code>```

Body:
I want to build a graph to accept variable size images. So after the last conv layer, I want to iterate through every pixel and feed that vector to softmax layer. And then calculate the mean of them.

It may look like this:

last_max_pool = tf.nn.max_pool(...)

output = tf.reshape(last_max_pool, [batch_size, None, channels])

results = []
for one_batch in output:
    result = []
    for pixel in one_batch:
        result.append(tf.nn.softmax(tf.matmul(pixel, W_sf) + B_sf))
    result = tf.reduce_mean(result)
    results.append(result)

But how to build the graph like this in tensorflow?

Body:
I don't think you need for loop, instead you can reshape last_max_pool to [None, channels]

output = tf.reshape(last_max_pool, [None, channels])
softmax = tf.nn.softmax(tf.matmul(output, W_sf) + B_sf)
final_output = tf.reduce_mean(results)


问:
How to get last two directories from a path using regexp?
I have a path C:\input\rsgc\statements_and_inserts\Australia\ and I want to get the last two directories using regular expression in java. It can be done in few steps. I do not know how many directories are in the path but I always want the last two.

Can this be done in reg exp or I need to use programming language?

答:
```<code>path = "C:\input\rsgc\statements_and_inserts\Australia\";
path = path.substring(0,path.length()-1);
String filename = path.substring(path.lastIndexOf("\") + 1);
String subPath = path.replace("\" + filename, "");
String lastTwoDir = path.substring(subPath.lastIndexOf("\") + 1);
</code>```


问:
Getting image path in public folder in laravel
I'm making direction using this method to upload my image

```<code> mkdir(public_path().'/website/'.$path,0777, true);
</code>```

It's supposed to create it on the root folder (Public_html) , but i found it created on new folder with name (public ) , so now i can't get the path of the image using this code

```<code> <img src="{{url('public/website/'.$file->path.$file->file)}}"  />
</code>```

how to get the correct path of the image or even create the folder on the public_html root path ?

答:
See Here for more info

You can use laravel helper function asset
for eg. $url = asset('img/photo.jpg'); then you will get full path with public directory. $url return www.your.domain.com/public/img/photo.jpg

Body:
I'm making direction using this method to upload my image

 mkdir(public_path().'/website/'.$path,0777, true);

It's supposed to create it on the root folder (Public_html) , but i found it created on new folder with name (public ) , so now i can't get the path of the image using this code

 path.$file->file)}}"  />

how to get the correct path of the image or even create the folder on the public_html root path ?


问:
Error handling on GoTo Bookmark if bookmark doesn't exist
I'm working on a macro to copy and paste bookmarked tables from one word document to another. It works fine as long as the value I put in the input box matches an existing bookmark, but if I mistype the value, it simply pulls in the top table from my source document. I understand why it does that (because it selects table 1 if it doesn't find a bookmark), but I can't figure out how to fix it. I tried putting in error handling, but since it doesn't trigger an error, what I added doesn't work. Can someone show me how to edit the code below to fix this issue? Also, is there a way to use relative pathways for the source document and target document? They will always be in the same folder, but each different user will have a copy of them in their own folder, and I don't want to rewrite the macro every time. Any other improvements or edits would be appreciated, such as how to not use the selection event so much here. Or how to not reopen the documents if they are already open. The command button (and code) is in the Target document (Product.docm)</p>

```<code>Private Sub CommandButton2_Click()

' Copy table from source document and add to table in target document

  Dim oTarDoc As Document, oSourceDoc As Document
  Dim oTable As Table
  Dim oNewRow As Row

    Set oSourceDoc = Documents.Open("H:\Test Documents\Tables.docx")
    Set oTarDoc = Documents.Open("H:\Test Documents\Product.docm")

    Application.ScreenUpdating = False

    oTarDoc.Activate
    Set oTable = oTarDoc.Tables(2)
    Set oNewRow = oTable.Rows(oTable.Rows.Count - 3)

    oSourceDoc.Activate
    Selection.GoTo What:=wdGoToBookmark, Name:="A" & InputBox("119f, 979, 981a...", "Enter Number and Letter as Shown")
    With oSourceDoc.Bookmarks
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With
    Selection.Tables(1).Select
    Selection.Copy

    oTarDoc.Activate
    oNewRow.Select
    Selection.Paste
       Application.ScreenUpdating = True    End Sub
</code>```

答:
Please try this code. I have added some comments which I hope you will find useful.

```<code>Private Sub CommandButton2_Click()

    ' Copy table from source document and add to table in target document

    Dim TarDoc As Document, SourDoc As Document
    Dim Tbl As Table
    Dim NewRow As Row
    Dim Mark As String, MarkText As String

    Set SourDoc = Documents.Open("H:\Test Documents\Tables.docx")
    Set TarDoc = Documents.Open("H:\Test Documents\Product.docm")

    Application.ScreenUpdating = False

'    TarDoc.Activate                            ' no need to activate
    ' actually, since ScreenUpdating is off, Activate is without effect
    Set Tbl = TarDoc.Tables(2)
    Set NewRow = Tbl.Rows(Tbl.Rows.Count - 3)   ' this is an existing row
    ' this code inserts a row before the existing row(3)
    ' With Tbl
    '    .Rows.Add BeforeRow:=.Rows(3)
    ' End With
    ' use Tbl.Rows.Add to append a row at the end
'    SourDoc.Activate                           ' no need to activate

    Do
        Mark = InputBox("119f, 979, 981a...", "Enter Number and Letter as Shown")
        If Len(Mark) Then              ' do nothing if user enters nothing
            Mark = "A" & Mark
            If SourDoc.Bookmarks.Exists(Mark) Then
                MarkText = SourDoc.Bookmarks(Mark).Range.Text
                ' This seems to serve no purpose:
                '    With SourDoc.Bookmarks
                '        .DefaultSorting = wdSortByName
                '        .ShowHidden = False
                '    End With
                '    Selection.Tables(1).Select ' no need to select
                '    Selection.Copy             ' MarktText already got the text
                '    TarDoc.Activate            ' no need to activate
                '    NewRow.Select              ' no need to select
                '    Selection.Paste            ' no need to paste
                NewRow.Cells(1).Range.Text = MarkText
                Mark = vbNullString    ' to enable existing the loop
            Else
                MsgBox "Bookmark """ & Mark & """ doesn't exist.", vbInformation, _
                       "Invalid entry"
            End If
        End If
    Loop While Len(Mark)               ' the user entered a wrong mark

    Application.ScreenUpdating = True
End Sub
</code>```

If the user enters a non-existing mark name he gets an error message and another chance. To exit the InputBox without entering a valid bookmark just leave it blank.

Body:
I'm working on a macro to copy and paste bookmarked tables from one word document to another. It works fine as long as the value I put in the input box matches an existing bookmark, but if I mistype the value, it simply pulls in the top table from my source document. I understand why it does that (because it selects table 1 if it doesn't find a bookmark), but I can't figure out how to fix it. I tried putting in error handling, but since it doesn't trigger an error, what I added doesn't work. Can someone show me how to edit the code below to fix this issue? Also, is there a way to use relative pathways for the source document and target document? They will always be in the same folder, but each different user will have a copy of them in their own folder, and I don't want to rewrite the macro every time. Any other improvements or edits would be appreciated, such as how to not use the selection event so much here. Or how to not reopen the documents if they are already open. The command button (and code) is in the Target document (Product.docm)

Private Sub CommandButton2_Click()

' Copy table from source document and add to table in target document

  Dim oTarDoc As Document, oSourceDoc As Document
  Dim oTable As Table
  Dim oNewRow As Row

    Set oSourceDoc = Documents.Open("H:\Test Documents\Tables.docx")
    Set oTarDoc = Documents.Open("H:\Test Documents\Product.docm")

    Application.ScreenUpdating = False

    oTarDoc.Activate
    Set oTable = oTarDoc.Tables(2)
    Set oNewRow = oTable.Rows(oTable.Rows.Count - 3)

    oSourceDoc.Activate
    Selection.GoTo What:=wdGoToBookmark, Name:="A" & InputBox("119f, 979, 981a...", "Enter Number and Letter as Shown")
    With oSourceDoc.Bookmarks
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With
    Selection.Tables(1).Select
    Selection.Copy

    oTarDoc.Activate
    oNewRow.Select
    Selection.Paste
       Application.ScreenUpdating = True    End Sub

Body:
Please try this code. I have added some comments which I hope you will find useful.

Private Sub CommandButton2_Click()

    ' Copy table from source document and add to table in target document

    Dim TarDoc As Document, SourDoc As Document
    Dim Tbl As Table
    Dim NewRow As Row
    Dim Mark As String, MarkText As String

    Set SourDoc = Documents.Open("H:\Test Documents\Tables.docx")
    Set TarDoc = Documents.Open("H:\Test Documents\Product.docm")

    Application.ScreenUpdating = False

'    TarDoc.Activate                            ' no need to activate
    ' actually, since ScreenUpdating is off, Activate is without effect
    Set Tbl = TarDoc.Tables(2)
    Set NewRow = Tbl.Rows(Tbl.Rows.Count - 3)   ' this is an existing row
    ' this code inserts a row before the existing row(3)
    ' With Tbl
    '    .Rows.Add BeforeRow:=.Rows(3)
    ' End With
    ' use Tbl.Rows.Add to append a row at the end
'    SourDoc.Activate                           ' no need to activate

    Do
        Mark = InputBox("119f, 979, 981a...", "Enter Number and Letter as Shown")
        If Len(Mark) Then              ' do nothing if user enters nothing
            Mark = "A" & Mark
            If SourDoc.Bookmarks.Exists(Mark) Then
                MarkText = SourDoc.Bookmarks(Mark).Range.Text
                ' This seems to serve no purpose:
                '    With SourDoc.Bookmarks
                '        .DefaultSorting = wdSortByName
                '        .ShowHidden = False
                '    End With
                '    Selection.Tables(1).Select ' no need to select
                '    Selection.Copy             ' MarktText already got the text
                '    TarDoc.Activate            ' no need to activate
                '    NewRow.Select              ' no need to select
                '    Selection.Paste            ' no need to paste
                NewRow.Cells(1).Range.Text = MarkText
                Mark = vbNullString    ' to enable existing the loop
            Else
                MsgBox "Bookmark """ & Mark & """ doesn't exist.", vbInformation, _
                       "Invalid entry"
            End If
        End If
    Loop While Len(Mark)               ' the user entered a wrong mark

    Application.ScreenUpdating = True
End Sub

If the user enters a non-existing mark name he gets an error message and another chance. To exit the InputBox without entering a valid bookmark just leave it blank.


问:
How to set a custom property naming strategy with MappingJackson2HttpMessageConverter using XML Config?
I want to define a custom naming strategy for json. I am trying to configure a different naming strategy in my spring-config.xml. I have added the MappingJackson2HttpMessageConverter as a message convertor with a custom object mapper:

```<code><mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="com.insta.hms.common.ObjectHttpMessageConverter" />
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="jacksonObjectMapper" />
        </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</code>```

And I am trying to define an object mapper for the JacksonMessageConvertor here:

```<code><bean id="jacksonObjectMapper" class ="com.fasterxml.jackson.databind.ObjectMapper">
    <property name = "PropertyNamingStrategy" value = "PropertyNamingStrategy.LOWER_CASE" />
</bean>
</code>```

This is not working; Spring says : Cannot convert value of type 'java.lang.String' to required type 'com.fasterxml.jackson.databind.PropertyNamingStrategy' for property 'PropertyNamingStrategy'

So my eventual aim is to replace 'value' of a propertyNamingStrategy with my custom class which implements propertyNamingStrategy.

I need help with configuring this using XML config.

答:
When you assign a property value = "PropertyNamingStrategy.LOWER_CASE" Spring evaluates it as a String. What you need is:

```<code><bean id="jacksonObjectMapper" class ="com.fasterxml.jackson.databind.ObjectMapper">
    <property name = "propertyNamingStrategy" value = "#{T(com.fasterxml.jackson.databind.PropertyNamingStrategy).LOWER_CASE}" />
</bean>
</code>```

Also, according to the answers for this question, the following is also possible:

```<code><bean id="jacksonObjectMapper" class ="com.fasterxml.jackson.databind.ObjectMapper">
    <property name = "propertyNamingStrategy" value = "LOWER_CASE" />
</bean>
</code>```

Body:
I want to define a custom naming strategy for json. I am trying to configure a different naming strategy in my spring-config.xml. I have added the MappingJackson2HttpMessageConverter as a message convertor with a custom object mapper:

<mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="com.insta.hms.common.ObjectHttpMessageConverter" />
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="jacksonObjectMapper" />
        </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

And I am trying to define an object mapper for the JacksonMessageConvertor here:

<bean id="jacksonObjectMapper" class ="com.fasterxml.jackson.databind.ObjectMapper">
    <property name = "PropertyNamingStrategy" value = "PropertyNamingStrategy.LOWER_CASE" />
</bean>

This is not working; Spring says : Cannot convert value of type 'java.lang.String' to required type 'com.fasterxml.jackson.databind.PropertyNamingStrategy' for property 'PropertyNamingStrategy'

So my eventual aim is to replace 'value' of a propertyNamingStrategy with my custom class which implements propertyNamingStrategy.

I need help with configuring this using XML config.

Body:
When you assign a property value = "PropertyNamingStrategy.LOWER_CASE" Spring evaluates it as a String. What you need is:

<bean id="jacksonObjectMapper" class ="com.fasterxml.jackson.databind.ObjectMapper">
    <property name = "propertyNamingStrategy" value = "#{T(com.fasterxml.jackson.databind.PropertyNamingStrategy).LOWER_CASE}" />
</bean>

Also, according to the answers for this question, the following is also possible:

<bean id="jacksonObjectMapper" class ="com.fasterxml.jackson.databind.ObjectMapper">
    <property name = "propertyNamingStrategy" value = "LOWER_CASE" />
</bean>


问:
Query Filter Django
I want to call nilai into a table in my template. This is my model:

```<code>class AlternatifJalur(models.Model):
    nama = models.CharField(max_length=100)
    def __str__(self):
        return self.nama

class KriteriaJalur(models.Model):
    TIPE_KRITERIA_CHOICES = (
        ('benefit', 'Benefit'),
        ('cost', 'Cost'),
    )
    nama = models.CharField(max_length=100)
    bobot = models.DecimalField(max_digits = 20, decimal_places = 2)
    keterangan = models.TextField()
    tipe = models.CharField(max_length=100, choices=TIPE_KRITERIA_CHOICES, default='Benefit')

    def __str__(self):
        return self.nama

class Matriks(models.Model):
    kriteria = models.ForeignKey(KriteriaJalur)
    alternatif = models.ForeignKey(AlternatifJalur)
    nilai = models.DecimalField(max_digits = 20, decimal_places = 2)

    def nilai_float(self):
        return float(self.nilai)
</code>```

This is my view :

```<code>def index(request):
    kriteria = KriteriaJalur.objects.all()
    alternatif = AlternatifJalur.objects.all()
    matriks = Matriks.objects.all()
    krite = KriteriaJalur.objects.get(nama='Jarak')
    return render(request, 'index.html', {"kriteria":kriteria, "alternatif":alternatif, "matriks":matriks})
</code>```

How can I call nilai from the Matriks class in my model so that kriteria in my Matriks class is equal to nama in my kriteria class and alternatif in my Matriks class is equal to nama in my alternatif class ?

答:
From what I understand you may want to use filter and/or Q in order to filter your matriks obj based on kriteria nama and/or alternatif nama.

Change your index view to this:

```<code>from django.db.models import Q

def index(request):
    kriteria = KriteriaJalur.objects.all()
    alternatif = AlternatifJalur.objects.all()

    # The below will contain all matriks whose kriteria nama is 'Kriteria A' AND alternatif nama is 'Jalur A'
    matriks = Matriks.objects.filter(kriteria__nama='Kriteria A', alternatif__nama='Jalur A')

    # The below will contain all matriks whose kriteria nama is 'Kriteria A' OR alternatif nama is 'Jalur A'
    matriks = Matriks.objects.filter(Q(kriteria__nama='Kriteria A') | Q(alternatif__nama='Jalur A'))

    krite = KriteriaJalur.objects.get(nama='Jarak')
    return render(request, 'index.html', {"kriteria":kriteria, "alternatif":alternatif, "matriks":matriks})
</code>```

How about this:

```<code><!-- index.html -->

{% for matrik in matriks %}
    {{ matrik.nilai }}
{% endfor %}

<table class="table table-hover">
    <tr>
        <th>#</th>
        {% for item in matriks %}
            <th>{{ item.kriteria.nama }} ({{ item.kriteria.bobot }} %)</th>
        {% endfor %}
        {% for item in alternatif %}
        <tr>
            <td>{{ item.nama }}</td>
            {% for matrik in matriks %}
                <td>{{ item.JalurA }}</td>
                <td></td>
                <td></td>
            {% endfor %}
        </tr>
        {% endfor %}
    </tr>
</table>
</code>```

Title: Query Filter Django

Body:
I want to call nilai into a table in my template. This is my model:

class AlternatifJalur(models.Model):
    nama = models.CharField(max_length=100)
    def __str__(self):
        return self.nama

class KriteriaJalur(models.Model):
    TIPE_KRITERIA_CHOICES = (
        ('benefit', 'Benefit'),
        ('cost', 'Cost'),
    )
    nama = models.CharField(max_length=100)
    bobot = models.DecimalField(max_digits = 20, decimal_places = 2)
    keterangan = models.TextField()
    tipe = models.CharField(max_length=100, choices=TIPE_KRITERIA_CHOICES, default='Benefit')

    def __str__(self):
        return self.nama

class Matriks(models.Model):
    kriteria = models.ForeignKey(KriteriaJalur)
    alternatif = models.ForeignKey(AlternatifJalur)
    nilai = models.DecimalField(max_digits = 20, decimal_places = 2)

    def nilai_float(self):
        return float(self.nilai)

This is my view :

def index(request):
    kriteria = KriteriaJalur.objects.all()
    alternatif = AlternatifJalur.objects.all()
    matriks = Matriks.objects.all()
    krite = KriteriaJalur.objects.get(nama='Jarak')
    return render(request, 'index.html', {"kriteria":kriteria, "alternatif":alternatif, "matriks":matriks})

How can I call nilai from the Matriks class in my model so that kriteria in my Matriks class is equal to nama in my kriteria class and alternatif in my Matriks class is equal to nama in my alternatif class ?

Body:
From what I understand you may want to use filter and/or Q in order to filter your matriks obj based on kriteria nama and/or alternatif nama.

Change your index view to this:

from django.db.models import Q

def index(request):
    kriteria = KriteriaJalur.objects.all()
    alternatif = AlternatifJalur.objects.all()

    # The below will contain all matriks whose kriteria nama is 'Kriteria A' AND alternatif nama is 'Jalur A'
    matriks = Matriks.objects.filter(kriteria__nama='Kriteria A', alternatif__nama='Jalur A')

    # The below will contain all matriks whose kriteria nama is 'Kriteria A' OR alternatif nama is 'Jalur A'
    matriks = Matriks.objects.filter(Q(kriteria__nama='Kriteria A') | Q(alternatif__nama='Jalur A'))

    krite = KriteriaJalur.objects.get(nama='Jarak')
    return render(request, 'index.html', {"kriteria":kriteria, "alternatif":alternatif, "matriks":matriks})

How about this:

<!-- index.html -->

{% for matrik in matriks %}
    {{ matrik.nilai }}
{% endfor %}

<table class="table table-hover">
    <tr>
        <th>#</th>
        {% for item in matriks %}
            <th>{{ item.kriteria.nama }} ({{ item.kriteria.bobot }} %)</th>
        {% endfor %}
        {% for item in alternatif %}
        <tr>
            <td>{{ item.nama }}</td>
            {% for matrik in matriks %}
                <td>{{ item.JalurA }}</td>
                <td></td>
                <td></td>
            {% endfor %}
        </tr>
        {% endfor %}
    </tr>
</table>


Title: Rearranging elements inside a superset of dictionaries

Body:
I have a dictionary in Python that comprises of multiple individual dicts:

raw1 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
raw2 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,5.4],'3M':[24,-31,53,5]}
raw3 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[9.8,56,56,7.4],'3M':[24,-31,53,5]}
top_dict = {
  'raw1': raw1,
  'raw2': raw2,
  'raw3': raw3
  }
print top_dict

I would like to flip the columns and rows in the individual dictionaries in my top_dict in such a manner that all the value fields get transposed to the Value Column and the date is appended as a row item.

As an example raw_1 in my top_dict after the flipping will look like this:

 raw_1 = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-14','2017-03-14','2017-03-14','2017-03-15','2017-03-15','2017-03-15'],'Value':[35.6,-7.8,24,56.7,56,-31,41,56,53,41,-3.4,5],'Desc':['SP','1M','3M','SP','1M','3M','SP','1M','3M','SP','1M','3M']}

I know I can use pandas melt on each individual dict but how to iterate that over the entire dictionary of top_dict?

Body:
You may use a dictionary comprehension:

def melt_pandas(sub_dict):
    df = pd.DataFrame(sub_dict)
    melted = pd.melt(df, id_vars='Series_Date')
    return melted.sort_values('Series_Date').to_dict('list')

result = {key: melt_pandas(sub_dict)
          for key, sub_dict in top_dict.items()}

However, you could actually rely on numpy here which should be way faster than creating a pandas DataFrame and melting it:

value_cols = ['SP','1M','3M']
index_col = 'Series_Date'

def melt(sub_dict, val_cols, idx_col):
    vals = np.array([sub_dict[val_col] for val_col in val_cols]).T.flatten()
    desc = val_cols * len(sub_dict[val_cols[0]])
    date = np.repeat(sub_dict[idx_col], len(val_cols))

    return {"Series_Date": date.tolist(),
            "Desc": desc,
            "Value": vals.tolist()}

result_dict = {key: melt(sub_dict, value_cols, index_col)
               for key, sub_dict in top_dict.items()}
print(result)

{'raw2': {'Series_Date': ['2017-03-10', '2017-03-10', '2017-03-10', '2017-03-13', '2017-03-13', '2017-03-13', '2017-03-14', '2017-03-14', '2017-03-14', '2017-03-15', '2017-03-15', '2017-03-15'],
          'Value': [35.6, -7.8, 24.0, 56.7, 56.0, -31.0, 41.0, 56.0, 53.0, 41.0, 5.4, 5.0],
          'Desc': ['SP', '1M', '3M', 'SP', '1M', '3M', 'SP', '1M', '3M', 'SP', '1M', '3M']},
 'raw3': {'Series_Date': ['2017-03-10', '2017-03-10', '2017-03-10', '2017-03-13', '2017-03-13', '2017-03-13', '2017-03-14', '2017-03-14', '2017-03-14', '2017-03-15', '2017-03-15', '2017-03-15'],
          'Value': [35.6, 9.8, 24.0, 56.7, 56.0, -31.0, 41.0, 56.0, 53.0, 41.0, 7.4, 5.0],
          'Desc': ['SP', '1M', '3M', 'SP', '1M', '3M', 'SP', '1M', '3M', 'SP', '1M', '3M']},
 'raw1': {'Series_Date': ['2017-03-10', '2017-03-10', '2017-03-10', '2017-03-13', '2017-03-13', '2017-03-13', '2017-03-14', '2017-03-14', '2017-03-14', '2017-03-15', '2017-03-15', '2017-03-15'],
          'Value': [35.6, -7.8, 24.0, 56.7, 56.0, -31.0, 41.0, 56.0, 53.0, 41.0, -3.4, 5.0],
          'Desc': ['SP', '1M', '3M', 'SP', '1M', '3M', 'SP', '1M', '3M', 'SP', '1M', '3M']}}

Timing the numpy solution yields 10000 loops, best of 3: 57.3 µs per loop in comparison to the pandas solution 100 loops, best of 3: 6.79 ms per loop.


问:
how to convert PHP generated Feed to XML
I've generated a Feed in xml-feed.php file using PHP SimpleXML, how can I "transfer" properly the output to XML file xml-feed.xml ? </p>

```<code>  $xmlFeed = simplexml_load_file('https://feed_URL.com');
  echo "<products>";
  foreach ($xmlFeed->product as $prod) {
    echo "<product>";
    echo "<merchant_id>".$prod->merchant_id."</merchant_id>";
    echo "<upc_ean>".$prod->upc_ean."</upc_ean>";
    echo "<product_url>".$prod->product_url."</product_url>";
    echo "<image_url>".$prod->image_url."</image_url>";
    echo "<designation>".$prod->designation."</designation>";
    echo "<description>".$prod->description."</description>";
    echo "<brand>".$prod->brand."</brand>";
    echo "<category>".$prod->category."</category>";
    echo "<price>".convertCurrency($prod->price, "USD", "PLN")."</price>";
    echo "<availability>".$prod->availability."</availability>";
    echo "<condition>".$prod->condition."</condition>";
    echo "</product>";
  }
  echo "</products>";
</code>```

答:
```<code><?php
$xmlFeed = simplexml_load_file('https://feed_URL.com');
$xml = "<products>\n";
foreach ($xmlFeed->product as $prod) {
    $xml.= "<product>\n";
        foreach($prod as $param => $param_val) {
            if($param!="price"){
                $xml.= "<$param>$param_val</$param>\n";
            }else{
                $xml.= "<$param>".convertCurrency($param_val, "USD", "PLN")."</$param>\n";
            }
        }
    $xml.= "</product>\n";
}
$xml.= "</products>\n";
//Writing to file
file_put_contents("xml-feed.xml", $xml)
</code>```

All you need is to instead of echoing save them in a variable and after write them to a file.

Body:
I've generated a Feed in xml-feed.php file using PHP SimpleXML, how can I "transfer" properly the output to XML file xml-feed.xml ?

  $xmlFeed = simplexml_load_file('https://feed_URL.com');
  echo "<products>";
  foreach ($xmlFeed->product as $prod) {
    echo "<product>";
    echo "<merchant_id>".$prod->merchant_id."</merchant_id>";
    echo "<upc_ean>".$prod->upc_ean."</upc_ean>";
    echo "<product_url>".$prod->product_url."</product_url>";
    echo "<image_url>".$prod->image_url."</image_url>";
    echo "<designation>".$prod->designation."</designation>";
    echo "<description>".$prod->description."</description>";
    echo "<brand>".$prod->brand."</brand>";
    echo "<category>".$prod->category."</category>";
    echo "<price>".convertCurrency($prod->price, "USD", "PLN")."</price>";
    echo "<availability>".$prod->availability."</availability>";
    echo "<condition>".$prod->condition."</condition>";
    echo "</product>";
  }
  echo "</products>";

Body:
<?php
$xmlFeed = simplexml_load_file('https://feed_URL.com');
$xml = "<products>\n";
foreach ($xmlFeed->product as $prod) {
    $xml.= "<product>\n";
        foreach($prod as $param => $param_val) {
            if($param!="price"){
                $xml.= "<$param>$param_val</$param>\n";
            }else{
                $xml.= "<$param>".convertCurrency($param_val, "USD", "PLN")."</$param>\n";
            }
        }
    $xml.= "</product>\n";
}
$xml.= "</products>\n";
//Writing to file
file_put_contents("xml-feed.xml", $xml)

All you need is to instead of echoing save them in a variable and after write them to a file.


问:
AdMob banner in fragments
so I have made an app and now Im putting ad banners here. I followed this tutorial https://firebase.google.com/docs/admob/android/quick-start and everything works fine but I want to put banners to my fragments too. I was looking here on website and I found this to put to fragment

```<code>    MobileAds.initialize(getApplicationContext(), "ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxx");

    AdView mAdView = (AdView)findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
</code>```

but when i click on fragment afterwards the app stop working

Im total beginner in this.

答:
Put bellow code in xml layout file

```<code> <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>
</code>```

Where banner_ad_unit_id is your ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxx

To crate ad unit id follow bellow link
  https://support.google.com/admob/answer/3052638

Add dependancy in build.gradle file

compile 'com.google.firebase:firebase-ads:10.0.0'

Now to display Ads write bellow code in Activity

```<code>        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
</code>```

Title: AdMob banner in fragments

Body:
so I have made an app and now Im putting ad banners here. I followed this tutorial https://firebase.google.com/docs/admob/android/quick-start and everything works fine but I want to put banners to my fragments too. I was looking here on website and I found this to put to fragment

    MobileAds.initialize(getApplicationContext(), "ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxx");

    AdView mAdView = (AdView)findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

but when i click on fragment afterwards the app stop working

Im total beginner in this.

Body:
Put bellow code in xml layout file

 <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>

Where banner_ad_unit_id is your ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxx

To crate ad unit id follow bellow link
  https://support.google.com/admob/answer/3052638

Add dependancy in build.gradle file

compile 'com.google.firebase:firebase-ads:10.0.0'

Now to display Ads write bellow code in Activity

        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);


问:
Laravel save($request->all()) Error
I have a question, I've been developing laravel application and I encountered this strange error:

QueryException in Connection.php line 770:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`testenv`.`products`, CONSTRAINT `products_tenant_id_foreign` FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`)) (SQL: insert into `products` () values ())
```

<p>and Here's my store function</p>

```public function store(Request $request)
{
    $product = new Product;

    /*
    $product->name = $request->name;
    $product->stockQty = $request->stockQty;
    $product->minimumQty = $request->minimumQty;
    $product->description = $request->description;
    $product->notes = $request->notes;
    $product->tenantMargin = $request->tenantMargin;
    $product->length = $request->length;
    $product->height = $request->height;
    $product->weight = $request->weight;
    $product->showLength = $request->showLength;
    $product->showHeight = $request->showHeight;
    $product->showWeight = $request->showWeight;
    $product->size = $request->size;
    $product->colorName = $request->colorName;
    $product->colorHex = $request->colorHex;
    $product->isActive =$request->isActive;
    $product->tenant_id = $request->tenant_id;
    $product->productviewid = $request->productviewid;
    */

    $product->save($request->all());

    return "product successfully created";
}
```

And the error only occurs if i use

$product->save($request->all());

but if I un-comment the the commented code and use

$product->save()

instead, it works, no error.

Can anyone help me to find the source of this problem?

答:
Since you're not using the mass assignment feature, you should use $product->save(); here.

If you want to use the mass assignment, just do this:

```<code>public function store(Request $request)
{
    Product::create($request->all());
}
</code>```

Title: Laravel save($request->all()) Error

Body:
I have a question, I've been developing laravel application and I encountered this strange error:

QueryException in Connection.php line 770:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`testenv`.`products`, CONSTRAINT `products_tenant_id_foreign` FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`)) (SQL: insert into `products` () values ())

and Here's my store function

public function store(Request $request)
{
    $product = new Product;

    /*
    $product->name = $request->name;
    $product->stockQty = $request->stockQty;
    $product->minimumQty = $request->minimumQty;
    $product->description = $request->description;
    $product->notes = $request->notes;
    $product->tenantMargin = $request->tenantMargin;
    $product->length = $request->length;
    $product->height = $request->height;
    $product->weight = $request->weight;
    $product->showLength = $request->showLength;
    $product->showHeight = $request->showHeight;
    $product->showWeight = $request->showWeight;
    $product->size = $request->size;
    $product->colorName = $request->colorName;
    $product->colorHex = $request->colorHex;
    $product->isActive =$request->isActive;
    $product->tenant_id = $request->tenant_id;
    $product->productviewid = $request->productviewid;
    */

    $product->save($request->all());

    return "product successfully created";
}

And the error only occurs if i use

$product->save($request->all());

but if I un-comment the the commented code and use

$product->save()

instead, it works, no error.

Can anyone help me to find the source of this problem?

Body:
Since you're not using the mass assignment feature, you should use $product->save(); here.

If you want to use the mass assignment, just do this:

public function store(Request $request)
{
    Product::create($request->all());
}


问:
Simple ViewPager Application causing memory leak error
I try to made a example simple ViewPager app but Ive got error. I thought it was the image resolution fault but after changing ImageView as TextView and writing example text on it Ive got the same error. (after commented the ViewPAger implementation works fine)

channel '2d5df67 com.example.k.myapplication/com.example.k.myapplication.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!

```<code>public class MainActivity extends AppCompatActivity {
List<String> list;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

  list = new ArrayList<>();
    list.add("https://www.w3schools.com/css/trolltunga.jpg");
    list.add("http://www.esa.int/var/esa/storage/images/esa_multimedia/images/2016/03/ultraviolet_image_shows_the_sun_s_intricate_atmosphere/15891756-1-eng-GB/Ultraviolet_image_shows_the_Sun_s_intricate_atmosphere_node_full_image_2.jpg");
    list.add("http://pnge.org/wp-content/uploads/2017/03/1488980395_548_image.jpg");
    list.add("http://pnge.org/wp-content/uploads/2017/03/image.png");
    list.add("https://www.w3schools.com/css/trolltunga.jpg");
    list.add("http://www.esa.int/var/esa/storage/images/esa_multimedia/images/2016/03/ultraviolet_image_shows_the_sun_s_intricate_atmosphere/15891756-1-eng-GB/Ultraviolet_image_shows_the_Sun_s_intricate_atmosphere_node_full_image_2.jpg");
    list.add("http://pnge.org/wp-content/uploads/2017/03/1488980395_548_image.jpg");
    list.add("http://pnge.org/wp-content/uploads/2017/03/image.png");
    viewPager  = (ViewPager)findViewById(R.id.viewPAger);
    ViewPAgerAdapter adapter = new ViewPAgerAdapter(MainActivity.this,list);
    viewPager.setAdapter(adapter);

}}
</code>```

Adapter Class

```<code>public class ViewPAgerAdapter extends PagerAdapter {

    private List<String> record;
    private Context context;
   private LayoutInflater inflater;
    public ViewPAgerAdapter(Context context, List<String>record) {
        this.record=record;
        this.context=context;
        inflater=(LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        View view = inflater.inflate(R.layout.item,container);

        ImageView img = (ImageView)view.findViewById(R.id.image);
      Glide.with(context).load(record.get(position)).fitCenter().into(img);

        container.addView(view);
        return view;
    }

    @Override
    public int getCount() {
        return record.size();
    }

    @Override
    public int getItemPosition(Object object) {
        return super.getItemPosition(object);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((LinearLayout) object);
    }
}
</code>```

Item layout

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image"
    />
</LinearLayout>
</code>```

activity layout

```<code>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.k.myapplication.MainActivity">

<android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/viewPAger"/>
</LinearLayout>
</code>```

答: try adding this to your manifest -- android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|mcc|mnc"</p>

Body:
I try to made a example simple ViewPager app but Ive got error. I thought it was the image resolution fault but after changing ImageView as TextView and writing example text on it Ive got the same error. (after commented the ViewPAger implementation works fine)

channel '2d5df67 com.example.k.myapplication/com.example.k.myapplication.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!

public class MainActivity extends AppCompatActivity {
List<String> list;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

  list = new ArrayList<>();
    list.add("https://www.w3schools.com/css/trolltunga.jpg");
    list.add("http://www.esa.int/var/esa/storage/images/esa_multimedia/images/2016/03/ultraviolet_image_shows_the_sun_s_intricate_atmosphere/15891756-1-eng-GB/Ultraviolet_image_shows_the_Sun_s_intricate_atmosphere_node_full_image_2.jpg");
    list.add("http://pnge.org/wp-content/uploads/2017/03/1488980395_548_image.jpg");
    list.add("http://pnge.org/wp-content/uploads/2017/03/image.png");
    list.add("https://www.w3schools.com/css/trolltunga.jpg");
    list.add("http://www.esa.int/var/esa/storage/images/esa_multimedia/images/2016/03/ultraviolet_image_shows_the_sun_s_intricate_atmosphere/15891756-1-eng-GB/Ultraviolet_image_shows_the_Sun_s_intricate_atmosphere_node_full_image_2.jpg");
    list.add("http://pnge.org/wp-content/uploads/2017/03/1488980395_548_image.jpg");
    list.add("http://pnge.org/wp-content/uploads/2017/03/image.png");
    viewPager  = (ViewPager)findViewById(R.id.viewPAger);
    ViewPAgerAdapter adapter = new ViewPAgerAdapter(MainActivity.this,list);
    viewPager.setAdapter(adapter);

}}

Adapter Class

public class ViewPAgerAdapter extends PagerAdapter {

    private List<String> record;
    private Context context;
   private LayoutInflater inflater;
    public ViewPAgerAdapter(Context context, List<String>record) {
        this.record=record;
        this.context=context;
        inflater=(LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        View view = inflater.inflate(R.layout.item,container);

        ImageView img = (ImageView)view.findViewById(R.id.image);
      Glide.with(context).load(record.get(position)).fitCenter().into(img);

        container.addView(view);
        return view;
    }

    @Override
    public int getCount() {
        return record.size();
    }

    @Override
    public int getItemPosition(Object object) {
        return super.getItemPosition(object);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((LinearLayout) object);
    }
}

Item layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image"
    />
</LinearLayout>

activity layout

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.k.myapplication.MainActivity">

<android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/viewPAger"/>
</LinearLayout>


问:
How to load a PHP page into a div with jQuery and AJAX?
I am trying to write a function that will call getproduct.php?id=xxx when clicked.  I can get the innerHTML portion to appear, but how do I also call the php page that actually does the work?

```<code>var id = id;
document.getElementById("digital_download").innerHTML =
    "Downloading...Please be patient. The process can take a few minutes.";
url = getproduct.php?id=id;
</code>```

答:
Hi You can call the below function to perform this it loads the data from server on success you can create fail function as well</p>

```<code> function setValue(Id) {
 document.getElementById("digital_download").innerHTML =
"Downloading...Please be patient. The process can take a few minutes.";
 var data1 = {
        message: Id,
    };

    $.ajax({
      data: data1,
      type: 'GET',
      url: "http://urltoscript/index.php",
     cache: false,
        dataType: "json",
        crossDomain: true,
        success: function(data) {
        console.log("Response for cancel is: " + data);

     document.getElementById("digital_download").innerHTML =  data

      }
    });

 }
</code>```

Body:
I am trying to write a function that will call getproduct.php?id=xxx when clicked.  I can get the innerHTML portion to appear, but how do I also call the php page that actually does the work?

var id = id;
document.getElementById("digital_download").innerHTML =
    "Downloading...Please be patient. The process can take a few minutes.";
url = getproduct.php?id=id;

Body:
Hi You can call the below function to perform this it loads the data from server on success you can create fail function as well

 function setValue(Id) {
 document.getElementById("digital_download").innerHTML =
"Downloading...Please be patient. The process can take a few minutes.";
 var data1 = {
        message: Id,
    };

    $.ajax({
      data: data1,
      type: 'GET',
      url: "http://urltoscript/index.php",
     cache: false,
        dataType: "json",
        crossDomain: true,
        success: function(data) {
        console.log("Response for cancel is: " + data);

     document.getElementById("digital_download").innerHTML =  data

      }
    });

 }


答: Looking at the third code block under section C.2.2.1 found here (property staticField). Names need to be fully qualified.</p>

Title: How to set a custom property naming strategy with MappingJackson2HttpMessageConverter using XML Config?