问:
Problems with PIC A/D conversion
I am trying to read analogic signal for a sort of mouse with a pic18f14k50 controller. Here the simple circuit: http://dl.dropbox.com/u/14663091/schematiconew.pdf . I have to read analogic signal from AN9 circuit port. Main function reads from the port, and blinks 30 time if threshold is reached:

```<code> void main(void) {
      InitializeSystem();

      #if defined(USB_INTERRUPT)
         USBDeviceAttach();
     #endif

     while(1) {

             if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) continue;

      if(!HIDTxHandleBusy(lastTransmission))
      {
       int readed = myReadADC2(); //Here i tried both myReadADC2() or myReadADC1()
       if(readed>40) { //If read threshold > 40, blink led 30 times
        int i;
        for(i=0; i<30; i++) {
         Delay1KTCYx(0);
         mLED_1_On();
         Delay1KTCYx(0);
         mLED_1_Off();
        }
              }
              lastTransmission = HIDTxPacket(HID_EP, (BYTE*)hid_report_in, 0x03);

     }//end while
 }//end main
</code>```

I used two method to read from the AN9 port, myReadADC() that uses OpenADC() API method:

```<code>int myReadADC(void) {
   #define ADC_REF_VDD_VDD_X 0b11110011
   OpenADC(ADC_FOSC_RC & ADC_RIGHT_JUST & ADC_12_TAD, ADC_CH9 & ADC_INT_OFF, ADC_REF_VDD_VDD_X & ADC_REF_VDD_VSS, 0b00000010); // channel 9
   SetChanADC(ADC_CH9);
   ConvertADC();                 // Start conversion
   while(BusyADC());             // Wait for completion
   return ReadADC();           // Read result
}
</code>```

and myReadADC2(), that implements manual read from the port.

```<code>int myReadADC2() {

  int iRet;
  OSCCON=0x70;         // Select 16 MHz internal clock
  ANSEL = 0b00000010;  // Set PORT AN9 to analog input
  ANSELH = 0;          // Set other PORTS as Digital I/O
  /* Init ADC */
  ADCON0=0b00100101;   // ADC port channel 9 (AN9), Enable ADC
  ADCON1=0b00000000;   // Use Internal Voltage Reference (Vdd and Vss)
  ADCON2=0b10101011;   // Right justify result, 12 TAD, Select the FRC for 16 MHz
  iRet=100;

  ADCON0bits.GO=1;
  while (ADCON0bits.GO);   // Wait conversion done
  iRet=ADRESL;           // Get the 8 bit LSB result
  iRet += (ADRESH << 8); // Get the 2 bit MSB result
  return iDelay;

}
</code>```

Both cases doesn't works, i touch (sending analogic signal) port AN9 but when I set high threshold (~50) led don't blinks, with low threshold (~0) it blinks immidiatly when i provide power to the PIC. Maybe i'm using wrong port? I'm actually passing AN9 as reading port? Or maybe threshold is wrong? How can i found the right value? Thank you

Here the MPLAB C18 Apis http://dl.dropbox.com/u/14663091/API%20microchip%20C18.pdf .

答:
Regarding function myReadADC2(): you need to switch ANSEL and ANSELH configs as RC7/AN9 is configured in bit 1 of ANSELH. Also call me paranoid but for the line

```<code>iRet += (ADRESH << 8);
</code>```

I always like to either save it a temporary variable first or cast explicitly the value ADRESH before shifting it up:

```<code>iRet += (((UINT) ADRESH) << 8);
</code>```

That way I know for sure the bits won't get lost when shifting up which has bitten me before.

Regarding function myReadADC():
OpenADC() only takes two parameters. I presume that bitfield in the third parameter field is for the analog enable (ADRESH/ADRES). I'm assuming that's handled by SetChanADC() but you may have to set ADRESH/ADRES manually. It may help to set a breakpoint in the debugger and stop after configuration is complete to make sure your registers are set appropriatley.

Title: Problems with PIC A/D conversion

Body:
I am trying to read analogic signal for a sort of mouse with a pic18f14k50 controller. Here the simple circuit: http://dl.dropbox.com/u/14663091/schematiconew.pdf . I have to read analogic signal from AN9 circuit port. Main function reads from the port, and blinks 30 time if threshold is reached:

 void main(void) {
      InitializeSystem();

      #if defined(USB_INTERRUPT)
         USBDeviceAttach();
     #endif

     while(1) {

             if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) continue;

      if(!HIDTxHandleBusy(lastTransmission))
      {
       int readed = myReadADC2(); //Here i tried both myReadADC2() or myReadADC1()
       if(readed>40) { //If read threshold > 40, blink led 30 times
        int i;
        for(i=0; i<30; i++) {
         Delay1KTCYx(0);
         mLED_1_On();
         Delay1KTCYx(0);
         mLED_1_Off();
        }
              }
              lastTransmission = HIDTxPacket(HID_EP, (BYTE*)hid_report_in, 0x03);

     }//end while
 }//end main

I used two method to read from the AN9 port, myReadADC() that uses OpenADC() API method:

int myReadADC(void) {
   #define ADC_REF_VDD_VDD_X 0b11110011
   OpenADC(ADC_FOSC_RC & ADC_RIGHT_JUST & ADC_12_TAD, ADC_CH9 & ADC_INT_OFF, ADC_REF_VDD_VDD_X & ADC_REF_VDD_VSS, 0b00000010); // channel 9
   SetChanADC(ADC_CH9);
   ConvertADC();                 // Start conversion
   while(BusyADC());             // Wait for completion
   return ReadADC();           // Read result
}

and myReadADC2(), that implements manual read from the port.

int myReadADC2() {

  int iRet;
  OSCCON=0x70;         // Select 16 MHz internal clock
  ANSEL = 0b00000010;  // Set PORT AN9 to analog input
  ANSELH = 0;          // Set other PORTS as Digital I/O
  /* Init ADC */
  ADCON0=0b00100101;   // ADC port channel 9 (AN9), Enable ADC
  ADCON1=0b00000000;   // Use Internal Voltage Reference (Vdd and Vss)
  ADCON2=0b10101011;   // Right justify result, 12 TAD, Select the FRC for 16 MHz
  iRet=100;

  ADCON0bits.GO=1;
  while (ADCON0bits.GO);   // Wait conversion done
  iRet=ADRESL;           // Get the 8 bit LSB result
  iRet += (ADRESH << 8); // Get the 2 bit MSB result
  return iDelay;

}

Both cases doesn't works, i touch (sending analogic signal) port AN9 but when I set high threshold (~50) led don't blinks, with low threshold (~0) it blinks immidiatly when i provide power to the PIC. Maybe i'm using wrong port? I'm actually passing AN9 as reading port? Or maybe threshold is wrong? How can i found the right value? Thank you

Here the MPLAB C18 Apis http://dl.dropbox.com/u/14663091/API%20microchip%20C18.pdf .

Body:
Regarding function myReadADC2(): you need to switch ANSEL and ANSELH configs as RC7/AN9 is configured in bit 1 of ANSELH. Also call me paranoid but for the line

iRet += (ADRESH << 8);

I always like to either save it a temporary variable first or cast explicitly the value ADRESH before shifting it up:

iRet += (((UINT) ADRESH) << 8);

That way I know for sure the bits won't get lost when shifting up which has bitten me before.

Regarding function myReadADC():
OpenADC() only takes two parameters. I presume that bitfield in the third parameter field is for the analog enable (ADRESH/ADRES). I'm assuming that's handled by SetChanADC() but you may have to set ADRESH/ADRES manually. It may help to set a breakpoint in the debugger and stop after configuration is complete to make sure your registers are set appropriatley.


来源: stackexchange

问:
Write a Java 8 predicate that filters against a value that is not in scope
I am trying to write a filtering predicate that will filter a list based on a value held in a different object, but the object that I want to extract the value to compare against is available at the time that the comparison is carried out, not at the time the predicate is defined.

Here's an SSCCE

```<code>import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class StreamTest {
    public static void main(String [] args){
        DataContainer dc = new DataContainer();
        Predicate<Integer> p = new Predicate<Integer>(){
            @Override
            public boolean test(Integer t) {
            /********************************************/
                return t > 6; // I need this to be t > the limitValue that is available when the predicate gets executed
            /********************************************/
            }
        };

        System.out.println(dc.numberOfValuesGreaterThan(p, new LimitValue(6)));
    }

}
class DataContainer{
    private List<Integer> l = Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9,10});

    public long numberOfValuesSatisfyingPredicate(Predicate predicate,LimitValue lv){
        return l.stream()
                .filter(predicate)
                .count();
    }
}
class LimitValue{
    private int limitValue;
    public LimitValue(int limitValue){
        this.limitValue = limitValue;
    }
    public int getValue(){
        return limitValue;
    }
}
</code>```

The code creates a DataContainer, that contains the numbers 1 - 10 and has a method that takes a Predicate and a Limit Value, allowing you to do things like get the number of elements greater than 5, or less that 9 by supplying different predicates.

However, at the time the Predicate is defined the LimitValue object is not in scope. Is it possible to define a Predicate that can access variables that are available at execution time but not at definition time?

答:
Here is my answer from different aspect:

First of all, numberOfValuesSatisfyingPredicate is totally unnecessary. This method doesn't do any extra job, comparing the stream API. It's inflexible.

Secondly, if you really want it, since you know the value when call the method, so there should be no second parameter LimitValue:

