问:
Vue.JS - How to have a button perform two separate actions on the same parent element?
On parent I have:

```<code><template>
  <b-container>
    <b-modal id="uw-qb-add-item-modal"
             ref="uw-qb-add-item-modal"
             title="Enter Item Number"
             @ok="handleNewItem">
      <form @submit.stop.prevent="handleSubmit">
        <b-form-input type="text"
                      placeholder="Enter the item number" />
      </form>
    </b-modal>

    <div class="row mb-3">
      <div class="col">
        <nuxt-link to="/">
          <i class="fa fa-chevron-left" aria-hidden="true"></i>
          Quote Build List
        </nuxt-link>
      </div>
    </div>
    <div class="row mb-3">
      <div class="col-md"><h2>Quote Build <b-badge :variant="buildBadgeVariant">{{ buildBadgeText }}</b-badge></h2></div>
      <div class="col-md text-right text-success"><h3><i class="fa fa-usd" aria-hidden="true"></i> {{ buildTotal | formatDollars }}</h3></div>
    </div>

    <div class="row mb-3">
      <div class="col-md form-group">
        <build-customer :buildNumber="buildNumber"/>
      </div>
      <div class="col-md form-group">
        <build-address :buildNumber="buildNumber" />
      </div>
      <div class="col-md form-group">
        <build-contact :buildNumber="buildNumber" />
      </div>
      <div class="col-md form-group">
        <label for="uw-qb-due-date">Due Date</label>
        <date-picker v-model="dueDate"/>
      </div>
    </div>

    <div class="row mb-3">
      <div class="col-sm form-group">
        <div class="form-check">
          <label class="form-check-label">
            <input class="form-check-input" type="checkbox" v-model="internal" />
            Internal Quote
          </label>
        </div>
        <build-requester-id v-if="internal" :buildNumber="buildNumber"/>
      </div>
      <div class="col-sm form-group">
        <label>RFQ Number</label>
        <b-form-input type="text" v-model="rfqNumber"/>
      </div>
      <div class="col-sm form-group">
        <div class="form-check">
          <label class="form-check-label mb-3">
            <input class="form-check-input" type="checkbox" v-model="update" />
            Quote Update
          </label>
          <label class="form-check-label">
            <input class="form-check-input" type="checkbox" v-model="correctiveAction" />
            Corrective Action
          </label>
        </div>
      </div>
      <div class="col-sm form-group">
        <label>Request Date</label>
        <date-picker v-model="requestDate" />
      </div>
    </div>

    <div class="row mb-3">
      <div class="col-md text-right">
        <b-btn variant="primary"
               v-b-toggle="editId"
               @click="newEditItem">
          <i class="mr-1 fa fa-plus" aria-hidden="true"></i>
          Add Item
        </b-btn>
      </div>
    </div>

    <b-collapse :id="editId">
      <build-item-edit @doOnEmit="expand" :buildNumber="buildNumber"
                       :itemNumber="editItemNumber"/>
    </b-collapse>

    <build-item-list @edit="edit" :buildNumber="buildNumber" />

    <build-breakdown-edit :buildNumber="buildNumber" :breakdownNumber="editBreakdownNumber"/>
    <build-breakdown-list :buildNumber="buildNumber"/>

  </b-container>
</template>

<script>
  import BuildCustomer from '@/components/buildCustomer'
  import BuildAddress from '@/components/buildAddress'
  import BuildContact from '@/components/buildContact'
  import BuildRequesterId from '@/components/buildRequesterId'

  import BuildItemEdit from '@/components/buildItemEdit'
  import BuildItemList from '@/components/buildItemList'

  import BuildBreakdownEdit from '@/components/buildBreakdownEdit'
  import BuildBreakdownList from '@/components/buildBreakdownList'

  import DatePicker from '@/components/datePicker'

  export default {
    data () {
      return {
        editItemNumber: null,
        editBreakdownNumber: null
      }
    },
    components: {
      'build-customer': BuildCustomer,
      'build-address': BuildAddress,
      'build-contact': BuildContact,
      'build-requester-id': BuildRequesterId,
      'build-item-edit': BuildItemEdit,
      'build-item-list': BuildItemList,
      'build-breakdown-edit': BuildBreakdownEdit,
      'build-breakdown-list': BuildBreakdownList,
      'date-picker': DatePicker
    },
    computed: {
      // nextItemNumber () {
      //   const itemNumbers = this.$store.getters['build/item/numbers'](this.buildNumber)
      //   return Math.min.apply(null, itemNumbers) - 1
      //  },
      editId () {
        return this.idGen('edit-item-collapse')
      },
      dueDate: {
        get () {
          return this.build.dueDate
        },
        set (value) {
          this.$store.commit('build/setDueDate', { buildNumber: this.buildNumber, dueDate: value })
        }
      },
      requestDate: {
        get () {
          return this.build.requestDate
        },
        set (value) {
          this.$store.commit('build/setRequestDate', { buildNumber: this.buildNumber, requestDate: value })
        }
      },
      internal: {
        get () {
          return this.build.internal
        },
        set (value) {
          this.$store.commit('build/setInternal', { buildNumber: this.buildNumber, internal: !!value })
        }
      },
      update: {
        get () {
          return this.build.update
        },
        set (value) {
          this.$store.commit('build/setUpdate', { buildNumber: this.buildNumber, update: !!value })
        }
      },
      correctiveAction: {
        get () {
          return this.build.correctiveAction
        },
        set (value) {
          this.$store.commit('build/setCorrectiveAction', { buildNumber: this.buildNumber, correctiveAction: !!value })
        }
      },
      requesterId: {
        get () {
          return this.build.requesterId
        },
        set (value) {
          if (value === null || this.$store.getters.employees.hasOwnProperty(value)) {
            this.$store.commit('build/setRequesterId', { buildNumber: this.buildNumber, requesterId: value })
          }
        }
      },
      rfqNumber: {
        get () {
          return this.build.rfqNumber
        },
        set (value) {
          this.$store.commit('build/setRfqNumber', {buildNumber: this.buildNumber, rfqNumber: value })
        }
      },
      employees () {
        const res = [{ value: null, text: 'Select requested by ...' }];
        for (var empId in this.$store.getters['employee/employees']) {
          res.push({ value: empId, text: this.$store.getters.employees[empId] });
        }
        return res;
      },
      buildNumber () {
        return parseInt(this.$route.params.buildNumber, 10);
      },
      build () {
        return this.$store.getters['build/build'](this.buildNumber);
      },
      buildBadgeVariant () {
        if (this.isNewBuild) { return 'primary'; }
        return 'info';
      },
      buildBadgeText () {
        if (this.isNewBuild) { return 'New'; }
        return this.buildNumber;
      },
      isNewBuild () {
        return this.buildNumber < 0;
      },
      buildTotal () {
        return this.$store.getters['build/total'](this.buildNumber);
      }
    },
    methods: {
      fetchData () {
        if (!this.isNewBuild) {
          // TODO - waiting on schema changes
          console.log('Fetching build data for ' + this.$route.params.buildNumber);
        }
      },
      handleNewItem () {
        this.$store.commit('setError', 'Adding items not supported');
      },
      newEditItem () {
        this.editItemNumber = this.nextItemNumber
      },
      edit(eventPayload) {
        this.editItemNumber = eventPayload
    },
      expand() {
      console.log("TEST")
       this.idGen('edit-item-collapse')
    }
    },
    fetch (context) {
      const buildNumber = parseInt(context.params.buildNumber, 10)
      const build = context.store.getters['build/build'](buildNumber)

      if (build === null && buildNumber >= 0) {
        console.log('load build')
      } else if (build === null && buildNumber < 0) {
        // if the build doesn't exist and it is a temp build
        // number, then just redirect to new
        context.app.router.replace('/new')
      }
    }
  }
</script>
</code>```

buildItemEdit

```<code><template>
  <b-container>
    <b-row>
      <b-col>
        <h3>Item</h3>
        <p></p>
        <b-row></b-row>
        <p></p>
      </b-col>
    </b-row>
    <b-row>
      <b-col>
        <b-row>
          <b-col>
            <label>Item No.</label>
            <b-form-input v-model='itemNum' type="text" :state="itemNoState" onkeypress='return event.charCode >= 48 && event.charCode <= 57'
            />
          </b-col>
          <b-col>
            <label>Item Type</label>
            <b-form-select v-model="type" :options="itemTypes" class="mb-3" :state="itemTypeState" />
          </b-col>
          <b-col>
            <label>Part No.</label>
            <b-form-input v-model='partNumber' type="text" :state="partNoState" onkeypress='return event.charCode >= 48 && event.charCode <= 57'
            />
          </b-col>
          <b-col>
            <label>Piece Amount</label>
            <b-form-input v-model='pieceCount' type="number" :state="pieceAmountState" onkeypress='return event.charCode >= 48 && event.charCode <= 57'
            />
          </b-col>
        </b-row>
        <b-row>
          <b-col>
            <label>Comments</label>
            <b-form-textarea id="comments" v-model="comments" placeholder="Enter comments here" :rows="3" :max-rows="6"></b-form-textarea>
          </b-col>
        </b-row>
        <p></p>
        <b-row>
          <b-col>
            <b-card-group deck class="mb-3">
              <b-card bg-variant="primary" text-variant="white" class="text-center">
                <p class="card-text">Breakdown 1</p>
              </b-card>
              <b-card bg-variant="secondary" text-variant="white" class="text-center">
                <p class="card-text">Breakdown 2</p>
              </b-card>
              <b-card bg-variant="success" text-variant="white" class="text-center">
                <p class="card-text">Breakdown 3</p>
              </b-card>
            </b-card-group>
          </b-col>
        </b-row>
      </b-col>
    </b-row>
    <b-row>
      <p></p>
    </b-row>
    <b-row>
      <p></p>
    </b-row>
    <b-row>
      <b-col>
        <div v-if="editmsg" class="col-md text-left">
          <b-btn size="" @click="editUpdate" variant='success'>
            <i class='mr-1 fa fa-plus' aria-hidden="true"></i> Save Edit</b-btn>
        </div>
        <p></p>
      </b-col>
      <b-col>
        <div class="col-md text-center">
          <b-btn size="" @click="addItem" variant='primary'>
            <i class='mr-1 fa fa-plus' aria-hidden="true"></i> Break Downs</b-btn>
        </div>
      </b-col>
      <b-col>
        <div class="col-md text-right">
          <b-btn size="" @click="addItem" variant='primary' v-bind:disabled="!canSave">
            <i class='mr-1 fa fa-plus' aria-hidden="true"></i> Save Item</b-btn>
        </div>
      </b-col>
    </b-row>
    <div v-if="existmsg">
      <p></p>
      <b-alert show variant="danger">{{ existmsg }}</b-alert>
    </div>
    <div v-if="editmsg">
      <p></p>
      <b-alert show variant="warning">{{ editmsg }}</b-alert>
    </div>
  </b-container>
</template>

<script>
import Util from '@/lib/util'
export default {
  props: ['buildNumber', 'itemNumber'],
  data() {
    return {
      itemNum: "",
      type: "",
      partNumber: "",
      pieceCount: "",
      comments: "",
      selected: "A",
    }
  },
  watch: {
    itemNumber: function (editItemNumber) {
      if (editItemNumber == null) {
        this.update({})
      } else {
        const item = this.item(editItemNumber)
        this.update(item)
        this.itemNum = editItemNumber
      }
    }
  },
  computed: {
    itemNoState() {
      return !isNaN(parseFloat(this.itemNum)) && isFinite(this.itemNum) ? null : false;
    },
    itemTypeState() {
      return (this.type) ? null : false;
    },
    partNoState() {
      return !isNaN(parseFloat(this.partNumber)) && isFinite(this.partNumber) ? null : false;
    },
    pieceAmountState() {
      return !isNaN(parseFloat(this.pieceCount)) && isFinite(this.pieceCount) ? null : false;
    },
    canSave() {
      return this.itemNumber != '' && this.type != '' && this.partNumber != '' && this.pieceCount != ''
    },
    editmsg: {
      get() {
        return this.$store.getters["build/item/editmsg"];
      },
      set(value) {
        this.$store.commit("build/item/seteditmsg", value);
      }
    },
    existmsg: {
      get() {
        return this.$store.getters["build/item/existmsg"];
      },
      set(value) {
        this.$store.commit("build/item/setexistmsg", value);
      }
    },
    itemTypes() {
      const iTypes = []
      const b = this.$store.getters['itemType/all']
      for (var itemValue in b) {
        iTypes.push({
          value: itemValue,
          text: b[itemValue]
        })
      }
      return iTypes
    }
  },
  methods: {
    item(itemNumber) {
      return this.$store.getters["build/item/item"](
        this.buildNumber,
        itemNumber
      );
    },
    addItem() {
      if (this.item(this.itemNum) == null)
      {
        this.$store.commit('build/item/add', {
        buildNumber: this.buildNumber,
        itemNumber: this.itemNum,
        item: {
          type: this.type,
          partNumber: this.partNumber,
          pieceCount: this.pieceCount,
          comments: this.comments
        }
      })
      this.update({})
      }
      else
      {
        this.existmsg = "Item number " + this.itemNum + " already exists on this quote"
      }
    },
    update(item) {
      this.itemNum = Util.field(item, 'itemNumber', '')
      this.type = Util.field(item, 'type', '')
      this.partNumber = Util.field(item, 'partNumber', '')
      this.pieceCount = Util.field(item, 'pieceCount', '')
      this.comments = Util.field(item, 'comments', '')

      this.existmsg = ""
    },
    editUpdate(item) {
      this.$store.commit('build/item/update', {
        buildNumber: this.buildNumber,
        itemNumber: this.itemNum,
        item: {
          type: this.type,
          partNumber: this.partNumber,
          pieceCount: this.pieceCount,
          comments: this.comments
        }
      })
      this.update({})

      this.editmsg = ""
    }
  }
}
</script>
</code>```

