问:
insert a record with value 0.1, 0.2 and when any flag changed it should start with 1.0,1.1.. and so on
I have a requirement while creating an initial quote, the number should start with 0.1, and then after that each number is added by +1 (i.e. 0.2) and so on...

In between if any flag is changed, then the number should start with 1.0, 1.1.. and so on...

How can I implement this?

答:
Here, I have created some data as per your sample.

```<code>    create table test_sample ( v VARCHAR(2), n NUMBER );

           create table sample_stage as
           SELECT 'S1' s, 'N' stage_flag FROM DUAL UNION ALL
           SELECT 'S2' s , 'N' stage_flag  FROM DUAL UNION ALL
           SELECT 'S3' s, 'N' stage_flag FROM DUAL UNION ALL
           SELECT 'S1' s, 'Y' stage_flag FROM DUAL UNION ALL
           SELECT 'S2' s, 'N' stage_flag FROM DUAL UNION ALL
           SELECT 'S3' s, 'N' stage_flag FROM DUAL UNION ALL
           SELECT 'S1' s, 'Y' stage_flag FROM DUAL ;
</code>```

Here is the Pl/SQL code.

```<code>           DECLARE
             incr NUMBER;
           BEGIN
             INSERT
             INTO test_sample VALUES
               (
                 'S1',
                 0.1
               ) ;
             FOR stg IN
             ( SELECT * FROM sample_stage ORDER BY ROWID
             )
             LOOP
               IF stg.stage_flag = 'N' THEN
                 SELECT n+0.1
                 INTO incr
                 FROM test_sample
                 WHERE ROWID IN
                   ( SELECT MAX(ROWID) FROM test_sample
                   );
               ELSE
                 incr := 1.0;
               END IF;
               INSERT INTO test_sample VALUES
                 ( stg.s , incr
                 );
             END LOOP;
           END;
           /
</code>```

Data   got inserted in the following form.

```<code> SELECT * FROM test_sample;

       S1   0.1
       S1   0.2
       S2   0.3
       S3   0.4
       S1   1
       S2   1.1
       S3   1.2
       S1   1
</code>```

Please Share your feedback.Thanks

Body:
Here, I have created some data as per your sample.

    create table test_sample ( v VARCHAR(2), n NUMBER );

           create table sample_stage as
           SELECT 'S1' s, 'N' stage_flag FROM DUAL UNION ALL
           SELECT 'S2' s , 'N' stage_flag  FROM DUAL UNION ALL
           SELECT 'S3' s, 'N' stage_flag FROM DUAL UNION ALL
           SELECT 'S1' s, 'Y' stage_flag FROM DUAL UNION ALL
           SELECT 'S2' s, 'N' stage_flag FROM DUAL UNION ALL
           SELECT 'S3' s, 'N' stage_flag FROM DUAL UNION ALL
           SELECT 'S1' s, 'Y' stage_flag FROM DUAL ;

Here is the Pl/SQL code.

           DECLARE
             incr NUMBER;
           BEGIN
             INSERT
             INTO test_sample VALUES
               (
                 'S1',
                 0.1
               ) ;
             FOR stg IN
             ( SELECT * FROM sample_stage ORDER BY ROWID
             )
             LOOP
               IF stg.stage_flag = 'N' THEN
                 SELECT n+0.1
                 INTO incr
                 FROM test_sample
                 WHERE ROWID IN
                   ( SELECT MAX(ROWID) FROM test_sample
                   );
               ELSE
                 incr := 1.0;
               END IF;
               INSERT INTO test_sample VALUES
                 ( stg.s , incr
                 );
             END LOOP;
           END;
           /

Data   got inserted in the following form.

 SELECT * FROM test_sample;

       S1   0.1
       S1   0.2
       S2   0.3
       S3   0.4
       S1   1
       S2   1.1
       S3   1.2
       S1   1

Please Share your feedback.Thanks


来源: stackexchange

问:
Finding complete SQL text running behind locked processes in SQL Server
How can I Identify which SQL is locking the table at the time of any transition, I want to see and analyze the full SQL text.

dbcc inputbuffer (pid); is not displaying the complete SQL Text.

答:
If you know the SPID, then you can use this:

```<code>SELECT text
FROM sys.dm_exec_requests
    CROSS APPLY ::fn_get_sql(sql_handle)
WHERE session_id=@spid
</code>```

Here's the MSDN reference for fn_get_sql

ContentLicense: CC BY-SA 2.5

Body:
If you know the SPID, then you can use this:

SELECT text
FROM sys.dm_exec_requests
    CROSS APPLY ::fn_get_sql(sql_handle)
WHERE session_id=@spid

Here's the MSDN reference for fn_get_sql


问:
Expected argument of type "AppBundle\Entity\MyMachine or null", "integer" given
I have problem that addin data with my database.

I have error

```<code>Expected argument of type "AppBundle\Entity\VoiceAnswerMachine or null", "integer" given
</code>```

My entity One

```<code>/**
 * @ORM\GeneratedValue(strategy="AUTO")
 * @ORM\Id
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="VoiceAnsweringMachine", inversedBy="uid")
 */
protected $uid;

/**
 * @ORM\Column(type="integer", nullable=true)
 */
private $buttonNumber;

/**
 * @ORM\Column(type="text", nullable=false)
 */
private $linkToMusic;

..... getters, setters

/**
 * Set uid
 *
 * @param \AppBundle\Entity\VoiceAnswerMachine $uid
 *
 * @return AnsweringMachine
 */
public function setUid(\AppBundle\Entity\VoiceAnswerMachine $uid = null)
{
    $this->uid = $uid;

    return $this;
}

/**
 * Get uid
 *
 * @return \AppBundle\Entity\VoiceAnswerMachine
 */
public function getUid()
{
    return $this->uid;
}
</code>```

My entity Two

```<code>/**
 * @ORM\GeneratedValue(strategy="AUTO")
 * @ORM\Id
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\OneToMany(targetEntity="AnsweringMachine", mappedBy="uid")
 */
private $uid;

/**
 * @ORM\Column(type="integer")
 */
private $numberMachine;

/**
 * @ORM\Column(type="string")
 */
private $nameMachine;

/**
 * @ORM\Column(type="text")
 */
private $linkToVoice;

/**
 * Constructor
 */
public function __construct()
{
    $this->uid = new \Doctrine\Common\Collections\ArrayCollection();
}

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set numberMachine
 *
 * @param integer $numberMachine
 *
 * @return VoiceAnsweringMachine
 */
public function setNumberMachine($numberMachine)
{
    $this->numberMachine = $numberMachine;

    return $this;
}

/**
 * Get numberMachine
 *
 * @return integer
 */
public function getNumberMachine()
{
    return $this->numberMachine;
}

/**
 * Set nameMachine
 *
 * @param string $nameMachine
 *
 * @return VoiceAnsweringMachine
 */
public function setNameMachine($nameMachine)
{
    $this->nameMachine = $nameMachine;

    return $this;
}

/**
 * Get nameMachine
 *
 * @return string
 */
public function getNameMachine()
{
    return $this->nameMachine;
}

/**
 * Set linkToVoice
 *
 * @param string $linkToVoice
 *
 * @return VoiceAnsweringMachine
 */
public function setLinkToVoice($linkToVoice)
{
    $this->linkToVoice = $linkToVoice;

    return $this;
}

/**
 * Get linkToVoice
 *
 * @return string
 */
public function getLinkToVoice()
{
    return $this->linkToVoice;
}

/**
 * Add uid
 *
 * @param \AppBundle\Entity\AnsweringMachine $uid
 *
 * @return VoiceAnsweringMachine
 */
public function addUid(\AppBundle\Entity\AnsweringMachine $uid)
{
    $this->uid[] = $uid;

    return $this;
}

/**
 * Remove uid
 *
 * @param \AppBundle\Entity\AnsweringMachine $uid
 */
public function removeUid(\AppBundle\Entity\AnsweringMachine $uid)
{
    $this->uid->removeElement($uid);
}

/**
 * Get uid
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getUid()
{
    return $this->uid;
}
</code>```

My Twig

```<code><div class="row">
                            <div class="col-sm-12">
                                {{ form_start(answeringForm, {'attr': {'autocomplete': 'off'}}) }}
                                <div class="form-group">
                                    <div class="col-sm-12">
                                        {{ form_label(answeringForm.uid, 'Wybierz maszynę') }}
                                    </div>
                                    <div class="col-sm-12" style="margin-bottom: 15px;">
                                        {{ form_errors(answeringForm.uid) }}
                                        {{ form_widget(answeringForm.uid) }}
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-sm-12">
                                        {{ form_label(answeringForm.buttonNumber, 'Numer przycisku do przekierowania') }}
                                    </div>
                                    <div class="col-sm-12" style="margin-bottom: 15px;">
                                        {{ form_errors(answeringForm.buttonNumber) }}
                                        {{ form_widget(answeringForm.buttonNumber) }}
                                    </div>
                                </div>
etc .....
</code>```

My build form

```<code>public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('uid', ChoiceType::class, array(
                    'choices'   => array('Dla dzwoniących' => 1, 'Oddzwaniająca' => 2),
                    'required'  => false,
                    'label' => 'Wybierz maszynę',
            ))
            ->add('buttonNumber', ChoiceType::class, array(
                    'choices'   => array('1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9),
                    'required'  => false,
                    'label' => 'Numer przycisku'
            ))
            ->add('linkToMusic', TextType::class, [
                'label' => 'Adres URL do muzyki',
                'required' => true
            ])
            ->add('telephoneNumber', PhoneNumberType::class, [
                'label' => 'Numer Telefonu',
                'required'  => false,
                'widget' => PhoneNumberType::WIDGET_COUNTRY_CHOICE,
                'preferred_country_choices' => ['PL']
            ])
            ->add('acceptRegulations', ChoiceType::class, array(
                    'choices'   => array('1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9),
                    'required'  => false,
                    'label' => 'Numer przycisku do akceptacji regulaminu'
            ))
            ->add('submit', \Symfony\Component\Form\Extension\Core\Type\SubmitType::class, array(
                'label' => 'Zapisz'
            ));
}
</code>```

I have adding $buttoNumber, $linkToMusic etc but I don't have adding $uid
I tried clear my cache but I don't know I have a problem. Help me :)

答:
```<code>'choices'   => array('Dla dzwoniących' => 1, 'Oddzwaniająca' => 2),
</code>```

You pass an integer , but you need to pass an entity of type VoiceAnswerMachine

ContentLicense: CC BY-SA 3.0

Body:
I have problem that addin data with my database.

I have error

Expected argument of type "AppBundle\Entity\VoiceAnswerMachine or null", "integer" given

My entity One

/**
 * @ORM\GeneratedValue(strategy="AUTO")
 * @ORM\Id
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="VoiceAnsweringMachine", inversedBy="uid")
 */
protected $uid;

/**
 * @ORM\Column(type="integer", nullable=true)
 */
private $buttonNumber;

/**
 * @ORM\Column(type="text", nullable=false)
 */
private $linkToMusic;

..... getters, setters

/**
 * Set uid
 *
 * @param \AppBundle\Entity\VoiceAnswerMachine $uid
 *
 * @return AnsweringMachine
 */
public function setUid(\AppBundle\Entity\VoiceAnswerMachine $uid = null)
{
    $this->uid = $uid;

    return $this;
}