```<code>public static void main(String[] args) {
    DataContainer dc = new DataContainer();
    // I think
    System.out.println(dc.numberOfValuesSatisfyingPredicate(i -> i > 6));

    // is much better than:
    Function<LimitValue, Predicate<Integer>> p = limitValue -> {
        return i -> i > limitValue.getValue();
    };
    System.out.println(dc.numberOfValuesSatisfyingPredicate(p, new LimitValue(6)));
}

class DataContainer {
    private List<Integer> l = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

    public long numberOfValuesSatisfyingPredicate(Predicate<Integer> predicate) {
        return l.stream().filter(predicate).count();
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write a filtering predicate that will filter a list based on a value held in a different object, but the object that I want to extract the value to compare against is available at the time that the comparison is carried out, not at the time the predicate is defined.

Here's an SSCCE

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class StreamTest {
    public static void main(String [] args){
        DataContainer dc = new DataContainer();
        Predicate<Integer> p = new Predicate<Integer>(){
            @Override
            public boolean test(Integer t) {
            /********************************************/
                return t > 6; // I need this to be t > the limitValue that is available when the predicate gets executed
            /********************************************/
            }
        };

        System.out.println(dc.numberOfValuesGreaterThan(p, new LimitValue(6)));
    }

}
class DataContainer{
    private List<Integer> l = Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9,10});

    public long numberOfValuesSatisfyingPredicate(Predicate predicate,LimitValue lv){
        return l.stream()
                .filter(predicate)
                .count();
    }
}
class LimitValue{
    private int limitValue;
    public LimitValue(int limitValue){
        this.limitValue = limitValue;
    }
    public int getValue(){
        return limitValue;
    }
}

The code creates a DataContainer, that contains the numbers 1 - 10 and has a method that takes a Predicate and a Limit Value, allowing you to do things like get the number of elements greater than 5, or less that 9 by supplying different predicates.

However, at the time the Predicate is defined the LimitValue object is not in scope. Is it possible to define a Predicate that can access variables that are available at execution time but not at definition time?

Body:
Here is my answer from different aspect:

First of all, numberOfValuesSatisfyingPredicate is totally unnecessary. This method doesn't do any extra job, comparing the stream API. It's inflexible.

Secondly, if you really want it, since you know the value when call the method, so there should be no second parameter LimitValue:

public static void main(String[] args) {
    DataContainer dc = new DataContainer();
    // I think
    System.out.println(dc.numberOfValuesSatisfyingPredicate(i -> i > 6));

    // is much better than:
    Function<LimitValue, Predicate<Integer>> p = limitValue -> {
        return i -> i > limitValue.getValue();
    };
    System.out.println(dc.numberOfValuesSatisfyingPredicate(p, new LimitValue(6)));
}

class DataContainer {
    private List<Integer> l = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

    public long numberOfValuesSatisfyingPredicate(Predicate<Integer> predicate) {
        return l.stream().filter(predicate).count();
    }
}


问:
How am I supposed to initialize pthread mutexes?
```<code>#include <pthread.h>

pthread_mutex_t* mut;

int main()
{
        mut = PTHREAD_MUTEX_INITIALIZER;
}
</code>```

The above code spits out error: expected expression before ‘{’ token.

```<code>#include <pthread.h>

pthread_mutex_t* mut = PTHREAD_MUTEX_INITIALIZER;

int main()
{

}
</code>```

The above code spits out warning: braces around scalar initializer

So how am I supposed to initialize a mutex?

答:
It is a type error, you should use: pthread_mutex_t instead of pthread_mutex_t*:

```<code>pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
</code>```

The reason why compiler complains is that is tries to assign this macro expansion of PTHREAD_MUTEX_INITIALIZER to a pointer:

```<code>{ { 0, 0, 0, 0, 0, __PTHREAD_SPINS, { 0, 0 } } }
</code>```

With the corrected approach, you may pass &mut everywhere you need pthread_mutex_t*.

Body:
#include <pthread.h>

pthread_mutex_t* mut;

int main()
{
        mut = PTHREAD_MUTEX_INITIALIZER;
}

The above code spits out error: expected expression before ‘{’ token.

#include <pthread.h>

pthread_mutex_t* mut = PTHREAD_MUTEX_INITIALIZER;

int main()
{

}

The above code spits out warning: braces around scalar initializer

So how am I supposed to initialize a mutex?

Body:
It is a type error, you should use: pthread_mutex_t instead of pthread_mutex_t*:

pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

The reason why compiler complains is that is tries to assign this macro expansion of PTHREAD_MUTEX_INITIALIZER to a pointer:

{ { 0, 0, 0, 0, 0, __PTHREAD_SPINS, { 0, 0 } } }

With the corrected approach, you may pass &mut everywhere you need pthread_mutex_t*.


问:
app engine logging to database and entity groups
In my application I have a Profile entity, which have some children, like ProfileAccount, ProfileLink, etc. They're usually updated in a transaction, like

```<code>def update_profile(key):
  profile = db.get(key)
  accounts = db.query("SELECT * FROM ProfileAccount WHERE ANCESTOR IS :1", profile)
  # do something with accounts and profile
  profile.put()
</code>```

I call it with db.run_in_transaction(update_profile, key), but I need to have an administrative log of everything that happens when the profile is updated, so I created a generic AdminLog entity which contains a reference to a Profile, the timestamp and arbitrary string data. This would be processed later to check what happened since the last user login.

The problem is as AdminLog doesn't belong to the same entity group as the Profile, I cannot add it on the same transaction, but on the other side, I don't think it would be clever to put all those logs under the same entity (Profile), as it's not essential data.

One thing I thought about would be a StringList on the Profile, that would be cleared on each login, so this way I'd have everything that happened to the profile. Do you think that's a nice approach, or maybe there's some other workaround for this kind of situation ?

Thanks in advance for any tips

答: Using child entities seems like the best option. It ensures you can update them transactionally, and associates the changes with the entity they apply to. If you wish, you can garbage collect old admin log entries to save space.</p>

ContentLicense: CC BY-SA 2.5

Body:
In my application I have a Profile entity, which have some children, like ProfileAccount, ProfileLink, etc. They're usually updated in a transaction, like

def update_profile(key):
  profile = db.get(key)
  accounts = db.query("SELECT * FROM ProfileAccount WHERE ANCESTOR IS :1", profile)
  # do something with accounts and profile
  profile.put()

I call it with db.run_in_transaction(update_profile, key), but I need to have an administrative log of everything that happens when the profile is updated, so I created a generic AdminLog entity which contains a reference to a Profile, the timestamp and arbitrary string data. This would be processed later to check what happened since the last user login.

The problem is as AdminLog doesn't belong to the same entity group as the Profile, I cannot add it on the same transaction, but on the other side, I don't think it would be clever to put all those logs under the same entity (Profile), as it's not essential data.

One thing I thought about would be a StringList on the Profile, that would be cleared on each login, so this way I'd have everything that happened to the profile. Do you think that's a nice approach, or maybe there's some other workaround for this kind of situation ?

Thanks in advance for any tips


问:
RxJS subscribe never finishes
I'm fairly new with rxjs. I'm calling a function below and the complete stream is read and the read console statements are printed, but I never see a "Subscibe done" and I don't know why. What will it take to get this stream to finish? Is something obviously wrong?</p>

```<code>const readline$ = RxNode.fromReadLineStream(rl)
    .filter((element, index, observable) => {
        if (index >= range.start && index < range.stop) {
            console.log(`kept line is ${JSON.stringify(element)}`);
            return true;
        } else {
            console.log(`not keeping line ${JSON.stringify(element)}`);
            return false;
        }
    })
    .concatMap(line => Rx.Observable.fromPromise(myFunction(line)))
    .do(response => console.log(JSON.stringify(response)));

readline$.subscribe(i => { console.log(`Subscribe object: ${util.inspect(i)}`); },
                  err => { console.error(`Subscribe error: ${util.inspect(err)}`); },
                 done => { console.log("Subscribe done."); // NEVER CALLED
                           anotherFunc();                  // NEVER CALLED
                     }
);
</code>```

答:
You can see from the source code that it send complete notification only when the source stream emits close event. https://github.com/Reactive-Extensions/rx-node/blob/master/index.js#L100-L102

So if you need the proper complete handler to be called you'll need to close the stream yourself, see How to close a readable stream (before end)?.

In other words the Observable doesn't complete automatically after reading the entire file.

Title: RxJS subscribe never finishes

Body:
I'm fairly new with rxjs. I'm calling a function below and the complete stream is read and the read console statements are printed, but I never see a "Subscibe done" and I don't know why. What will it take to get this stream to finish? Is something obviously wrong?

const readline$ = RxNode.fromReadLineStream(rl)
    .filter((element, index, observable) => {
        if (index >= range.start && index < range.stop) {
            console.log(`kept line is ${JSON.stringify(element)}`);
            return true;
        } else {
            console.log(`not keeping line ${JSON.stringify(element)}`);
            return false;
        }
    })
    .concatMap(line => Rx.Observable.fromPromise(myFunction(line)))
    .do(response => console.log(JSON.stringify(response)));

readline$.subscribe(i => { console.log(`Subscribe object: ${util.inspect(i)}`); },
                  err => { console.error(`Subscribe error: ${util.inspect(err)}`); },
                 done => { console.log("Subscribe done."); // NEVER CALLED
                           anotherFunc();                  // NEVER CALLED
                     }
);


问:
Add an extra column to this form
How do I add an extra column to the form used here? I am trying to achieve something like this, where there is info on the right with the form on the left. I tried adding another div under the div with class=row and floating the div with class=well left but it shrunk the form and I couldn't get it to return to its original size without sending the text underneath.
Listing code below anyways:</p>

```<code><div class="container">
    <div class="row">
      <div class="col-md-6 col-md-offset-3">
        <div class="well well-sm">
          <form class="form-horizontal" action="" method="post">
          <fieldset>
            <legend class="text-center">Contact us</legend>

            <!-- Name input-->
            <div class="form-group">
              <label class="col-md-3 control-label" for="name">Name</label>
              <div class="col-md-9">
                <input id="name" name="name" type="text" placeholder="Your name" class="form-control">
              </div>
            </div>

            <!-- Email input-->
            <div class="form-group">
              <label class="col-md-3 control-label" for="email">Your E-mail</label>
              <div class="col-md-9">
                <input id="email" name="email" type="text" placeholder="Your email" class="form-control">
              </div>
            </div>

            <!-- Message body -->
            <div class="form-group">
              <label class="col-md-3 control-label" for="message">Your message</label>
              <div class="col-md-9">
                <textarea class="form-control" id="message" name="message" placeholder="Please enter your message here..." rows="5"></textarea>
              </div>
            </div>

            <!-- Form actions -->
            <div class="form-group">
              <div class="col-md-12 text-right">
                <button type="submit" class="btn btn-primary btn-lg">Submit</button>
              </div>
            </div>
          </fieldset>
          </form>
        </div>
      </div>
    </div>