Now on the child I already have a button that emits an item number to the parent (editItemNumber) above.  But I always want that same button on the child to expand this collapse on the parent only if its not collapsed.

Below is the existing child.

```<code>edit(item) {
     const payload = {
    item
};
  this.$emit('edit', item.itemNumber);
  this.editmsg = "Edit your item above and then click 'Save Edit'"
}
</code>```

buildItemList

```<code><template>
  <b-container>
    <div>
      <p></p>
      <h5>Items</h5>
      <p></p>
      <b-table show-empty bordered striped hover :items="itemTableList" :fields="fields">
        <template slot="actions" scope="row">
          <b-btn variant='success' size="sm" v-on:click="edit(row.item,$event.target)">Edit</b-btn>
          <b-btn variant='danger' size="sm" @click.stop="delRow(row.item,row.index,$event.target)">Delete</b-btn>
        </template>
      </b-table>
    </div>
      </b-container>
</template>

<script>
import Util from "@/lib/util";

export default {
  data() {
    return {
      fields: [
        { key: "itemNumber", label: "Item No.", sortable: true },
        { key: "type", label: "Item Type", sortable: false },
        { key: "partNumber", label: "Part No.", sortable: false },
        { key: "pieceCount", label: "Piece Amount", sortable: false },
        { key: "comments", label: "Comments", sortable: false },
        { actions: { label: "Actions" } }
      ]
    };
  },
  props: ["buildNumber"],
  computed: {
    itemNumbers() {
      console.log("DEVELOPER")
      console.log(this.buildNumber)
      const items = this.$store.getters["build/item/items"](this.buildNumber);

      return Util.numSortedKeys(items);
    },
    itemTableList() {
      const itemList = [];
      for (var i of this.itemNumbers) {
        const item = this.item(i);

        itemList.push({
          itemNumber: i,
          type: item.type,
          partNumber: item.partNumber,
          pieceCount: item.pieceCount,
          comments: item.comments
        });
      }
      return itemList;
    },
  editmsg: {
      get() {
        return this.$store.getters["build/item/editmsg"];
      },
      set(value) {
        this.$store.commit("build/item/seteditmsg", value);
      }
    }
  },
  methods: {
    item(itemNumber) {
      return this.$store.getters["build/item/item"](
        this.buildNumber,
        itemNumber
      );
    },
    edit(item) {
         const payload = {
        item
    };
      this.$emit('doOnEmit')
      this.$emit('edit', item.itemNumber);
      // this.editmsg = "Edit your item above and then click 'Save Edit'"
    }
  }
};
</script>
</code>```

So to reiterate, when the button edit is clicked, beyond what it's currently doing I want to expand that toggle collapse if not expanded on the parent component.

Is that possible?

答:
I assume <build-item-edit> is your own component so just add a callback event to it i.e

```<code><build-item-edit @doOnEmit="someFunctionOnTheParent" :buildNumber="buildNumber" :itemNumber="editItemNumber"/>
</code>```

Then on the parent component, define the method someFunctionOnTheParent and run the code that does your UI stuff.

Then in the build-item-edit component, before you emit the value, call this.$emit('doOnEmit')

Body:
On parent I have:

<template>

      <form @submit.stop.prevent="handleSubmit">

      </form>

        <nuxt-link to="/">

          Quote Build List
        </nuxt-link>

Quote Build {{ buildBadgeText }}

 {{ buildTotal | formatDollars }}

        <build-customer :buildNumber="buildNumber"/>

        <build-address :buildNumber="buildNumber" />

        <build-contact :buildNumber="buildNumber" />

        Due Date
        <date-picker v-model="dueDate"/>

            <input class="form-check-input" type="checkbox" v-model="internal" />
            Internal Quote

        <build-requester-id v-if="internal" :buildNumber="buildNumber"/>

        RFQ Number

            <input class="form-check-input" type="checkbox" v-model="update" />
            Quote Update

            <input class="form-check-input" type="checkbox" v-model="correctiveAction" />
            Corrective Action

        Request Date
        <date-picker v-model="requestDate" />

          Add Item

      <build-item-edit @doOnEmit="expand" :buildNumber="buildNumber"
                       :itemNumber="editItemNumber"/>

    <build-item-list @edit="edit" :buildNumber="buildNumber" />

    <build-breakdown-edit :buildNumber="buildNumber" :breakdownNumber="editBreakdownNumber"/>
    <build-breakdown-list :buildNumber="buildNumber"/>

</template>

buildItemEdit

<template>

Item

            Item No.
            = 48 && event.charCode <= 57'
            />

            Item Type

            Part No.
            = 48 && event.charCode <= 57'
            />

            Piece Amount
            = 48 && event.charCode <= 57'
            />

            Comments

Breakdown 1

Breakdown 2

Breakdown 3

             Save Edit

             Break Downs

             Save Item

      {{ existmsg }}

      {{ editmsg }}

</template>

Now on the child I already have a button that emits an item number to the parent (editItemNumber) above.  But I always want that same button on the child to expand this collapse on the parent only if its not collapsed.

Below is the existing child.

edit(item) {
     const payload = {
    item
};
  this.$emit('edit', item.itemNumber);
  this.editmsg = "Edit your item above and then click 'Save Edit'"
}

buildItemList

<template>

Items

        <template slot="actions" scope="row">
          Edit
          Delete
        </template>

</template>

So to reiterate, when the button edit is clicked, beyond what it's currently doing I want to expand that toggle collapse if not expanded on the parent component.

Is that possible?

Body:
I assume <build-item-edit> is your own component so just add a callback event to it i.e

<build-item-edit @doOnEmit="someFunctionOnTheParent" :buildNumber="buildNumber" :itemNumber="editItemNumber"/>

Then on the parent component, define the method someFunctionOnTheParent and run the code that does your UI stuff.

Then in the build-item-edit component, before you emit the value, call this.$emit('doOnEmit')


来源: stackexchange

问:
Why does trying to create a tkinter messagebox cause a 'module not callable' error?
In this, when I run it and press the 'yes' option on wanting to play, I get an error that says

line 36, in <module>
    tkinter.messagebox("Snake","Have fun!")
TypeError: 'module' object is not callable
```

<p>I'm not sure why I'm getting this error as I have imported the <code>messagebox</code> module multiple times and it still doesn't work. can anyone offer improvements or an explanation?</p>

<p>Code:</p>

```#importing modules that I need
import tkinter
from tkinter import *
from msvcrt import *
#importing messagebox module separately
from tkinter import messagebox

#the function that closes the window
def closeitall(self):
    board.destroy()

#creating the game board
board=tkinter.Tk()

#setting background colour
board.configure(background="#B3C9D0")

#sets title of board window
board.title("Snake")

#sets size of board
board.geometry("700x500")

#makes it so that the board can't be resized
board.resizable(0,0)

#asks question
play=messagebox.askquestion("Snake","Do you want to play snake?")

#closes window if answer is no
if play=="no":
    closeitall(board)
#creates a messagebox
else:
    tkinter.messagebox("Snake","Have fun!")

#closes board when escape key pressed
board.bind("<Escape>",closeitall)

board.mainloop()
```

答:
You are using messagebox like a function.

It is actually a module, so you can't call it.

ContentLicense: CC BY-SA 3.0

Body:
In this, when I run it and press the 'yes' option on wanting to play, I get an error that says

line 36, in <module>
    tkinter.messagebox("Snake","Have fun!")
TypeError: 'module' object is not callable

I'm not sure why I'm getting this error as I have imported the messagebox module multiple times and it still doesn't work. can anyone offer improvements or an explanation?

Code:

#importing modules that I need
import tkinter
from tkinter import *
from msvcrt import *
#importing messagebox module separately
from tkinter import messagebox

#the function that closes the window
def closeitall(self):
    board.destroy()

#creating the game board
board=tkinter.Tk()

#setting background colour
board.configure(background="#B3C9D0")

#sets title of board window
board.title("Snake")

#sets size of board
board.geometry("700x500")

#makes it so that the board can't be resized
board.resizable(0,0)

#asks question
play=messagebox.askquestion("Snake","Do you want to play snake?")

#closes window if answer is no
if play=="no":
    closeitall(board)
#creates a messagebox
else:
    tkinter.messagebox("Snake","Have fun!")

#closes board when escape key pressed
board.bind("<Escape>",closeitall)

board.mainloop()


问:
Java generics - Map of (typed) maps
I'm working on a (simple) caching solution of sorts, where a service can request a Cache object from a Map of caches. A Cache object works essentially just like a Map, too, with a key and a value and methods to access and store objects.

I came up with the following solution, but as you can see, it contains a cast (because get() can't know what the types of the nested object are supposed to be).

```<code>private final  Map<String, Cache<?, ?>> caches = new HashMap<String, Cache<?, ?>>();