/**
 * Get uid
 *
 * @return \AppBundle\Entity\VoiceAnswerMachine
 */
public function getUid()
{
    return $this->uid;
}

My entity Two

/**
 * @ORM\GeneratedValue(strategy="AUTO")
 * @ORM\Id
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\OneToMany(targetEntity="AnsweringMachine", mappedBy="uid")
 */
private $uid;

/**
 * @ORM\Column(type="integer")
 */
private $numberMachine;

/**
 * @ORM\Column(type="string")
 */
private $nameMachine;

/**
 * @ORM\Column(type="text")
 */
private $linkToVoice;

/**
 * Constructor
 */
public function __construct()
{
    $this->uid = new \Doctrine\Common\Collections\ArrayCollection();
}

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set numberMachine
 *
 * @param integer $numberMachine
 *
 * @return VoiceAnsweringMachine
 */
public function setNumberMachine($numberMachine)
{
    $this->numberMachine = $numberMachine;

    return $this;
}

/**
 * Get numberMachine
 *
 * @return integer
 */
public function getNumberMachine()
{
    return $this->numberMachine;
}

/**
 * Set nameMachine
 *
 * @param string $nameMachine
 *
 * @return VoiceAnsweringMachine
 */
public function setNameMachine($nameMachine)
{
    $this->nameMachine = $nameMachine;

    return $this;
}

/**
 * Get nameMachine
 *
 * @return string
 */
public function getNameMachine()
{
    return $this->nameMachine;
}

/**
 * Set linkToVoice
 *
 * @param string $linkToVoice
 *
 * @return VoiceAnsweringMachine
 */
public function setLinkToVoice($linkToVoice)
{
    $this->linkToVoice = $linkToVoice;

    return $this;
}

/**
 * Get linkToVoice
 *
 * @return string
 */
public function getLinkToVoice()
{
    return $this->linkToVoice;
}

/**
 * Add uid
 *
 * @param \AppBundle\Entity\AnsweringMachine $uid
 *
 * @return VoiceAnsweringMachine
 */
public function addUid(\AppBundle\Entity\AnsweringMachine $uid)
{
    $this->uid[] = $uid;

    return $this;
}

/**
 * Remove uid
 *
 * @param \AppBundle\Entity\AnsweringMachine $uid
 */
public function removeUid(\AppBundle\Entity\AnsweringMachine $uid)
{
    $this->uid->removeElement($uid);
}