</div>
</code>```

答:
You could try by adding two columns , and adding your current code, in the bigger scaled column

 <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      <form class="form-horizontal" action="" method="post">
      <fieldset>
        <legend class="text-center">Contact us</legend>

          Name

            <input id="name" name="name" type="text" placeholder="Your name" class="form-control">

          Your E-mail

            <input id="email" name="email" type="text" placeholder="Your email" class="form-control">

          Your message

            <textarea class="form-control" id="message" name="message" placeholder="Please enter your message here..." rows="5"></textarea>

            <button type="submit" class="btn btn-primary btn-lg">Submit</button>

      </fieldset>
      </form>

Contact Details

 hello

 hello

 hello

 hello

Social

Logos

Project Opportunities

Lorem Ipsum Lorem IpsumLorem IpsumLorem IpsumLorem Lorem Ipsum Lorem Ipsum

```

Title: Add an extra column to this form

Body:
How do I add an extra column to the form used here? I am trying to achieve something like this, where there is info on the right with the form on the left. I tried adding another div under the div with class=row and floating the div with class=well left but it shrunk the form and I couldn't get it to return to its original size without sending the text underneath.
Listing code below anyways:

          <form class="form-horizontal" action="" method="post">
          <fieldset>
            <legend class="text-center">Contact us</legend>

              Name

                <input id="name" name="name" type="text" placeholder="Your name" class="form-control">

              Your E-mail

                <input id="email" name="email" type="text" placeholder="Your email" class="form-control">

              Your message

                <textarea class="form-control" id="message" name="message" placeholder="Please enter your message here..." rows="5"></textarea>

                <button type="submit" class="btn btn-primary btn-lg">Submit</button>

          </fieldset>
          </form>

Body:
You could try by adding two columns , and adding your current code, in the bigger scaled column

 <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="container">
 <div class="well well-sm">
<div class="row">

  <div class="col-md-8">
  <div class="col-md-6 col-md-offset-3">

      <form class="form-horizontal" action="" method="post">
      <fieldset>
        <legend class="text-center">Contact us</legend>

        <!-- Name input-->
        <div class="form-group">
          <label class="col-md-3 control-label" for="name">Name</label>
          <div class="col-md-9">
            <input id="name" name="name" type="text" placeholder="Your name" class="form-control">
          </div>
        </div>

        <!-- Email input-->
        <div class="form-group">
          <label class="col-md-3 control-label" for="email">Your E-mail</label>
          <div class="col-md-9">
            <input id="email" name="email" type="text" placeholder="Your email" class="form-control">
          </div>
        </div>

        <!-- Message body -->
        <div class="form-group">
          <label class="col-md-3 control-label" for="message">Your message</label>
          <div class="col-md-9">
            <textarea class="form-control" id="message" name="message" placeholder="Please enter your message here..." rows="5"></textarea>
          </div>
        </div>

        <!-- Form actions -->
        <div class="form-group">
          <div class="col-md-12 text-right">
            <button type="submit" class="btn btn-primary btn-lg">Submit</button>
          </div>
        </div>
      </fieldset>
      </form>
    </div>

</div>
<div class="col-md-4" style="padding:40px;">
  <div class="row">
<h4>Contact Details</h4>

 <p><span class="glyphicon glyphicon-envelope"></span> hello</p>
<p><span class="glyphicon glyphicon-envelope"></span> hello</p>

<p><span class="glyphicon glyphicon-envelope"></span> hello</p>
  <p><span class="glyphicon glyphicon-envelope"></span> hello</p>
  </div>

  <div class="row">
<h4>Social</h4>
<p>Logos</p>
  </div>

  <div class="row">
<h4>Project Opportunities</h4>
 <p>Lorem Ipsum Lorem IpsumLorem IpsumLorem IpsumLorem Lorem Ipsum Lorem Ipsum</p>
  </div>
  </div>
  </div>
 </div>
</div>


问:
Catamorphism and tree-traversing in Haskell
I am impatient, looking forward to understanding catamorphism related to this SO question :)

I have only practiced the beginning of Real World Haskell tutorial. So, Maybe I'm gonna ask for way too much right now, if it was the case, just tell me the concepts I should learn.

Below, I quote the wikipedia code sample for catamorphism.

I would like to know your opinion about foldTree below, a way of traversing a Tree, compared to this other SO question and answer, also dealing with traversing a Tree n-ary tree traversal. (independantly from being binary or not, I think the catamorphism below can be written so as to manage n-ary tree)

I put in comment what I understand, and be glad if you could correct me, and clarify some things.

```<code>{-this is a binary tree definition-}
data Tree a = Leaf a
            | Branch (Tree a) (Tree a)

{-I dont understand the structure between{}
however it defines two morphisms, leaf and branch
leaf take an a and returns an r, branch takes two r and returns an r-}
data TreeAlgebra a r = TreeAlgebra { leaf   :: a      -> r
                                   , branch :: r -> r -> r }

{- foldTree is a morphism that takes: a TreeAlgebra for Tree a with result r, a Tree a
and returns an r -}
foldTree :: TreeAlgebra a r -> Tree a -> r
foldTree a@(TreeAlgebra {leaf   = f}) (Leaf   x  ) = f x
foldTree a@(TreeAlgebra {branch = g}) (Branch l r) = g (foldTree a l) (foldTree a r)
</code>```

at this point I am having many difficulties, I seem to guess that the morphism leaf
will be applied to any Leaf
But so as to use this code for real, foldTree needs to be fed a defined TreeAlgebra,
a TreeAlgebra that has a defined morphism leaf so as to do something ?

but in this case in the foldTree code I would expect {f = leaf} and not the contrary

Any clarification from you would be really welcome.

答:
Not exactly sure what you're asking.  But yeah, you feed a TreeAlgebra to foldTree corresponding to the computation you want to perform on the tree. For example, to sum all the elements in a tree of Ints you would use this algebra:

```<code>sumAlgebra :: TreeAlgebra Int Int
sumAlgebra = TreeAlgebra { leaf = id
                         , branch = (+) }
</code>```

Which means, to get the sum of a leaf, apply id (do nothing) to the value in the leaf.  To get the sum of a branch, add together the sums of each of the children.

The fact that we can say (+) for branch instead of, say, \x y -> sumTree x + sumTree y is the essential property of the catamorphism.  It says that to compute some function f on some recursive data structure it suffices to have the values of f for its immediate children.

Haskell is a pretty unique language in that we can formalize the idea of catamorphism abstractly.  Let's make a data type for a single node in your tree, parameterized over its children:

```<code>data TreeNode a child
    = Leaf a
    | Branch child child
</code>```

See what we did there?  We just replaced the recursive children with a type of our choosing.  This is so that we can put the subtrees' sums there when we are folding.

Now for the really magical thing.  I'm going to write this in pseudohaskell -- writing it in real Haskell is possible, but we have to add some annotations to help the typechecker which can be kind of confusing.  We take the "fixed point" of a parameterized data type -- that is, constructing a data type T such that T = TreeNode a T.  They call this operator Mu.

```<code>type Mu f = f (Mu f)
</code>```

Look carefully here.  The argument to Mu isn't a type, like Int or Foo -> Bar.  It's a type constructor like Maybe or TreeNode Int -- the argument to Mu itself takes an argument.  (The possibility of abstracting over type constructors is one of the things that makes Haskell's type system really stand out in its expressive power).

So the type Mu f is defined as taking f and filling in its type parameter with Mu f itself.  I'm going to define a synonym to reduce some of the noise:

```<code>type IntNode = TreeNode Int
</code>```

Expanding Mu IntNode, we get:

```<code>Mu IntNode = IntNode (Mu IntNode)
           = Leaf Int | Branch (Mu IntNode) (Mu IntNode)
</code>```

Do you see how Mu IntNode is equivalent to your Tree Int? We have just torn the recursive structure apart and then used Mu to put it back together again. This gives us the advantage that we can talk about all Mu types at once.  This gives us what we need to define a catamorphism.

Let's define:

```<code>type IntTree = Mu IntNode
</code>```

I said the essential property of the catamorphism is that to compute some function f, it suffices to have the values of f for its immediate children.  Let's call the type of the thing we are trying to compute r, and the data structure node (IntNode would be a possible instantiation of this).  So to compute r on a particular node, we need the node with its children replaced with their rs.  This computation has type node r -> r.  So a catamorphism says that if we have one of these computations, then we can compute r for the entire recursive structure (remember recursion is denoted explicitly here with Mu):

```<code>cata :: (node r -> r) -> Mu node -> r
</code>```

Making this concrete for our example, this looks like:

```<code>cata :: (IntNode r -> r) -> IntTree -> r
</code>```

Restating, if we can take a node with rs for its children and compute an r, then we can compute an r for an entire tree.

In order to actually compute this, we need node to be a Functor -- that is we need to be able to map an arbitrary function over the children of a node.

```<code>fmap :: (a -> b) -> node a -> node b
</code>```

This can be done straightforwardly for IntNode.

```<code>fmap f (Leaf x) = Leaf x                  -- has no children, so stays the same
fmap f (Branch l r) = Branch (f l) (f r)  -- apply function to each child
</code>```

Now, finally, we can give a definition for cata  (the Functor node constraint just says that node has a suitable fmap):

```<code>cata :: (Functor node) => (node r -> r) -> Mu node -> r
cata f t = f (fmap (cata f) t)
</code>```

I used the parameter name t for the mnemonic value of "tree".  This is an abstract, dense definition, but it is really very simple.  It says: recursively perform cata f -- the computation we are doing over the tree -- on each of t's children (which are themselves Mu nodes) to get a node r, and then pass that result to f compute the result for t itself.

Tying this back to the beginning, the algebra you are defining is essentially a way of defining that node r -> r function.  Indeed, given a TreeAlgebra, we can easily get the fold function:

```<code>foldFunction :: TreeAlgebra a r -> (TreeNode a r -> r)
foldFunction alg (Leaf a) = leaf alg a
foldFunction alg (Branch l r) = branch alg l r
</code>```

Thus the tree catamorphism can be defined in terms of our generic one as follows:

```<code>type Tree a = Mu (TreeNode a)

treeCata :: TreeAlgebra a r -> (Tree a -> r)
treeCata alg = cata (foldFunction alg)
</code>```

I'm out of time.  I know that got really abstract really fast, but I hope it at least gave you a new viewpoint to help your learning.  Good luck!

Body:
I am impatient, looking forward to understanding catamorphism related to this SO question :)