public <K, V> Cache<K, V> getOrCreateCache(String identifier) {
    if (caches.containsKey(identifier)) {
        return (Cache<K, V>) caches.get(identifier);
    } else {
        Cache<K, V> cache = new CacheImpl<K, V>();
        caches.put(identifier, cache);
        return cache;
    }
}

private void test() {
    Cache<String, String> strCache = getOrCreateCache("string cache");
    strCache.set("key", "value");
}
</code>```

Now, my questions:

Is this a 'safe' approach, as long as classcastexceptions are handled properly? (probably going to catch those and pack them into a custom exception class)

Is there a 'safe' alternative? One with generics, if at all possible, because I like them and dislike casts.

(not directly related) Is this threadsafe? I assume not, but then, I'm no threading expert. Is it enough to just make the whole method synchronized, or would that (with half a dozen clients) cause too much overhead / locking? Is there a neat solution for that?

Edit: Woo, lots of answers, thanks! Editing here to describe an oddity I found while actually testing this:

```<code>    Cache<String, String> someCache = service.getOrCreateCache(cacheIdentifier);
    someCache.set("asdf", "sdfa");
    Cache<String, Integer> someCacheRetrievedAgain = service.getOrCreateCache(cacheIdentifier);
    System.out.println(someCacheRetrievedAgain.get("asdf")); // prints "sdfa". No errors whatsoever. Odd.
</code>```

答:
You could create a composite key that consists of your current identifier and two instances of Class (one for key, one for value)

```<code>public <K, V> Cache<K, V> getOrCreateCache(String identifier, Class<K> keyClass, Class<V> valueClass) {
  Identifier cacheIdentifier = new Identifier(identifier, keyClass, valueClass);
  // safe cast as we know that this cacheIdentifier must has a Cache<K, V>
  Cache<K, V> cache = (Cache<K, V>) caches.get(identifier);
  if (cache == null) {
    cache = new CacheImpl<K, V>();
    caches.put(cacheIdentifier, cache);
  }
  return cache;
}

/*
 * not the most efficient implementation, but correctly implements hashCode and equals
 * which is all we need
 */
private static class CacheIdentifier extends ArrayList<Object> {
  private CacheIdentifier(String identifier, Class<K> keyClass, Class<V> valueClass) {
    super(3);
    // TODO check for null
    add(identifier);
    add(keyClass);
    add(valueClass);
  }
}
</code>```

To make this thread safe, use a ConcurrentHashMap instead along with putIfAbsent(..)

ContentLicense: CC BY-SA 2.5

Title: Java generics - Map of (typed) maps

Body:
I'm working on a (simple) caching solution of sorts, where a service can request a Cache object from a Map of caches. A Cache object works essentially just like a Map, too, with a key and a value and methods to access and store objects.

I came up with the following solution, but as you can see, it contains a cast (because get() can't know what the types of the nested object are supposed to be).

private final  Map<String, Cache<?, ?>> caches = new HashMap<String, Cache<?, ?>>();

public <K, V> Cache<K, V> getOrCreateCache(String identifier) {
    if (caches.containsKey(identifier)) {
        return (Cache<K, V>) caches.get(identifier);
    } else {
        Cache<K, V> cache = new CacheImpl<K, V>();
        caches.put(identifier, cache);
        return cache;
    }
}

private void test() {
    Cache<String, String> strCache = getOrCreateCache("string cache");
    strCache.set("key", "value");
}

Now, my questions:

Is this a 'safe' approach, as long as classcastexceptions are handled properly? (probably going to catch those and pack them into a custom exception class)

Is there a 'safe' alternative? One with generics, if at all possible, because I like them and dislike casts.

(not directly related) Is this threadsafe? I assume not, but then, I'm no threading expert. Is it enough to just make the whole method synchronized, or would that (with half a dozen clients) cause too much overhead / locking? Is there a neat solution for that?

Edit: Woo, lots of answers, thanks! Editing here to describe an oddity I found while actually testing this:

    Cache<String, String> someCache = service.getOrCreateCache(cacheIdentifier);
    someCache.set("asdf", "sdfa");
    Cache<String, Integer> someCacheRetrievedAgain = service.getOrCreateCache(cacheIdentifier);
    System.out.println(someCacheRetrievedAgain.get("asdf")); // prints "sdfa". No errors whatsoever. Odd.

Body:
You could create a composite key that consists of your current identifier and two instances of Class (one for key, one for value)

public <K, V> Cache<K, V> getOrCreateCache(String identifier, Class<K> keyClass, Class<V> valueClass) {
  Identifier cacheIdentifier = new Identifier(identifier, keyClass, valueClass);
  // safe cast as we know that this cacheIdentifier must has a Cache<K, V>
  Cache<K, V> cache = (Cache<K, V>) caches.get(identifier);
  if (cache == null) {
    cache = new CacheImpl<K, V>();
    caches.put(cacheIdentifier, cache);
  }
  return cache;
}

/*
 * not the most efficient implementation, but correctly implements hashCode and equals
 * which is all we need
 */
private static class CacheIdentifier extends ArrayList<Object> {
  private CacheIdentifier(String identifier, Class<K> keyClass, Class<V> valueClass) {
    super(3);
    // TODO check for null
    add(identifier);
    add(keyClass);
    add(valueClass);
  }
}

To make this thread safe, use a ConcurrentHashMap instead along with putIfAbsent(..)


问:
How repeat part of function Swift
still learning the basics. I have a function in which there is a block, that needs to be repeated without calling the whole function again. How is this done in Swift? </p>

```<code>func connected(to peripheral: Peripheral) {
    let cwConnection = CWStatusBarNotification()
    cwConnection.display(withMessage: "Ring Connected", forDuration: 3)

    BluejayManager.shared.getHeliosInfo { (success) in
        if success {
            // Go on
        } else {
            // Repeat this block (BluejayManager.shared.getHeliosInfo)
        }
    }
}
</code>```

答:
You can use repeat - while around and BluejayManager.shared.getHeliosInfo check for success as break condition:

```<code>repeatGetInfo: repeat {
    BluejayManager.shared.getHeliosInfo
    { (success) in
            if success
            {
                // do your stuff.
                break repeatGetInfo
            } else
            {
                continue repeatGetInfo
            }
        }
} while true
</code>```

Hope this helps

Title: How repeat part of function Swift

Body:
still learning the basics. I have a function in which there is a block, that needs to be repeated without calling the whole function again. How is this done in Swift?

func connected(to peripheral: Peripheral) {
    let cwConnection = CWStatusBarNotification()
    cwConnection.display(withMessage: "Ring Connected", forDuration: 3)

    BluejayManager.shared.getHeliosInfo { (success) in
        if success {
            // Go on
        } else {
            // Repeat this block (BluejayManager.shared.getHeliosInfo)
        }
    }
}

Body:
You can use repeat - while around and BluejayManager.shared.getHeliosInfo check for success as break condition:

repeatGetInfo: repeat {
    BluejayManager.shared.getHeliosInfo
    { (success) in
            if success
            {
                // do your stuff.
                break repeatGetInfo
            } else
            {
                continue repeatGetInfo
            }
        }
} while true

Hope this helps


问:
List[Nothing] cant be appended to in Scala
have a var, why its var is because it could be updated during the program intended.

```<code>var Encountered = List.empty
</code>```

when i try to make it Encountered needs to be added a string, it gives me a value += is not a member of List[Nothing]

```<code>     else{
      Encountered += (Name)

    }
</code>```

答:
Scala List is an alias for scala.collection.immutable
List
 which is immutable, so it doesn't have this method.

var is a variable that can be reassigned, but it doesn't make the object it holds mutable.

Body:
have a var, why its var is because it could be updated during the program intended.

var Encountered = List.empty

when i try to make it Encountered needs to be added a string, it gives me a value += is not a member of List[Nothing]

     else{
      Encountered += (Name)

    }


问:
How use Xamarin.Forms MessagingCenter without tied it to the UI?
I have a long running task that need to be notified to the user using Toast-like messages. However, the user could move around the app freely.

Looking at https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/messaging-center/, it show that is necessary to bind to the UI to it to work?

```<code>MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) => {
    // do something whenever the "Hi" message is sent
});
MessagingCenter.Send<MainPage> (this, "Hi")
</code>```

I need to send notifications in the background, and I don't know from there to who.

答: You could subscribe to the message in your App.xaml.cs (or App.cs) class. Then just send the message from where ever and the subscriber's delegate will be run.

Body:
I have a long running task that need to be notified to the user using Toast-like messages. However, the user could move around the app freely.

Looking at https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/messaging-center/, it show that is necessary to bind to the UI to it to work?

MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) => {
    // do something whenever the "Hi" message is sent
});
MessagingCenter.Send<MainPage> (this, "Hi")

I need to send notifications in the background, and I don't know from there to who.


答: On the thread safety question, no it's not thread safe.  You should look at ConcurrentHashMap or Google Guava's MapMaker</p>

Title: Java generics - Map of (typed) maps


答:
You should use something like

```<code>tkinter.messagebox.showinfo("Snake","Have fun!")
</code>```

cause messagebox is a module and not a function.

Title: Why does trying to create a tkinter messagebox cause a 'module not callable' error?

Body:
You should use something like

tkinter.messagebox.showinfo("Snake","Have fun!")

cause messagebox is a module and not a function.


问:
Error incorrect syntax near keyword 'Delete' in SP
My SP is throwing error where I am trying to delete some entries from the tables. To be in safe side I got IF EXISTS and under it I have the delete statement but I am getting this error

Incorrect syntax near the keyword 'DELETE'.

Delete stmt

```<code>IF EXISTS (DELETE FROM myTable WHERE id IN ((SELECT ids FROM @tranId)));
</code>```

I am not sure if the syntax is incorrect.

答:
The IF is unnecessary, as are the extra parentheses:

```<code>DELETE FROM ESG.DOCUMENT_SET_TRANS_MDATA
    WHERE DOCUMENT_SET_TRANS_MDATA.DOCUMENT_SET_TRANSACTION_ID IN (SELECT ids FROM @tranId);

DELETE FROM ESG.DOCUMENT_TRANSACTION
    WHERE DOCUMENT_TRANSACTION.DOCUMENT_SET_TRANSACTION_ID IN (SELECT ids FROM @tranId);

DELETE FROM ESG.DOCUMENT_SET_TRANSACTION
    WHERE DOCUMENT_SET_TRANSACTION.DOCUMENT_SET_TRANSACTION_ID IN (SELECT ids FROM @tranId);