/**
 * Get uid
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getUid()
{
    return $this->uid;
}

My Twig

                                {{ form_start(answeringForm, {'attr': {'autocomplete': 'off'}}) }}

                                        {{ form_label(answeringForm.uid, 'Wybierz maszynę') }}

                                        {{ form_errors(answeringForm.uid) }}
                                        {{ form_widget(answeringForm.uid) }}

                                        {{ form_label(answeringForm.buttonNumber, 'Numer przycisku do przekierowania') }}

                                        {{ form_errors(answeringForm.buttonNumber) }}
                                        {{ form_widget(answeringForm.buttonNumber) }}

etc .....

My build form

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('uid', ChoiceType::class, array(
                    'choices'   => array('Dla dzwoniących' => 1, 'Oddzwaniająca' => 2),
                    'required'  => false,
                    'label' => 'Wybierz maszynę',
            ))
            ->add('buttonNumber', ChoiceType::class, array(
                    'choices'   => array('1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9),
                    'required'  => false,
                    'label' => 'Numer przycisku'
            ))
            ->add('linkToMusic', TextType::class, [
                'label' => 'Adres URL do muzyki',
                'required' => true
            ])
            ->add('telephoneNumber', PhoneNumberType::class, [
                'label' => 'Numer Telefonu',
                'required'  => false,
                'widget' => PhoneNumberType::WIDGET_COUNTRY_CHOICE,
                'preferred_country_choices' => ['PL']
            ])
            ->add('acceptRegulations', ChoiceType::class, array(
                    'choices'   => array('1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9),
                    'required'  => false,
                    'label' => 'Numer przycisku do akceptacji regulaminu'
            ))
            ->add('submit', \Symfony\Component\Form\Extension\Core\Type\SubmitType::class, array(
                'label' => 'Zapisz'
            ));
}

I have adding $buttoNumber, $linkToMusic etc but I don't have adding $uid
I tried clear my cache but I don't know I have a problem. Help me :)

Body:
'choices'   => array('Dla dzwoniących' => 1, 'Oddzwaniająca' => 2),

You pass an integer , but you need to pass an entity of type VoiceAnswerMachine


问:
Read comma separated string in Sql server in loop
I have nvarchar data like this:

'20030,20031,20033,20034,20065,20045,20044'

I want to read all this by spliting into array or read one by one in spliting process and do further process.

I have tried this good article but not able to do it.

答:
Not hard at all. It can be best solved using recursion

```<code>create table #Testdata2(Data varchar(max))
insert #Testdata2 select '20030,20031,20033,20034,20065,20045,20044'

;with tmp(DataItem, Data) as (
select LEFT(Data, CHARINDEX(',',Data+',')-1),
    STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from #Testdata2
union all
select LEFT(Data, CHARINDEX(',',Data+',')-1),
    STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from tmp
where Data > ''
)
select DataItem
from tmp
OPTION (maxrecursion 0)
</code>```

output :

```<code>(select)
 Data
 ----------------
 20030,20031,20033,20034,20065,20045,20044

(query)
DataItem
----------------
20030
20031
20033
20034
20065
20045
20044
</code>```

Body:
Not hard at all. It can be best solved using recursion

create table #Testdata2(Data varchar(max))
insert #Testdata2 select '20030,20031,20033,20034,20065,20045,20044'

;with tmp(DataItem, Data) as (
select LEFT(Data, CHARINDEX(',',Data+',')-1),
    STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from #Testdata2
union all
select LEFT(Data, CHARINDEX(',',Data+',')-1),
    STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from tmp
where Data > ''
)
select DataItem
from tmp
OPTION (maxrecursion 0)

output :

(select)
 Data
 ----------------
 20030,20031,20033,20034,20065,20045,20044

(query)
DataItem
----------------
20030
20031
20033
20034
20065
20045
20044


问:
How to avoid "knp_menu.factory" deprecation?
I'm trying to use KNPMenuBundle with Sumfony 3.3 but I'm getting this annoying warning:

Autowiring services based on the types they implement is deprecated
  since Symfony 3.3 and won't be supported in version 4.0. You should
  rename (or alias) the "knp_menu.factory" service to
  "Knp\Menu\FactoryInterface" instead.

Trace:
    {..../vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php:344:
    }

I did not set this knp_menu.factory at all, probably it was automatically set by the bundle.

Do I need to configure anything to make this warning go away?

答:
I resolved it like this:

```<code>app.component_menu.builder:
    class: AppBundle\Component\Menu\Builder
    arguments: ['@knp_menu.factory', '@event_dispatcher']
    calls:
        - [setAuthorizationChecker, ['@security.authorization_checker']]

Knp\Menu\ItemInterface:
    class: Knp\Menu\MenuItem
    factory: ['@app.component_menu.builder', mainMenu]
    arguments: ['@knp_menu.matcher']
    tags:
        - { name: knp_menu.menu, alias: main }

Knp\Menu\FactoryInterface:
    alias: knp_menu.factory
    public: false
</code>```

Not sure if this is the recommended resolution, but it removes the deprecation notices.

Body:
I resolved it like this:

app.component_menu.builder:
    class: AppBundle\Component\Menu\Builder
    arguments: ['@knp_menu.factory', '@event_dispatcher']
    calls:
        - [setAuthorizationChecker, ['@security.authorization_checker']]

Knp\Menu\ItemInterface:
    class: Knp\Menu\MenuItem
    factory: ['@app.component_menu.builder', mainMenu]
    arguments: ['@knp_menu.matcher']
    tags:
        - { name: knp_menu.menu, alias: main }

Knp\Menu\FactoryInterface:
    alias: knp_menu.factory
    public: false

Not sure if this is the recommended resolution, but it removes the deprecation notices.


问:
Cutting a text file into multiple parts in Emacs
I am using the GNU Emacs 23 editor. I have this huge text file containing about 10,000 lines which I want to chop into multiple files. Using the mouse to select the required text to paste in another file is the really painful.  Also this is prone to errors too.

If I want to divide the text file according to the line numbers into say 4 file where
first file:lines 1-2500
second file:lines 2500-5000
third file :lines 5000-7500
fourth file: lines: 7500-10000

how do I do this? At  the very least, is there any efficient way to copy large regions of the file just by specifying line numbers

答:
C-u is your friend. Try this:</p>

```<code>C-spc (set mark at point)
C-u 2500 <down> (equivalent to pressing the down key 2500 times)
M-w (copy)
</code>```

Body:
C-u is your friend. Try this:

C-spc (set mark at point)
C-u 2500 <down> (equivalent to pressing the down key 2500 times)
M-w (copy)


问:
Calling a function in a separate function file - matlab
From what I understood of matlab, if you want to define a function and use it in your "main file" you need to write the function in a separate file and to call it at the beginning of your "main file" with addpath('...\myfunction.m').

Now let's say I define a function f1 in a file f1.m that I use in main.m, if I want to define a function f2 (in another file) that needs to call f1, can I use addpath()...\f1.m in my f2.m file ? Or what is the best way of calling f1 in f2 ?

答:
You should create a startup.m file that you run at the start. located in your current directory. This should include all of your paths you need to add.

So your m file would look like :

```<code>startup
f1
f2
</code>```

Body:
You should create a startup.m file that you run at the start. located in your current directory. This should include all of your paths you need to add.

So your m file would look like :

startup
f1
f2


问:
finding loop in linked list using HashMap in java
i am writing code for lop detection in linked list using hashmap. why it goes in infinite loop?</p>

```<code>boolean hasCycle(Node head) {
    HashMap<Integer,Node> map = new HashMap<Integer,Node>();
         //<Address,data>
    if(head == null || head.next == null)
        return false;
    Node p = head;
    while(p.next!=null)
    {
        if(map.containsValue(p.next))
        {
            return true;
        }
        else
        {
            map.put(p.data,p.next);
        }
        p = p.next;
    }
    return false;
}
</code>```

答:
Your code calls

```<code>map.containsValue(p.next)
</code>```

This method iterates through the whole map looking for an object that is equal to the passed argument. To do that, it calls your Node.equals() method. It is highly probable that this is where it's going into an infinite loop.

To solve it, you could just use a HashSet of the Node objects (as mentioned in the comments) and check that your equals() and hashCode() methods are correct. But there is also another way to check for cycles, which doesn't involve the use of any extra memory. You just use two iterators, one going at half the speed of the other. If there is a cycle, the faster iterator will lap the slower one.

Body:
i am writing code for lop detection in linked list using hashmap. why it goes in infinite loop?

boolean hasCycle(Node head) {
    HashMap<Integer,Node> map = new HashMap<Integer,Node>();
         //<Address,data>
    if(head == null || head.next == null)
        return false;
    Node p = head;
    while(p.next!=null)
    {
        if(map.containsValue(p.next))
        {
            return true;
        }
        else
        {
            map.put(p.data,p.next);
        }
        p = p.next;
    }
    return false;
}

Body:
Your code calls

map.containsValue(p.next)

This method iterates through the whole map looking for an object that is equal to the passed argument. To do that, it calls your Node.equals() method. It is highly probable that this is where it's going into an infinite loop.

To solve it, you could just use a HashSet of the Node objects (as mentioned in the comments) and check that your equals() and hashCode() methods are correct. But there is also another way to check for cycles, which doesn't involve the use of any extra memory. You just use two iterators, one going at half the speed of the other. If there is a cycle, the faster iterator will lap the slower one.


答:
Use the Node as key and the data field as value and then check whether the HashMap contains the key:

```<code>boolean hasCycle(Node head) {
   HashMap<Node,Integer> map = new HashMap<Node,Integer>();
   if(head == null || head.next == null)
      return false;
   Node p = head;
   while(p.next!=null) {
      if (map.containsKey(p.next)) {
         return true;
      } else {
         map.put(p.next,p.data);
      }
      p = p.next;
    }
    return false;
}
</code>```

And also follow the Java Code Conventions.

Title: finding loop in linked list using HashMap in java

Body:
Use the Node as key and the data field as value and then check whether the HashMap contains the key:

boolean hasCycle(Node head) {
   HashMap<Node,Integer> map = new HashMap<Node,Integer>();
   if(head == null || head.next == null)
      return false;
   Node p = head;
   while(p.next!=null) {
      if (map.containsKey(p.next)) {
         return true;
      } else {
         map.put(p.next,p.data);
      }
      p = p.next;
    }
    return false;
}

And also follow the Java Code Conventions.


问:
sort array according to date
Sort array according to date,
problem is date saved in string format can this is possible to sort array without change date in NSDate object.(Core Data).

string format is mm/dd/yyyy

答:
```<code>    -(NSMutableArray *)sortByStringDate:(NSMutableArray *)unsortedArray
{
    NSMutableArray *tempArray=[NSMutableArray array];
    for(int i=0;i<[unsortedArray count];i++)
    {

        NSDateFormatter *df=[[NSDateFormatter alloc]init];
      objModel=[unsortedArray objectAtIndex:i];

        [df setDateFormat:@"MM/dd/yyyy"];
        NSDate *date=[df dateFromString:objModel.sDate];
        NSMutableDictionary *dict=[NSMutableDictionary dictionary];
        [dict setObject:objModel forKey:@"entity"];
        [dict setObject:date forKey:@"date"];
        [tempArray addObject:dict];
    }

    NSInteger counter=[tempArray count];
    NSDate *compareDate;
    NSInteger index;
    for(int i=0;i<counter;i++)
    {
        index=i;
        compareDate=[[tempArray objectAtIndex:i] valueForKey:@"date"];
        NSDate *compareDateSecond;
        for(int j=i+1;j<counter;j++)
        {
            compareDateSecond=[[tempArray objectAtIndex:j] valueForKey:@"date"];
            NSComparisonResult result = [compareDate compare:compareDateSecond];
           if(result == NSOrderedAscending)
           {
               compareDate=compareDateSecond;
               index=j;
           }
        }
        if(i!=index)
          [tempArray exchangeObjectAtIndex:i withObjectAtIndex:index];
    }

    [unsortedArray removeAllObjects];
    for(int i=0;i<[tempArray count];i++)
    {
        [unshortedArray addObject:[[tempArray objectAtIndex:i] valueForKey:@"entity"]];
    }
    return unsortedArray;

}
</code>```

This works for me.

Title: sort array according to date

Body:
    -(NSMutableArray *)sortByStringDate:(NSMutableArray *)unsortedArray
{
    NSMutableArray *tempArray=[NSMutableArray array];
    for(int i=0;i<[unsortedArray count];i++)
    {

        NSDateFormatter *df=[[NSDateFormatter alloc]init];
      objModel=[unsortedArray objectAtIndex:i];

        [df setDateFormat:@"MM/dd/yyyy"];
        NSDate *date=[df dateFromString:objModel.sDate];
        NSMutableDictionary *dict=[NSMutableDictionary dictionary];
        [dict setObject:objModel forKey:@"entity"];
        [dict setObject:date forKey:@"date"];
        [tempArray addObject:dict];
    }

    NSInteger counter=[tempArray count];
    NSDate *compareDate;
    NSInteger index;
    for(int i=0;i<counter;i++)
    {
        index=i;
        compareDate=[[tempArray objectAtIndex:i] valueForKey:@"date"];
        NSDate *compareDateSecond;
        for(int j=i+1;j<counter;j++)
        {
            compareDateSecond=[[tempArray objectAtIndex:j] valueForKey:@"date"];
            NSComparisonResult result = [compareDate compare:compareDateSecond];
           if(result == NSOrderedAscending)
           {
               compareDate=compareDateSecond;
               index=j;
           }
        }
        if(i!=index)
          [tempArray exchangeObjectAtIndex:i withObjectAtIndex:index];
    }

    [unsortedArray removeAllObjects];
    for(int i=0;i<[tempArray count];i++)
    {
        [unshortedArray addObject:[[tempArray objectAtIndex:i] valueForKey:@"entity"]];
    }
    return unsortedArray;

}

This works for me.


问:
How can I check if the user char input is contained in 2 Strings?
The question seems confusing. The program does this: It asks the user for input in char form and then stores it in 2 variables. There are 2 Strings which I've already created. One contains the letters a-g and the other for the letters h-o. These are basically 2 routes which a user can go, but the user can't put for example "a" as start and "h" as destination since they are from a different String. He/She has to have the start and destination in the same String. If the start is and destination aren't in the same String, there will be an error.

This method I have looks as follows:

```<code>private void neueRoute() {
    Scanner in = new Scanner(System.in);

    String bereich1 = "aAbBcCdDeEfFgG";
    String bereich2 = "hHiIjJkKlLmMnNoO";
    char start = ' ';
    char ziel = ' ';
    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;

    System.out.println("Themenbereich 1: Bahn A - G: ");
    System.out.println("\nA\nB\nC\nD\nE\nF\nG\n");
    System.out.println("Themenbereich 2: Bahn H - O: ");
    System.out.println("\nH\nI\nJ\nK\nL\nM\nN\nO");

    while((a == 0 && b == 0) || (c == 0 && d ==0)){

        System.out.println("Put in a starting point please: ");
        start = in.next().charAt(0);

        while(start != 'a' && start != 'A' && start != 'b' && start != 'B' &&
              start != 'c' && start != 'C' && start != 'd' && start != 'D' &&
              start != 'e' && start != 'E' && start != 'f' && start != 'F' &&
              start != 'g' && start != 'G' && start != 'h' && start != 'H' &&
              start != 'i' && start != 'I' && start != 'j' && start != 'J' &&
              start != 'k' && start != 'K' && start != 'l' && start != 'L' &&
              start != 'm' && start != 'M' && start != 'n' && start != 'N' &&
              start != 'o' && start != 'O') {
            System.out.println("Put in a correct starting point please: ");
            start = in.next().charAt(0);
        }

        System.out.println("Put in a destination point please: ");
        ziel = in.next().charAt(0);

        while(ziel != 'a' && ziel != 'A' && ziel != 'b' && ziel != 'B' &&
              ziel != 'c' && ziel != 'C' && ziel != 'd' && ziel != 'D' &&
              ziel != 'e' && ziel != 'E' && ziel != 'f' && ziel != 'F' &&
              ziel != 'g' && ziel != 'G' && ziel != 'h' && ziel != 'H' &&
              ziel != 'i' && ziel != 'I' && ziel != 'j' && ziel != 'J' &&
              ziel != 'k' && ziel != 'K' && ziel != 'l' && ziel != 'L' &&
              ziel != 'm' && ziel != 'M' && ziel != 'n' && ziel != 'N' &&
              ziel != 'o' && ziel != 'O') {
            System.out.println("Put in a correct destination point please: ");
            ziel = in.next().charAt(0);
        }

        a = bereich1.indexOf(start);
        b = bereich2.indexOf(ziel);

        c = bereich2.indexOf(start);
        d = bereich1.indexOf(ziel);

    }
}
</code>```

I tried using .indexOf() today, which I have here with this while loop:

```<code>while((a == 0 && b == 0) || (c == 0 && d ==0)){
</code>```

And these variables:

```<code>a = bereich1.indexOf(start);
b = bereich2.indexOf(ziel);

c = bereich2.indexOf(start);
d = bereich1.indexOf(ziel);
</code>```

I just can't get it to work and it's been working my mind for a couple of days. Any help or pinpointing in the right direction is greatly appreciated. Please let me know if there is anything insufficient given by me or if you need any more information.

Thank you.

答:
You're using bereich1.indexOf(start) == 0, which is equivalent to bereich1.startsWith(""+start), i.e. you're checking not for whether a string contains another string, but for whether it starts with another string.

What you actually want to use is bereich1.contains(""+start), so your while loop would look like this:

```<code>while (bereich1.contains(""+start) && bereich2.contains(""+ziel)
       || bereich2.contains(""+start) && bereich1.contains(""+ziel)) {
</code>```

PS: for checking whether a character is between 'a' and 'o', you can use if ('a' <= ziel && ziel <= 'o' || 'A' <= ziel && ziel <= 'O') instead of your huge if-statement.

Body:
The question seems confusing. The program does this: It asks the user for input in char form and then stores it in 2 variables. There are 2 Strings which I've already created. One contains the letters a-g and the other for the letters h-o. These are basically 2 routes which a user can go, but the user can't put for example "a" as start and "h" as destination since they are from a different String. He/She has to have the start and destination in the same String. If the start is and destination aren't in the same String, there will be an error.

This method I have looks as follows:

private void neueRoute() {
    Scanner in = new Scanner(System.in);

    String bereich1 = "aAbBcCdDeEfFgG";
    String bereich2 = "hHiIjJkKlLmMnNoO";
    char start = ' ';
    char ziel = ' ';
    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;

    System.out.println("Themenbereich 1: Bahn A - G: ");
    System.out.println("\nA\nB\nC\nD\nE\nF\nG\n");
    System.out.println("Themenbereich 2: Bahn H - O: ");
    System.out.println("\nH\nI\nJ\nK\nL\nM\nN\nO");

    while((a == 0 && b == 0) || (c == 0 && d ==0)){

        System.out.println("Put in a starting point please: ");
        start = in.next().charAt(0);

        while(start != 'a' && start != 'A' && start != 'b' && start != 'B' &&
              start != 'c' && start != 'C' && start != 'd' && start != 'D' &&
              start != 'e' && start != 'E' && start != 'f' && start != 'F' &&
              start != 'g' && start != 'G' && start != 'h' && start != 'H' &&
              start != 'i' && start != 'I' && start != 'j' && start != 'J' &&
              start != 'k' && start != 'K' && start != 'l' && start != 'L' &&
              start != 'm' && start != 'M' && start != 'n' && start != 'N' &&
              start != 'o' && start != 'O') {
            System.out.println("Put in a correct starting point please: ");
            start = in.next().charAt(0);
        }

        System.out.println("Put in a destination point please: ");
        ziel = in.next().charAt(0);

        while(ziel != 'a' && ziel != 'A' && ziel != 'b' && ziel != 'B' &&
              ziel != 'c' && ziel != 'C' && ziel != 'd' && ziel != 'D' &&
              ziel != 'e' && ziel != 'E' && ziel != 'f' && ziel != 'F' &&
              ziel != 'g' && ziel != 'G' && ziel != 'h' && ziel != 'H' &&
              ziel != 'i' && ziel != 'I' && ziel != 'j' && ziel != 'J' &&
              ziel != 'k' && ziel != 'K' && ziel != 'l' && ziel != 'L' &&
              ziel != 'm' && ziel != 'M' && ziel != 'n' && ziel != 'N' &&
              ziel != 'o' && ziel != 'O') {
            System.out.println("Put in a correct destination point please: ");
            ziel = in.next().charAt(0);
        }

        a = bereich1.indexOf(start);
        b = bereich2.indexOf(ziel);

        c = bereich2.indexOf(start);
        d = bereich1.indexOf(ziel);

    }
}

I tried using .indexOf() today, which I have here with this while loop:

while((a == 0 && b == 0) || (c == 0 && d ==0)){

And these variables:

a = bereich1.indexOf(start);
b = bereich2.indexOf(ziel);

c = bereich2.indexOf(start);
d = bereich1.indexOf(ziel);

I just can't get it to work and it's been working my mind for a couple of days. Any help or pinpointing in the right direction is greatly appreciated. Please let me know if there is anything insufficient given by me or if you need any more information.

Thank you.

Body:
You're using bereich1.indexOf(start) == 0, which is equivalent to bereich1.startsWith(""+start), i.e. you're checking not for whether a string contains another string, but for whether it starts with another string.

What you actually want to use is bereich1.contains(""+start), so your while loop would look like this:

while (bereich1.contains(""+start) && bereich2.contains(""+ziel)
       || bereich2.contains(""+start) && bereich1.contains(""+ziel)) {

PS: for checking whether a character is between 'a' and 'o', you can use if ('a' <= ziel && ziel <= 'o' || 'A' <= ziel && ziel <= 'O') instead of your huge if-statement.


问:
How to make a foreach of an object in javascript?
I am currently building a mashup in Qlik Sense in JavaScript and jQuery. I have made some data selection and I have put them in a variable object :

```<code>var CurrentSelec = app1.selectionState().selections;
console.log(CurrentSelec);`
console.log(typeof CurrentSelec);
</code>```

This is what I get on my browser console :

I'm trying to show the qSelected value in a Foreach :

I have tried with Javascript :

```<code>for(var index in CurrentSelec) {
    console.log(index.qSelected);
}
</code>```

I have tried with jQuery:

```<code>$.each(CurrentSelec, function(i, index) {
  console.log(index.qSelected)
});
</code>```

But my browser console do not show the log of my foreach.

Do you know how to properly make a foreach of an object and show its content on a browser console, please ?

Regards.

答:
Your CurrentSelec variable is an array, not an ordinary object, so just use its forEach method:

```<code>CurrentSelec.forEach(function (el) {
    console.log(el.qSelected);
});
</code>```

Body:
I am currently building a mashup in Qlik Sense in JavaScript and jQuery. I have made some data selection and I have put them in a variable object :

var CurrentSelec = app1.selectionState().selections;
console.log(CurrentSelec);`
console.log(typeof CurrentSelec);

This is what I get on my browser console :

I'm trying to show the qSelected value in a Foreach :

I have tried with Javascript :

for(var index in CurrentSelec) {
    console.log(index.qSelected);
}

I have tried with jQuery:

$.each(CurrentSelec, function(i, index) {
  console.log(index.qSelected)
});

But my browser console do not show the log of my foreach.

Do you know how to properly make a foreach of an object and show its content on a browser console, please ?

Regards.

Body:
Your CurrentSelec variable is an array, not an ordinary object, so just use its forEach method:

CurrentSelec.forEach(function (el) {
    console.log(el.qSelected);
});


问:
Magento 1.7 cannot reindex product flat data

Magento 1.7 cannot reindex product flat data... I get the following error when trying to reindex my database.

```<code>Product Flat Data index process unknown error:
exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot          add or update a child row: a foreign key constraint fails (`d014505f`.<result 2 when explaining filename '#sql-1f6c_39a11d'>, CONSTRAINT `FK_CAT_PRD_FLAT_1_ENTT_ID_CAT_PRD_ENTT_ENTT_ID` FOREIGN KEY (`entity_id`) REFERENCES `catalog_product_entity` (`e)' in /www/htdocs/w00f5624/lib/Zend/Db/Statement/Pdo.php:228

Stack trace:#0 /www/htdocs/w00f5624/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement-    >execute(Array)
#1 /www/htdocs/w00f5624/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#2 /www/htdocs/w00f5624/lib/Zend/Db/Statement.php(300): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#3 /www/htdocs/w00f5624/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
#4 /www/htdocs/w00f5624/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('ALTER TABLE `ca...', Array)
#5 /www/htdocs/w00f5624/lib/Varien/Db/Adapter/Pdo/Mysql.php(419): Zend_Db_Adapter_Pdo_Abstract->query('ALTER TABLE `ca...', Array)
#6 /www/htdocs/w00f5624/lib/Varien/Db/Adapter/Pdo/Mysql.php(340): Varien_Db_Adapter_Pdo_Mysql->query('ALTER TABLE `ca...')
#7 /www/htdocs/w00f5624/lib/Varien/Db/Adapter/Pdo/Mysql.php(2569): Varien_Db_Adapter_Pdo_Mysql->raw_query('ALTER TABLE `ca...')
#8 /www/htdocs/w00f5624/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php(816): Varien_Db_Adapter_Pdo_Mysql->addForeignKey('FK_CAT_PRD_FLAT...', 'catalog_product...', 'entity_id', 'catalog_product...', 'entity_id', 'CASCADE', 'CASCADE')
#9 /www/htdocs/w00f5624/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php(1390): Mage_Catalog_Model_Resource_Product_Flat_Indexer->prepareFlatTable(1)
#10 /www/htdocs/w00f5624/app/code/core/Mage/Catalog/Model/Product/Flat/Indexer.php(296): Mage_Catalog_Model_Resource_Product_Flat_Indexer->reindexAll()
#11 /www/htdocs/w00f5624/app/code/core/Mage/Catalog/Model/Product/Indexer/Flat.php(336): Mage_Catalog_Model_Product_Flat_Indexer->reindexAll()
#12 /www/htdocs/w00f5624/app/code/core/Mage/Index/Model/Process.php(209): Mage_Catalog_Model_Product_Indexer_Flat->reindexAll()
#13 /www/htdocs/w00f5624/app/code/core/Mage/Index/Model/Process.php(255): Mage_Index_Model_Process->reindexAll()
#14 /www/htdocs/w00f5624/shell/indexer.php(158): Mage_Index_Model_Process->reindexEverything()
#15 /www/htdocs/w00f5624/shell/indexer.php(198): Mage_Shell_Compiler->run()
#16 {main}
</code>```

答:
```<code>SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE catalog_product_flat_1;
TRUNCATE TABLE catalog_product_flat_2;
SET FOREIGN_KEY_CHECKS=1;
</code>```

Worked for me.

Afterwards I could reindex from CLI.

Body:
Magento 1.7 cannot reindex product flat data... I get the following error when trying to reindex my database.

Product Flat Data index process unknown error:
exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot          add or update a child row: a foreign key constraint fails (`d014505f`.<result 2 when explaining filename '#sql-1f6c_39a11d'>, CONSTRAINT `FK_CAT_PRD_FLAT_1_ENTT_ID_CAT_PRD_ENTT_ENTT_ID` FOREIGN KEY (`entity_id`) REFERENCES `catalog_product_entity` (`e)' in /www/htdocs/w00f5624/lib/Zend/Db/Statement/Pdo.php:228

Stack trace:#0 /www/htdocs/w00f5624/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement-    >execute(Array)
#1 /www/htdocs/w00f5624/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#2 /www/htdocs/w00f5624/lib/Zend/Db/Statement.php(300): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#3 /www/htdocs/w00f5624/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
#4 /www/htdocs/w00f5624/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('ALTER TABLE `ca...', Array)
#5 /www/htdocs/w00f5624/lib/Varien/Db/Adapter/Pdo/Mysql.php(419): Zend_Db_Adapter_Pdo_Abstract->query('ALTER TABLE `ca...', Array)
#6 /www/htdocs/w00f5624/lib/Varien/Db/Adapter/Pdo/Mysql.php(340): Varien_Db_Adapter_Pdo_Mysql->query('ALTER TABLE `ca...')
#7 /www/htdocs/w00f5624/lib/Varien/Db/Adapter/Pdo/Mysql.php(2569): Varien_Db_Adapter_Pdo_Mysql->raw_query('ALTER TABLE `ca...')
#8 /www/htdocs/w00f5624/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php(816): Varien_Db_Adapter_Pdo_Mysql->addForeignKey('FK_CAT_PRD_FLAT...', 'catalog_product...', 'entity_id', 'catalog_product...', 'entity_id', 'CASCADE', 'CASCADE')
#9 /www/htdocs/w00f5624/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php(1390): Mage_Catalog_Model_Resource_Product_Flat_Indexer->prepareFlatTable(1)
#10 /www/htdocs/w00f5624/app/code/core/Mage/Catalog/Model/Product/Flat/Indexer.php(296): Mage_Catalog_Model_Resource_Product_Flat_Indexer->reindexAll()
#11 /www/htdocs/w00f5624/app/code/core/Mage/Catalog/Model/Product/Indexer/Flat.php(336): Mage_Catalog_Model_Product_Flat_Indexer->reindexAll()
#12 /www/htdocs/w00f5624/app/code/core/Mage/Index/Model/Process.php(209): Mage_Catalog_Model_Product_Indexer_Flat->reindexAll()
#13 /www/htdocs/w00f5624/app/code/core/Mage/Index/Model/Process.php(255): Mage_Index_Model_Process->reindexAll()
#14 /www/htdocs/w00f5624/shell/indexer.php(158): Mage_Index_Model_Process->reindexEverything()
#15 /www/htdocs/w00f5624/shell/indexer.php(198): Mage_Shell_Compiler->run()
#16 {main}

Body:
SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE catalog_product_flat_1;
TRUNCATE TABLE catalog_product_flat_2;
SET FOREIGN_KEY_CHECKS=1;

Worked for me.

Afterwards I could reindex from CLI.


问:
Sort three numbers in array from least to greatest
I have to create a function that takes 3 numbers. The function should return an array containing the numbers from least to greatest. So far I have this.I know it isn't correct but it's a start.I'm not using native functions as well. Can anyone give me some tips? Appreciate any help.</p>

```<code>   function leastToGreatest (num) {
        var array = [];
        var num1 = 0;
        var num2 = 0;
        var num3 = 0;
        for (var i = 0; i < num.length; i++) {
           if(num[i] < num[i] && num[i] < num[i]) {
                  num[i] = num1;
                  array.push(num1);
           }
           else if(num[i] > num[i] && num[i] < num[i]) {
             num[i] = num2;
             array.push(num2);
           }
           else if(num[i] > num[i] && num[i] > num[i])
             num[i] = num3;
             array.push(num3);
           }
           return array;
     }
     leastToGreatest(2,1,3);
</code>```

答:
If it's just three items you want to sort, you can do it quite easily with three comparisons and swaps:

```<code>if (num[0] > num[1])
{
    // swap num[0] and num[1]
    temp = num[0]; num[0] = num[1]; num[1] = temp;
}
if (num[0] > num[2])
{
    // swap num[0] and num[2]
    temp = num[0]; num[0] = num[2]; num[2] = temp;
}

// at this point, num[0] contains the smallest of the three numbers

if (num[1] > num[2])
{
    // swap num[1] and num[2]
    temp = num[1]; num[1] = num[2]; num[1] = temp;
}

// your three items are sorted
</code>```

This is easy to prove correct by hand. Write the numbers 1, 2, and 3 on small pieces of paper, lay them out in random order, and then perform those steps above. No matter what order you start with, this will sort those three items.

Understand, the above only works for three items. If you want a way to sort any number of items, then you'll want to use the built-in sorting method.

Body:
I have to create a function that takes 3 numbers. The function should return an array containing the numbers from least to greatest. So far I have this.I know it isn't correct but it's a start.I'm not using native functions as well. Can anyone give me some tips? Appreciate any help.

   function leastToGreatest (num) {
        var array = [];
        var num1 = 0;
        var num2 = 0;
        var num3 = 0;
        for (var i = 0; i < num.length; i++) {
           if(num[i] < num[i] && num[i] < num[i]) {
                  num[i] = num1;
                  array.push(num1);
           }
           else if(num[i] > num[i] && num[i] < num[i]) {
             num[i] = num2;
             array.push(num2);
           }
           else if(num[i] > num[i] && num[i] > num[i])
             num[i] = num3;
             array.push(num3);
           }
           return array;
     }
     leastToGreatest(2,1,3);

Body:
If it's just three items you want to sort, you can do it quite easily with three comparisons and swaps:

if (num[0] > num[1])
{
    // swap num[0] and num[1]
    temp = num[0]; num[0] = num[1]; num[1] = temp;
}
if (num[0] > num[2])
{
    // swap num[0] and num[2]
    temp = num[0]; num[0] = num[2]; num[2] = temp;
}

// at this point, num[0] contains the smallest of the three numbers

if (num[1] > num[2])
{
    // swap num[1] and num[2]
    temp = num[1]; num[1] = num[2]; num[1] = temp;
}

// your three items are sorted

This is easy to prove correct by hand. Write the numbers 1, 2, and 3 on small pieces of paper, lay them out in random order, and then perform those steps above. No matter what order you start with, this will sort those three items.

Understand, the above only works for three items. If you want a way to sort any number of items, then you'll want to use the built-in sorting method.


问:
With Python win32com how to get a reference to a chart data table?
With Python win32com how to get a reference to a chart data table?

I can create a chart with a data table (PowerPoint pops it up in a separate window)
like:

```<code>    import win32com
    from MSO import constants as msoconst

    Application = win32com.client.Dispatch("PowerPoint.Application")
    Application.Visible = True
    Presentation = Application.Presentations.Add()

    FirstSlide = Presentation.Slides.Add(1, 12)

... no problem adding slides, shapes and text and setting font size and color ....

    InventoryChart = FirstSlide.Shapes.AddChart2(201,msoconst.xlColumnClustered ,10,80,470,220,False) # 0 = Clustered Column, 1 = Combo Area, 2 = Clustered Column
    InventoryChartData = InventoryChart.ChartData
</code>```

ChartData doesn't work: AttributeError: '' object has no attribute 'ChartData'

So, how do you get a reference to the table that PowerPoint creates? Or how do I define the table to be used for my data?

答:
I had the same question a while back and spent a lot of time trying to find an answer.

ChartData is a property of the Chart object. So to access the ChartData object, you need to tell PowerPoint that the shape you just added is a Chart.

Here are two ways to do do that.

```<code># Option 1 - Add .Chart to end of AddChart2 method
InventoryChart = FirstSlide.Shapes.AddChart2(201,msoconst.xlColumnClustered,10,80,470,220,False).Chart

# Option 2 - Define Chart object separate from AddChart2
InventoryChart = FirstSlide.Shapes(1).Chart

# You can now access the chart's data worksheet
InventoryChartData = InventoryChart.ChartData.Workbook.Worksheets(1)

# Write a value to worksheet
InventoryChartData.Range('F1').Value = 150

# Apply numeric formatting to Series 1 values
InventoryChartData.Range('B2:B5').NumberFormat = '0.00'
</code>```

Body:
With Python win32com how to get a reference to a chart data table?

I can create a chart with a data table (PowerPoint pops it up in a separate window)
like:

    import win32com
    from MSO import constants as msoconst

    Application = win32com.client.Dispatch("PowerPoint.Application")
    Application.Visible = True
    Presentation = Application.Presentations.Add()

    FirstSlide = Presentation.Slides.Add(1, 12)

... no problem adding slides, shapes and text and setting font size and color ....

    InventoryChart = FirstSlide.Shapes.AddChart2(201,msoconst.xlColumnClustered ,10,80,470,220,False) # 0 = Clustered Column, 1 = Combo Area, 2 = Clustered Column
    InventoryChartData = InventoryChart.ChartData

ChartData doesn't work: AttributeError: '' object has no attribute 'ChartData'

So, how do you get a reference to the table that PowerPoint creates? Or how do I define the table to be used for my data?

Body:
I had the same question a while back and spent a lot of time trying to find an answer.

ChartData is a property of the Chart object. So to access the ChartData object, you need to tell PowerPoint that the shape you just added is a Chart.

Here are two ways to do do that.

# Option 1 - Add .Chart to end of AddChart2 method
InventoryChart = FirstSlide.Shapes.AddChart2(201,msoconst.xlColumnClustered,10,80,470,220,False).Chart

# Option 2 - Define Chart object separate from AddChart2
InventoryChart = FirstSlide.Shapes(1).Chart

# You can now access the chart's data worksheet
InventoryChartData = InventoryChart.ChartData.Workbook.Worksheets(1)

# Write a value to worksheet
InventoryChartData.Range('F1').Value = 150

# Apply numeric formatting to Series 1 values
InventoryChartData.Range('B2:B5').NumberFormat = '0.00'


问:
Prevent expansion of wildcards in non-quoted python script argument when running in UNIX environment
I have a python script that I'd like to supply with an argument (usually) containing wildcards, referring to a series of files that I'd like to do stuff with. Example here:

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

import argparse
import glob

parser = argparse.ArgumentParser()
parser.add_argument('-i', action="store", dest="i")
results = parser.parse_args()
print 'argument i is: ', results.i
list_of_matched_files = glob.glob(results.i)
</code>```

In this case, everything works great if the user adds quotes to the passed argument like so:

```<code>./test_script.py -i "foo*.txt"
</code>```

...but often times the users forget to add quotes to the argument and are stumped when the list only contains the first match because UNIX already expanded the list and argparse only then gets the first list element.

Is there a way (within the script) to prevent UNIX from expanding the list before passing it to python? Or maybe even just to test if the argument doesn't contain quotes and then warn the user?

答: No.  Wildcards are expanded by the shell (Bash, zsh, csh, fish, whatever) before the script even runs, and the script can't do anything about them.  Testing whether the argument contains quotes also won't work, as the shell similarly strips the quotes from "foo*.txt" before passing the argument to the script, so all Python sees is foo*.txt.

Body:
I have a python script that I'd like to supply with an argument (usually) containing wildcards, referring to a series of files that I'd like to do stuff with. Example here:

#!/usr/bin/env python

import argparse
import glob

parser = argparse.ArgumentParser()
parser.add_argument('-i', action="store", dest="i")
results = parser.parse_args()
print 'argument i is: ', results.i
list_of_matched_files = glob.glob(results.i)

In this case, everything works great if the user adds quotes to the passed argument like so:

./test_script.py -i "foo*.txt"

...but often times the users forget to add quotes to the argument and are stumped when the list only contains the first match because UNIX already expanded the list and argparse only then gets the first list element.

Is there a way (within the script) to prevent UNIX from expanding the list before passing it to python? Or maybe even just to test if the argument doesn't contain quotes and then warn the user?


问:
Wait Until another function finish
I have a problem. Two function are called from one event almost on the same time. Function1 is doing some asynchronous staff  :

```<code>function1 (callback_Data){
   //some other callbacks here
}

function2 (){

}
</code>```

I want function2 to wait until all callbacks which are in function1 to finish and then to start.

答:
You can use promises for async actions    </p>

```<code>'use strict';

// creating object promise
let promise = new Promise((resolve, reject) => {

  setTimeout(() => {
    // this will make promise fulfilled with result "result"
    resolve("result");
    // this will make promise rejected with result "error"
    // reject("error");
  }, 1000);

});

// promise.then adds functions on success and failure
promise
  .then(
    result => {
      // first function - will be executed on resolve
      alert("Fulfilled: " + result); // result - argument resolve
    },
    error => {
      // second function will be executed on reject
      alert("Rejected: " + error); // error - argument reject
    }
  );
</code>```

Title: Wait Until another function finish

Body:
I have a problem. Two function are called from one event almost on the same time. Function1 is doing some asynchronous staff  :

function1 (callback_Data){
   //some other callbacks here
}

function2 (){

}

I want function2 to wait until all callbacks which are in function1 to finish and then to start.

Body:
You can use promises for async actions

'use strict';

// creating object promise
let promise = new Promise((resolve, reject) => {

  setTimeout(() => {
    // this will make promise fulfilled with result "result"
    resolve("result");
    // this will make promise rejected with result "error"
    // reject("error");
  }, 1000);

});

// promise.then adds functions on success and failure
promise
  .then(
    result => {
      // first function - will be executed on resolve
      alert("Fulfilled: " + result); // result - argument resolve
    },
    error => {
      // second function will be executed on reject
      alert("Rejected: " + error); // error - argument reject
    }
  );


问:
When should use Readonly and Get only properties
In a .NET application when should I use "ReadOnly" properties and when should I use just "Get". What is the difference between these two.

```<code>private readonly double Fuel= 0;

public double FuelConsumption
{
    get
    {
        return Fuel;
    }
}
</code>```

or

```<code>private double Fuel= 0;

public double FuelConsumption
{
     get
     {
          return Fuel;
     }
}
</code>```

答:
As of 2015's C# 6 you can declare and initialise a read-only auto-property in one line:

```<code>double FuelConsumption { get; } = 2;
</code>```

You can set the value from the constructor but not other methods.

Body:
In a .NET application when should I use "ReadOnly" properties and when should I use just "Get". What is the difference between these two.

private readonly double Fuel= 0;

public double FuelConsumption
{
    get
    {
        return Fuel;
    }
}

or

private double Fuel= 0;

public double FuelConsumption
{
     get
     {
          return Fuel;
     }
}

Body:
As of 2015's C# 6 you can declare and initialise a read-only auto-property in one line:

double FuelConsumption { get; } = 2;

You can set the value from the constructor but not other methods.

ContentLicense: CC BY-SA 4.0


问:
With regards to urllib AttributeError: 'module' object has no attribute 'urlopen'
```<code>import re
import string
import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random

filehandle = urllib.urlopen('http://www.google.com/') #open webpage
s = filehandle.read() #read
print s #display

#what i plan to do with it once i get the first part working
#results = re.findall('[<td style="font-weight:bold;" nowrap>$][0-9][0-9][0-9][.][0-9][0-9][</td></tr></tfoot></table>]',s)
#earnings = '$ '
#for money in results:
#earnings = earnings + money[1]+money[2]+money[3]+'.'+money[5]+money[6]
#print earnings
#raw_input()
</code>```

this is the code that i have so far. now i have looked at all the other forums that give solutions such as the name of the script, which is parse_Money.py, and i have tried doing it with urllib.request.urlopen AND i have tried running it on python 2.5, 2.6, and 2.7. If anybody has any suggestions it would be really welcome, thanks everyone!!
--Matt

---EDIT---
I also tried this code and it worked, so im thinking its some kind of syntax error, so if anybody with a sharp eye can point it out, i would be very appreciative.

```<code>import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random
b = 3

#find URL
URL = raw_input('Type the URL you would like to read from[Example: http://www.google.com/] :')

while b == 3:
    #get file name
    file1 = raw_input('Enter a file name for the downloaded code:')
    filepath = file1 + '.txt'
    if os.path.isfile(filepath):
        print 'File already exists'
        b = 3
    else:
        print 'Filename accepted'
        b = 4

file_path = filepath
#open file
FileWrite = open(file_path, 'a')

#acces URL
filehandle = urllib.urlopen(URL)

#display souce code
for lines in filehandle.readlines():
    FileWrite.write(lines)
    print lines
print 'The above has been saved in both a text and html file'

#close files
filehandle.close()
FileWrite.close()
</code>```

答:
I see that you are using Python2 or at least intend to use Python2.
urlopen helper function is available in both urllib and urllib2 in Python2.

What you need to do this, execute this script against the correct version of your python

```<code>C:\Python26\python.exe yourscript.py
</code>```

Body:
import re
import string
import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random

filehandle = urllib.urlopen('http://www.google.com/') #open webpage
s = filehandle.read() #read
print s #display

#what i plan to do with it once i get the first part working
#results = re.findall('[$][0-9][0-9][0-9][.][0-9][0-9][

]',s)
#earnings = '$ '
#for money in results:
#earnings = earnings + money[1]+money[2]+money[3]+'.'+money[5]+money[6]
#print earnings
#raw_input()

this is the code that i have so far. now i have looked at all the other forums that give solutions such as the name of the script, which is parse_Money.py, and i have tried doing it with urllib.request.urlopen AND i have tried running it on python 2.5, 2.6, and 2.7. If anybody has any suggestions it would be really welcome, thanks everyone!!
--Matt

---EDIT---
I also tried this code and it worked, so im thinking its some kind of syntax error, so if anybody with a sharp eye can point it out, i would be very appreciative.

import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random
b = 3

#find URL
URL = raw_input('Type the URL you would like to read from[Example: http://www.google.com/] :')

while b == 3:
    #get file name
    file1 = raw_input('Enter a file name for the downloaded code:')
    filepath = file1 + '.txt'
    if os.path.isfile(filepath):
        print 'File already exists'
        b = 3
    else:
        print 'Filename accepted'
        b = 4

file_path = filepath
#open file
FileWrite = open(file_path, 'a')

#acces URL
filehandle = urllib.urlopen(URL)

#display souce code
for lines in filehandle.readlines():
    FileWrite.write(lines)
    print lines
print 'The above has been saved in both a text and html file'

#close files
filehandle.close()
FileWrite.close()

Body:
I see that you are using Python2 or at least intend to use Python2.
urlopen helper function is available in both urllib and urllib2 in Python2.

What you need to do this, execute this script against the correct version of your python

C:\Python26\python.exe yourscript.py


问:
Using two mice to perform completely different actions in Windows
I'm currently trying to develop an application to use two mice to perform completely different actions in Windows. However, after having spent couple days on it, I'm starting to wonder if what I want to do is even possible using Windows APIs. As I'm far from being an expert in Windows APIs, I would like to get your opinions to know whether I'm going in the right direction or whether I should try to do it completely differently (maybe developing a driver ?).

Here's what I want to do : Imagine two mice are plugged in my computer. I would like to use the first one as a regular mouse, while the second one would be used to perform completely different actions. For instance, by clicking the second left mouse button, it would open a new tab in Firefox (sending a CTRL+T command to FireFox app) and when clicking the right button, it would send a CTRL+C. Then, by moving the second mouse upwards, it would zoom in, and when moving it downwards, the firefox page would zoom out (so the mouse cursor on screen would remain fix while doing that !). The idea is to recognize as well which application is currently used (which one has mouse/keyboard focus) and perform different actions depending on it. So for instance, the second mouse left click would generate a CTRL+T in FireFox, a CTRL+B in WORD and a CTRL+S in Notepad (in fact, the idea is to parameterize those actions at will). All of that while the first mouse must continue to act just as a regular mouse.

So, it's important to understand that my application will run in the background and will never, per se, interact directly with the user (no GUI as it doesn't require the user to input anything). Its purpose is just to modify the mouse inputs coming from the second mouse and send other inputs(messages) to the application currently being used.

So far, I'm using raw input. I'm able to differentiate which mouse is being used and I'm able to send messages (application specific) to other applications when an action is performed on the second mouse. I'm even able to lock the cursor on screen when the second mouse is moved (so as only the corresponding message is sent to the application of interest !). However, I'm unable to block the button messages sent by the second mouse to the app with the mouse focus. Hence, when clicking on the second mouse right button in Notepad for instance, my specific command ("aaa" for the moment as I'm just trying with letters for sake of simplicity) is sent (and displayed in the notepad window) BUT the contextual Notepad menu opens as well…  (hence it's received as well a WM_RBUTTONDOWN message).

My question is then : How can I block the mouse button messages ((WM_RBUTTONDOWN, and so on…) to be received by other applications when the second mouse is used? Is it even possible ? The problem is that (in my understanding) those messages have higher priority over the WM_input messages… So when I read the WM_input message in my application and detects that the button was pressed from the second mouse, it's already too late and the WM_xBUTTONDOWN was already sent !)

I know that using the mouse hooks, I could block those but then, there is no way to differentiate the origin of the message (and of course, detecting which mouse is used is the main point of my application).

I've tried as well using DirectInput8 but it doesn't support anymore the usage of several mice (Windows specifically says to use raw input to this effect).

So, I guess that by know you've gotten that I'm quite lost and have no idea whether what I want to do it even achievable. Any help would be more than welcome.

Looking forward to reading your replies.

答:
I was about to suggest hooks, but then I read that you looked into that already. I guess, the last resort for your problem would be to write your own driver.
After Windows installed the second mouse in it's usual way, you can go to the Device Manager and change the driver of the mouse you want to "repurpose" to your own driver.

Although, developing a driver is probably nothing one will do as a side task in a project.


问:
Sequential invocation of asynchronous methods enforced by interface, Angular 4
I have the following interface:

```<code>export interface Data {
    getText(): string;
}
</code>```

Two classes implement mentioned interface:

```<code>export class LocalStorageData implements Data {
    public getText(): string {
        return localStorage.getItem('data');
    }
}

export class HttpData implements Data {
    public constructor(private http: Http) {
    }

    public getText(): string {
        let text = '';

        this.http.get('http://server.com:3000/data').subscribe((response) => {
            text = response.toString();
        });

        return text;
    }
}
</code>```

There is a class which uses LocalStorageData and HttpData classes:

```<code>export class Main {
    private http: Http;

    ...

    private getData(fromLocalStorage: boolean): Data {
        let data: Data;

        if (fromLocalStorage)
            data = new LocalStorageData();
        else
            data = new HttpData(this.http);

        return data;
    }

    public getText() {
        console.log(this.getData(true).getText());
        console.log(this.getData(false).getText());
    }
}
</code>```

When getText() from Main class will be invoked, second console log will print an empty string because get() method from Http service is asynchronous.

How can I implement Data interface using asynchronous methods from Http service?

答:
change interface

from

```<code>export interface Data {
    getText(): string;
}
</code>```

to

```<code>export interface Data {
    getText(): Observable<string>;
}
</code>```

and return from local storage as

```<code>Observable.of(localStorage.getItem('data'))
</code>```

and from HttpData as

```<code>export class HttpData implements Data {
    public constructor(private http: Http) {
    }

    public getText(): Observable<string> {
        let text = '';

         return this.http.get('http://server.com:3000/data').map(res => res.json());

    }
}
</code>```

and use this as follows

```<code>public getText() {
        this.getData(true).subscribe(test=> {
          console.log(text);
        })

        this.getData(false).subscribe(test=> {
          console.log(text);
        })
    }
</code>```

Body:
I have the following interface:

export interface Data {
    getText(): string;
}

Two classes implement mentioned interface:

export class LocalStorageData implements Data {
    public getText(): string {
        return localStorage.getItem('data');
    }
}

export class HttpData implements Data {
    public constructor(private http: Http) {
    }

    public getText(): string {
        let text = '';

        this.http.get('http://server.com:3000/data').subscribe((response) => {
            text = response.toString();
        });

        return text;
    }
}

There is a class which uses LocalStorageData and HttpData classes:

export class Main {
    private http: Http;

    ...

    private getData(fromLocalStorage: boolean): Data {
        let data: Data;

        if (fromLocalStorage)
            data = new LocalStorageData();
        else
            data = new HttpData(this.http);

        return data;
    }

    public getText() {
        console.log(this.getData(true).getText());
        console.log(this.getData(false).getText());
    }
}

When getText() from Main class will be invoked, second console log will print an empty string because get() method from Http service is asynchronous.

How can I implement Data interface using asynchronous methods from Http service?

Body:
change interface

from

export interface Data {
    getText(): string;
}

to

export interface Data {
    getText(): Observable<string>;
}

and return from local storage as

Observable.of(localStorage.getItem('data'))

and from HttpData as

export class HttpData implements Data {
    public constructor(private http: Http) {
    }

    public getText(): Observable<string> {
        let text = '';

         return this.http.get('http://server.com:3000/data').map(res => res.json());

    }
}

and use this as follows

public getText() {
        this.getData(true).subscribe(test=> {
          console.log(text);
        })

        this.getData(false).subscribe(test=> {
          console.log(text);
        })
    }


问:
jQuery target id inside iframe and alert
My code is like below.

```<code><!DOCTYPE html>
<html>

  <head>
    <title>TODO</title>
  </head>

  <body>
    <div id="btn">
      <button id="clickme">Click Me</button>
    </div>
    <div class="iframebox">
      <iframe id="messageiframe">
        <html>

        <head>
          <title>test</title>
        </head>

        <body>
          <div id="textpreview">
            <p id="pre">some text</p>
          </div>
        </body>

        </html>
      </iframe>
    </div>
  </body>

</html>
</code>```

I am trying to target id="textpreview" inside iframe using jQuery. I can successfully target any id outside iframe but unable to target inside iframe.

My jQuery code is:

```<code>$('#clickme').on('click', function() {
  if ($("#textpreview").length > 0) {
    alert("success");
  }
});
</code>```

How can I achieve this?

Thanks in advance.

答:
<!DOCTYPE html>

    <title>TODO</title>

      <button id="clickme">Click Me</button>

          <title>test</title>

some text

```

Check whether it has the id.

Body:
My code is like below.

<!DOCTYPE html>

    <title>TODO</title>

      <button id="clickme">Click Me</button>

          <title>test</title>

some text

I am trying to target id="textpreview" inside iframe using jQuery. I can successfully target any id outside iframe but unable to target inside iframe.

My jQuery code is:

$('#clickme').on('click', function() {
  if ($("#textpreview").length > 0) {
    alert("success");
  }
});

How can I achieve this?

Thanks in advance.

Body:
<!DOCTYPE html>
<html>

  <head>
    <title>TODO</title>
  </head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <body>
    <div id="btn">
      <button id="clickme">Click Me</button>
    </div>
    <div class="iframebox">
      <iframe id="messageiframe">
        <html>

        <head>
          <title>test</title>
        </head>

        <body>
          <div id="textpreview">
            <p id="pre">some text</p>
          </div>
        </body>

        </html>
      </iframe>
    </div>
  </body>
<script>

$('#clickme').on('click', function() {

  if ($("#textpreview").has("pre")) {
    alert("success");
  }
});
</script>
</html>

Check whether it has the id.


问:
Filter Comments in the language of the node
I put the comments on nodes but I'm puzzled about the fact that the comments are not filtered by language. And I don't find a solution about that.

When I'm on a french page, I got the comments in french but also in chinese.

Also when you post a new comment on a chinese page, stating that the comment is in chinese, there's a redirection to the default language of the node (here in french). I fixed this problem with a hook...

But I still have a mixed language of contents whatever the language node is. I tried different hook (hook_comment_view_alter or hook_comment_load) and I see the comments before rendering but I'm not able to remove the comment in different language of the page I'm on. So is there a way to filter the comments on the basic Drupal8 comment system ?

答:
My complete solution here :

```<code>function hook_query_comment_filter_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
    $clangcode = \Drupal::service('language_manager')->getCurrentLanguage(\Drupal\Core\Language\LanguageInterface::TYPE_CONTENT);
    $query->condition('langcode', $clangcode->getId());
}
</code>```

You can strip the namespace with some "use".

Body:
My complete solution here :

function hook_query_comment_filter_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
    $clangcode = \Drupal::service('language_manager')->getCurrentLanguage(\Drupal\Core\Language\LanguageInterface::TYPE_CONTENT);
    $query->condition('langcode', $clangcode->getId());
}

You can strip the namespace with some "use".


问:
C# Webclient returning error 404
I'm using below script to retrieve HTML from an URL.

```<code>string webURL = @"https://nl.wiktionary.org/wiki/" + word.ToLower();
                using (WebClient client = new WebClient())
                {
                      string htmlCode = client.DownloadString(webURL);
                }
</code>```

The variable word can be any word. In case there is no WIKI page for the "word" be retrieved the code is ending in error with code 404, while retrievng the URL with a browser opens a WIKI page, saying there is no page for this item yet.

What I want is that the code always gets the HTML, also when the WIKI page says there is no info yet. I do not want to avoid the error 404 with a try and catch.

Does anyone has an idea why this is not working with a Webclient?

答:
Since this WIKI-server use case-sensitive url mapping, just don't modify case of URL to harvest (remove ".ToLower()" from you code).

Ex.:
Lower case:

https://nl.wiktionary.org/wiki/categorie:onderwerpen_in_het_nynorsk

Result: HTTP 404(Not Found)

Normal (unmodified) case:

https://nl.wiktionary.org/wiki/Categorie:Onderwerpen_in_het_Nynorsk

Result: HTTP 200(OK)

Also, keep in mind what most (if not all) WiKi servers (including this one) generates custom 404 pages, so in browser they looks like "normal" pages, but, despite this, they are serving with 404 http code.

Title: C# Webclient returning error 404

Body:
I'm using below script to retrieve HTML from an URL.

string webURL = @"https://nl.wiktionary.org/wiki/" + word.ToLower();
                using (WebClient client = new WebClient())
                {
                      string htmlCode = client.DownloadString(webURL);
                }

The variable word can be any word. In case there is no WIKI page for the "word" be retrieved the code is ending in error with code 404, while retrievng the URL with a browser opens a WIKI page, saying there is no page for this item yet.

What I want is that the code always gets the HTML, also when the WIKI page says there is no info yet. I do not want to avoid the error 404 with a try and catch.

Does anyone has an idea why this is not working with a Webclient?


问:
Unit test for creation object
I'm started to learn unit test using jasmine. And maybe someone can explain me - how I need to check creating new object like:

```<code>const outLog = {
  time: newTime,
  request: {
    direction: 'OUT',
    method: data.request.method,
    title: data.request.url,
    body: data.request.data,
    headers: getHeaders(data.request.headers),
  },
  response: {
    status: '',
    headers: {},
    body: {},
  },
};

if (data.response && data.response !== null) {
  outLog.response.status = data.response.status;
  outLog.response.body = data.response.data;
  outLog.response.headers = getHeaders(data.response.headers);
}

log.out.push(outLog);
</code>```

Do I need to fill the fields like request method, request title with real data and check

```<code>const outLog = {
  request: {
    method: 'POST',
    title: 'title',
    ...
    ...
  },
}
</code>```

expect(outLog.request.method).toEqual('POST');
   expect(outLog.request.title).toEqual('title');

Thanks!

答:
For checking objects, most frameworks usually provide some sort of pretty diff when you compare two objects.

To get this you'd first need to compare it to an object literal:

```<code>expect(outLog).toEqual({
   request: {
     method: 'POST',
     title: 'title',
     ...
})
</code>```

This also removes a LOT of logic from all the expect statements, which should help with maintenance and debugging.  Additionally, when there are many different assertions, the earlier ones mask the later ones, creating unnecessary feedback loops, when the same thing could be accomplished with a single assertion.  one of the unit testing thought leaders addresses this by recommending that unit tests should only ever have a single assertion to help keep them focused, reduce debugging time, and make them easier to work on and understand.

Title: Unit test for creation object

Body:
I'm started to learn unit test using jasmine. And maybe someone can explain me - how I need to check creating new object like:

const outLog = {
  time: newTime,
  request: {
    direction: 'OUT',
    method: data.request.method,
    title: data.request.url,
    body: data.request.data,
    headers: getHeaders(data.request.headers),
  },
  response: {
    status: '',
    headers: {},
    body: {},
  },
};

if (data.response && data.response !== null) {
  outLog.response.status = data.response.status;
  outLog.response.body = data.response.data;
  outLog.response.headers = getHeaders(data.response.headers);
}

log.out.push(outLog);

Do I need to fill the fields like request method, request title with real data and check

const outLog = {
  request: {
    method: 'POST',
    title: 'title',
    ...
    ...
  },
}

expect(outLog.request.method).toEqual('POST');
   expect(outLog.request.title).toEqual('title');

Thanks!

Body:
For checking objects, most frameworks usually provide some sort of pretty diff when you compare two objects.

To get this you'd first need to compare it to an object literal:

expect(outLog).toEqual({
   request: {
     method: 'POST',
     title: 'title',
     ...
})

This also removes a LOT of logic from all the expect statements, which should help with maintenance and debugging.  Additionally, when there are many different assertions, the earlier ones mask the later ones, creating unnecessary feedback loops, when the same thing could be accomplished with a single assertion.  one of the unit testing thought leaders addresses this by recommending that unit tests should only ever have a single assertion to help keep them focused, reduce debugging time, and make them easier to work on and understand.


问:
Disclosure indicator to specific cell in static TableView in Swift
I created a static TableView and I would like to add or remove a disclosure indicator depending if we are consulting our own account or a guest account.

This is what I would like :

```<code>let index = IndexPath(row: 4, section: 0)

let cell = tableView.cellForRow(at: index)
if currentUser {
   cell.accessoryType = .none
   //cell.backgroundColor = UIColor.red
}
</code>```

I tried to put it in the viewDidLoad function but it didn't work. I tried cellForRowAt indexPath also and same result.

How could I do that?

答: Your are working with static cells so cellForRow will not get called. Instead, simply drag connect your cell and set it up, like this

Body:
I created a static TableView and I would like to add or remove a disclosure indicator depending if we are consulting our own account or a guest account.

This is what I would like :

let index = IndexPath(row: 4, section: 0)

let cell = tableView.cellForRow(at: index)
if currentUser {
   cell.accessoryType = .none
   //cell.backgroundColor = UIColor.red
}

I tried to put it in the viewDidLoad function but it didn't work. I tried cellForRowAt indexPath also and same result.

How could I do that?


问:
Windows Power State change event notification in Qt
I developing a GUI in QT where I have to show the battery status icon. To get the system power status, I am using the windows API. But to show status anytime , do i need to use a thread to continuously read and display the power status?

I am thinking of using event handler. But not sure how to implement. I am thinking that for just one status icon I will run a thread. Anybody has any better suggestion, please share.

答:
Using a thread might be a overkill, but using a timer might be much more suitable for this case.

QTimer can be used to update battery status on given interval. Just create QTimer object and connect it's timeout() signal to slot in your object, perhaps in some battery state widget. In this slot you just read the new state and update icon accordingly. Start QTimer instance with interval of your choice in milliseconds.

Btw. Qt Mobility API can be used to read power state also on desktop. Anyway if porting is not an issue, it might be easier just to use API that platform already provides.


答:
With your JavaScript example, you are incorrectly navigating through the Object. In order to move through it, use [] and the variable you set. For example,

```<code>for (var index in CurrentSelec) {
  console.log(CurrentSelec[index].qSelected);
}
</code>```

This chooses each child inside of CurrentSelec and prints out its corresponding qSelected value.

In your example, when you say for (var index in CurrentSelec) {...};, you are saying for each child inside of CurrentSelec, set index = child (where child is only a key to your CurrentSelec Object), and then proceed with the for loop.

Therefore, when you say console.log(index.qSelected), you are trying to navigate to the qSelected value under index, which will never exist. Instead you should navigate through the parent Object using each index you receive in your for loop.

Title: How to make a foreach of an object in javascript?

Body:
I am currently building a mashup in Qlik Sense in JavaScript and jQuery. I have made some data selection and I have put them in a variable object :

var CurrentSelec = app1.selectionState().selections;
console.log(CurrentSelec);`
console.log(typeof CurrentSelec);

This is what I get on my browser console :

I'm trying to show the qSelected value in a Foreach :

I have tried with Javascript :

for(var index in CurrentSelec) {
    console.log(index.qSelected);
}

I have tried with jQuery:

$.each(CurrentSelec, function(i, index) {
  console.log(index.qSelected)
});

But my browser console do not show the log of my foreach.

Do you know how to properly make a foreach of an object and show its content on a browser console, please ?

Regards.

Body:
With your JavaScript example, you are incorrectly navigating through the Object. In order to move through it, use [] and the variable you set. For example,

for (var index in CurrentSelec) {
  console.log(CurrentSelec[index].qSelected);
}

This chooses each child inside of CurrentSelec and prints out its corresponding qSelected value.

In your example, when you say for (var index in CurrentSelec) {...};, you are saying for each child inside of CurrentSelec, set index = child (where child is only a key to your CurrentSelec Object), and then proceed with the for loop.

Therefore, when you say console.log(index.qSelected), you are trying to navigate to the qSelected value under index, which will never exist. Instead you should navigate through the parent Object using each index you receive in your for loop.


问:
Python function scope
I have a question about the scope in python functions. I've included an example that demonstrates the issue I am having.

fun0 redefines the first entry in varible c's list. This change is reflected outside of fun0, even when I don't return any values from fun0.

fun1 redefines the variable c entirely, but the change isn't reflected outside of fun1. Similarly, fun2 redefines c, and the change isn't reflected outside of fun2.

My question is, why does fun0 modify val3 in the main function, while fun1 and fun2 don't modify val4 and val7, respectively?

```<code>def fun0(a, b, c):
    c[0] = a[0] + b[0]
    return

def fun1(a, b, c):
    c = a[0] + b[0]
    return

def fun2(a, b, c):
    c = a + b
    return

def main():
    val1 = ['one']
    val2 = ['two']
    val3 = ['']
    fun0(val1, val2, val3)
    print val3

    val4 = []
    fun1(val1, val2, val4)
    print val4

    val5 = 1
    val6 = 1
    val7 = 0
    fun2(val5, val6, val7)
    print val7
    return

if __name__=='__main__':
    main()
</code>```

答:
My question is, why does fun0 modify val3 in the main function, while fun1 and fun2 don't modify val4 and val7, respectively?

This is because of the way Python passes arguments.

When you pass arguments to a function, Python passes them by assignment.This means it binds the argument references to the parameter names. That's the only way the parameter and argument names are related. In your first example, you simply passed a reference to val3, and since both val3 and c were referring to the same list object, the changes were reflected across both names.

However, when you reassigned c inside of your functions, you replaced the reference to the lists c was holding and reassigned c a new reference.

Title: Python function scope

Body:
I have a question about the scope in python functions. I've included an example that demonstrates the issue I am having.

fun0 redefines the first entry in varible c's list. This change is reflected outside of fun0, even when I don't return any values from fun0.

fun1 redefines the variable c entirely, but the change isn't reflected outside of fun1. Similarly, fun2 redefines c, and the change isn't reflected outside of fun2.

My question is, why does fun0 modify val3 in the main function, while fun1 and fun2 don't modify val4 and val7, respectively?

def fun0(a, b, c):
    c[0] = a[0] + b[0]
    return

def fun1(a, b, c):
    c = a[0] + b[0]
    return

def fun2(a, b, c):
    c = a + b
    return

def main():
    val1 = ['one']
    val2 = ['two']
    val3 = ['']
    fun0(val1, val2, val3)
    print val3

    val4 = []
    fun1(val1, val2, val4)
    print val4

    val5 = 1
    val6 = 1
    val7 = 0
    fun2(val5, val6, val7)
    print val7
    return

if __name__=='__main__':
    main()


问:
Limit iOS App even after the user re-installs it
I created an app that gives the user 3 coins at the first launch.

Once the user finished the 3 coins he should buy unlimited coins by an In-App purchase.

The problem is that if the user doesn't want to buy unlimited coins he can delete the app, install the app again and he will have again the 3 coins again.
And he can do this forever without ever buying the In-App purchase.

Is there a simple way to prevent this? How can I know if a user finished the coins inside the app even after deleting it?

答:
You can get unique device id from device keychain and save to server and after App first launch you have to check this unique device id is already available to your server or not.

I am using Keychain library to have an easy access to app keychain.

You can use the below method to get and check unique device id

```<code>// MARK: - Get UUID from keychain because delete app and reintall changes the UUID.
    class var getUniqueDeviceIdentifierAsString : String {

        let appname =  Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String

        var strApplicationUUID: String? = KeychainWrapper.standard.string(forKey: appname)
        if strApplicationUUID == nil {
            strApplicationUUID = UIDevice.current.identifierForVendor?.uuidString
            _ = KeychainWrapper.standard.set(strApplicationUUID!, forKey: appname)
        }

        return strApplicationUUID!
    }
</code>```

Body:
You can get unique device id from device keychain and save to server and after App first launch you have to check this unique device id is already available to your server or not.

I am using Keychain library to have an easy access to app keychain.

You can use the below method to get and check unique device id

// MARK: - Get UUID from keychain because delete app and reintall changes the UUID.
    class var getUniqueDeviceIdentifierAsString : String {

        let appname =  Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String

        var strApplicationUUID: String? = KeychainWrapper.standard.string(forKey: appname)
        if strApplicationUUID == nil {
            strApplicationUUID = UIDevice.current.identifierForVendor?.uuidString
            _ = KeychainWrapper.standard.set(strApplicationUUID!, forKey: appname)
        }

        return strApplicationUUID!
    }


问:
Webpack Code splitting with libraryTarget
I have a web application who's (client side) javascript is written in es6 with the main entry point in app.js.

I can bundle it up using webpack, either referencing vendor libraries like jQuery externally, or including them in the bundle - depending on preference. In order for it to work correctly in the browser I have to specify libraryTarget and library like so:

```<code>//snip
entry: {
    "app.bundle": ["./app.js"],
},
output: {
    path: path.join(__dirname, "wwwroot\\js"),
    filename: "[name].js",
    libraryTarget: "var",
    library: "app"
}
//snip
</code>```

However I'd like to have my vendor libraries bundled separately.

I can do this using CommonsChunkPlugin, but then it doesn't seem to play nicely with library* properties as they get applied to it as well. i.e I end up with app.jQuery instead of just jQuery

How can I separate out my vendor code and provide the appropriate globals to whatever needs them, while also exposing my application code to the browser correctly?

webpack.config here:

```<code>var path = require('path'),
    webpack = require('webpack');

module.exports = {
    context: path.join(__dirname, 'wwwroot'),
    entry: {
        "app.bundle": ['./js/app.js'],
        "vendor.bundle": ['jquery', 'jquery-validation', 'jquery-validation-unobtrusive']
    },
    output: {
        path: path.join(__dirname, 'wwwroot\\js'),
        filename: '[name].js',
        libraryTarget: 'var',
        library: 'app'
    },
    module: {
        loaders: [
            {
                test: /.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'stage-0']
                }
            }
        ]
    },
    resolve: {
        extensions: ['*', '.js']
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor.bundle',
            minChunks: Infinity
        }),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery'
        })
    ]
}
</code>```

答:
If your jquery plugins are provided externally and you are developing a library, I'd suggest to use externals instead of ProvidePlugin. This means that you will have to provide jQuery explicitly when you will test your bundled library.

Externals

```<code>externals: {
  $: require.resolve('jquery'),
  'window.$': require.resolve('jquery')
  // ... and so on
}
</code>```

And your index.html where you test your bundled library will me something like:

```<code><script src='jquery.min.js'></script>
<script src='myLibrary.min.js'></script>
</code>```

Body:
I have a web application who's (client side) javascript is written in es6 with the main entry point in app.js.

I can bundle it up using webpack, either referencing vendor libraries like jQuery externally, or including them in the bundle - depending on preference. In order for it to work correctly in the browser I have to specify libraryTarget and library like so:

//snip
entry: {
    "app.bundle": ["./app.js"],
},
output: {
    path: path.join(__dirname, "wwwroot\\js"),
    filename: "[name].js",
    libraryTarget: "var",
    library: "app"
}
//snip

However I'd like to have my vendor libraries bundled separately.

I can do this using CommonsChunkPlugin, but then it doesn't seem to play nicely with library* properties as they get applied to it as well. i.e I end up with app.jQuery instead of just jQuery

How can I separate out my vendor code and provide the appropriate globals to whatever needs them, while also exposing my application code to the browser correctly?

webpack.config here:

var path = require('path'),
    webpack = require('webpack');

module.exports = {
    context: path.join(__dirname, 'wwwroot'),
    entry: {
        "app.bundle": ['./js/app.js'],
        "vendor.bundle": ['jquery', 'jquery-validation', 'jquery-validation-unobtrusive']
    },
    output: {
        path: path.join(__dirname, 'wwwroot\\js'),
        filename: '[name].js',
        libraryTarget: 'var',
        library: 'app'
    },
    module: {
        loaders: [
            {
                test: /.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'stage-0']
                }
            }
        ]
    },
    resolve: {
        extensions: ['*', '.js']
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor.bundle',
            minChunks: Infinity
        }),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery'
        })
    ]
}

Body:
If your jquery plugins are provided externally and you are developing a library, I'd suggest to use externals instead of ProvidePlugin. This means that you will have to provide jQuery explicitly when you will test your bundled library.

Externals

externals: {
  $: require.resolve('jquery'),
  'window.$': require.resolve('jquery')
  // ... and so on
}

And your index.html where you test your bundled library will me something like:

<script src='jquery.min.js'></script>
<script src='myLibrary.min.js'></script>


问:
no such elemnts in second class testng
i need help i run code from xml file the first class called login it runs correctly but when it goes to setting class it fails that tells no such element

```<code><suite name="myapp">
    <test name="first">
    <classes>
    <class name="cybertalents.loginclass"></class>
    <class name="cybertalents.Settingclass"></class>
    </classes>
    </test>
</suite>

public class suiteclass {
    WebDriver driver;

    @BeforeTest
    public void beforeSuite() {
        System.setProperty("webdriver.gecko.driver", "E:/Software Testing/Selenium/Programs/geckodriver.exe");
        driver = new FirefoxDriver();
        driver.get("http://52.211.167.71");
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
    }
    @AfterTest
    public void aftersuite() {
        driver.close();
    }

public class loginclass extends suiteclass {
    @Test
    public void loginpage() {
        loginpage login = new loginpage(driver);
        login.presslogin();
        login.sendkeys("", "");
        login.loginbutton();
        login.seetingpage();
    }
}

public class Settingclass extends suiteclass {
    @Test
    public void Method1()
    {
        setting st = new setting(driver);
        st.clear();
        st.sendkeys("", "", "", "]", "Software Testing",
                "", "", "");
        st.birthdate("25", "Jan", "2010");
        st.graduation("9", "Aug", "2015");
        st.selectfunction("f", "Angola", "Afghanistan", "Afghanistan", "Arabic");
    }
}
</code>```

**test case of setting class related to login class i want to do it after finish login test case but it tells bo such element **

答: **Great i found the result ** the webdriver must be static</p>

Title: no such elemnts in second class testng

Body:
i need help i run code from xml file the first class called login it runs correctly but when it goes to setting class it fails that tells no such element

<suite name="myapp">
    <test name="first">
    <classes>
    <class name="cybertalents.loginclass"></class>
    <class name="cybertalents.Settingclass"></class>
    </classes>
    </test>
</suite>

public class suiteclass {
    WebDriver driver;

    @BeforeTest
    public void beforeSuite() {
        System.setProperty("webdriver.gecko.driver", "E:/Software Testing/Selenium/Programs/geckodriver.exe");
        driver = new FirefoxDriver();
        driver.get("http://52.211.167.71");
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
    }
    @AfterTest
    public void aftersuite() {
        driver.close();
    }

public class loginclass extends suiteclass {
    @Test
    public void loginpage() {
        loginpage login = new loginpage(driver);
        login.presslogin();
        login.sendkeys("", "");
        login.loginbutton();
        login.seetingpage();
    }
}

public class Settingclass extends suiteclass {
    @Test
    public void Method1()
    {
        setting st = new setting(driver);
        st.clear();
        st.sendkeys("", "", "", "]", "Software Testing",
                "", "", "");
        st.birthdate("25", "Jan", "2010");
        st.graduation("9", "Aug", "2015");
        st.selectfunction("f", "Angola", "Afghanistan", "Afghanistan", "Arabic");
    }
}

**test case of setting class related to login class i want to do it after finish login test case but it tells bo such element **


问:
I can't see my changes in Windows Form Application
I am working on windows form app in C#. 1 week ago I created a form and I add some tools. Today I opened same application. Now, I add new button but when I run it I can't see. Previous version of the application is shown. For example, there was a DataGridView and I changed it with listView but when I run the program I still see the DataGridView. Why this is happening?</p>

答: Try rebuild your project (Build->Rebuild Solution) before launch application. Maybe you have an error in your project and select option to start previous successful build.</p>