I have only practiced the beginning of Real World Haskell tutorial. So, Maybe I'm gonna ask for way too much right now, if it was the case, just tell me the concepts I should learn.

Below, I quote the wikipedia code sample for catamorphism.

I would like to know your opinion about foldTree below, a way of traversing a Tree, compared to this other SO question and answer, also dealing with traversing a Tree n-ary tree traversal. (independantly from being binary or not, I think the catamorphism below can be written so as to manage n-ary tree)

I put in comment what I understand, and be glad if you could correct me, and clarify some things.

{-this is a binary tree definition-}
data Tree a = Leaf a
            | Branch (Tree a) (Tree a)

{-I dont understand the structure between{}
however it defines two morphisms, leaf and branch
leaf take an a and returns an r, branch takes two r and returns an r-}
data TreeAlgebra a r = TreeAlgebra { leaf   :: a      -> r
                                   , branch :: r -> r -> r }

{- foldTree is a morphism that takes: a TreeAlgebra for Tree a with result r, a Tree a
and returns an r -}
foldTree :: TreeAlgebra a r -> Tree a -> r
foldTree a@(TreeAlgebra {leaf   = f}) (Leaf   x  ) = f x
foldTree a@(TreeAlgebra {branch = g}) (Branch l r) = g (foldTree a l) (foldTree a r)

at this point I am having many difficulties, I seem to guess that the morphism leaf
will be applied to any Leaf
But so as to use this code for real, foldTree needs to be fed a defined TreeAlgebra,
a TreeAlgebra that has a defined morphism leaf so as to do something ?

but in this case in the foldTree code I would expect {f = leaf} and not the contrary

Any clarification from you would be really welcome.

Body:
Not exactly sure what you're asking.  But yeah, you feed a TreeAlgebra to foldTree corresponding to the computation you want to perform on the tree. For example, to sum all the elements in a tree of Ints you would use this algebra:

sumAlgebra :: TreeAlgebra Int Int
sumAlgebra = TreeAlgebra { leaf = id
                         , branch = (+) }

Which means, to get the sum of a leaf, apply id (do nothing) to the value in the leaf.  To get the sum of a branch, add together the sums of each of the children.

The fact that we can say (+) for branch instead of, say, \x y -> sumTree x + sumTree y is the essential property of the catamorphism.  It says that to compute some function f on some recursive data structure it suffices to have the values of f for its immediate children.

Haskell is a pretty unique language in that we can formalize the idea of catamorphism abstractly.  Let's make a data type for a single node in your tree, parameterized over its children:

data TreeNode a child
    = Leaf a
    | Branch child child

See what we did there?  We just replaced the recursive children with a type of our choosing.  This is so that we can put the subtrees' sums there when we are folding.

Now for the really magical thing.  I'm going to write this in pseudohaskell -- writing it in real Haskell is possible, but we have to add some annotations to help the typechecker which can be kind of confusing.  We take the "fixed point" of a parameterized data type -- that is, constructing a data type T such that T = TreeNode a T.  They call this operator Mu.

type Mu f = f (Mu f)

Look carefully here.  The argument to Mu isn't a type, like Int or Foo -> Bar.  It's a type constructor like Maybe or TreeNode Int -- the argument to Mu itself takes an argument.  (The possibility of abstracting over type constructors is one of the things that makes Haskell's type system really stand out in its expressive power).

So the type Mu f is defined as taking f and filling in its type parameter with Mu f itself.  I'm going to define a synonym to reduce some of the noise:

type IntNode = TreeNode Int

Expanding Mu IntNode, we get:

Mu IntNode = IntNode (Mu IntNode)
           = Leaf Int | Branch (Mu IntNode) (Mu IntNode)

Do you see how Mu IntNode is equivalent to your Tree Int? We have just torn the recursive structure apart and then used Mu to put it back together again. This gives us the advantage that we can talk about all Mu types at once.  This gives us what we need to define a catamorphism.

Let's define:

type IntTree = Mu IntNode

I said the essential property of the catamorphism is that to compute some function f, it suffices to have the values of f for its immediate children.  Let's call the type of the thing we are trying to compute r, and the data structure node (IntNode would be a possible instantiation of this).  So to compute r on a particular node, we need the node with its children replaced with their rs.  This computation has type node r -> r.  So a catamorphism says that if we have one of these computations, then we can compute r for the entire recursive structure (remember recursion is denoted explicitly here with Mu):

cata :: (node r -> r) -> Mu node -> r

Making this concrete for our example, this looks like:

cata :: (IntNode r -> r) -> IntTree -> r

Restating, if we can take a node with rs for its children and compute an r, then we can compute an r for an entire tree.

In order to actually compute this, we need node to be a Functor -- that is we need to be able to map an arbitrary function over the children of a node.

fmap :: (a -> b) -> node a -> node b

This can be done straightforwardly for IntNode.

fmap f (Leaf x) = Leaf x                  -- has no children, so stays the same
fmap f (Branch l r) = Branch (f l) (f r)  -- apply function to each child

Now, finally, we can give a definition for cata  (the Functor node constraint just says that node has a suitable fmap):

cata :: (Functor node) => (node r -> r) -> Mu node -> r
cata f t = f (fmap (cata f) t)

I used the parameter name t for the mnemonic value of "tree".  This is an abstract, dense definition, but it is really very simple.  It says: recursively perform cata f -- the computation we are doing over the tree -- on each of t's children (which are themselves Mu nodes) to get a node r, and then pass that result to f compute the result for t itself.

Tying this back to the beginning, the algebra you are defining is essentially a way of defining that node r -> r function.  Indeed, given a TreeAlgebra, we can easily get the fold function:

foldFunction :: TreeAlgebra a r -> (TreeNode a r -> r)
foldFunction alg (Leaf a) = leaf alg a
foldFunction alg (Branch l r) = branch alg l r

Thus the tree catamorphism can be defined in terms of our generic one as follows:

type Tree a = Mu (TreeNode a)

treeCata :: TreeAlgebra a r -> (Tree a -> r)
treeCata alg = cata (foldFunction alg)

I'm out of time.  I know that got really abstract really fast, but I hope it at least gave you a new viewpoint to help your learning.  Good luck!


问:
jquery.on() get reference to attached listener
I attach an event listeners:

```<code>selector.on('DOMSubtreeModified', {email: email}, handler);

function handler(event) {
                    if (hasLoaded()) {
                        selector.off('DOMSubtreeModified', handler);
                        otherStuff(event.email);
                    }
                }
</code>```

This can happen multiple times and when the first event triggers the off method, all listeners get removed. Is it possible to trigger off only on for the specific attachment. something like:

```<code>var listener = selector.on('DOMSubtreeModified', function() {
                    if (hasLoaded()) {
                        selector.off(listener);
                        otherStuff(email);
                    }
                });
</code>```

答:
Yes, you can remove only one handler.

The doc says:
A handler can also be removed by
specifying the function name in the handler argument. When jQuery attaches an event handler, it assigns a unique id to the handler function.

http://api.jquery.com/off/

Body:
I attach an event listeners:

selector.on('DOMSubtreeModified', {email: email}, handler);

function handler(event) {
                    if (hasLoaded()) {
                        selector.off('DOMSubtreeModified', handler);
                        otherStuff(event.email);
                    }
                }

This can happen multiple times and when the first event triggers the off method, all listeners get removed. Is it possible to trigger off only on for the specific attachment. something like:

var listener = selector.on('DOMSubtreeModified', function() {
                    if (hasLoaded()) {
                        selector.off(listener);
                        otherStuff(email);
                    }
                });


问:
Recursion in c++ (generate binary codes)
I am trying to write a program that generates all the binary codes given an input number (for the number of bits). For example, if the user inputs 3, it should generate all the numbers below:

```<code>000
001
010
011
100
101
110
111
</code>```

The function is called generateBinaryCode(), and it has to be recursive (that's the challenge of the question).

The following is my attempt but it doesn't work. Can anyone please offer me some insights?

Thanks in advance.

```<code>#include <iostream>
#include <string>
#include <vector>

using namespace std;
vector<string> generateBinaryCode(int nBits);

int main()
{
    int input;

    while (true)
    {
        cout << "Enter an integer (any negative numbers are sentinel): ";
        cin >> input;
        if (input < 0) break;

        for (unsigned i = 0; i < generateBinaryCode(input).size(); i++)
            cout << generateBinaryCode(input).at(i) << endl;
    }

    return 0;
}

vector<string> generateBinaryCode(int nBits)
{
    vector<string> result;
    int size = result.size();
    std::vector<string>::iterator it;

    if (nBits == 1) {

        result.push_back("0");
        result.push_back("1");

    } else {
        result = generateBinaryCode(nBits - 1);

        for (unsigned int i = 0; i < result.size(); i++)
        {
            result.push_back("0" + result.at(i));
            result.at(i) = "1" + result.at(i);
        }

    }

    return result;
}
</code>```

答:
simpler and concise solution</p>

```<code>void printBin(std::string prefix, int n)
{
    if(prefix.size() == n)
    {

        std::cout <<prefix <<std::endl;
        return;
    }

    printBin(prefix + '0', n);
    printBin(prefix + '1', n);

    return;

}

int main()
{
    int n;
    std::cin >> n;
    printBin("", n);
    return 0;
 }
</code>```

Body:
I am trying to write a program that generates all the binary codes given an input number (for the number of bits). For example, if the user inputs 3, it should generate all the numbers below:

000
001
010
011
100
101
110
111

The function is called generateBinaryCode(), and it has to be recursive (that's the challenge of the question).

The following is my attempt but it doesn't work. Can anyone please offer me some insights?

Thanks in advance.

#include <iostream>
#include <string>
#include <vector>

using namespace std;
vector<string> generateBinaryCode(int nBits);

int main()
{
    int input;

    while (true)
    {
        cout << "Enter an integer (any negative numbers are sentinel): ";
        cin >> input;
        if (input < 0) break;

        for (unsigned i = 0; i < generateBinaryCode(input).size(); i++)
            cout << generateBinaryCode(input).at(i) << endl;
    }

    return 0;
}

vector<string> generateBinaryCode(int nBits)
{
    vector<string> result;
    int size = result.size();
    std::vector<string>::iterator it;

    if (nBits == 1) {

        result.push_back("0");
        result.push_back("1");

    } else {
        result = generateBinaryCode(nBits - 1);

        for (unsigned int i = 0; i < result.size(); i++)
        {
            result.push_back("0" + result.at(i));
            result.at(i) = "1" + result.at(i);
        }

    }

    return result;
}

Body:
simpler and concise solution

void printBin(std::string prefix, int n)
{
    if(prefix.size() == n)
    {

        std::cout <<prefix <<std::endl;
        return;
    }

    printBin(prefix + '0', n);
    printBin(prefix + '1', n);

    return;

}

int main()
{
    int n;
    std::cin >> n;
    printBin("", n);
    return 0;
 }


问:
Is there any File-System based database in PHP?
I am using a server, which has a restriction on the database usage i.e. I can't use more than 10mb of data, in the MySQL tables. So, I am searching for a alternate way of storing data, I need a database which stores data in form of files and it is also easy to use too.</p>

答:
You could try using XML files in order to save your data.

Regarding the database limit, MySQL saves the data in files as well, so that must be a limitation on MySQL itself. You could ask them if you could use another DBMS, like PostgreSQL.


问:
Play2 IntelliJ leads to akka.stream.BindFailedException$: bind failed on Linux
When I try to run my (local) play application via the play2 plugin from intellij I get:

```<code>[ERROR] [06/03/2017 23:21:10.985] [play-dev-mode-akka.actor.default-dispatcher-2] [akka://play-dev-mode/system/IO-TCP/selectors/$a/0] Bind failed for TCP channel on endpoint [/0.0.0.0:80]
java.net.SocketException: Permission denied
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:433)
    at sun.nio.ch.Net.bind(Net.java:425)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at akka.io.TcpListener.liftedTree1$1(TcpListener.scala:56)
    at akka.io.TcpListener.<init>(TcpListener.scala:53)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at akka.util.Reflect$.instantiate(Reflect.scala:65)
    at akka.actor.ArgsReflectConstructor.produce(IndirectActorProducer.scala:96)
    at akka.actor.Props.newActor(Props.scala:213)
    at akka.actor.ActorCell.newActor(ActorCell.scala:555)
    at akka.actor.ActorCell.create(ActorCell.scala:581)
    at akka.actor.ActorCell.invokeAll$1(ActorCell.scala:454)
    at akka.actor.ActorCell.systemInvoke(ActorCell.scala:476)
    at akka.dispatch.Mailbox.processAllSystemMessages(Mailbox.scala:282)
    at akka.dispatch.Mailbox.run(Mailbox.scala:223)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
    at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

akka.stream.BindFailedException$: bind failed
</code>```

If however, I run it via sbt run, everything works like a charm.

1) Why is that?
2) How can I fix this? (Running on Linux 4.11 here - I understand that the port is only allowed "sudoers", but then I wonder why the sbt-way works)
3) Any other way to run play in "debug mode"? I would like to set some break points and analyze the flow.