</code>```

Body:
My SP is throwing error where I am trying to delete some entries from the tables. To be in safe side I got IF EXISTS and under it I have the delete statement but I am getting this error

Incorrect syntax near the keyword 'DELETE'.

Delete stmt

IF EXISTS (DELETE FROM myTable WHERE id IN ((SELECT ids FROM @tranId)));

I am not sure if the syntax is incorrect.

Body:
The IF is unnecessary, as are the extra parentheses:

DELETE FROM ESG.DOCUMENT_SET_TRANS_MDATA
    WHERE DOCUMENT_SET_TRANS_MDATA.DOCUMENT_SET_TRANSACTION_ID IN (SELECT ids FROM @tranId);

DELETE FROM ESG.DOCUMENT_TRANSACTION
    WHERE DOCUMENT_TRANSACTION.DOCUMENT_SET_TRANSACTION_ID IN (SELECT ids FROM @tranId);

DELETE FROM ESG.DOCUMENT_SET_TRANSACTION
    WHERE DOCUMENT_SET_TRANSACTION.DOCUMENT_SET_TRANSACTION_ID IN (SELECT ids FROM @tranId);


问:
Web application architecture question
We're planning to develop a medium - larger sized web appliaction

mostly CRUD operations

reporting

intranet/internet ready

Someone had an idea to split the application into two separete solutions

ASP.NET Web application - frontend

Core application - data access,domain logic.. hosted in a windows service

The communication would be realized with WCF (tcp,named pipes)

I'm wondering what are the cons and pros of this solution ?

Mostly I'm worried about that the development proces will get to complex. All this communication over WCF.

Could you please share some thoughs or have you any experiences with a similar project ?

答:
This is one way to look at it, but if you code your application in a 'standard' n-tier fashion, so that the web front end is not relying on concrete classes from your back end, you 'could' put this in later on if needed, but doing it up front 'just in case' adds a lot of complexity to your system.

Another approach is the ability to put your application in a web farm with a load balancer - this reduces your code complexity and allows you scale out as required.

(I'd also note that 100 concurrent users isn't really all that large).

Title: Web application architecture question


问:
BigQuery billing. How 10 GB free quote exactly works?
On BigQuery pricing page it is said "First 10 GB is free each month, see Storage pricing for details.". Does it mean that:

- each month i can load <10 GB of data into tables and don't get billed at all

Example for three months:

```<code>12 = 12 - 10 = 2 - i get billed for 2 GB
12 + 9 = 12 - 10 + 9 - 10 = 2 + 0 = 2 - i get billed for 2 GB
12 + 9 + 14 = 12 - 10 + 9 - 10 + 14 - 10 = 2 + 0 + 4 = 6 - i get billed for 6 GB.
</code>```

each month i don't pay for 10 GB from summed table size.

Example for three months:

```<code>12 = 12 - 10 = 2 - i get billed for 2 GB
12 + 9 = 12 + 9 - 10 = 11 - i get billed for 11 GB
12 + 9 + 14 = 12 + 9 + 14 - 10 = 25 - i get billed for 25 GB
</code>```

All other aspects of billing are described pretty clear but this is a bit confusing to me (i am not a native english speaker)

Thanks for attention.

答: It doesn't matter how much data is loaded each month. What matters is the total amount of data stored in BigQuery. If you have 10GB or less of data stored in BigQuery, then there is no cost. If you have more than 10GB, then you pay $0.02 (or an equivalent local rate) per GB per month for any data stored in addition to the first 10GB.</p>

Body:
On BigQuery pricing page it is said "First 10 GB is free each month, see Storage pricing for details.". Does it mean that:

- each month i can load <10 GB of data into tables and don't get billed at all

Example for three months:

12 = 12 - 10 = 2 - i get billed for 2 GB
12 + 9 = 12 - 10 + 9 - 10 = 2 + 0 = 2 - i get billed for 2 GB
12 + 9 + 14 = 12 - 10 + 9 - 10 + 14 - 10 = 2 + 0 + 4 = 6 - i get billed for 6 GB.

each month i don't pay for 10 GB from summed table size.

Example for three months:

12 = 12 - 10 = 2 - i get billed for 2 GB
12 + 9 = 12 + 9 - 10 = 11 - i get billed for 11 GB
12 + 9 + 14 = 12 + 9 + 14 - 10 = 25 - i get billed for 25 GB

All other aspects of billing are described pretty clear but this is a bit confusing to me (i am not a native english speaker)

Thanks for attention.


答:
First of all, familiesEncountered += (familyName) is not the way to add an element to a list in Scala.

Second, Say the type explicitly:

```<code>var Encountered: List[String] = List.empty
Encountered =  "elem1" :: Encountered
</code>```

Another way:

```<code>var encountered: List[String] = Nil
encountered =  "elem1" :: encountered
</code>```

Because if you do:

```<code>var Encountered = List.empty
Encountered =  "elem1" :: Encountered
</code>```

it won't compile, because if you don't say the type, the type of the list will be Encountered : List[Nothing]

Title: List[Nothing] cant be appended to in Scala

Body:
First of all, familiesEncountered += (familyName) is not the way to add an element to a list in Scala.

Second, Say the type explicitly:

var Encountered: List[String] = List.empty
Encountered =  "elem1" :: Encountered

Another way:

var encountered: List[String] = Nil
encountered =  "elem1" :: encountered

Because if you do:

var Encountered = List.empty
Encountered =  "elem1" :: Encountered

it won't compile, because if you don't say the type, the type of the list will be Encountered : List[Nothing]


问:
Why does XAML element-to-xml binding only partially work?
In the below code, the ListBox gets filled with the names of the colors from the XML file, but those names strangely do not appear in the TextBox.

However, if you bind the textbox to the static "lbColor2", those names do appear.

So what could be different about the names when they come from the XML source which makes them not get passed on?

```<code><StackPanel>
    <StackPanel.Resources>
        <XmlDataProvider x:Key="ExternalColors" Source="App_Data/main.xml" XPath="/colors"/>
    </StackPanel.Resources>
    <TextBlock Text="Colors:"/>
    <ListBox Name="lbColor" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource ExternalColors}, XPath=color/@name}"/>
    <ListBox Name="lbColor2">
        <ListBoxItem>Red</ListBoxItem>
        <ListBoxItem>Orange</ListBoxItem>
        <ListBoxItem>Cyan</ListBoxItem>
    </ListBox>
    <TextBlock Text="You selected color:"/>
    <TextBox
        Text="{Binding ElementName=lbColor, Path=SelectedItem.Content}"
        >
    </TextBox>
</StackPanel>
</code>```

Here is the XML file:

```<code><?xml version="1.0" encoding="utf-8" ?>
<colors>
  <color name="Pink"/>
  <color name="Cyan"/>
  <color name="LightBlue"/>
  <color name="LightGreen"/>
  <color name="Another One"/>
</colors>
</code>```

答:
You've bound the TextBox to SelectedItem.Content, but XmlAttribute does not have a property called Content. Change to this and you'll be fine:

```<code><TextBox Text="{Binding ElementName=lbColor, Path=SelectedItem.Value}"/>
</code>```

OwnerDisplayName: Edward Tanguay

Body:
In the below code, the ListBox gets filled with the names of the colors from the XML file, but those names strangely do not appear in the TextBox.

However, if you bind the textbox to the static "lbColor2", those names do appear.

So what could be different about the names when they come from the XML source which makes them not get passed on?

<StackPanel>
    <StackPanel.Resources>
        <XmlDataProvider x:Key="ExternalColors" Source="App_Data/main.xml" XPath="/colors"/>
    </StackPanel.Resources>
    <TextBlock Text="Colors:"/>
    <ListBox Name="lbColor" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource ExternalColors}, XPath=color/@name}"/>
    <ListBox Name="lbColor2">
        <ListBoxItem>Red</ListBoxItem>
        <ListBoxItem>Orange</ListBoxItem>
        <ListBoxItem>Cyan</ListBoxItem>
    </ListBox>
    <TextBlock Text="You selected color:"/>
    <TextBox
        Text="{Binding ElementName=lbColor, Path=SelectedItem.Content}"
        >
    </TextBox>
</StackPanel>

Here is the XML file:

<?xml version="1.0" encoding="utf-8" ?>
<colors>
  <color name="Pink"/>
  <color name="Cyan"/>
  <color name="LightBlue"/>
  <color name="LightGreen"/>
  <color name="Another One"/>
</colors>

Body:
You've bound the TextBox to SelectedItem.Content, but XmlAttribute does not have a property called Content. Change to this and you'll be fine:

<TextBox Text="{Binding ElementName=lbColor, Path=SelectedItem.Value}"/>

OwnerDisplayName: Kent Boogaart


问:
Simple Rails Conditional Statement
Pretty simple I'm sure... but I can't figure out why it wouldn't work.

```<code><tr<% if film.viewed == true %> class="viewed"<% end %>>
</code>```

The film.viewed is a boolean but its not rendering the class if its true. Probably a syntax error. Any help? Also is there an easier way to write this without opening and closing? I tried using:

```<code><tr<% if film.viewed == true puts class=\"viewed\" end %>>
</code>```

Again probably a syntax error. I'm coming from PHP so I'm still learning.

Thanks.

答:
I would rather do something like this.</p>

```<code><tr class="<%= film.viewed ? "viewed" : "" -%>"></tr>
</code>```

Title: Simple Rails Conditional Statement

Body:
Pretty simple I'm sure... but I can't figure out why it wouldn't work.

<tr<% if film.viewed == true %> class="viewed"<% end %>>

The film.viewed is a boolean but its not rendering the class if its true. Probably a syntax error. Any help? Also is there an easier way to write this without opening and closing? I tried using:

<tr<% if film.viewed == true puts class=\"viewed\" end %>>

Again probably a syntax error. I'm coming from PHP so I'm still learning.

Thanks.

Body:
I would rather do something like this.

<tr class="<%= film.viewed ? "viewed" : "" -%>"></tr>


问:
Modular Java Application on GIT repository
I'm working on a "modular Java application", it has around 60 independent modules, all obviously "buildable" on their own.

I'm trying to understand what can be the best approach to structure this type of application under GIT.

I'll explain better myself:

I've been working several years with SVN and it would be really easy for me to structure a project like this under a centralized version control tool such as SVN, while I'm not sure about the GIT best practices and pros/cons.

With SVN:

I would import all the project under the same repository

I would consider two different approaches, with similar consequences, for example:

```<code> mod_A
   |___trunk
   |___branches
   |   |___branch_A
   |
   |___tags
 mod_B
   |___trunk
   |___branches
   |   |___branch_A
   |   |___branch_B
   |
   |___tags
</code>```

OR

```<code> trunk
   |___mod_a
   |___mod_b
   |___mod_c
 branches
   |___branch_A
   |   |___mod_a
   |___branch_B
       |___mod_a
       |___mod_b
</code>```

With both the approaches it would be really easy for me to achieve information like, which are the modules branched for a particular feature, and see the application from the modules prospective but also from the branches prospective.

Moreover, with both the structures I would be able to easily branch just some of the modules without being forced to branch them all anytime.

With GIT:

At the moment the modular application i'm working with is structured with a single independent repo for any module, in my view this structure, even if brings some advantages, has also a real big issue.

In fact it looks hard for me to have a clear whole overview of the application, cause I've to connect to every single repository and check the branches to understand which modules are involved in a particular branch, so if I've to manage a branched version of my application, that for example involves just 7 modules to be branched in a particular BUG_FIXING or FEATURE branch and not the whole application, I would have no way to get this info through GIT, and I should manage this information in a custom way.

Then even if the application would have been set up within the same repo, i would have been unable to decide to branch just a subset of modules cause "Git operates on the entire repository, not on individual directories".

Can you please clarify how can be the best approach to follow with a modular application, can GIT sub modules be a solution? Is there any other approach i'm not considering, or i'm moving from wrong assumptions?

Thanks a lot!

答:
Aside: Do not use branches to manage different modules. Branches are to be short lived and ultimately merged back to master when ready for release.

If the modules "change/release" together, you could lean towards keeping them in one repo. Though the fact that each module had its own trunk/branches folders in SVN seems to indicate they change separately.

If you're using maven with your java application, it could be setup in one repo as a multi-module project.

If you go with separate repos, you can name your branches similarly (add a ticket number or such like feature/ticket-123-more-cow-bells) so you know a given feature impacts multiple modules/repos.

If you go with separate repos per module, then you could use git sub-modules to glue them back together but that's more of a workaround.

Perhaps also reading about a few different git branching strategies would help you understand how 'git thinks' about branches.

Body:
I'm working on a "modular Java application", it has around 60 independent modules, all obviously "buildable" on their own.

I'm trying to understand what can be the best approach to structure this type of application under GIT.

I'll explain better myself:

I've been working several years with SVN and it would be really easy for me to structure a project like this under a centralized version control tool such as SVN, while I'm not sure about the GIT best practices and pros/cons.

With SVN:

I would import all the project under the same repository

I would consider two different approaches, with similar consequences, for example:

 mod_A
   |___trunk
   |___branches
   |   |___branch_A
   |
   |___tags
 mod_B
   |___trunk
   |___branches
   |   |___branch_A
   |   |___branch_B
   |
   |___tags

OR

 trunk
   |___mod_a
   |___mod_b
   |___mod_c
 branches
   |___branch_A
   |   |___mod_a
   |___branch_B
       |___mod_a
       |___mod_b

With both the approaches it would be really easy for me to achieve information like, which are the modules branched for a particular feature, and see the application from the modules prospective but also from the branches prospective.

Moreover, with both the structures I would be able to easily branch just some of the modules without being forced to branch them all anytime.

With GIT:

At the moment the modular application i'm working with is structured with a single independent repo for any module, in my view this structure, even if brings some advantages, has also a real big issue.

In fact it looks hard for me to have a clear whole overview of the application, cause I've to connect to every single repository and check the branches to understand which modules are involved in a particular branch, so if I've to manage a branched version of my application, that for example involves just 7 modules to be branched in a particular BUG_FIXING or FEATURE branch and not the whole application, I would have no way to get this info through GIT, and I should manage this information in a custom way.

Then even if the application would have been set up within the same repo, i would have been unable to decide to branch just a subset of modules cause "Git operates on the entire repository, not on individual directories".

Can you please clarify how can be the best approach to follow with a modular application, can GIT sub modules be a solution? Is there any other approach i'm not considering, or i'm moving from wrong assumptions?

Thanks a lot!


问:
Swift - Identify word before cursor in textView (with special Characters)
I have an extension which identify and return the word before the cursor:

```<code>extension UITextView {

var currentWord : String? {

    let beginning = beginningOfDocument

    if let start = position(from: beginning, offset: selectedRange.location),
        let end = position(from: start, offset: selectedRange.length) {

        let textRange = tokenizer.rangeEnclosingPosition(end, with: .word, inDirection: 1)

        if let textRange = textRange {
            return text(in: textRange)
        }
    }
    return nil
}
</code>```

I am using UItextGranularity.word and works fine.

However my issue is this:

If at the beginning of the word i have an @ it won't be returned.
so if i have @jon the currentword will be jon.
Is there a way to include the @ so to have the complete word with the special Character?

Thank you

答:
It doesn't seem like you can do it with UITextInputTokenizer. You can try this solution:

```<code>var currentWord: String? {
    let regex = try! NSRegularExpression(pattern: "\\S+$")
    let textRange = NSRange(location: 0, length: selectedRange.location)
    if let range = regex.firstMatch(in: text, range: textRange)?.range {
        return String(text[Range(range, in: text)!])
    }
    return nil
}
</code>```

Body:
I have an extension which identify and return the word before the cursor:

extension UITextView {

var currentWord : String? {

    let beginning = beginningOfDocument

    if let start = position(from: beginning, offset: selectedRange.location),
        let end = position(from: start, offset: selectedRange.length) {

        let textRange = tokenizer.rangeEnclosingPosition(end, with: .word, inDirection: 1)

        if let textRange = textRange {
            return text(in: textRange)
        }
    }
    return nil
}

I am using UItextGranularity.word and works fine.

However my issue is this:

If at the beginning of the word i have an @ it won't be returned.
so if i have @jon the currentword will be jon.
Is there a way to include the @ so to have the complete word with the special Character?

Thank you

Body:
It doesn't seem like you can do it with UITextInputTokenizer. You can try this solution:

var currentWord: String? {
    let regex = try! NSRegularExpression(pattern: "\\S+$")
    let textRange = NSRange(location: 0, length: selectedRange.location)
    if let range = regex.firstMatch(in: text, range: textRange)?.range {
        return String(text[Range(range, in: text)!])
    }
    return nil
}


问:
Is it safe to put the entire user in a session vs just the user ID for node/express?
I am using node/express and was wondering if it is safe to put the entire user object in the session rather than just the Id. If I do just the Id then this means I must make another DB call when I go to get the currentUser.

I have seen people do it, but if it is more safe to just put the Id then I will go about doing that. I should state that I would take the password off the user before attaching it to the session or any other sensitive data.

答:
There's nothing especially unsafe about it, but generally not considered a good practice. When you update your user data, you have to update your session and database, so now you have to keep those in sync, which creates challenges.

Also keep in mind your session store.  The more data in your session, the larger the storage requirements for your session store, maybe not a problem, but something to consider.


问:
Why does Android Studio keep asking for a "Expression Expected"?
Here is my code:

```<code> @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnSighin = (Button) findViewById(R.id.btnSignIn);
    btnSignUp = (Button) findViewById(R.id.btnSignUp);

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent j = new Intent(MainActivity.this, SignUp.class);
            startActivity(SignUp);
        }
    });

    btnSighin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            Intent k = new Intent(MainActivity.this, SignIn.class);
            startActivity(SignIn);

        }
    });
}
</code>```

I am working on an app that allows customers to book appointments and in order to do so, they need to sign up or sign in. I have activities made for both of them and I can't run it without getting the "Expression Expected" and I'm new to Android Studio and have no idea what to do. Any help?

答:
You are missing some information. Anyway, i see that you have mistakes in lines

```<code>startActivity(SignUp);
</code>```

and

```<code>startActivity(SignIn);
</code>```

The correct way should be startActivity(j) and startActivity(k) respectively

Body:
Here is my code:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnSighin = (Button) findViewById(R.id.btnSignIn);
    btnSignUp = (Button) findViewById(R.id.btnSignUp);

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent j = new Intent(MainActivity.this, SignUp.class);
            startActivity(SignUp);
        }
    });

    btnSighin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            Intent k = new Intent(MainActivity.this, SignIn.class);
            startActivity(SignIn);

        }
    });
}

I am working on an app that allows customers to book appointments and in order to do so, they need to sign up or sign in. I have activities made for both of them and I can't run it without getting the "Expression Expected" and I'm new to Android Studio and have no idea what to do. Any help?

Body:
You are missing some information. Anyway, i see that you have mistakes in lines

startActivity(SignUp);

and

startActivity(SignIn);

The correct way should be startActivity(j) and startActivity(k) respectively


问:
Symfony Form Validation Choices Case Insensitive
On the form level validation in Symfony 3.3, I'm trying to figure out how to make it so that it is case insensitive. It is comparing against an array of choices.

```<code>public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', CollectionType::class, [
            'entry_type' => ChoiceType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'entry_options'  => array(
                'choices'  => array(
                                "Sample Option",
                                "Sample Option 2",
                                "Sample Option 3",
                                "Sample Option 4"
                            )
            ),
            'error_bubbling' => false
        ]);
</code>```

Under entry_options in choices is the array that it is using for form validation.

What I'm looking to do is be able to pass a case insensitive value like "sample option" or "sample Option" and have that pass the form level validation.

Thanks in advance for any help on this.

Update - As Kevin mentioned, I'm interested in figuring out how/where this should be updated in the framework.

答:
What ended up happening here in case anyone else has a similar problem is there was difficulty getting the data transformer to transform with the CollectionType and ChoiceType.

Instead of using CollectionType, I changed it to TextType. This passed through the data transformer and was able to have the desired result.

```<code>$builder->add('title', TextType::class);
</code>```

Body:
On the form level validation in Symfony 3.3, I'm trying to figure out how to make it so that it is case insensitive. It is comparing against an array of choices.

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', CollectionType::class, [
            'entry_type' => ChoiceType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'entry_options'  => array(
                'choices'  => array(
                                "Sample Option",
                                "Sample Option 2",
                                "Sample Option 3",
                                "Sample Option 4"
                            )
            ),
            'error_bubbling' => false
        ]);

Under entry_options in choices is the array that it is using for form validation.

What I'm looking to do is be able to pass a case insensitive value like "sample option" or "sample Option" and have that pass the form level validation.

Thanks in advance for any help on this.

Update - As Kevin mentioned, I'm interested in figuring out how/where this should be updated in the framework.

Body:
What ended up happening here in case anyone else has a similar problem is there was difficulty getting the data transformer to transform with the CollectionType and ChoiceType.

Instead of using CollectionType, I changed it to TextType. This passed through the data transformer and was able to have the desired result.

$builder->add('title', TextType::class);


问:
Scraping multiple tables and storing each table header as rows in csv
I'm trying to scrape multiple tables which have a table name stored under a h3 tag. There is Columns of data I can scrape no problem and when I feed the next url I can append this data to the csv file.
The problem I can't solve is to get the table header and store this relative to each row of table. The reason for this is when the next table is fed I need to know which table it belongs. Is it possible to use a len loop on we say 'Round' to establish the table length and then write the table header to each row? is it possible to do with item exports?

Here's my code
spider.py

```<code>from bigcrawler.items import BigcrawlerItem
from scrapy import Spider, Request, Selector

from scrapy.selector import Selector

from bigcrawler.items import MatchStatItemLoader

class CrawlbotSpider(Spider):
   name = 'bigcrawler'
   allowed_domains = ['www.matchstat.com']
   start_urls =   [

      'https://matchstat.com/tennis/tournaments/w/Taipei/2015',
      'https://matchstat.com/tennis/tournaments/w/Hong%20Kong/2017',
                ]