答:
I ran into similiar issues before. Deploying to port requires permissions, if you want to strt the service on local, you can change the port to 9000, if you don'5 want this issue to occur. Then, when you deploy on production, you can change it to 80 and follow this guide :

https://www.playframework.com/documentation/2.5.x/Deploying

Body:
When I try to run my (local) play application via the play2 plugin from intellij I get:

[ERROR] [06/03/2017 23:21:10.985] [play-dev-mode-akka.actor.default-dispatcher-2] [akka://play-dev-mode/system/IO-TCP/selectors/$a/0] Bind failed for TCP channel on endpoint [/0.0.0.0:80]
java.net.SocketException: Permission denied
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:433)
    at sun.nio.ch.Net.bind(Net.java:425)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at akka.io.TcpListener.liftedTree1$1(TcpListener.scala:56)
    at akka.io.TcpListener.<init>(TcpListener.scala:53)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at akka.util.Reflect$.instantiate(Reflect.scala:65)
    at akka.actor.ArgsReflectConstructor.produce(IndirectActorProducer.scala:96)
    at akka.actor.Props.newActor(Props.scala:213)
    at akka.actor.ActorCell.newActor(ActorCell.scala:555)
    at akka.actor.ActorCell.create(ActorCell.scala:581)
    at akka.actor.ActorCell.invokeAll$1(ActorCell.scala:454)
    at akka.actor.ActorCell.systemInvoke(ActorCell.scala:476)
    at akka.dispatch.Mailbox.processAllSystemMessages(Mailbox.scala:282)
    at akka.dispatch.Mailbox.run(Mailbox.scala:223)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
    at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

akka.stream.BindFailedException$: bind failed

If however, I run it via sbt run, everything works like a charm.

1) Why is that?
2) How can I fix this? (Running on Linux 4.11 here - I understand that the port is only allowed "sudoers", but then I wonder why the sbt-way works)
3) Any other way to run play in "debug mode"? I would like to set some break points and analyze the flow.


问:
D3 - Select SVG center path when drilled into and display zoom out background image
I'd like to add a background image to the center of this sunburst:

https://bl.ocks.org/mbostock/4348373

so that once the user has clicked to drill into the burst, the center circle instead of being a solid background color would display a "zoom out" background image.

I don't know how to identify the center circle and change the fill color from solid to a background image. The zoom out image would only be displayed when the user has drilled down. When the user is expanded all the way out (the default state when the page is loaded), then the zoom out image would not be displayed.

Thanks for any help.

答:
you can put another circle or g element with circle and text into center and give it

```<code>yourZoomOutEleement
.attr('opacity',0)
.attr('pointer-events','none')
</code>```

when sunburst is zoomed in, you can display your circle (or g with other elements in it) by specifying opacity

yourZoomOutEleement.attr('opacity',1)

see the block

Body:
you can put another circle or g element with circle and text into center and give it

yourZoomOutEleement
.attr('opacity',0)
.attr('pointer-events','none')

when sunburst is zoomed in, you can display your circle (or g with other elements in it) by specifying opacity

yourZoomOutEleement.attr('opacity',1)

see the block


问:
Git will escape the backslash on my remote path for Network
This will not work because Git will escape the double backslash into one backslash and it will throw and error that \MyTestServer\c$\Repository\TestProject is not a valid repository..

```<code>git remote add -m master TestServer "\\MyTestServer\c$\Repository\TestProject"

git fetch TestServer
</code>```

Any help please..

答:
Note: Git 2.14 (Q3 2017) will make Git more robust when using paths with backslash.

It makes sure that "foo\bar\baz" in "git fetch foo\bar\baz", even though there is no slashes in it, cannot be a nickname (as in git remote name) for a remote on Windows, as that is likely to be a pathname on a local filesystem.

See commit d9244ec (25 May 2017), and commit e20b5b5 (22 May 2017) by Johannes Sixt (j6t).

(Merged by Junio C Hamano -- gitster -- in commit 7d26aa3, 02 Jun 2017)

Windows: do not treat a path with backslashes as a remote's nick name

On Windows, the remote repository name in, e.g., git fetch foo\bar
  is clearly not a nickname for a configured remote repository.

  However, the function valid_remote_nick() does not account for backslashes.

  Use is_dir_sep() to check for both slashes and backslashes on Windows.

This was discovered while playing with Duy's patches that warn after
  fopen() failures.

  The functions that read the branches and remotes
  files are protected by a valid_remote_nick() check.

  Without this change, a Windows style absolute path is incorrectly regarded as
  nickname and is concatenated to a prefix and used with fopen().

  This triggers warnings because a colon in a path name is not allowed:

```<code>C:\Temp\gittest>git fetch C:\Temp\gittest
warning: unable to access '.git/remotes/C:\Temp\gittest': Invalid argument
warning: unable to access '.git/branches/C:\Temp\gittest': Invalid argument
From C:\Temp\gittest
 * branch            HEAD       -> FETCH_HEAD
</code>```

Body:
This will not work because Git will escape the double backslash into one backslash and it will throw and error that \MyTestServer\c$\Repository\TestProject is not a valid repository..

git remote add -m master TestServer "\\MyTestServer\c$\Repository\TestProject"

git fetch TestServer

Any help please..

Body:
Note: Git 2.14 (Q3 2017) will make Git more robust when using paths with backslash.

It makes sure that "foo\bar\baz" in "git fetch foo\bar\baz", even though there is no slashes in it, cannot be a nickname (as in git remote name) for a remote on Windows, as that is likely to be a pathname on a local filesystem.

See commit d9244ec (25 May 2017), and commit e20b5b5 (22 May 2017) by Johannes Sixt (j6t).