def parse_header(self , response):
    hxs = Selector(response)
    for tb in hxs.css('tr.match'):

      heading = tb.xpath('//*[@id="AWS"]/div/h3/text()').extract()[0]

        for td in tb.xpath(".//tr[contains(@class,
                    'match')]/td[contains(@class, 'round')]/text()"):
            il = BigcrawlerItem(selector=td)

            il.add_value('event_title' , heading)
            yield il.load_item()

 def parse(self , response):
    for row in response.css('tr.match'):
        il = MatchStatItemLoader(selector=row)
        il.add_css('round' , '.round::text')
        il.add_css('event1' , '.event-name a::text')
        il.add_css('player_1' , '.player-name:nth-child(2) a::text')
        il.add_css('player_2' , '.player-name:nth-child(3) a::text')
        il.add_css('player_1_odds' , '.odds-td.odds-0
       [payout]::text')
        il.add_css('player_2_odds' , '.odds-td.odds-1
       [payout]::text')
        il.add_css('h_2_h' , 'a.h2h::text')
        yield il.load_item()
</code>```

items.py

```<code>   import scrapy

   from scrapy.loader import ItemLoader
   from scrapy.loader.processors import TakeFirst, MapCompose
   from operator import methodcaller
   from scrapy import Spider, Request, Selector

   class BigcrawlerItem(scrapy.Item):
  # define the fields for your item here like:

       event_title = scrapy.Field()

       round = scrapy.Field()

       event1 = scrapy.Field()

      player_1 = scrapy.Field()

      player_2 = scrapy.Field()

      player_1_odds = scrapy.Field()

     player_2_odds = scrapy.Field()

     h_2_h = scrapy.Field()

  class MatchStatItemLoader(ItemLoader):
  default_item_class = BigcrawlerItem
  default_input_processor = MapCompose(methodcaller('strip'))
  default_output_processor = TakeFirst()
</code>```

答:
If there's only one of those headings you don't need to be relative to the current node, try this:

```<code>il.add_xpath('event_title', '//*[@id="AWS"]//h3/text()')
</code>```

but if you need it to be relative to the current node you could also do this:

```<code>il.add_xpath('event_title', './ancestor::*[@id="AWS"]//h3/text()')
</code>```

Body:
I'm trying to scrape multiple tables which have a table name stored under a h3 tag. There is Columns of data I can scrape no problem and when I feed the next url I can append this data to the csv file.
The problem I can't solve is to get the table header and store this relative to each row of table. The reason for this is when the next table is fed I need to know which table it belongs. Is it possible to use a len loop on we say 'Round' to establish the table length and then write the table header to each row? is it possible to do with item exports?

Here's my code
spider.py

from bigcrawler.items import BigcrawlerItem
from scrapy import Spider, Request, Selector

from scrapy.selector import Selector

from bigcrawler.items import MatchStatItemLoader

class CrawlbotSpider(Spider):
   name = 'bigcrawler'
   allowed_domains = ['www.matchstat.com']
   start_urls =   [

      'https://matchstat.com/tennis/tournaments/w/Taipei/2015',
      'https://matchstat.com/tennis/tournaments/w/Hong%20Kong/2017',
                ]
def parse_header(self , response):
    hxs = Selector(response)
    for tb in hxs.css('tr.match'):

      heading = tb.xpath('//*[@id="AWS"]/div/h3/text()').extract()[0]

        for td in tb.xpath(".//tr[contains(@class,
                    'match')]/td[contains(@class, 'round')]/text()"):
            il = BigcrawlerItem(selector=td)

            il.add_value('event_title' , heading)
            yield il.load_item()

 def parse(self , response):
    for row in response.css('tr.match'):
        il = MatchStatItemLoader(selector=row)
        il.add_css('round' , '.round::text')
        il.add_css('event1' , '.event-name a::text')
        il.add_css('player_1' , '.player-name:nth-child(2) a::text')
        il.add_css('player_2' , '.player-name:nth-child(3) a::text')
        il.add_css('player_1_odds' , '.odds-td.odds-0
       [payout]::text')
        il.add_css('player_2_odds' , '.odds-td.odds-1
       [payout]::text')
        il.add_css('h_2_h' , 'a.h2h::text')
        yield il.load_item()

items.py

   import scrapy

   from scrapy.loader import ItemLoader
   from scrapy.loader.processors import TakeFirst, MapCompose
   from operator import methodcaller
   from scrapy import Spider, Request, Selector

   class BigcrawlerItem(scrapy.Item):
  # define the fields for your item here like:

       event_title = scrapy.Field()

       round = scrapy.Field()

       event1 = scrapy.Field()

      player_1 = scrapy.Field()

      player_2 = scrapy.Field()

      player_1_odds = scrapy.Field()

     player_2_odds = scrapy.Field()

     h_2_h = scrapy.Field()

  class MatchStatItemLoader(ItemLoader):
  default_item_class = BigcrawlerItem
  default_input_processor = MapCompose(methodcaller('strip'))
  default_output_processor = TakeFirst()

Body:
If there's only one of those headings you don't need to be relative to the current node, try this:

il.add_xpath('event_title', '//*[@id="AWS"]//h3/text()')

but if you need it to be relative to the current node you could also do this:

il.add_xpath('event_title', './ancestor::*[@id="AWS"]//h3/text()')


问:
Forwarding a subdomain to new port on same IP and Websocket error
I have a server that I use to run node.js applications. One of which is a messaging app (similar to slack) that we use at my office. When I run the app, the app is reachable at http://0.0.0.0:8000/ so to reach it externally (from outside the server system) I set up port forwarding using VirtualHost in a conf file. I run the webserver using Apache2.4.18 by the way.
For more details, its running using pm2 on Ubuntu 16.04 LTS

I set up the config file like this:

<VirtualHost *:80>
    ServerAdmin me@mydomain.com
    ServerName messenger.mydomain.com
    ProxyPreserveHost On
    # setup the proxy
    <Proxy *>
        Order allow,deny
        Allow from all
    </Proxy>
    ProxyPass / http://0.0.0.0:8000/
    ProxyPassReverse / http://0.0.0.0:8000/
</VirtualHost>

The connection works successfully, and I can write to the NoSQL database file just fine, but items dont seem to be getting read from the NoSQL database due to this error

WebSocket connection to 'ws://messenger.mydomain.com/' failed: Error during WebSocket handshake: Unexpected response code: 200

I don't really have much experience setting up reverse proxies and dealing with WebSockets so after some extensive googling, I'm not exactly sure what I need to get the WebSocket working. I tried learning about like a Ratchet thing for PHP and clank but honestly I'm at a loss. Can anyone provide some direction?

答:
I've resolved it.

I needed to run this command a2enmod rewrite
PS: make sure you already ran a2enmod proxy
a2enmod proxy_wstunnel
a2enmod proxy_http

Then added to my subdomain.mydomain.com.conf file:

RewriteEngine on
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]
RewriteRule .* ws://localhost:8000%{REQUEST_URI} [P]

Since I was using port 8000 locally on my server.

This resolved the issue and allows everything to load appropriately.

So my apache2/sites-available/subdomain.mydoamin.com.conf looks like this:

```<code><VirtualHost *:80>
    ServerAdmin me@mydomain.com
    ServerName subdomain.mydomain.com

RewriteEngine on
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]
RewriteRule .* ws://localhost:8000%{REQUEST_URI} [P]
    # setup the proxy
    <Proxy *>
        Order allow,deny
        Allow from all
    </Proxy>
    ProxyPass / http://0.0.0.0:8000/
    ProxyPassReverse / http://0.0.0.0:8000/
</VirtualHost>
</code>```

Then I ran service apache2 restart

All was good.

Body:
I've resolved it.

I needed to run this command a2enmod rewrite
PS: make sure you already ran a2enmod proxy
a2enmod proxy_wstunnel
a2enmod proxy_http

Then added to my subdomain.mydomain.com.conf file:

RewriteEngine on
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]
RewriteRule .* ws://localhost:8000%{REQUEST_URI} [P]

Since I was using port 8000 locally on my server.

This resolved the issue and allows everything to load appropriately.

So my apache2/sites-available/subdomain.mydoamin.com.conf looks like this:

<VirtualHost *:80>
    ServerAdmin me@mydomain.com
    ServerName subdomain.mydomain.com

RewriteEngine on
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]
RewriteRule .* ws://localhost:8000%{REQUEST_URI} [P]
    # setup the proxy
    <Proxy *>
        Order allow,deny
        Allow from all
    </Proxy>
    ProxyPass / http://0.0.0.0:8000/
    ProxyPassReverse / http://0.0.0.0:8000/
</VirtualHost>

Then I ran service apache2 restart

All was good.


问:
c# What happens if I use code a .NET 3.5 function on a machine that has .Net 2 installed
Just out of interest, if I built some code using the Enumerable.Distinct function which appeared in .Net 3.5 and then ran it on a machine with .Net 2.0 on it, what would happen?</p>

答: Most probably your code will complain about .net 3.5 being not installed at the startup.</p>


问:
Get id of element
I wanted to get the id of the active tab. My code is not working. Help

//if it's the second tab, refresh it
var liID = $('#menu').hasClass('active').attr(id);
console.log(liID);```
<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>

<ul class="nav nav-tabs" role="tablist" id="menu">
  <li role="presentation" class="active">

      <span class="round-tab">
                                <i class="fa fa-archive"></i>
                            </span>

  </li>
  <li role="presentation" class="disabled">

      <span class="round-tab">
                                <i class="glyphicon glyphicon-pencil"></i>
                            </span>

  </li>
  <li role="presentation" class="disabled">

      <span class="round-tab">
                                <i class="glyphicon glyphicon-ok"></i>
                            </span>

  </li>
</ul></code>```

答:
You are not selecting the li that is active and you are missing quotes. You are chekcing to see if the "menu" element is active and you read its value.

```<code>$('#menu').find('.active').attr('id')
</code>```

or

```<code>$('#menu .active').attr('id')
</code>```

Title: Get id of element

Body:
You are not selecting the li that is active and you are missing quotes. You are chekcing to see if the "menu" element is active and you read its value.

$('#menu').find('.active').attr('id')

or

$('#menu .active').attr('id')


问:
DI in Azure Functions
I have some class libraries that I use in my ASP.NET Web API app that handle all my backend stuff e.g. CRUD operations to multiple databases like Azure SQL Database, Cosmos DB, etc.

I don't want to re-invent the wheel and able to use them in a new Azure Functions that I'm creating in Visual Studio 2017. All my repository methods use an interface. So, how will I implement dependency injection in my new Azure function?

I'm not seeing any support for DI but I'm a bit confused. It appears Azure Functions are based on the same SDK as WebJobs and I think last year Microsoft had started supporting DI in WebJobs - I know for sure because I implemented it using Ninject.

Is there way around this so that I can use my existing libraries in my new Azure Functions project?

答:
I see these two techniques in addition to the service locator (anti)pattern. I asked the Azure Functions team for their comments as well.

https://blog.wille-zone.de/post/azure-functions-dependency-injection/

https://blog.wille-zone.de/post/azure-functions-proper-dependency-injection/

Title: DI in Azure Functions


问:
Save 3D object from Paraview for future use in Paraview
I have some data I would like to visualize in 3D (oxygen values in a water column).  It has the general structure of (x,y,z,d).  I can convert the data to a 3D structure with delauney3D that I can then take slices of or otherwise manipulate to get the visualizations I want.

The problem is that I have over a hundred of these data sets in a time series and it takes a relatively long time to run the the delauney3D filter on just one and I can't seem to save the result of that filter in a way that will run faster once reloaded into Paraview.

Is there a way to save the output of the delauney3D filter that isn't a csv and that will reload into Paraview as a 3D object?

Edit:  I've tried saving it as a .vtu, but get this error:

```<code>ERROR: In /home/buildslave/dashboards/buildbot/paraview-pvbinsdash-linux-shared-release_superbuild/build/superbuild/paraview/src/VTK/Common/ExecutionModel/vtkExecutive.cxx, line 784

vtkPVCompositeDataPipeline (0x7910cf0): Algorithm
vtkXMLUnstructuredGridReader(0x7b08d10) returned failure for request:    vtkInformation (0x7d56390)

Debug: Off
Modified Time: 198948
Reference Count: 1
Registered Events: (none)
Request: REQUEST_INFORMATION
ALGORITHM_AFTER_FORWARD: 1
FORWARD_DIRECTION: 0
</code>```

答: Is the connectivity between the points found by the Delauney3D that important? Because you could use a Point Volume Interpolator filter for example to transform each point set into a vtkImageData (*.vti) and visualize/analyze the whole sequence with the fitting tools in ParaView afterwards depending on your needs. With this solution, Paraview will be able to take advantage of the structure of the regular grid and load the dataset faster (the main cost in memory comes from the scalar field). And on top of that, if you choose the same dimensions for each vtkImageData of your time series, ParaView will handle the sequence itself efficiently.</p>

Body:
I have some data I would like to visualize in 3D (oxygen values in a water column).  It has the general structure of (x,y,z,d).  I can convert the data to a 3D structure with delauney3D that I can then take slices of or otherwise manipulate to get the visualizations I want.

The problem is that I have over a hundred of these data sets in a time series and it takes a relatively long time to run the the delauney3D filter on just one and I can't seem to save the result of that filter in a way that will run faster once reloaded into Paraview.

Is there a way to save the output of the delauney3D filter that isn't a csv and that will reload into Paraview as a 3D object?

Edit:  I've tried saving it as a .vtu, but get this error:

ERROR: In /home/buildslave/dashboards/buildbot/paraview-pvbinsdash-linux-shared-release_superbuild/build/superbuild/paraview/src/VTK/Common/ExecutionModel/vtkExecutive.cxx, line 784

vtkPVCompositeDataPipeline (0x7910cf0): Algorithm
vtkXMLUnstructuredGridReader(0x7b08d10) returned failure for request:    vtkInformation (0x7d56390)

Debug: Off
Modified Time: 198948
Reference Count: 1
Registered Events: (none)
Request: REQUEST_INFORMATION
ALGORITHM_AFTER_FORWARD: 1
FORWARD_DIRECTION: 0


答:
id must be in quotes, otherwise it's thought of as a variable, which you don't have declared.

Next, your attempt to get the ID is incorrect because .hasClass() returns a boolean, not the element that has the class, so calling .attr() on the return value will fail.

Lastly, your active element doesn't even have and id anyway.

Here's a corrected version:

//if it's the second tab, refresh it
if($('#menu li').hasClass('active')){
  var liID = $('#menu li.active').attr("id");
  console.log(liID);
}```
<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>

<ul class="nav nav-tabs" role="tablist" id="menu">
  <li role="presentation" class="active" id="HELLO">

      <span class="round-tab"><i class="fa fa-archive"></i></span>

  </li>
  <li role="presentation" class="disabled">

      <span class="round-tab"><i class="glyphicon glyphicon-pencil"></i></span>

  </li>
  <li role="presentation" class="disabled">

      <span class="round-tab"><i class="glyphicon glyphicon-ok"></i></span>

  </li>
</ul></code>```

But really, this should be even simpler:

// Just query for the active element and then use it:
console.log($('#menu li.active').attr("id"));```
<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>

<ul class="nav nav-tabs" role="tablist" id="menu">
  <li role="presentation" class="active" id="HELLO">

      <span class="round-tab"><i class="fa fa-archive"></i></span>

  </li>
  <li role="presentation" class="disabled">

      <span class="round-tab"><i class="glyphicon glyphicon-pencil"></i></span>

  </li>
  <li role="presentation" class="disabled">

      <span class="round-tab"><i class="glyphicon glyphicon-ok"></i></span>

  </li>
</ul></code>```

Title: Get id of element

Body:
I wanted to get the id of the active tab. My code is not working. Help

//if it's the second tab, refresh it
var liID = $('#menu').hasClass('active').attr(id);
console.log(liID);

Body:
id must be in quotes, otherwise it's thought of as a variable, which you don't have declared.

Next, your attempt to get the ID is incorrect because .hasClass() returns a boolean, not the element that has the class, so calling .attr() on the return value will fail.

Lastly, your active element doesn't even have and id anyway.

Here's a corrected version:

//if it's the second tab, refresh it
if($('#menu li').hasClass('active')){
  var liID = $('#menu li.active').attr("id");
  console.log(liID);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="nav nav-tabs" role="tablist" id="menu">
  <li role="presentation" class="active" id="HELLO">
    <a href="#container" data-toggle="tab" aria-controls="step1" role="tab" title="Container">
      <span class="round-tab"><i class="fa fa-archive"></i></span>
    </a>
  </li>
  <li role="presentation" class="disabled">
    <a href="#parameters" data-toggle="tab" aria-controls="step2" role="tab" title="Parameters">
      <span class="round-tab"><i class="glyphicon glyphicon-pencil"></i></span>
    </a>
  </li>
  <li role="presentation" class="disabled">
    <a href="#results" data-toggle="tab" aria-controls="step3" role="tab" title="Results">
      <span class="round-tab"><i class="glyphicon glyphicon-ok"></i></span>
    </a>
  </li>
</ul>

But really, this should be even simpler:

// Just query for the active element and then use it:
console.log($('#menu li.active').attr("id"));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="nav nav-tabs" role="tablist" id="menu">
  <li role="presentation" class="active" id="HELLO">
    <a href="#container" data-toggle="tab" aria-controls="step1" role="tab" title="Container">
      <span class="round-tab"><i class="fa fa-archive"></i></span>
    </a>
  </li>
  <li role="presentation" class="disabled">
    <a href="#parameters" data-toggle="tab" aria-controls="step2" role="tab" title="Parameters">
      <span class="round-tab"><i class="glyphicon glyphicon-pencil"></i></span>
    </a>
  </li>
  <li role="presentation" class="disabled">
    <a href="#results" data-toggle="tab" aria-controls="step3" role="tab" title="Results">
      <span class="round-tab"><i class="glyphicon glyphicon-ok"></i></span>
    </a>
  </li>
</ul>


问:
Realm JavaScript Object Notification
In the Swift version of Realm, you can get notifications on a given object. For instance

```<code>class Test: Object { ... }
let t = Test()
t.observe { ... }
</code>```

However, this functionality does not seem to exist in the realm-js documentation. My question is if anybody has been able to implement notifications for a particular object in Realm JavaScript?

答: It is correct, Realm JS doesn't currently support object notifications. The issue is https://github.com/realm/realm-js/issues/763.</p>

Title: Realm JavaScript Object Notification

Body:
In the Swift version of Realm, you can get notifications on a given object. For instance

class Test: Object { ... }
let t = Test()
t.observe { ... }

However, this functionality does not seem to exist in the realm-js documentation. My question is if anybody has been able to implement notifications for a particular object in Realm JavaScript?


答:
Wrap id with quote. hasClass returns a boolean. So

```<code>var liID = $('#menu li.active').attr('id');
</code>```

will set liID to id of an li element with a parent "menu" and with class active, if any.

Title: Get id of element

Body:
Wrap id with quote. hasClass returns a boolean. So

var liID = $('#menu li.active').attr('id');

will set liID to id of an li element with a parent "menu" and with class active, if any.


问:
how to do subquery or backlink query in realm react-native?
The problem I'm trying to solve is this.  If I have product, I'd like to know what other products I can purchase as a combination that's on-sale.  If this were MySQL, I'd set up my tables and queries like so:

```<code>t_product: product_id, product_name
t_combination: combination_id, on_sale
t_product_combination: combination_id, product_id

// what other products should I buy along with my product_id == 1 to get a good deal?
SELECT product_id
FROM t_product
WHERE product_id IN (
    SELECT product_id
    FROM t_combination_product
    WHERE combination_id IN (
        SELECT combination_id
        FROM t_combination
        WHERE on_sale = 'yes'
        AND combination_id IN (SELECT combination_id FROM t_combination_product WHERE product_id = 1)
    )
)
</code>```

I tried to do this in realm react-native as shown below:

I have two collections: Product and a Combination, set up as follows

```<code>class Product {};
Product.schema = {
    name: 'Product',
    primaryKey:'productId',
    properties: {
        productId:'int',
        product:'string'
    }
};

class Combination {};
Combination.schema = {
    name: 'Combination',
    properties: {
        onSale: {type: 'string'},
        products: {type: 'list',objectType:'Product'},
    }
};
</code>```

What I want to do is given that I have Product.productId=1, I want to find all other products that belong to Combinations that have Combination.onSale='yes' and Product.productId IS IN (Combination.products ).

This is the query I tried to do in realm with react-native:

```<code>let queryFilter = "ANY Combination.onSale = 'yes' AND Combination.products = 1";
let data = realm.objects('Product').objectsWhere(queryFilter);
</code>```

But when I run this, I get the error

undefined is not a function (evaluating
  'realm.objects('Product').objectsWhere(queryFilter)')

If I remove the objectsWhere(queryFilter), then it just returns me the list of all Products that hasn't been filtered.

So it seems I'm using objectsWhere incorrectly? How do I fix this to find a list of all products that are onsale if purchased with product 1?

答:
If you had

```<code>class Product {};
  Product.schema = {
    name: 'Product',
    primaryKey:'productId',
    properties: {
        productId:'int',
        product:'string'
        combinations: {type: 'linkingObjects', objectType: 'Combination', property: 'products'}
    }
};
</code>```

Backlink queries are not yet supported, so I think what you have to do is something like this:

```<code>let queryFilter = 'productId = 1';
let data = realm.objects('Product').filtered(queryFilter);
let combinations = data.combinations.filtered('onSale = true');
let linkedProducts = [];
for(let i = 0; i < combinations.length; i++) {
    linkedProducts.push(combinations[i]);
}
// linked products should contain what you need
</code>```

Body:
The problem I'm trying to solve is this.  If I have product, I'd like to know what other products I can purchase as a combination that's on-sale.  If this were MySQL, I'd set up my tables and queries like so:

t_product: product_id, product_name
t_combination: combination_id, on_sale
t_product_combination: combination_id, product_id

// what other products should I buy along with my product_id == 1 to get a good deal?
SELECT product_id
FROM t_product
WHERE product_id IN (
    SELECT product_id
    FROM t_combination_product
    WHERE combination_id IN (
        SELECT combination_id
        FROM t_combination
        WHERE on_sale = 'yes'
        AND combination_id IN (SELECT combination_id FROM t_combination_product WHERE product_id = 1)
    )
)

I tried to do this in realm react-native as shown below:

I have two collections: Product and a Combination, set up as follows

class Product {};
Product.schema = {
    name: 'Product',
    primaryKey:'productId',
    properties: {
        productId:'int',
        product:'string'
    }
};

class Combination {};
Combination.schema = {
    name: 'Combination',
    properties: {
        onSale: {type: 'string'},
        products: {type: 'list',objectType:'Product'},
    }
};

What I want to do is given that I have Product.productId=1, I want to find all other products that belong to Combinations that have Combination.onSale='yes' and Product.productId IS IN (Combination.products ).

This is the query I tried to do in realm with react-native:

let queryFilter = "ANY Combination.onSale = 'yes' AND Combination.products = 1";
let data = realm.objects('Product').objectsWhere(queryFilter);

But when I run this, I get the error

undefined is not a function (evaluating
  'realm.objects('Product').objectsWhere(queryFilter)')

If I remove the objectsWhere(queryFilter), then it just returns me the list of all Products that hasn't been filtered.

So it seems I'm using objectsWhere incorrectly? How do I fix this to find a list of all products that are onsale if purchased with product 1?

Body:
If you had

class Product {};
  Product.schema = {
    name: 'Product',
    primaryKey:'productId',
    properties: {
        productId:'int',
        product:'string'
        combinations: {type: 'linkingObjects', objectType: 'Combination', property: 'products'}
    }
};

Backlink queries are not yet supported, so I think what you have to do is something like this:

let queryFilter = 'productId = 1';
let data = realm.objects('Product').filtered(queryFilter);
let combinations = data.combinations.filtered('onSale = true');
let linkedProducts = [];
for(let i = 0; i < combinations.length; i++) {
    linkedProducts.push(combinations[i]);
}
// linked products should contain what you need


问:
Construct Binary Search Tree from PreOrder
Way to construct binary search tree from preorderTransaversal.Please suggest if there is any suggestion.</p>

```<code>Node constructTreeFromPreorder(int[] arr,int start,int end)
{
if(arr==null){
    return null;
}else{
    if(start>end){
        return null;
    }
    int element=arr[start];
    Node node=new Node(element); // create node
    if(start==end){
        return node;
    }
    int index=start+1;
    for(int i=index;i<=end;i++){
          index=i;
        if(arr[i]>element){
            break;
        }
    }
    node.left=constructTreeFromPreorder(arr, start+1, index-1);
    node.right=constructTreeFromPreorder(arr, index, end);
    return node;
}
</code>```

答:
There are multiple binary trees that correspond to any preorder traversal. For example, consider the preorder traversal [2,1,3]. That is the preorder traversal for all of these trees:

```<code>  2         2     2          2      2
1   3     1         1      1          1
        3         3          3          3
</code>```

You need more information than just a preorder traversal if you want to uniquely describe a binary tree.

Added after you modified the question: Of those, only the first is a valid binary search tree. I'm not sure if there are multiple BSTs for a given preorder traversal.

If there are duplicate items in the list, then there can be multiple trees for any given preorder traversal.

Body:
Way to construct binary search tree from preorderTransaversal.Please suggest if there is any suggestion.

Node constructTreeFromPreorder(int[] arr,int start,int end)
{
if(arr==null){
    return null;
}else{
    if(start>end){
        return null;
    }
    int element=arr[start];
    Node node=new Node(element); // create node
    if(start==end){
        return node;
    }
    int index=start+1;
    for(int i=index;i<=end;i++){
          index=i;
        if(arr[i]>element){
            break;
        }
    }
    node.left=constructTreeFromPreorder(arr, start+1, index-1);
    node.right=constructTreeFromPreorder(arr, index, end);
    return node;
}

Body:
There are multiple binary trees that correspond to any preorder traversal. For example, consider the preorder traversal [2,1,3]. That is the preorder traversal for all of these trees:

  2         2     2          2      2
1   3     1         1      1          1
        3         3          3          3

You need more information than just a preorder traversal if you want to uniquely describe a binary tree.

Added after you modified the question: Of those, only the first is a valid binary search tree. I'm not sure if there are multiple BSTs for a given preorder traversal.

If there are duplicate items in the list, then there can be multiple trees for any given preorder traversal.


问:
Recover from "Fatal error: Uncaught SoapFault exception"
I already have functional code, but I'm currently trying to find ways to break it so that I can find exceptions to catch. The code below connects to a Bluecat/Proteus API and attempts to allocate a DHCP Reservation against a list of IP/MAC combos being uploaded via CSV. Knowing the people who would be using this tool, typos in the IP and/or MAC are possible and there could potentially be hundreds of items to process in a given CSV upload.

To test, I'm passing an IP with an invalid octet and a MAC with the same problem. Unfortunately, I've come across this error type and from what I've searched for, there is no way to gracefully catch and log the error and move on to the next item in the list to be processed.

Here is my code:

```<code><?php
session_start();
$client = new SoapClient("...server with WSDL thingy...");
$client->login($_SESSION['user'], $_SESSION['pass']);

# List of items to process taken from a form upload on a preceeding page
# List saved as array in 'csv'

foreach ($_SESSION['csv'] as $i=>$row) {

try {
$_SESSION['csv'][$i] = array_combine($_SESSION['keys'], $row);

$client->assignIP4Address('5',$_SESSION['csv'][$i]['ip4Address'],$_SESSION['csv'][$i]['macAddress'],'','MAKE_DHCP_RESERVED','');
}

catch (Exception $e) {
#Exception messaging goes here
}
}
?>
</code>```

The specific errors I'm getting are:

Fatal error: Uncaught SoapFault exception: [env:Server] Invalid octet value: 666 in C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php:30 Stack trace: #0 C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php(30): SoapClient->__call('assignIP4Addres...', Array) #1 C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php(30): SoapClient->assignIP4Address('5', '10.166.28.666', 'cc:dd:ee:ff:00:...', '', 'MAKE_DHCP_RESER...', '') #2 {main} thrown in C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php on line 30

and

SoapFault: Invalid octet value: 666 in C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php on line 30

Note that the error kills the script at the invalid IP as it comes first in the list of arguments for the method call to the soap provider. I have no clue what the error for the invalid MAC would be yet, but I'm guessing something similar.

The invalid IP/MAC octets are as such: x.x.x.666 and xx:xx:xx:xx:xx:ZZ

Is there any way to catch this specific type of fatal error and continue processing with the next item in the foreach loop? As I said, there could be hundreds of rows in the source CSV and having the script die at some random place because of a typo would be a pain in the ass.

This question is for PHP 5.6, just to be complete.

答:
Beautiful. I had to add a couple more things to test the actual allocation step, but it's working nicely now. Here is what I ended up with, in case anyone was curious:</p>

```<code>foreach ($_SESSION['csv'] as $i=>$row){

$_SESSION['csv'][$i] = array_combine($_SESSION['keys'],$row);

if (filter_var($_SESSION['csv'][$i]['ip4Address'],FILTER_VALIDATE_IP) && filter_var($_SESSION['csv'][$i]['macAddress'],FILTER_VALIDATE_MAC)){

    $success = true;

    try {
        $client->assignIP4Address('5',$_SESSION['csv'][$i]['ip4Address'],$_SESSION['csv'][$i]['macAddress'],'','MAKE_DHCP_RESERVED','');
        }
    catch (Exception $e) {
        echo "Failure: " . $_SESSION['csv'][$i]['ip4Address'] . "/" . $_SESSION['csv'][$i]['macAddress'] . " could not be allocated. Cause: " . $e->getMessage() . "<br>";
        $success = false;
        }
    if ($success) {
        echo "Success: " . $_SESSION['csv'][$i]['ip4Address'] . " has been allocated to " . $_SESSION['csv'][$i]['macAddress'] . "<br>";
    }
}
else{
    echo "Failure: " . $_SESSION['csv'][$i]['ip4Address'] . "/" . $_SESSION['csv'][$i]['macAddress'] . " could not be allocated. Please check that the IP or MAC is valid. <br>";
    }
}
</code>```

Body:
I already have functional code, but I'm currently trying to find ways to break it so that I can find exceptions to catch. The code below connects to a Bluecat/Proteus API and attempts to allocate a DHCP Reservation against a list of IP/MAC combos being uploaded via CSV. Knowing the people who would be using this tool, typos in the IP and/or MAC are possible and there could potentially be hundreds of items to process in a given CSV upload.

To test, I'm passing an IP with an invalid octet and a MAC with the same problem. Unfortunately, I've come across this error type and from what I've searched for, there is no way to gracefully catch and log the error and move on to the next item in the list to be processed.

Here is my code:

<?php
session_start();
$client = new SoapClient("...server with WSDL thingy...");
$client->login($_SESSION['user'], $_SESSION['pass']);

# List of items to process taken from a form upload on a preceeding page
# List saved as array in 'csv'

foreach ($_SESSION['csv'] as $i=>$row) {

try {
$_SESSION['csv'][$i] = array_combine($_SESSION['keys'], $row);

$client->assignIP4Address('5',$_SESSION['csv'][$i]['ip4Address'],$_SESSION['csv'][$i]['macAddress'],'','MAKE_DHCP_RESERVED','');
}

catch (Exception $e) {
#Exception messaging goes here
}
}
?>

The specific errors I'm getting are:

Fatal error: Uncaught SoapFault exception: [env:Server] Invalid octet value: 666 in C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php:30 Stack trace: #0 C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php(30): SoapClient->__call('assignIP4Addres...', Array) #1 C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php(30): SoapClient->assignIP4Address('5', '10.166.28.666', 'cc:dd:ee:ff:00:...', '', 'MAKE_DHCP_RESER...', '') #2 {main} thrown in C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php on line 30

and

SoapFault: Invalid octet value: 666 in C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php on line 30

Note that the error kills the script at the invalid IP as it comes first in the list of arguments for the method call to the soap provider. I have no clue what the error for the invalid MAC would be yet, but I'm guessing something similar.

The invalid IP/MAC octets are as such: x.x.x.666 and xx:xx:xx:xx:xx:ZZ

Is there any way to catch this specific type of fatal error and continue processing with the next item in the foreach loop? As I said, there could be hundreds of rows in the source CSV and having the script die at some random place because of a typo would be a pain in the ass.

This question is for PHP 5.6, just to be complete.

Body:
Beautiful. I had to add a couple more things to test the actual allocation step, but it's working nicely now. Here is what I ended up with, in case anyone was curious:

foreach ($_SESSION['csv'] as $i=>$row){

$_SESSION['csv'][$i] = array_combine($_SESSION['keys'],$row);

if (filter_var($_SESSION['csv'][$i]['ip4Address'],FILTER_VALIDATE_IP) && filter_var($_SESSION['csv'][$i]['macAddress'],FILTER_VALIDATE_MAC)){

    $success = true;

    try {
        $client->assignIP4Address('5',$_SESSION['csv'][$i]['ip4Address'],$_SESSION['csv'][$i]['macAddress'],'','MAKE_DHCP_RESERVED','');
        }
    catch (Exception $e) {
        echo "Failure: " . $_SESSION['csv'][$i]['ip4Address'] . "/" . $_SESSION['csv'][$i]['macAddress'] . " could not be allocated. Cause: " . $e->getMessage() . "<br>";
        $success = false;
        }
    if ($success) {
        echo "Success: " . $_SESSION['csv'][$i]['ip4Address'] . " has been allocated to " . $_SESSION['csv'][$i]['macAddress'] . "<br>";
    }
}
else{
    echo "Failure: " . $_SESSION['csv'][$i]['ip4Address'] . "/" . $_SESSION['csv'][$i]['macAddress'] . " could not be allocated. Please check that the IP or MAC is valid. <br>";
    }
}