(Merged by Junio C Hamano -- gitster -- in commit 7d26aa3, 02 Jun 2017)

Windows: do not treat a path with backslashes as a remote's nick name

On Windows, the remote repository name in, e.g., git fetch foo\bar
  is clearly not a nickname for a configured remote repository.

  However, the function valid_remote_nick() does not account for backslashes.

  Use is_dir_sep() to check for both slashes and backslashes on Windows.

This was discovered while playing with Duy's patches that warn after
  fopen() failures.

  The functions that read the branches and remotes
  files are protected by a valid_remote_nick() check.

  Without this change, a Windows style absolute path is incorrectly regarded as
  nickname and is concatenated to a prefix and used with fopen().

  This triggers warnings because a colon in a path name is not allowed:

C:\Temp\gittest>git fetch C:\Temp\gittest
warning: unable to access '.git/remotes/C:\Temp\gittest': Invalid argument
warning: unable to access '.git/branches/C:\Temp\gittest': Invalid argument
From C:\Temp\gittest
 * branch            HEAD       -> FETCH_HEAD


答: I suggest to use SQLite. This is a lightweight database that works natively in PHP and includes many of the functions that you are used to using in MySQL.

Title: Is there any File-System based database in PHP?

Body: I am using a server, which has a restriction on the database usage i.e. I can't use more than 10mb of data, in the MySQL tables. So, I am searching for a alternate way of storing data, I need a database which stores data in form of files and it is also easy to use too.


答:
Everything uses files in the end.
You could overcome the server limitation by having mysql in a separate server which does not have this restriction. Anyhow, if your data increases, this 10 MB limit will get exceeded.

PHP allows you to connect to external systems for database connectivity. Just set the servername variable in the connection query.


问:
Get the name of the current method
This is kind of a silly question, but is it possible to get the name of the method that is currently being executed from within that method?

```<code>Public Sub SomeMethod()

   Dim methodName as String = System.Reflection.[function to get the current method name here?]

End Sub
</code>```

Thanks

答:
Another approach would be to use CallerMemberNameAttribute from the System.Runtime.CompilerServices namespace to populate an optional parameter.  For example ...

```<code>Private Function GetMethodName(<System.Runtime.CompilerServices.CallerMemberName>
    Optional memberName As String = Nothing) As String

    Return memberName

End Function
</code>```

The function would be invoked as you would expect...

```<code>Public Sub DoSomeWork()
    Dim methodName As String = GetMethodName()
    Console.WriteLine($"Entered {methodName}")

    ' Do some work
End Sub
</code>```

Rather than 'just' retrieving the method name, the function might also make use of the method name retrieved to further simplify code.  For example...

```<code>Private Sub TraceEnter(
    <System.Runtime.CompilerServices.CallerMemberName>
    Optional memberName As String = Nothing)

    Console.WriteLine($"Entered {memberName}")

End Sub
</code>```

... which might be used like this ...

```<code>Public Sub DoSomeWork()
    TraceEnter()

    ' Do some work

End Sub
</code>```

Other attributes in the CompilerServices namespace may be used in similar fashion to retrieve the full path (at compile time) of the source file and/or the line number of the call.  See the CallerMemberNameAttribute documentation for sample code.

Title: Get the name of the current method

Body:
This is kind of a silly question, but is it possible to get the name of the method that is currently being executed from within that method?

Public Sub SomeMethod()

   Dim methodName as String = System.Reflection.[function to get the current method name here?]

End Sub

Thanks

Body:
Another approach would be to use CallerMemberNameAttribute from the System.Runtime.CompilerServices namespace to populate an optional parameter.  For example ...

Private Function GetMethodName(<System.Runtime.CompilerServices.CallerMemberName>
    Optional memberName As String = Nothing) As String

    Return memberName

End Function

The function would be invoked as you would expect...

Public Sub DoSomeWork()
    Dim methodName As String = GetMethodName()
    Console.WriteLine($"Entered {methodName}")

    ' Do some work
End Sub

Rather than 'just' retrieving the method name, the function might also make use of the method name retrieved to further simplify code.  For example...

Private Sub TraceEnter(
    <System.Runtime.CompilerServices.CallerMemberName>
    Optional memberName As String = Nothing)

    Console.WriteLine($"Entered {memberName}")

End Sub

... which might be used like this ...

Public Sub DoSomeWork()
    TraceEnter()

    ' Do some work

End Sub

Other attributes in the CompilerServices namespace may be used in similar fashion to retrieve the full path (at compile time) of the source file and/or the line number of the call.  See the CallerMemberNameAttribute documentation for sample code.


问:
How can I reshape data from long to wide
** Sample data added after comment**

What I have:

pmts <- data.frame(stringsAsFactors=FALSE,
           name = c("johndoe", "johndoe", "janedoe", "foo", "foo", "foo"),
           pmt_amount = c(550L, 550L, 995L, 375L, 375L, 375L),
           pmt_date = c("9/1/16", "11/1/16", "12/15/16", "1/5/17", "3/5/17", "5/5/17")
)

#>      name pmt_amount pmt_date
#> 1 johndoe        550   9/1/16
#> 2 johndoe        550  11/1/16
#> 3 janedoe        995 12/15/16
#> 4     foo        375   1/5/17
#> 5     foo        375   3/5/17
#> 6     foo        375   5/5/17
```

<p>What I am looking to achieve:</p>

<pre class="lang-r prettyprint-override"><code>read.table(header = T, text =
"name    pmt_amount  first_pmt   second_pmt  third_pmt
johndoe    550        9/1/16       11/1/16    NA
  janedoe    995        12/15/16       NA       NA
  foo       375        1/5/17       3/5/17   5/5/17"
)

#>      name pmt_amount first_pmt second_pmt third_pmt
#> 1 johndoe        550    9/1/16    11/1/16      <NA>
#> 2 janedoe        995  12/15/16       <NA>      <NA>
#> 3     foo        375    1/5/17     3/5/17    5/5/17
</code>```

** End of update**

I have a large dataset with payment information for different products. Some of these products have a pay-in-full option as well as a two-pay and three-pay option. I need to create fields that would be First_Payment, Second_Payment, and Third_Payment and would populate NA in the respective fields if there was only one or two payments.

I've tried a couple options and the best workaround I have thus far is this:

pmts %>%
  group_by(Email, Name, Amount, Form.Title) %>%
  summarise(First_Payment = min(Payment.Date),
           Second_Payment = median(Payment.Date),
           Last_Payment = max(Payment.Date)) -> pmts
```

<p>This obviously is not ideal as is making up a payment date for the 2-pay plans and I would have to instruct the end-user to ignore this field and just look at the 1st and 3rd fields. </p>

<p>I also tried to summarise with partial sorts like this:</p>

<pre class="lang-r prettyprint-override"><code>n <- length(pmts$Payment.Date)
sort(pmts$Payment.Date,partial=n-1)[n-1]
</code>```

However, if there wasn't three payments for the person, it would take the n-1 date from the entire data set and apply to all other fields.

Ideally, I would have it so if it was a pay-in-full the the First_Payment field would have the date and the 2nd/3rd fields would say NA. The 2-pay would have 1st and 2nd dates and the 3rd field would say NA. And finally the 3 pay would have all 3 dates.

The end users here are not super data savvy so I'm trying to make this as easy to interpret as possible. Any suggestions would be tremendously appreciated. Thank you!

答:
Using data.table this is a simple one-liner

```<code>library(data.table) #v1.9.8+
dcast(setDT(pmts), name + pmt_amount ~ rowid(pmt_amount))
# Using 'pmt_date' as value column. Use 'value.var' to override
#       name pmt_amount        1       2      3
# 1:     foo        375   1/5/17  3/5/17 5/5/17
# 2: janedoe        995 12/15/16      NA     NA
# 3: johndoe        550   9/1/16 11/1/16     NA
</code>```

dcast converts from long to wide and it accepts expressions. rowid is just adding a row counter per pmt_amount.

Body:
** Sample data added after comment**

What I have:

pmts <- data.frame(stringsAsFactors=FALSE,
           name = c("johndoe", "johndoe", "janedoe", "foo", "foo", "foo"),
           pmt_amount = c(550L, 550L, 995L, 375L, 375L, 375L),
           pmt_date = c("9/1/16", "11/1/16", "12/15/16", "1/5/17", "3/5/17", "5/5/17")
)

#>      name pmt_amount pmt_date
#> 1 johndoe        550   9/1/16
#> 2 johndoe        550  11/1/16
#> 3 janedoe        995 12/15/16
#> 4     foo        375   1/5/17
#> 5     foo        375   3/5/17
#> 6     foo        375   5/5/17

What I am looking to achieve:

read.table(header = T, text =
"name    pmt_amount  first_pmt   second_pmt  third_pmt
johndoe    550        9/1/16       11/1/16    NA
  janedoe    995        12/15/16       NA       NA
  foo       375        1/5/17       3/5/17   5/5/17"
)

#>      name pmt_amount first_pmt second_pmt third_pmt
#> 1 johndoe        550    9/1/16    11/1/16      <NA>
#> 2 janedoe        995  12/15/16       <NA>      <NA>
#> 3     foo        375    1/5/17     3/5/17    5/5/17

** End of update**

I have a large dataset with payment information for different products. Some of these products have a pay-in-full option as well as a two-pay and three-pay option. I need to create fields that would be First_Payment, Second_Payment, and Third_Payment and would populate NA in the respective fields if there was only one or two payments.

I've tried a couple options and the best workaround I have thus far is this:

pmts %>%
  group_by(Email, Name, Amount, Form.Title) %>%
  summarise(First_Payment = min(Payment.Date),
           Second_Payment = median(Payment.Date),
           Last_Payment = max(Payment.Date)) -> pmts

This obviously is not ideal as is making up a payment date for the 2-pay plans and I would have to instruct the end-user to ignore this field and just look at the 1st and 3rd fields.

I also tried to summarise with partial sorts like this:

n <- length(pmts$Payment.Date)
sort(pmts$Payment.Date,partial=n-1)[n-1]

However, if there wasn't three payments for the person, it would take the n-1 date from the entire data set and apply to all other fields.

Ideally, I would have it so if it was a pay-in-full the the First_Payment field would have the date and the 2nd/3rd fields would say NA. The 2-pay would have 1st and 2nd dates and the 3rd field would say NA. And finally the 3 pay would have all 3 dates.

The end users here are not super data savvy so I'm trying to make this as easy to interpret as possible. Any suggestions would be tremendously appreciated. Thank you!

Body:
Using data.table this is a simple one-liner

library(data.table) #v1.9.8+
dcast(setDT(pmts), name + pmt_amount ~ rowid(pmt_amount))
# Using 'pmt_date' as value column. Use 'value.var' to override
#       name pmt_amount        1       2      3
# 1:     foo        375   1/5/17  3/5/17 5/5/17
# 2: janedoe        995 12/15/16      NA     NA
# 3: johndoe        550   9/1/16 11/1/16     NA

dcast converts from long to wide and it accepts expressions. rowid is just adding a row counter per pmt_amount.


问:
How to navigate into other divs and access their contents

I want to to navigate from the #toDoListContainer div into the #taskDiv, how do I do this in jquery.

I want to navigate from div to div to be able to access the data of each div to get the picture to appear

I did the command

```<code>console.log($("#toDoListContainer")[0]);
</code>```

so i was trying to navigate the div like this..

console.log($("#toDoListContainer")[0].children);

I should be able to get into the zeroth div by doing:

console.log($("#toDoListContainer")[0].children[0]);

but I get undefined instead. any Ideas ?

答:
It is not recommended to have same id for multiple elements but still if you want to keep HTML code as it is following snippet can help.

var taskDivs = $("div #taskDiv");
taskDivs.each(function(x) {
  console.log(taskDivs[x])
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toDoListContainer">
  <div id="taskDiv"> Task 1 </div>
  <div id="taskDiv"> Task 2 </div>
  <div id="taskDiv"> Task 3 </div>
</div></code>```

Body:
I want to to navigate from the #toDoListContainer div into the #taskDiv, how do I do this in jquery.

I want to navigate from div to div to be able to access the data of each div to get the picture to appear

I did the command

console.log($("#toDoListContainer")[0]);

so i was trying to navigate the div like this..

console.log($("#toDoListContainer")[0].children);

I should be able to get into the zeroth div by doing:

console.log($("#toDoListContainer")[0].children[0]);

but I get undefined instead. any Ideas ?

Body:
It is not recommended to have same id for multiple elements but still if you want to keep HTML code as it is following snippet can help.

var taskDivs = $("div #taskDiv");
taskDivs.each(function(x) {
  console.log(taskDivs[x])
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toDoListContainer">
  <div id="taskDiv"> Task 1 </div>
  <div id="taskDiv"> Task 2 </div>
  <div id="taskDiv"> Task 3 </div>
</div>


问:
Element not clickable - error work around not working as expected using Python and Selenium webdriver
While trying to scrape review data from tripadvisor's new website, am trying to click on the more button to expand the reviews before picking them up. The code works fine on the first page, but throws error on the subsequent pages.
Here's the part of code that I am using:

```<code>for num in range(page_count):
    try:
        if num != 0:
            try:
                nxt = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.nav.next.arrowNav.taLnk")))
                #nxt = driver.find_element_by_css_selector("a.nav.next.rndBtn.ui_button.primary.taLnk")
                nxt.click()
                driver.implicitly_wait(5)
            except NoSuchElementException:
                print("this is a NEE1")
                driver.refresh()
                nxt = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.nav.next.arrowNav.taLnk")))
                #actions = ActionChains(driver).move_to_element(nxt).click().perform()
                driver.implicitly_wait(5)
            except WebDriverException:
                print("this is a WDE1")
                #nxt = driver.find_element_by_css_selector("a.nav.next.rndBtn.ui_button.primary.taLnk")
                nxt = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.nav.next.arrowNav.taLnk")))
                actions = ActionChains(driver).move_to_element(nxt)
                driver.implicitly_wait(2)
                actions.click()
                actions.perform()
        try:
            more = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.taLnk.ulBlueLinks")))
            #WebDriverWait(driver, 20).until(EC.invisibility_of_element_located(By.CLASS_NAME, 'loadingWhiteBox'))
            #more = driver.find_element_by_css_selector("span.taLnk.ulBlueLinks")
            #more.location_once_scrolled_into_view
            #driver.execute_script("arguments[0].scrollIntoView();", more)
            more.click()
            time.sleep(1)
        except TimeoutException:
            print("There is no 'more' button on page %d" % (num+1))
        except WebDriverException:
            print("this is a WDE2")
            more = driver.find_element_by_css_selector("span.taLnk.ulBlueLinks")
            more = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.taLnk.ulBlueLinks")))
            #more.location_once_scrolled_into_view
            #driver.execute_script("arguments[0].scrollIntoView();", more)
            #WebDriverWait(driver, 20).until(EC.invisibility_of_element_located(By.CLASS_NAME, "loadingWhiteBox"))
#            actions = ActionChains(driver).move_to_element(more)
#            driver.implicitly_wait(2)
#            actions.click()
#            actions.perform()
            time.sleep(1)

        review_result = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'entry')))
        review_date = driver.find_element_by_css_selector("span.ratingDate.relativeDate").get_attribute('title')

        with open('input.txt', 'a') as fid:
            for date,review in zip(review_date,review_result):
                         fid.write(unidecode(review_date))
                         fid.write(sep1)
                         fid.write(unidecode(review.text))
                         fid.write(sep)
                         fid.write(line_break)
</code>```

Below is the error:

```<code>> WebDriverException: unknown error: Element <span class="taLnk
> ulBlueLinks"
> onclick="ta.prwidgets.call('handlers.clickCollapse',event,this);">...</span>
> is not clickable at point (292, 615). Other element would receive the
> click: <div class="loadingWhiteBox"></div>
</code>```

I looked up to a number of posts related to same issues and found out few work around for the error and tried them all. The only thing that seemed to be working was using ActionChains, which is currently uncommented in the code. It doesn't throws any error but it wouldn't actually click on the more button and expand the reviews. Moreover, the code processes till a certain page and then get stuck on the same page till the loop ends picking same reviews again and again. I am unable to find any solution for this issue. Please help.

The element is attached to the tag

span.taLnk.ulBlueLinks

答:
This occurs due to page refresh or changes when driver attempt to perform action on the element. The location of the element has changed after the driver has stored its reference and now some other element is present at the desired location

We may use Javascript to scroll to that particular element and the perform the action:

```<code>WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
</code>```

Body:
While trying to scrape review data from tripadvisor's new website, am trying to click on the more button to expand the reviews before picking them up. The code works fine on the first page, but throws error on the subsequent pages.
Here's the part of code that I am using:

for num in range(page_count):
    try:
        if num != 0:
            try:
                nxt = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.nav.next.arrowNav.taLnk")))
                #nxt = driver.find_element_by_css_selector("a.nav.next.rndBtn.ui_button.primary.taLnk")
                nxt.click()
                driver.implicitly_wait(5)
            except NoSuchElementException:
                print("this is a NEE1")
                driver.refresh()
                nxt = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.nav.next.arrowNav.taLnk")))
                #actions = ActionChains(driver).move_to_element(nxt).click().perform()
                driver.implicitly_wait(5)
            except WebDriverException:
                print("this is a WDE1")
                #nxt = driver.find_element_by_css_selector("a.nav.next.rndBtn.ui_button.primary.taLnk")
                nxt = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.nav.next.arrowNav.taLnk")))
                actions = ActionChains(driver).move_to_element(nxt)
                driver.implicitly_wait(2)
                actions.click()
                actions.perform()
        try:
            more = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.taLnk.ulBlueLinks")))
            #WebDriverWait(driver, 20).until(EC.invisibility_of_element_located(By.CLASS_NAME, 'loadingWhiteBox'))
            #more = driver.find_element_by_css_selector("span.taLnk.ulBlueLinks")
            #more.location_once_scrolled_into_view
            #driver.execute_script("arguments[0].scrollIntoView();", more)
            more.click()
            time.sleep(1)
        except TimeoutException:
            print("There is no 'more' button on page %d" % (num+1))
        except WebDriverException:
            print("this is a WDE2")
            more = driver.find_element_by_css_selector("span.taLnk.ulBlueLinks")
            more = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.taLnk.ulBlueLinks")))
            #more.location_once_scrolled_into_view
            #driver.execute_script("arguments[0].scrollIntoView();", more)
            #WebDriverWait(driver, 20).until(EC.invisibility_of_element_located(By.CLASS_NAME, "loadingWhiteBox"))
#            actions = ActionChains(driver).move_to_element(more)
#            driver.implicitly_wait(2)
#            actions.click()
#            actions.perform()
            time.sleep(1)

        review_result = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'entry')))
        review_date = driver.find_element_by_css_selector("span.ratingDate.relativeDate").get_attribute('title')

        with open('input.txt', 'a') as fid:
            for date,review in zip(review_date,review_result):
                         fid.write(unidecode(review_date))
                         fid.write(sep1)
                         fid.write(unidecode(review.text))
                         fid.write(sep)
                         fid.write(line_break)

Below is the error:

> WebDriverException: unknown error: Element  ulBlueLinks"
> onclick="ta.prwidgets.call('handlers.clickCollapse',event,this);">...
> is not clickable at point (292, 615). Other element would receive the
> click:

I looked up to a number of posts related to same issues and found out few work around for the error and tried them all. The only thing that seemed to be working was using ActionChains, which is currently uncommented in the code. It doesn't throws any error but it wouldn't actually click on the more button and expand the reviews. Moreover, the code processes till a certain page and then get stuck on the same page till the loop ends picking same reviews again and again. I am unable to find any solution for this issue. Please help.

The element is attached to the tag

span.taLnk.ulBlueLinks

Body:
This occurs due to page refresh or changes when driver attempt to perform action on the element. The location of the element has changed after the driver has stored its reference and now some other element is present at the desired location

We may use Javascript to scroll to that particular element and the perform the action:

WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);


问:
Pass form data to the called activity
How do i get all the user input fields from signupActivity which is currently taking email, passwords and rest of the fields as input from the user and use it in finalactivity.

I already have made the xml layout and wonder how can i display all these fields to a newer activity which is called when signup button is pressed.

My SignupActivity.java:-

```<code>public class SignupActivity extends AppCompatActivity {
    @Bind(R.id.input_name) EditText _nameText;
    @Bind(R.id.input_email) EditText _emailText;
    @Bind(R.id.input_password) EditText _passwordText;
    @Bind(R.id.btn_signup) Button _signupButton;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signing);
        ButterKnife.bind(this);
        _signupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  signup();
            }
        });
    }
    public void signup(){
        //call the finalactivity and do the
    }
}
</code>```

And now finally the signup() function should call the activity finalActivity and print the info. Maybe like this-
For eg in the finalactivity i want to display-

Your name is :"name here"

  And your email is :"email here"

My question is different from How do I pass data between Activities in Android application? as i want to pass multiple variables (~50) and obviously dont want to create 50 Intents.

答:
In your current Activity, pass the result via Intent:

```<code>Intent i = new Intent(FirstActivity.this,SecondActivity.class);
i.putExtra("NAME_KEY", "NAME_VALUE");
i.putExtra("EMAIL_KEY", "EMAIL_VALUE");
i.putExtra("PASSWORD_KEY", "PASSWORD_VALUE");
startActivity(i);
</code>```

Retrieve the result from another Activity:

```<code>Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String name = extras.getString("NAME_KEY");
        String email = extras.getString("EMAIL_KEY");
        String password = extras.getString("PASSWORD_KEY");
    }
</code>```

Title: Pass form data to the called activity

Body:
How do i get all the user input fields from signupActivity which is currently taking email, passwords and rest of the fields as input from the user and use it in finalactivity.

I already have made the xml layout and wonder how can i display all these fields to a newer activity which is called when signup button is pressed.

My SignupActivity.java:-

public class SignupActivity extends AppCompatActivity {
    @Bind(R.id.input_name) EditText _nameText;
    @Bind(R.id.input_email) EditText _emailText;
    @Bind(R.id.input_password) EditText _passwordText;
    @Bind(R.id.btn_signup) Button _signupButton;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signing);
        ButterKnife.bind(this);
        _signupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  signup();
            }
        });
    }
    public void signup(){
        //call the finalactivity and do the
    }
}

And now finally the signup() function should call the activity finalActivity and print the info. Maybe like this-
For eg in the finalactivity i want to display-

Your name is :"name here"

  And your email is :"email here"

My question is different from How do I pass data between Activities in Android application? as i want to pass multiple variables (~50) and obviously dont want to create 50 Intents.

Body:
In your current Activity, pass the result via Intent:

Intent i = new Intent(FirstActivity.this,SecondActivity.class);
i.putExtra("NAME_KEY", "NAME_VALUE");
i.putExtra("EMAIL_KEY", "EMAIL_VALUE");
i.putExtra("PASSWORD_KEY", "PASSWORD_VALUE");
startActivity(i);

Retrieve the result from another Activity:

Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String name = extras.getString("NAME_KEY");
        String email = extras.getString("EMAIL_KEY");
        String password = extras.getString("PASSWORD_KEY");
    }


问:
In JavaScript, can you force a loop to not process the next iteration before the current iteration is complete?
I have a data set which contains an array of layers for an HTML5 canvas. I’m using fabric.js to manage all elements of my canvas. The layers are supposed to load in order, forming different scenes. I’m looping through the data set via a forEach loop. (EDIT - after further research, I see that both for and forEach loops are synchronous).

The problem is, once the code gets to the point of loading an image, asynchronous behavior kicks in and the process jumps to the next iteration of my loop to start processing the next layer. As you can imagine, this leads to layers appearing out of order on the canvas and ultimately distorted scenes.

I’ve been working on this and researching it for weeks and haven’t had much luck.

Is there any way to prevent a forEach loop (or a for loop for that matter) to not start the next iteration before the current one finishes?

Here is my code for the forEach loop:

```<code>$.ajax({
    url: url,
    method: "GET"
}).done(function (data) {
    data.forEach(function (data) {
        switch (data.layer_type) {
            case "texture":
                {
                    addTexture(data)
                    break;
                }
            case "color":
                {
                    addColor(data)
                    break;
                }
            case "room":
                {
                    addBaseImg(data);
                    break;
                }
            case "decor":
                {
                    addBaseImg(data);
                    break;
                }
            case "floor":
                {
                    addBaseImg(data);
                    break;
                }
            default:
                {
                    addOtherObjects(data);
                }
        }
    });
});
</code>```

Here is an example of a case that loads an image:

The initial function triggers a click event:

```<code>function addTexture(data) {
    $('img[data-obj-id="' + data.object_id + '"]').trigger("click");
}
</code>```

that leads to this function:

```<code>$(document).on("click", ".img-patt", function () {

    var imgURL = $(this).data("src");

    var _this = this;

    //this is where the process skips to the next iteration, before the image is loaded and added to the canvas

    fabric.Image.fromURL(imgURL, function (img) {

        //some code to handle the pattern removed from here just to shorten up the snippet

        var rect = new fabric.Rect({
            name: "texture",
            visible: true,
            selectable: false,
            data: {
                type: $(_this).data("type"),
                objid: $(_this).data("obj-id")
            },
            top: 0,
            left: 0,
            width: fabCanvas.width,
            height: fabCanvas.height,
            fill: pattern
        });

        fabCanvas.add(rect);
        fabCanvas.renderAll();
    });

});
</code>```

答:
You may want to use a trick and you should get what you want.

Before starting the for set a variable that force the wait.

Now I show you in your case

```<code>var wait = false;
$.ajax({
    url: url,
    method: "GET"
}).done(function (data) {
    wait = true;
    data.forEach(function (data) {
        switch (data.layer_type) {
            case "texture":
                {
                    addTexture(data)
                    break;
                }
            ...
            default:
                {
                    addOtherObjects(data);
                }
        }
    });
    wait=false;
});
</code>```

And at the click event you have to do so

```<code>$(document).on("click", ".img-patt", function () {
    if (wait){
    // do samething
    }else{

    }
});
</code>```

In addition if you put a timer and a function becomes more reliable

```<code>function DoSamething(){
    if (wait){
        // do samething
    }else{
        window.setInterval(DoSamething, 1000);
    }
}
</code>```

Your click event will be so

```<code>$(document).on("click", ".img-patt", function () {
     window.setInterval(DoSamething, 1000);
});
</code>```

Body:
I have a data set which contains an array of layers for an HTML5 canvas. I’m using fabric.js to manage all elements of my canvas. The layers are supposed to load in order, forming different scenes. I’m looping through the data set via a forEach loop. (EDIT - after further research, I see that both for and forEach loops are synchronous).

The problem is, once the code gets to the point of loading an image, asynchronous behavior kicks in and the process jumps to the next iteration of my loop to start processing the next layer. As you can imagine, this leads to layers appearing out of order on the canvas and ultimately distorted scenes.

I’ve been working on this and researching it for weeks and haven’t had much luck.

Is there any way to prevent a forEach loop (or a for loop for that matter) to not start the next iteration before the current one finishes?

Here is my code for the forEach loop:

$.ajax({
    url: url,
    method: "GET"
}).done(function (data) {
    data.forEach(function (data) {
        switch (data.layer_type) {
            case "texture":
                {
                    addTexture(data)
                    break;
                }
            case "color":
                {
                    addColor(data)
                    break;
                }
            case "room":
                {
                    addBaseImg(data);
                    break;
                }
            case "decor":
                {
                    addBaseImg(data);
                    break;
                }
            case "floor":
                {
                    addBaseImg(data);
                    break;
                }
            default:
                {
                    addOtherObjects(data);
                }
        }
    });
});

Here is an example of a case that loads an image:

The initial function triggers a click event:

function addTexture(data) {
    $('img[data-obj-id="' + data.object_id + '"]').trigger("click");
}

that leads to this function:

$(document).on("click", ".img-patt", function () {

    var imgURL = $(this).data("src");

    var _this = this;

    //this is where the process skips to the next iteration, before the image is loaded and added to the canvas

    fabric.Image.fromURL(imgURL, function (img) {

        //some code to handle the pattern removed from here just to shorten up the snippet

        var rect = new fabric.Rect({
            name: "texture",
            visible: true,
            selectable: false,
            data: {
                type: $(_this).data("type"),
                objid: $(_this).data("obj-id")
            },
            top: 0,
            left: 0,
            width: fabCanvas.width,
            height: fabCanvas.height,
            fill: pattern
        });

        fabCanvas.add(rect);
        fabCanvas.renderAll();
    });

});

Body:
You may want to use a trick and you should get what you want.

Before starting the for set a variable that force the wait.

Now I show you in your case

var wait = false;
$.ajax({
    url: url,
    method: "GET"
}).done(function (data) {
    wait = true;
    data.forEach(function (data) {
        switch (data.layer_type) {
            case "texture":
                {
                    addTexture(data)
                    break;
                }
            ...
            default:
                {
                    addOtherObjects(data);
                }
        }
    });
    wait=false;
});

And at the click event you have to do so

$(document).on("click", ".img-patt", function () {
    if (wait){
    // do samething
    }else{

    }
});

In addition if you put a timer and a function becomes more reliable

function DoSamething(){
    if (wait){
        // do samething
    }else{
        window.setInterval(DoSamething, 1000);
    }
}

Your click event will be so

$(document).on("click", ".img-patt", function () {
     window.setInterval(DoSamething, 1000);
});