问:
Does a UICollectionView use its dataSource under the hood when cellForItem(at:) is called?
So UICollectionViews expose the method cellForItem(at:) which allows us to access a cell contained in a collection view.

We also know the collectionView uses its datasource's collectionView(_:cellForItemAt:) method in order to create and configure its cells.

However, using a breakpoint it appears collectionView(_:cellForItemAt:) is never called when calling cellForItem(at:). What's going on here? Doesn't the collection view have to access its data source in order to know what cell to return? Is it caching all its cells at some point and if it is when is that caching happening?

答: cellForItem(at:) returns nil if a cell is not onscreen, so there is no need for it to call collectionView(_:cellForItemAt:) to get the cell.  It simply returns the cell if it is onscreen, and nil otherwise.


来源: stackexchange

问:
How to addClass to one button in button group via jQuery?
I have a HTML table with a button group on each row. When the user selects a button I want to highlight that button, and not the others. I'm trying to use a class in order to do this. But, how can I remove this class from the other 2 buttons?

```<code>.selectedAnswer {
  font-weight: bold;
  border: 1px solid blue;
}

 <table>
  <tr>
    <td>
      Question 1
    </td>
    <td>
      <div class="btn-group" role="group" aria-label="..." id="Rating">
        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>
      </div>
    </td>
  </tr>
  <tr>
    <td>
      Question 2
    </td>
    <td>
      <div class="btn-group" role="group" aria-label="..." id="Rating">
        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>
      </div>
    </td>
  </tr>
  <tr>
    <td>
      Question 3
    </td>
    <td>
      <div class="btn-group" role="group" aria-label="..." id="Rating">
        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>
      </div>
    </td>
  </tr>
  <tr>
    <td>
      Question 4
    </td>
    <td>
      <div class="btn-group" role="group" aria-label="..." id="Rating">
        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>
      </div>
    </td>
  </tr>

</table>
</code>```

Here is the jQuery...

```<code>//Set up click event on the Remove button
$('.btn-response').click(function(event) {
  $(this).addClass("selectedAnswer");
});
</code>```

Link: https://jsfiddle.net/webdevguy2/0mzjyvw2/2/

Any suggestions on a better way to do this?

答:
Your approach is perfectly sufficient; you just forgot to first remove the class from any .btn-response before adding it.  Easiest way to do that is just modify your script:

```<code>$('.btn-response').click(function (event) {
  // We're removing the class here
  $('.btn-response').removeClass("selectedAnswer");

  // And were adding it to JUST THE CLICKED ONE here
  $(this).addClass("selectedAnswer");
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a HTML table with a button group on each row. When the user selects a button I want to highlight that button, and not the others. I'm trying to use a class in order to do this. But, how can I remove this class from the other 2 buttons?

.selectedAnswer {
  font-weight: bold;
  border: 1px solid blue;
}

      Question 1

        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>

      Question 2

        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>

      Question 3

        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>

      Question 4

        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>

Here is the jQuery...

//Set up click event on the Remove button
$('.btn-response').click(function(event) {
  $(this).addClass("selectedAnswer");
});

Link: https://jsfiddle.net/webdevguy2/0mzjyvw2/2/

Any suggestions on a better way to do this?

Body:
Your approach is perfectly sufficient; you just forgot to first remove the class from any .btn-response before adding it.  Easiest way to do that is just modify your script:

$('.btn-response').click(function (event) {
  // We're removing the class here
  $('.btn-response').removeClass("selectedAnswer");

  // And were adding it to JUST THE CLICKED ONE here
  $(this).addClass("selectedAnswer");
});


问:
Weird pickling error running Apache Beam Python on Dataflow
We're running a fairly simple job which reads JSON, does some processing and outputs JSON.
For some reason, this always fails with a very weird "pickling" error:

```<code>PicklingError: Can't pickle <type 'generator'>: attribute lookup __builtin__.generator failed [while running 'map to user_activity']
</code>```

It fails almost immediately on processing the first line of data.  The preceding stage emits a tuple of (String, []).  When the 'map to user_activity' stage runs, it will fail if it tries to iterate the [].

There are no lambdas, which seem to be a common source of these pickling errors.  We've narrowed it down to iterating over the [] in the input tuple.  If we don't iterate, then the job will "work".  As soon as we do:

```<code>for entry in input_tuple:
    pass
</code>```

The job fails immediately.

**** Update ****
It turns out, iterating over the input tuple isn't the key.  ANY for loop in the Map function will cause a crash, even something like this:

```<code>q=[1,2,3,4,5,6]
for a in q:
  pass
</code>```

Here's the full stack trace for the error:

An exception was raised when trying to execute the workitem 4985068250752295797 : Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 582, in do_work
    work_executor.execute()
  File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/executor.py", line 166, in execute
    op.start()
  File "dataflow_worker/native_operations.py", line 38, in dataflow_worker.native_operations.NativeReadOperation.start (dataflow_worker/native_operations.c:3175)
    def start(self):
  File "dataflow_worker/native_operations.py", line 39, in dataflow_worker.native_operations.NativeReadOperation.start (dataflow_worker/native_operations.c:3079)
    with self.scoped_start_state:
  File "dataflow_worker/native_operations.py", line 44, in dataflow_worker.native_operations.NativeReadOperation.start (dataflow_worker/native_operations.c:2994)
    with self.spec.source.reader() as reader:
  File "dataflow_worker/native_operations.py", line 54, in dataflow_worker.native_operations.NativeReadOperation.start (dataflow_worker/native_operations.c:2938)
    self.output(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 154, in apache_beam.runners.worker.operations.Operation.output (apache_beam/runners/worker/operations.c:5783)
    cython.cast(Receiver, self.receivers[output_index]).receive(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 86, in apache_beam.runners.worker.operations.ConsumerSet.receive (apache_beam/runners/worker/operations.c:3622)
    cython.cast(Operation, consumer).process(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 339, in apache_beam.runners.worker.operations.DoOperation.process (apache_beam/runners/worker/operations.c:11089)
    with self.scoped_process_state:
  File "apache_beam/runners/worker/operations.py", line 340, in apache_beam.runners.worker.operations.DoOperation.process (apache_beam/runners/worker/operations.c:11043)
    self.dofn_receiver.receive(o)
  File "apache_beam/runners/common.py", line 382, in apache_beam.runners.common.DoFnRunner.receive (apache_beam/runners/common.c:10156)
    self.process(windowed_value)
  File "apache_beam/runners/common.py", line 390, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:10458)
    self._reraise_augmented(exn)
  File "apache_beam/runners/common.py", line 415, in apache_beam.runners.common.DoFnRunner._reraise_augmented (apache_beam/runners/common.c:11363)
    raise
  File "apache_beam/runners/common.py", line 388, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:10371)
    self.do_fn_invoker.invoke_process(windowed_value)
  File "apache_beam/runners/common.py", line 189, in apache_beam.runners.common.SimpleInvoker.invoke_process (apache_beam/runners/common.c:6270)
    self.output_processor.process_outputs(
  File "apache_beam/runners/common.py", line 480, in apache_beam.runners.common._OutputProcessor.process_outputs (apache_beam/runners/common.c:12500)
    self.main_receivers.receive(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 86, in apache_beam.runners.worker.operations.ConsumerSet.receive (apache_beam/runners/worker/operations.c:3622)
    cython.cast(Operation, consumer).process(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 339, in apache_beam.runners.worker.operations.DoOperation.process (apache_beam/runners/worker/operations.c:11089)
    with self.scoped_process_state:
  File "apache_beam/runners/worker/operations.py", line 340, in apache_beam.runners.worker.operations.DoOperation.process (apache_beam/runners/worker/operations.c:11043)
    self.dofn_receiver.receive(o)
  File "apache_beam/runners/common.py", line 382, in apache_beam.runners.common.DoFnRunner.receive (apache_beam/runners/common.c:10156)
    self.process(windowed_value)
  File "apache_beam/runners/common.py", line 390, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:10458)
    self._reraise_augmented(exn)
  File "apache_beam/runners/common.py", line 431, in apache_beam.runners.common.DoFnRunner._reraise_augmented (apache_beam/runners/common.c:11673)
    raise new_exn, None, original_traceback
  File "apache_beam/runners/common.py", line 388, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:10371)
    self.do_fn_invoker.invoke_process(windowed_value)
  File "apache_beam/runners/common.py", line 189, in apache_beam.runners.common.SimpleInvoker.invoke_process (apache_beam/runners/common.c:6270)
    self.output_processor.process_outputs(
  File "apache_beam/runners/common.py", line 480, in apache_beam.runners.common._OutputProcessor.process_outputs (apache_beam/runners/common.c:12500)
    self.main_receivers.receive(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 84, in apache_beam.runners.worker.operations.ConsumerSet.receive (apache_beam/runners/worker/operations.c:3588)
    self.update_counters_start(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 90, in apache_beam.runners.worker.operations.ConsumerSet.update_counters_start (apache_beam/runners/worker/operations.c:3808)
    self.opcounter.update_from(windowed_value)
  File "apache_beam/runners/worker/opcounters.py", line 62, in apache_beam.runners.worker.opcounters.OperationCounters.update_from (apache_beam/runners/worker/opcounters.c:2396)
    self.do_sample(windowed_value)
  File "apache_beam/runners/worker/opcounters.py", line 80, in apache_beam.runners.worker.opcounters.OperationCounters.do_sample (apache_beam/runners/worker/opcounters.c:3017)
    self.coder_impl.get_estimated_size_and_observables(windowed_value))
  File "apache_beam/coders/coder_impl.py", line 730, in apache_beam.coders.coder_impl.WindowedValueCoderImpl.get_estimated_size_and_observables (apache_beam/coders/coder_impl.c:22968)
    def get_estimated_size_and_observables(self, value, nested=False):
  File "apache_beam/coders/coder_impl.py", line 739, in apache_beam.coders.coder_impl.WindowedValueCoderImpl.get_estimated_size_and_observables (apache_beam/coders/coder_impl.c:22687)
    self._value_coder.get_estimated_size_and_observables(
  File "apache_beam/coders/coder_impl.py", line 260, in apache_beam.coders.coder_impl.FastPrimitivesCoderImpl.get_estimated_size_and_observables (apache_beam/coders/coder_impl.c:9578)
    self.encode_to_stream(value, out, nested)
  File "apache_beam/coders/coder_impl.py", line 298, in apache_beam.coders.coder_impl.FastPrimitivesCoderImpl.encode_to_stream (apache_beam/coders/coder_impl.c:10416)
    self.fallback_coder_impl.encode_to_stream(value, stream, nested)
  File "apache_beam/coders/coder_impl.py", line 154, in apache_beam.coders.coder_impl.CallbackCoderImpl.encode_to_stream (apache_beam/coders/coder_impl.c:5883)
    return stream.write(self._encoder(value), nested)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/coders/coders.py", line 437, in <lambda>
    lambda x: dumps(x, HIGHEST_PROTOCOL), pickle.loads)
PicklingError: Can't pickle <type 'generator'>: attribute lookup __builtin__.generator failed [while running 'map to user_activity']
```

答: Perhaps this is due to using beam.Map rather than beam.FlatMap for a function where you wish for multiple elements to be returned (yielded?)</p>

ContentLicense: CC BY-SA 4.0

Body:
We're running a fairly simple job which reads JSON, does some processing and outputs JSON.
For some reason, this always fails with a very weird "pickling" error:

PicklingError: Can't pickle <type 'generator'>: attribute lookup __builtin__.generator failed [while running 'map to user_activity']

It fails almost immediately on processing the first line of data.  The preceding stage emits a tuple of (String, []).  When the 'map to user_activity' stage runs, it will fail if it tries to iterate the [].

There are no lambdas, which seem to be a common source of these pickling errors.  We've narrowed it down to iterating over the [] in the input tuple.  If we don't iterate, then the job will "work".  As soon as we do:

for entry in input_tuple:
    pass

The job fails immediately.

**** Update ****
It turns out, iterating over the input tuple isn't the key.  ANY for loop in the Map function will cause a crash, even something like this:

q=[1,2,3,4,5,6]
for a in q:
  pass

Here's the full stack trace for the error:

An exception was raised when trying to execute the workitem 4985068250752295797 : Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 582, in do_work
    work_executor.execute()
  File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/executor.py", line 166, in execute
    op.start()
  File "dataflow_worker/native_operations.py", line 38, in dataflow_worker.native_operations.NativeReadOperation.start (dataflow_worker/native_operations.c:3175)
    def start(self):
  File "dataflow_worker/native_operations.py", line 39, in dataflow_worker.native_operations.NativeReadOperation.start (dataflow_worker/native_operations.c:3079)
    with self.scoped_start_state:
  File "dataflow_worker/native_operations.py", line 44, in dataflow_worker.native_operations.NativeReadOperation.start (dataflow_worker/native_operations.c:2994)
    with self.spec.source.reader() as reader:
  File "dataflow_worker/native_operations.py", line 54, in dataflow_worker.native_operations.NativeReadOperation.start (dataflow_worker/native_operations.c:2938)
    self.output(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 154, in apache_beam.runners.worker.operations.Operation.output (apache_beam/runners/worker/operations.c:5783)
    cython.cast(Receiver, self.receivers[output_index]).receive(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 86, in apache_beam.runners.worker.operations.ConsumerSet.receive (apache_beam/runners/worker/operations.c:3622)
    cython.cast(Operation, consumer).process(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 339, in apache_beam.runners.worker.operations.DoOperation.process (apache_beam/runners/worker/operations.c:11089)
    with self.scoped_process_state:
  File "apache_beam/runners/worker/operations.py", line 340, in apache_beam.runners.worker.operations.DoOperation.process (apache_beam/runners/worker/operations.c:11043)
    self.dofn_receiver.receive(o)
  File "apache_beam/runners/common.py", line 382, in apache_beam.runners.common.DoFnRunner.receive (apache_beam/runners/common.c:10156)
    self.process(windowed_value)
  File "apache_beam/runners/common.py", line 390, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:10458)
    self._reraise_augmented(exn)
  File "apache_beam/runners/common.py", line 415, in apache_beam.runners.common.DoFnRunner._reraise_augmented (apache_beam/runners/common.c:11363)
    raise
  File "apache_beam/runners/common.py", line 388, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:10371)
    self.do_fn_invoker.invoke_process(windowed_value)
  File "apache_beam/runners/common.py", line 189, in apache_beam.runners.common.SimpleInvoker.invoke_process (apache_beam/runners/common.c:6270)
    self.output_processor.process_outputs(
  File "apache_beam/runners/common.py", line 480, in apache_beam.runners.common._OutputProcessor.process_outputs (apache_beam/runners/common.c:12500)
    self.main_receivers.receive(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 86, in apache_beam.runners.worker.operations.ConsumerSet.receive (apache_beam/runners/worker/operations.c:3622)
    cython.cast(Operation, consumer).process(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 339, in apache_beam.runners.worker.operations.DoOperation.process (apache_beam/runners/worker/operations.c:11089)
    with self.scoped_process_state:
  File "apache_beam/runners/worker/operations.py", line 340, in apache_beam.runners.worker.operations.DoOperation.process (apache_beam/runners/worker/operations.c:11043)
    self.dofn_receiver.receive(o)
  File "apache_beam/runners/common.py", line 382, in apache_beam.runners.common.DoFnRunner.receive (apache_beam/runners/common.c:10156)
    self.process(windowed_value)
  File "apache_beam/runners/common.py", line 390, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:10458)
    self._reraise_augmented(exn)
  File "apache_beam/runners/common.py", line 431, in apache_beam.runners.common.DoFnRunner._reraise_augmented (apache_beam/runners/common.c:11673)
    raise new_exn, None, original_traceback
  File "apache_beam/runners/common.py", line 388, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:10371)
    self.do_fn_invoker.invoke_process(windowed_value)
  File "apache_beam/runners/common.py", line 189, in apache_beam.runners.common.SimpleInvoker.invoke_process (apache_beam/runners/common.c:6270)
    self.output_processor.process_outputs(
  File "apache_beam/runners/common.py", line 480, in apache_beam.runners.common._OutputProcessor.process_outputs (apache_beam/runners/common.c:12500)
    self.main_receivers.receive(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 84, in apache_beam.runners.worker.operations.ConsumerSet.receive (apache_beam/runners/worker/operations.c:3588)
    self.update_counters_start(windowed_value)
  File "apache_beam/runners/worker/operations.py", line 90, in apache_beam.runners.worker.operations.ConsumerSet.update_counters_start (apache_beam/runners/worker/operations.c:3808)
    self.opcounter.update_from(windowed_value)
  File "apache_beam/runners/worker/opcounters.py", line 62, in apache_beam.runners.worker.opcounters.OperationCounters.update_from (apache_beam/runners/worker/opcounters.c:2396)
    self.do_sample(windowed_value)
  File "apache_beam/runners/worker/opcounters.py", line 80, in apache_beam.runners.worker.opcounters.OperationCounters.do_sample (apache_beam/runners/worker/opcounters.c:3017)
    self.coder_impl.get_estimated_size_and_observables(windowed_value))
  File "apache_beam/coders/coder_impl.py", line 730, in apache_beam.coders.coder_impl.WindowedValueCoderImpl.get_estimated_size_and_observables (apache_beam/coders/coder_impl.c:22968)
    def get_estimated_size_and_observables(self, value, nested=False):
  File "apache_beam/coders/coder_impl.py", line 739, in apache_beam.coders.coder_impl.WindowedValueCoderImpl.get_estimated_size_and_observables (apache_beam/coders/coder_impl.c:22687)
    self._value_coder.get_estimated_size_and_observables(
  File "apache_beam/coders/coder_impl.py", line 260, in apache_beam.coders.coder_impl.FastPrimitivesCoderImpl.get_estimated_size_and_observables (apache_beam/coders/coder_impl.c:9578)
    self.encode_to_stream(value, out, nested)
  File "apache_beam/coders/coder_impl.py", line 298, in apache_beam.coders.coder_impl.FastPrimitivesCoderImpl.encode_to_stream (apache_beam/coders/coder_impl.c:10416)
    self.fallback_coder_impl.encode_to_stream(value, stream, nested)
  File "apache_beam/coders/coder_impl.py", line 154, in apache_beam.coders.coder_impl.CallbackCoderImpl.encode_to_stream (apache_beam/coders/coder_impl.c:5883)
    return stream.write(self._encoder(value), nested)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/coders/coders.py", line 437, in <lambda>
    lambda x: dumps(x, HIGHEST_PROTOCOL), pickle.loads)
PicklingError: Can't pickle <type 'generator'>: attribute lookup __builtin__.generator failed [while running 'map to user_activity']


问:
Labels on only root and terminal vertices in igraph (R)?
```<code>inst2 = c(2, 3, 4, 5, 6)
motherinst2 = c(7, 8, 2, 10, 11)
km = c(20, 30, 40, 25, 60)
df2 = data.frame(inst2, motherinst2)
df2 = cbind(df2, km)
g2 = graph_from_data_frame(df2)
tkplot(g2)
</code>```

how would I approach adding labels to exclusively my root and terminal vertices in a graph? I know it would involve this function, but how would you set it up? Assuming the graph object is just called 'g', or something obvious.

```<code>vertex.label =
</code>```

答:
The solution from @eipi1o is good, but the OP says "I'm finding it difficult to apply to my large data set effectively."  I suspect that the issue is finding which are the intermediate nodes whose name should be blanked out. I will continue the example of @eipi10.  Since my answer is based on his, if you upvote my answer, please upvote his as well.

You can use the neighbors function to determine which points are sources and sinks. Everything else is an intermediate node.

```<code>## original graph from eipi10
g = graph_from_edgelist(cbind(c(rep(1,10),2:11), c(2:21)))

## Identify which nodes are intermediate
SOURCES = which(sapply(V(g), function(x) length(neighbors(g, x, mode="in"))) == 0)
SINKS   = which(sapply(V(g), function(x) length(neighbors(g, x, mode="out"))) == 0)
INTERMED = setdiff(V(g), c(SINKS, SOURCES))

## Fix up the node names and plot
V(g)$name = V(g)
V(g)$name[INTERMED] = ""
plot(g)
</code>```

Body:
inst2 = c(2, 3, 4, 5, 6)
motherinst2 = c(7, 8, 2, 10, 11)
km = c(20, 30, 40, 25, 60)
df2 = data.frame(inst2, motherinst2)
df2 = cbind(df2, km)
g2 = graph_from_data_frame(df2)
tkplot(g2)

how would I approach adding labels to exclusively my root and terminal vertices in a graph? I know it would involve this function, but how would you set it up? Assuming the graph object is just called 'g', or something obvious.

vertex.label =

Body:
The solution from @eipi1o is good, but the OP says "I'm finding it difficult to apply to my large data set effectively."  I suspect that the issue is finding which are the intermediate nodes whose name should be blanked out. I will continue the example of @eipi10.  Since my answer is based on his, if you upvote my answer, please upvote his as well.

You can use the neighbors function to determine which points are sources and sinks. Everything else is an intermediate node.

## original graph from eipi10
g = graph_from_edgelist(cbind(c(rep(1,10),2:11), c(2:21)))

## Identify which nodes are intermediate
SOURCES = which(sapply(V(g), function(x) length(neighbors(g, x, mode="in"))) == 0)
SINKS   = which(sapply(V(g), function(x) length(neighbors(g, x, mode="out"))) == 0)
INTERMED = setdiff(V(g), c(SINKS, SOURCES))

## Fix up the node names and plot
V(g)$name = V(g)
V(g)$name[INTERMED] = ""
plot(g)


问:
angular 4 ngFor doesn't update list when add
I have an object called "objective" that have a list of objects "keyresults" inside. Every objective has a list of keyresults. When I select an objective, I have access to the list of keyresults of this objective through a modal. So, in this modal, I have a field that I can add a new key result, I just put the name and click Add. But, when I add a new keyresult, the list doesn't update, I need to refresh the page and select the objective again to see the new key result.
I want that the list update and show the new key result just after I add a new. How can I do this?

My html modal:

```<code><div class="modal-body">
    <div class="col-md-9" style="float:left; border-right:solid">
        <b>{{itemSelected.title}}</b>
        <select [(ngModel)]="itemSelected.state" (change)="updateState(itemSelected.state)">
            >
            <option *ngFor="let item of states" [value]="item.Id">{{item.Name}}</option>
        </select>
        <p>{{itemSelected.description}}</p>
        <div>
            <b>{{itemSelected.dueDate}}</b>
            <b>{{itemSelected.ownerPersonName}}</b>
        </div>
        <br />

        <b>Key Results</b>
        <hr />
        <div *ngFor="let keyResult of itemSelected.keyResults">
            {{keyResult.description}}
        </div>

        <input [(ngModel)]="newKeyResult.description" type="text">

        <select [(ngModel)]="newKeyResult.metricType">
            <option *ngFor="let item of keyResultTypes" [value]="item.Id">{{item.Name}}</option>
        </select>

        <button type="button" (click)="addKeyResult(itemSelected.id)">Adicionar</button>
        <br />
        <div *ngIf="successKeyResult" class="alert alert-success">{{successKeyResult}}</div>
        <div *ngIf="errorKeyResult" class="alert alert-danger">{{errorKeyResult}}</div>
    </div>
</code>```

My TS method:

```<code>private addKeyResult(objectiveId: any) {
    this.objectiveService.addKeyResult(objectiveId, this.newKeyResult).subscribe((ok) => {
        console.log(ok);
        this.successKeyResult = "KeyResult adicionado com sucesso";
    }, (error) => {
        this.errorKeyResult = this.objectiveService.getError(error.status);
    });
}
</code>```

Thanks!!

UPDATE

Hugo Noro helped me with the solution. I just need to add two lines in my method "addKeyResult" to update the client side list after saving it:

```<code>this.itemSelected.keyResults = [...this.itemSelected.keyResults, this.newKeyResult];
this.newKeyResult = {};
</code>```

Like this:

```<code>private addKeyResult(objectiveId: any) {
    this.newKeyResult.metricValueFrom = 0;
    this.newKeyResult.metricValueTo = 0;
    this.newKeyResult.actualValue = 0;
    this.newKeyResult.state = 0;

    this.objectiveService.addKeyResult(objectiveId, this.newKeyResult).subscribe((ok) => {
        console.log(ok);
        this.itemSelected.keyResults = [...this.itemSelected.keyResults, this.newKeyResult];
        this.successKeyResult = "KeyResult adicionado com sucesso";
        this.newKeyResult = {};
    }, (error) => {
        this.errorKeyResult = this.objectiveService.getError(error.status);
    });
}
</code>```

答:
OK so my understanding here is that you are effectively persisting the addition of the new key on the server by calling the service but you are not updating the client side list after saving it. </p>

<p>Try something like this </p>

```<code>private addKeyResult(objectiveId: any) {
this.objectiveService.addKeyResult(objectiveId, this.newKeyResult).subscribe((ok) => {
    this.itemSelected.keyResults = [...this.itemSelected.keyResults, this.newKeyResult];
console.log(ok);
    this.successKeyResult = "KeyResult adicionado com sucesso";
}, (error) => {
    this.errorKeyResult = this.objectiveService.getError(error.status);
});
}
</code>```

Body:
I have an object called "objective" that have a list of objects "keyresults" inside. Every objective has a list of keyresults. When I select an objective, I have access to the list of keyresults of this objective through a modal. So, in this modal, I have a field that I can add a new key result, I just put the name and click Add. But, when I add a new keyresult, the list doesn't update, I need to refresh the page and select the objective again to see the new key result.
I want that the list update and show the new key result just after I add a new. How can I do this?

My html modal:

        {{itemSelected.title}}
        <select [(ngModel)]="itemSelected.state" (change)="updateState(itemSelected.state)">
            >
            <option *ngFor="let item of states" [value]="item.Id">{{item.Name}}</option>
        </select>

{{itemSelected.description}}

            {{itemSelected.dueDate}}
            {{itemSelected.ownerPersonName}}

        Key Results

            {{keyResult.description}}

        <input [(ngModel)]="newKeyResult.description" type="text">

        <select [(ngModel)]="newKeyResult.metricType">
            <option *ngFor="let item of keyResultTypes" [value]="item.Id">{{item.Name}}</option>
        </select>

        <button type="button" (click)="addKeyResult(itemSelected.id)">Adicionar</button>

{{successKeyResult}}

{{errorKeyResult}}

My TS method:

private addKeyResult(objectiveId: any) {
    this.objectiveService.addKeyResult(objectiveId, this.newKeyResult).subscribe((ok) => {
        console.log(ok);
        this.successKeyResult = "KeyResult adicionado com sucesso";
    }, (error) => {
        this.errorKeyResult = this.objectiveService.getError(error.status);
    });
}

Thanks!!

UPDATE

Hugo Noro helped me with the solution. I just need to add two lines in my method "addKeyResult" to update the client side list after saving it:

this.itemSelected.keyResults = [...this.itemSelected.keyResults, this.newKeyResult];
this.newKeyResult = {};

Like this:

private addKeyResult(objectiveId: any) {
    this.newKeyResult.metricValueFrom = 0;
    this.newKeyResult.metricValueTo = 0;
    this.newKeyResult.actualValue = 0;
    this.newKeyResult.state = 0;

    this.objectiveService.addKeyResult(objectiveId, this.newKeyResult).subscribe((ok) => {
        console.log(ok);
        this.itemSelected.keyResults = [...this.itemSelected.keyResults, this.newKeyResult];
        this.successKeyResult = "KeyResult adicionado com sucesso";
        this.newKeyResult = {};
    }, (error) => {
        this.errorKeyResult = this.objectiveService.getError(error.status);
    });
}

Body:
OK so my understanding here is that you are effectively persisting the addition of the new key on the server by calling the service but you are not updating the client side list after saving it.

Try something like this

private addKeyResult(objectiveId: any) {
this.objectiveService.addKeyResult(objectiveId, this.newKeyResult).subscribe((ok) => {
    this.itemSelected.keyResults = [...this.itemSelected.keyResults, this.newKeyResult];
console.log(ok);
    this.successKeyResult = "KeyResult adicionado com sucesso";
}, (error) => {
    this.errorKeyResult = this.objectiveService.getError(error.status);
});
}


问:
OpenGL ES - How to Draw a filled Polygon?
I tried googling and searching on stack but I didn't find anything :-(

( Mapping irregular shapes or other polygons (cartoons, sprites) to triangles in OpenGL ES )

I want to draw a filled polygon in OpenGL ES on iPad (2D, don't need 3D)
(I'm new to OpenGL && OpenGL ES)
It seems simple on OpenGL but with ES with just can draw triangle.

But I can't find any good tutorial about this :-(
Does it exist any wrapper / library or anything else that could help me ?

I don't want to use CoreGraphics, it's too slow for what I'm doing ^^

And if possible, avoiding too (big) library like Cocos2D.

Edit : Working On the Problem, here are some useful links (will edit)

Links

- Polygon Triangulation

http://www.vterrain.org/Implementation/Libs/triangulate.html

http://en.wikipedia.org/wiki/Polygon_triangulation  (WIKI)
http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml  (polygon WITHOUT holes)
http://www.cs.unc.edu/~dm/CODE/GEM/chapter.html (polygon WITH holes, C code)

Solution

I will try using polygon tessellation to get triangles. At first I'm going to try ( http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml ) and as I need polygon with holes, the second one ( http://www.cs.unc.edu/~dm/CODE/GEM/chapter.html ). If anyone has a better way, PLEASE, tell me with a comment ^^

Thanks :-)

答:
On the Wikipedia Polygon Triangulation Talk page I argue that more triangles will in fact be faster.

I have written a triangulation engine that supports holes and runs in O(n log (n)) time. I tested it under Gdk and then made an Android app from it.

ContentLicense: CC BY-SA 2.5


问:
Tampermonkey script only sporadically working?
I'm trying to get Tampermonkey to complete an online form.
It works every 1 out of 4 times, all I want it to do is a simple check out process on a bigcartel store. Can anyone help?

It should work on any shop using their platform as they are all quite generic, i.e http://groundup.bigcartel.com

my code;

```<code>// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @include      https://checkout.bigcartel.com/*
// @include      https://*.bigcartel.com/product
// @include      https://*.bigcartel.com/cart
// @grant        none
// ==/UserScript==

// on "/cart" page click checkout button
document.getElementByName("checkout").click();

// fill first three form fields
document.getElementById("buyer_first_name").value = "John";
document.getElementById("buyer_last_name").value = "Smith";
document.getElementById("buyer_email").value = "john@doe.com";

// click "next" button
document.getElementByType("submit").click();
</code>```

答:
There are four major issues with your TM script.

1.) Your include tags use https instead of http

2.) document.getElementByName doesn't exist.

Fix: Use document.getElementsByName("checkout")[0]

3.) Once you click the checkout button, the script immediately try to set the values of the input fields, you must wait for the page to load.

4.) document.getElementByType doesn't exist either.

Here is the working script:

```<code>// ==UserScript==
// @name         Script
// @version      0.1
// @description  try to take over the world!
// @author       You
// @include      https://checkout.bigcartel.com/*
// @include      http://*.bigcartel.com/product
// @include      http://*.bigcartel.com/cart
// @grant        none
// ==/UserScript==

// on "/cart" page click checkout button
if (window.location.origin !== "https://checkout.bigcartel.com") document.getElementsByName("checkout")[0].click();
else {
    // fill first three form fields
    document.getElementById("buyer_first_name").value = "John";
    document.getElementById("buyer_last_name").value = "Smith";
    document.getElementById("buyer_email").value = "john@doe.com";
    // click "next" button
    document.getElementsByTagName("button")[0].click();
}
</code>```

Body:
I'm trying to get Tampermonkey to complete an online form.
It works every 1 out of 4 times, all I want it to do is a simple check out process on a bigcartel store. Can anyone help?

It should work on any shop using their platform as they are all quite generic, i.e http://groundup.bigcartel.com

my code;

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @include      https://checkout.bigcartel.com/*
// @include      https://*.bigcartel.com/product
// @include      https://*.bigcartel.com/cart
// @grant        none
// ==/UserScript==

// on "/cart" page click checkout button
document.getElementByName("checkout").click();

// fill first three form fields
document.getElementById("buyer_first_name").value = "John";
document.getElementById("buyer_last_name").value = "Smith";
document.getElementById("buyer_email").value = "john@doe.com";

// click "next" button
document.getElementByType("submit").click();

Body:
There are four major issues with your TM script.

1.) Your include tags use https instead of http

2.) document.getElementByName doesn't exist.

Fix: Use document.getElementsByName("checkout")[0]

3.) Once you click the checkout button, the script immediately try to set the values of the input fields, you must wait for the page to load.

4.) document.getElementByType doesn't exist either.

Here is the working script:

// ==UserScript==
// @name         Script
// @version      0.1
// @description  try to take over the world!
// @author       You
// @include      https://checkout.bigcartel.com/*
// @include      http://*.bigcartel.com/product
// @include      http://*.bigcartel.com/cart
// @grant        none
// ==/UserScript==

// on "/cart" page click checkout button
if (window.location.origin !== "https://checkout.bigcartel.com") document.getElementsByName("checkout")[0].click();
else {
    // fill first three form fields
    document.getElementById("buyer_first_name").value = "John";
    document.getElementById("buyer_last_name").value = "Smith";
    document.getElementById("buyer_email").value = "john@doe.com";
    // click "next" button
    document.getElementsByTagName("button")[0].click();
}


问:
How to use $get request in AngularJS after node fetches the data?
I'm building a web app that is going to use an API to display cards when you hover over card text on the app.

I'm using unirest to make the call to the API on my node express server as follows -

```<code>unirest.get("https://omgvamp-hearthstone-v1.p.mashape.com/cards")
.header("X-Mashape-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.end(function (result) {
  console.log(result.status, result.headers, result.body);
});
</code>```

The data returns correctly and is displayed in my git bash console as JSON.

How do I use the Angular $get service to make a call against what node has just pulled? I guess my question is , where is this data pulled to once node gets a handle on it?

From what I understand, I would parse this information, but do I have to send this data to use it in my Angular.js file?

I hope I wrote enough information for an answer.

Thank you

答:
If you want to pass the data to your UI, you need to make it accessible through an endpoint, so you could do something like this in your server (I'm using express for simplicity):

```<code>app.get('/my-data-endpoint', (req, res) => {
  unirest.get("https://omgvamp-hearthstone-v1.p.mashape.com/cards")
    .header("X-Mashape-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
    .end((result) => {
      console.log(result.status, result.headers, result.body);
      res.send(result);
    });
});
</code>```

and in your angular controller you can do:

```<code>$http.get('/my-data-endpoint')
  .then((response) => {
    console.log(response);
  });
</code>```

just remember to inject the $http dependency in your controller and you should be able to see the response.

Body:
I'm building a web app that is going to use an API to display cards when you hover over card text on the app.

I'm using unirest to make the call to the API on my node express server as follows -

unirest.get("https://omgvamp-hearthstone-v1.p.mashape.com/cards")
.header("X-Mashape-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.end(function (result) {
  console.log(result.status, result.headers, result.body);
});

The data returns correctly and is displayed in my git bash console as JSON.

How do I use the Angular $get service to make a call against what node has just pulled? I guess my question is , where is this data pulled to once node gets a handle on it?

From what I understand, I would parse this information, but do I have to send this data to use it in my Angular.js file?

I hope I wrote enough information for an answer.

Thank you

Body:
If you want to pass the data to your UI, you need to make it accessible through an endpoint, so you could do something like this in your server (I'm using express for simplicity):

app.get('/my-data-endpoint', (req, res) => {
  unirest.get("https://omgvamp-hearthstone-v1.p.mashape.com/cards")
    .header("X-Mashape-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
    .end((result) => {
      console.log(result.status, result.headers, result.body);
      res.send(result);
    });
});

and in your angular controller you can do:

$http.get('/my-data-endpoint')
  .then((response) => {
    console.log(response);
  });

just remember to inject the $http dependency in your controller and you should be able to see the response.


问:
losing object when calling [[.. alloc] init]
I'm experiencing a strange problem when calling alloc/init:

When I call:

```<code>Card *card = [[Card alloc] init];
return card; //here debugger reports that card is an NSMutableArray*, not a Card*
</code>```

However, if I call:

```<code>Card *card = [Card alloc];
[card init];
return card; //here debugger reports that card is Card*
</code>```

Card is declared as

```<code>@interface Card : NSObject { ...
</code>```

I've experienced this exact same pattern with other object allocations in my code.  Its as though the object is getting released before the return, or the stack is getting stepped on.

I understand that I'm supposed to use alloc/init together, but am having this problem.

答: Does your init function return self?  My guess would be that it isn't, and that's probably your problem.

Body:
I'm experiencing a strange problem when calling alloc/init:

When I call:

Card *card = [[Card alloc] init];
return card; //here debugger reports that card is an NSMutableArray*, not a Card*

However, if I call:

Card *card = [Card alloc];
[card init];
return card; //here debugger reports that card is Card*

Card is declared as

@interface Card : NSObject { ...

I've experienced this exact same pattern with other object allocations in my code.  Its as though the object is getting released before the return, or the stack is getting stepped on.

I understand that I'm supposed to use alloc/init together, but am having this problem.


问:
Unable to get the designer view window back using windows forms with Visual Studio 2010
I am in process of writing a C# Windows Forms application using Visual Studio Express 2010 ENU SP1.  Further VS specifics are at the bottom of this post.  I recently made some changes using the designer view to the layout and then decided that I did not want the changes so I closed the designer window.  The code window was still up when I closed the project and the changes were saved any way.  I don't care about the changes because the layout can be restored easily except for the fact that I cannot find any way to reopen the visual designer window.  To get the window back I have tried the following:

Shift F7

Right click in the designer code window

Double click the designer file under the solution explorer

Select the designer file under the solution explorer and use the context menu to bring up the file

I have an evaluation copy of the VS 2010 Team and it displays exactly the same behavior when utilizing my project

I have tried a backup copy of the project but it displays the same problem in both the Express and Team versions

I have been all over the MSDN, VS forum, and the internet at large and not found any solutions

When I first started the project I did rename the Form1.cs file from within the solution explorer because I wanted to have a different name than Form1 for the application.  When doing this it asked the following:

"You are renaming a file.  Would you like to perform a rename in this project of all references to the code element 'projectname'?

I replied yes.  So now I don't have a Form1.cs file but a file with my "projectname.cs" and the designer file named "projectname.Design.cs.  This is the only change that I made that I can think of that might be relevant.  I did try renaming it back to Form1.cs but that also did not resolve the problem.

I have to say that I am new to using Visual Studio.  So far I like it quite a bit but I am dead in the water right now and unless I can get this resolved I will lose two weeks worth of work.  Any assistance would be greatly appreciated.

Thanks,
-Tom

Additional Details:

Windows 7 Professional SP1 32 bit x86

Microsoft Visual Studio 2010
Version 10.0.40219.1 SP1Rel
Microsoft .NET Framework
Version 4.0.30319 SP1Rel

Installed Version: C# Express

Microsoft Visual C# 2010   01014-169-2560017-70726
Microsoft Visual C# 2010

Microsoft Visual C# 2010 Express - ENU Service Pack 1 (KB983509)   KB983509
This service pack is for Microsoft Visual C# 2010 Express - ENU.
If you later install a more recent service pack, this service pack will be uninstalled automatically.

答:
Tried all the suggestions mentioned in this question, nothing worked for Visual Studio Community 2017

no Shift-F7 shotcut

no context menu item visible

no double clicking on MainForm.cs

no wrong class order inside MainForm.cs

no wrong entries in mysolutionname.csproj file

But this worked for me

Right click your MainForm.cs file (or 'Form.cs' depending how you named it)

'Exlude from project'. This temporarily removes MainForm.cs, MainForm.Designer.cs and MainForm.resx

Use 'Add » Existing item' and select MainForm.cs. This will re-include all three files.

Of course you should add them back to the same folder as they were before

Double click on MainForm.cs and Design view magically openes


问:
scale_x_discrete not displayed on the plot
I have a data set that looks like this:

```<code>df <- data.frame(
  EventMonth = c('2015-01', '2015-02', '2015-03', '2015-04', '2015-05', '2015-06', '2015-07', '2015-08', '2015-09', '2015-10', '2015-11', '2015-12',
                 '2016-01', '2016-02', '2016-03', '2016-04', '2016-05', '2016-06', '2016-07', '2016-08', '2016-09', '2016-10', '2016-11', '2016-12'),
  EventQuarter = c('2015-Q1', '2015-Q1', '2015-Q1', '2015-Q2', '2015-Q2', '2015-Q2', '2015-Q3', '2015-Q3', '2015-Q3', '2015-Q4', '2015-Q4', '2015-Q4',
                   '2016-Q1', '2016-Q1', '2016-Q1', '2016-Q2', '2016-Q2', '2016-Q2', '2016-Q3', '2016-Q3', '2016-Q3', '2016-Q4', '2016-Q4', '2016-Q4'),
  score = c(2.59, 2.58, 2.82, 2.60, 2.69, 2.76, 2.68, 2.65, 2.58, 2.51, 2.90, 2.50, 2.65, 2.87, 2.48, 2.59, 2.83, 2.63, 2.73, 2.41, 2.63, 2.60, 2.64, 2.51),
  stringsAsFactors = F
)
</code>```

I am using a command like below to show line graph:

```<code>ggplot(df, aes(EventMonth, score)) +
  geom_line(stat='identity', group = 1) +
  theme_few() + ylim(0, survey[item == col, max.val])  +
  ylab(survey[item == col, title]) +
  theme(axis.text.x = element_text(angle=90)) +
  stat_smooth(aes(as.integer(as.factor(EventMonth)), score), method='loess')
</code>```

This works beautifully, but there are too many tick marks on the X axis. I would like to instead show only one tick mark per quarter.

As a starting point, I tried adding this to the command, to just show some arbitrary values for each quarter:

+ scale_x_discrete('Event Quarter', c(2, 5, 8, 11), c('a', 'b', 'c', 'd')

But this just makes the entire x-axis ticks and labels disappear, without showing a, b, c, d in places that I expect to see them. What am I doing wrong?

Also, my x axis is an integer axis, so I tried using scale_x_continuous too but couldn't get that to work either. It complained about me supplying discrete values for a continuous scale: scale_x_continuous('Event Quarter', c(2, 5, 8, 11), c('a', 'b', 'c', 'd'))

答:
The answer is that the value for breaks in the scale_x_discrete function is not an integer, but a mapping to the string values.

Essentially, even though in my data df$EventMonth is of type character, ggplot will convert it to a factor to display it. While you would think that using values like 1, 2, 3, ... to reference the x-axis should work (after all, a factor is a numeric type with some labels), it does not work here; instead, if you pass the character values (i.e. the levels of that factor) in the parameter for breaks it will work.

Here is the working code:

```<code>ggplot(df, aes(EventMonth, score)) +
  geom_line(stat='identity', group = 1) +
  theme_few() + ylim(0, survey[item == col, max.val])  +
  ylab(survey[item == col, title]) +
  theme(axis.text.x = element_text(angle=90)) +
  stat_smooth(aes(as.integer(as.factor(EventMonth)), score), method='loess') +
  scale_x_discrete('Event Quarter',
                   c('2015-02', '2015-05', '2015-08', '2015-11'),
                   c('2015-Q1', '2015-Q2', '2015-Q3', '2015-Q4'))
</code>```

Body:
I have a data set that looks like this:

df <- data.frame(
  EventMonth = c('2015-01', '2015-02', '2015-03', '2015-04', '2015-05', '2015-06', '2015-07', '2015-08', '2015-09', '2015-10', '2015-11', '2015-12',
                 '2016-01', '2016-02', '2016-03', '2016-04', '2016-05', '2016-06', '2016-07', '2016-08', '2016-09', '2016-10', '2016-11', '2016-12'),
  EventQuarter = c('2015-Q1', '2015-Q1', '2015-Q1', '2015-Q2', '2015-Q2', '2015-Q2', '2015-Q3', '2015-Q3', '2015-Q3', '2015-Q4', '2015-Q4', '2015-Q4',
                   '2016-Q1', '2016-Q1', '2016-Q1', '2016-Q2', '2016-Q2', '2016-Q2', '2016-Q3', '2016-Q3', '2016-Q3', '2016-Q4', '2016-Q4', '2016-Q4'),
  score = c(2.59, 2.58, 2.82, 2.60, 2.69, 2.76, 2.68, 2.65, 2.58, 2.51, 2.90, 2.50, 2.65, 2.87, 2.48, 2.59, 2.83, 2.63, 2.73, 2.41, 2.63, 2.60, 2.64, 2.51),
  stringsAsFactors = F
)

I am using a command like below to show line graph:

ggplot(df, aes(EventMonth, score)) +
  geom_line(stat='identity', group = 1) +
  theme_few() + ylim(0, survey[item == col, max.val])  +
  ylab(survey[item == col, title]) +
  theme(axis.text.x = element_text(angle=90)) +
  stat_smooth(aes(as.integer(as.factor(EventMonth)), score), method='loess')

This works beautifully, but there are too many tick marks on the X axis. I would like to instead show only one tick mark per quarter.

As a starting point, I tried adding this to the command, to just show some arbitrary values for each quarter:

+ scale_x_discrete('Event Quarter', c(2, 5, 8, 11), c('a', 'b', 'c', 'd')

But this just makes the entire x-axis ticks and labels disappear, without showing a, b, c, d in places that I expect to see them. What am I doing wrong?

Also, my x axis is an integer axis, so I tried using scale_x_continuous too but couldn't get that to work either. It complained about me supplying discrete values for a continuous scale: scale_x_continuous('Event Quarter', c(2, 5, 8, 11), c('a', 'b', 'c', 'd'))

Body:
The answer is that the value for breaks in the scale_x_discrete function is not an integer, but a mapping to the string values.

Essentially, even though in my data df$EventMonth is of type character, ggplot will convert it to a factor to display it. While you would think that using values like 1, 2, 3, ... to reference the x-axis should work (after all, a factor is a numeric type with some labels), it does not work here; instead, if you pass the character values (i.e. the levels of that factor) in the parameter for breaks it will work.

Here is the working code:

ggplot(df, aes(EventMonth, score)) +
  geom_line(stat='identity', group = 1) +
  theme_few() + ylim(0, survey[item == col, max.val])  +
  ylab(survey[item == col, title]) +
  theme(axis.text.x = element_text(angle=90)) +
  stat_smooth(aes(as.integer(as.factor(EventMonth)), score), method='loess') +
  scale_x_discrete('Event Quarter',
                   c('2015-02', '2015-05', '2015-08', '2015-11'),
                   c('2015-Q1', '2015-Q2', '2015-Q3', '2015-Q4'))


问:
No idea where this stylesheet is coming from - wordpress php
I'm trying to update my website but one thing I'm noticing is that I can't get rid of the original stylesheet. Right now I've gone into my bluehost control panel and replaced the style.css file. I also went into the custom css and deleted any css I had there to make sure there was nothing there that could possibly over ride it. But still if you go to the website you will see there are 2 stylesheets. I even searched my wordpress admin panel to make sure I didn't cache anything but I don't have a caching plugin. so that leads me to assume I messed up in the php somewhere but I'm not sure.

So when you go to the website and open the inspector and go to the sources you will see 2 stylesheets. style.css?ver=4.9.1 (the right one) and style.css?ver=1.0 (the old one). The old style sheet is making the navbar invisible and justifying the contact form to the left. The new stylesheet fixes those issues but for whatever reason the old stylesheet persists to exist and override the changes.

www.mustafasprojects.com

here's the header:

```<code><!doctype html>
<html <?php language_attributes(); ?> class="no-js">
    <head>
        <meta charset="<?php bloginfo('charset'); ?>">
        <title><?php wp_title(''); ?><?php if(wp_title('', false)) { echo ' :'; } ?> <?php bloginfo('name'); ?></title>

        <link href="//www.google-analytics.com" rel="dns-prefetch">

        <link href="<?php echo get_template_directory_uri(); ?>/img/icons/touch.png" rel="apple-touch-icon-precomposed">

        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="<?php bloginfo('description'); ?>">

        <?php wp_head(); ?>
        <script>
        // conditionizr.com
        // configure environment tests
        conditionizr.config({
            assets: '<?php echo get_template_directory_uri(); ?>',
            tests: {}
        });
        </script>

    </head>
    <body <?php body_class(); ?>>

        <div id="page-wrapper">
</code>```

here's the function.php

```<code>// Load any external files you have here

function theme_styles() {
    wp_enqueue_style( 'bootstrap_css', 'http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css' );
    wp_enqueue_style( 'b_css', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css' );
    wp_enqueue_style( 'style_css', get_template_directory_uri() . '/style.css' );
}

add_action( 'wp_enqueue_scripts', 'theme_styles' );

function theme_js() {
    wp_enqueue_script( 'bootstrap_js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js');
}

add_action( 'wp_enqueue_scripts', 'themes_js');

add_action('wp_enqueue_scripts', 'add_my_script'); // initiate the function

function add_my_script() {
wp_register_script ( 'colorbox-min' , get_stylesheet_directory_uri() . '/js/jquery.colorbox-min.js', array( 'jquery' ), '1', true );
wp_enqueue_script( 'colorbox-min' );

// Commented out because you probably want to use the minified version of the script
//wp_register_script ( 'colorbox' , get_stylesheet_directory_uri() . '/js/jquery.colorbox.js', array( 'jquery' ), '1', true );
//wp_enqueue_script( 'colorbox' );

wp_register_style ('ihatecolorboxcss', get_stylesheet_directory_uri() . '/ihatecolorbox.css','', '1', 'all');
wp_enqueue_style( 'colorbox' );
}
</code>```

edit: other place I hooked in a style sheet

```<code>function html5blank_styles()
{
    wp_register_style('normalize', get_template_directory_uri() . '/normalize.css', array(), '1.0', 'all');
    wp_enqueue_style('normalize'); //

    wp_register_style('html5blank', get_template_directory_uri() . '/style.css', array(), '1.0', 'all');
    wp_enqueue_style('html5blank');
</code>```

答:
In your code replace this line:

```<code>wp_enqueue_style( 'style_css', get_template_directory_uri() . '/style.css' );
</code>```

with:

```<code>wp_enqueue_style( 'style_css', get_template_directory_uri() );
</code>```

Body:
I'm trying to update my website but one thing I'm noticing is that I can't get rid of the original stylesheet. Right now I've gone into my bluehost control panel and replaced the style.css file. I also went into the custom css and deleted any css I had there to make sure there was nothing there that could possibly over ride it. But still if you go to the website you will see there are 2 stylesheets. I even searched my wordpress admin panel to make sure I didn't cache anything but I don't have a caching plugin. so that leads me to assume I messed up in the php somewhere but I'm not sure.

So when you go to the website and open the inspector and go to the sources you will see 2 stylesheets. style.css?ver=4.9.1 (the right one) and style.css?ver=1.0 (the old one). The old style sheet is making the navbar invisible and justifying the contact form to the left. The new stylesheet fixes those issues but for whatever reason the old stylesheet persists to exist and override the changes.

www.mustafasprojects.com

here's the header:

<!doctype html>
<html <?php language_attributes(); ?> class="no-js">

        <meta charset="<?php bloginfo('charset'); ?>">
        <title><?php wp_title(''); ?><?php if(wp_title('', false)) { echo ' :'; } ?> <?php bloginfo('name'); ?></title>

        <link href="//www.google-analytics.com" rel="dns-prefetch">

        <link href="<?php echo get_template_directory_uri(); ?>/img/icons/touch.png" rel="apple-touch-icon-precomposed">

        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="<?php bloginfo('description'); ?>">

        <?php wp_head(); ?>

    <body <?php body_class(); ?>>

here's the function.php

// Load any external files you have here

function theme_styles() {
    wp_enqueue_style( 'bootstrap_css', 'http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css' );
    wp_enqueue_style( 'b_css', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css' );
    wp_enqueue_style( 'style_css', get_template_directory_uri() . '/style.css' );
}

add_action( 'wp_enqueue_scripts', 'theme_styles' );

function theme_js() {
    wp_enqueue_script( 'bootstrap_js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js');
}

add_action( 'wp_enqueue_scripts', 'themes_js');

add_action('wp_enqueue_scripts', 'add_my_script'); // initiate the function

function add_my_script() {
wp_register_script ( 'colorbox-min' , get_stylesheet_directory_uri() . '/js/jquery.colorbox-min.js', array( 'jquery' ), '1', true );
wp_enqueue_script( 'colorbox-min' );

// Commented out because you probably want to use the minified version of the script
//wp_register_script ( 'colorbox' , get_stylesheet_directory_uri() . '/js/jquery.colorbox.js', array( 'jquery' ), '1', true );
//wp_enqueue_script( 'colorbox' );

wp_register_style ('ihatecolorboxcss', get_stylesheet_directory_uri() . '/ihatecolorbox.css','', '1', 'all');
wp_enqueue_style( 'colorbox' );
}

edit: other place I hooked in a style sheet

function html5blank_styles()
{
    wp_register_style('normalize', get_template_directory_uri() . '/normalize.css', array(), '1.0', 'all');
    wp_enqueue_style('normalize'); //

    wp_register_style('html5blank', get_template_directory_uri() . '/style.css', array(), '1.0', 'all');
    wp_enqueue_style('html5blank');

Body:
In your code replace this line:

wp_enqueue_style( 'style_css', get_template_directory_uri() . '/style.css' );

with:

wp_enqueue_style( 'style_css', get_template_directory_uri() );


问:
pushing or adding arrays as values into a multi-dimensional array in actionscript 3.0
I am running into some trouble adding an array into another array to create a multi-dimensional array.

The code appears as below:

```<code>var slideDataArray:Array = new Array();
var slideShowDataArray:Array = new Array();

slideDataArray[0] = xmlData.SlideShowParameters.SlideShowImagesDirectory;
slideDataArray[1] = xmlData.SlideShowParameters.SlideShowTimeInterval.valueOf();
slideDataArray[2] = xmlData.SlideShowParameters.SlideShowWidth.valueOf();
slideDataArray[3] = xmlData.SlideShowParameters.SlideShowHeight.valueOf();
slideDataArray[4] = slides.length();

slideShowDataArray[0] = slideDataArray;

for (i = 0; i < slides.length(); i++)   {
    // Read data from Slides tag in the XML file into slideDataArray
    slideDataArray[0] = slides[i].SlideImage.toString();
    slideDataArray[1] = slides[i].SlideText.toString();
    slideDataArray[2] = slides[i].SlideLink.toString();

    // Input the data from slideDataArray into the array for the slideshow (slideShowDataArray)
    slideShowDataArray[i + 1] = slideDataArray;
}
// end of FOR loop
</code>```

I am looking for a means of placing the slideDataArray into a 'slot' or value of slideShowDataArray so that I can in the end pass the slideShowDataArray as a parameter to another function.

As of now, the last slideDataArray appears 11 times (the loop runs 11 times) in slideShowDataArray and the way the code is written the slideDataArray is unique every iteration of the loop.

Any help is appreciated.

Thanks in advance...

答:
Remember you are not adding an array, but a reference to slideDataArray to your multidimensional array. Each reference points to the same array - which just contains different values on every iteration of the loop.  In other words: Every time you add that reference, you "link" to the same address in memory.

To get around this, move the inner part of the loop to a separate function and create a new local array on every call:

```<code>function createDataArray ( slide:Object ) : Array {
    var slideDataArray:Array = [];
    slideDataArray[0] = slide.SlideImage.toString();
    slideDataArray[1] = slide.SlideText.toString();
    slideDataArray[2] = slide.SlideLink.toString();
    return slideDataArray;
}
</code>```

Then call it from your loop:

```<code>for (i = 0; i < slides.length(); i++)   {
    slideShowDataArray.push( createDataArray (slides[i]) );
}
</code>```

You should end up with 11 unique arrays instead of one array that is overwritten 11 times.

Body:
I am running into some trouble adding an array into another array to create a multi-dimensional array.

The code appears as below:

var slideDataArray:Array = new Array();
var slideShowDataArray:Array = new Array();

slideDataArray[0] = xmlData.SlideShowParameters.SlideShowImagesDirectory;
slideDataArray[1] = xmlData.SlideShowParameters.SlideShowTimeInterval.valueOf();
slideDataArray[2] = xmlData.SlideShowParameters.SlideShowWidth.valueOf();
slideDataArray[3] = xmlData.SlideShowParameters.SlideShowHeight.valueOf();
slideDataArray[4] = slides.length();

slideShowDataArray[0] = slideDataArray;

for (i = 0; i < slides.length(); i++)   {
    // Read data from Slides tag in the XML file into slideDataArray
    slideDataArray[0] = slides[i].SlideImage.toString();
    slideDataArray[1] = slides[i].SlideText.toString();
    slideDataArray[2] = slides[i].SlideLink.toString();

    // Input the data from slideDataArray into the array for the slideshow (slideShowDataArray)
    slideShowDataArray[i + 1] = slideDataArray;
}
// end of FOR loop

I am looking for a means of placing the slideDataArray into a 'slot' or value of slideShowDataArray so that I can in the end pass the slideShowDataArray as a parameter to another function.

As of now, the last slideDataArray appears 11 times (the loop runs 11 times) in slideShowDataArray and the way the code is written the slideDataArray is unique every iteration of the loop.

Any help is appreciated.

Thanks in advance...

Body:
Remember you are not adding an array, but a reference to slideDataArray to your multidimensional array. Each reference points to the same array - which just contains different values on every iteration of the loop.  In other words: Every time you add that reference, you "link" to the same address in memory.

To get around this, move the inner part of the loop to a separate function and create a new local array on every call:

function createDataArray ( slide:Object ) : Array {
    var slideDataArray:Array = [];
    slideDataArray[0] = slide.SlideImage.toString();
    slideDataArray[1] = slide.SlideText.toString();
    slideDataArray[2] = slide.SlideLink.toString();
    return slideDataArray;
}

Then call it from your loop:

for (i = 0; i < slides.length(); i++)   {
    slideShowDataArray.push( createDataArray (slides[i]) );
}

You should end up with 11 unique arrays instead of one array that is overwritten 11 times.


问:
Get text before the last br in div jquery
Hi Guys i have this in html

```<code><div class="flexmls_connect__sr_address">
  <div class="flexmls_connect__ld_price">$9,000,000</div>
  Km. 16.5 Carr. Barra de Navidad, Villa Armonia Estate
  <br>
  Puerto Vallarta, JA
  <br>MLS# 11187
  <br>//NEED THIS NUMBER---- >5 beds  |  //AND THIS NUMBER---- >8 baths  |  11836 sqft
  <br>
</div>
</code>```

and this in jquery

```<code>    var baths = $(res).find('.flexmls_connect__sr_address').before('br').last().contents().filter(function() {
        return this.nodeType == 3;
    }).text();
</code>```

I need obtain the beds and baths, and for clearify not is my html code i obtain from a very old API and i cant change the HTML, i neee that values with only jquery or javascript. not neccesary with my answer all methos are welcome i only try many of theme and the last is get text before last tag br but any help is great, thanks :D

答:
You have to find text node content:

In this sample is //NEED THIS NUMBER---- >5 beds  |  //AND THIS NUMBER---- >8 baths  |  11836 sqft then remove all characters except numbers and | char with regex such as this:

```<code>var textNodeContent = '//NEED THIS NUMBER---- >5 beds  |  //AND THIS NUMBER---- >8 baths  |  11836 sqft',
stripped = textNodeContent.replace(/[^0-9\|]/g, '');
// the result will be 5|8|11836
</code>```

Body:
Hi Guys i have this in html

$9,000,000

  Km. 16.5 Carr. Barra de Navidad, Villa Armonia Estate

  Puerto Vallarta, JA

MLS# 11187

//NEED THIS NUMBER---- >5 beds  |  //AND THIS NUMBER---- >8 baths  |  11836 sqft

and this in jquery

    var baths = $(res).find('.flexmls_connect__sr_address').before('br').last().contents().filter(function() {
        return this.nodeType == 3;
    }).text();

I need obtain the beds and baths, and for clearify not is my html code i obtain from a very old API and i cant change the HTML, i neee that values with only jquery or javascript. not neccesary with my answer all methos are welcome i only try many of theme and the last is get text before last tag br but any help is great, thanks :D

Body:
You have to find text node content:

In this sample is //NEED THIS NUMBER---- >5 beds &nbsp;|&nbsp; //AND THIS NUMBER---- >8 baths &nbsp;|&nbsp; 11836 sqft then remove all characters except numbers and | char with regex such as this:

var textNodeContent = '//NEED THIS NUMBER---- >5 beds &nbsp;|&nbsp; //AND THIS NUMBER---- >8 baths &nbsp;|&nbsp; 11836 sqft',
stripped = textNodeContent.replace(/[^0-9\|]/g, '');
// the result will be 5|8|11836


问:
Received length differs from sent length
I am using an Android app to send a base64 encoded string to a CherryPy server. The Android code works like this:

```<code>URL url = new URL("http://foo.bar/blabla");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(base64s.length());

OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(base64s.getBytes());
</code>```

So, you'd say the amount of bytes sent equals the amount of bytes in the Content-Length header. However, in Python, when I run this:

```<code>cl = cherrypy.request.headers['Content-Length']
rawbody = cherrypy.request.body.read()

print "{} bytes, {}".format(len(rawbody), cl)
</code>```

The numbers cl and len(rawbody) are different.

How can that be?

答: your server sould send a "close header" so the client will no its end stream for him.</p>

Body:
I am using an Android app to send a base64 encoded string to a CherryPy server. The Android code works like this:

URL url = new URL("http://foo.bar/blabla");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(base64s.length());

OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(base64s.getBytes());

So, you'd say the amount of bytes sent equals the amount of bytes in the Content-Length header. However, in Python, when I run this:

cl = cherrypy.request.headers['Content-Length']
rawbody = cherrypy.request.body.read()

print "{} bytes, {}".format(len(rawbody), cl)

The numbers cl and len(rawbody) are different.

How can that be?


问:
Python error handling two dependent tasks
What's the best way to handle this? I want to create a file and add a record to a database, but if either one fails, I want to undo the other. It looks kind of messy to have a try, except, else with another try, except inside it to handle undoing the first task if the second fails.</p>

```<code>try:
    open and write file
except:
    pass
else:
    try:
        add record to db
    except:
        delete file
</code>```

答:
What you said you wanted to do and what the code does might be different. Depending on your implementation of open and write file you may be left with an undeleted file.

Solution

"Flat is better than nested" - The Zen of Python

```<code>try:
    open and write file
    add record to db
except:
    delete file
    rollback database session
</code>```

You could take it a step further and create a context manager that you could use as follows:

```<code>with record() as rec:
    open and write record to file
    add record to db
</code>```

Body:
What's the best way to handle this? I want to create a file and add a record to a database, but if either one fails, I want to undo the other. It looks kind of messy to have a try, except, else with another try, except inside it to handle undoing the first task if the second fails.

try:
    open and write file
except:
    pass
else:
    try:
        add record to db
    except:
        delete file

Body:
What you said you wanted to do and what the code does might be different. Depending on your implementation of open and write file you may be left with an undeleted file.

Solution

"Flat is better than nested" - The Zen of Python

try:
    open and write file
    add record to db
except:
    delete file
    rollback database session

You could take it a step further and create a context manager that you could use as follows:

with record() as rec:
    open and write record to file
    add record to db


问:
PHP PDO statement will NOT submit information to database
I have literally been working on this for hours. And I have absolutely 0 clue why it will not send my information to my database... I have used the same tactic before and it has worked brilliantly. Now it will not INSERT no matter what. Please help!

```<code>if ($validForm) {

    try {
        $stmt = $conn->prepare('INSERT INTO credentials (firstname, lastname, username, password) VALUES (:fname, :lname, :username, :password)');
        $stmt->bindValue(':fname',$firstname);
        $stmt->bindValue(':lname',$lastname);
        $stmt->bindValue(':username',$username);
        $stmt->bindValue(':password',$password);
        $passwordHash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
        $stmt->bindValue(':password',$passwordHash);
        $stmt->execute();
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
?>

<p class="success-message">Thank You. Your Form Has Been Submitted.</p>

<?php
}
</code>```

答:
I think you should one of these:

```<code>$stmt->bindValue(':password',$passwordHash);
</code>```

Or

```<code>$stmt->bindValue(':password',$password);
</code>```

Body:
I have literally been working on this for hours. And I have absolutely 0 clue why it will not send my information to my database... I have used the same tactic before and it has worked brilliantly. Now it will not INSERT no matter what. Please help!

if ($validForm) {

    try {
        $stmt = $conn->prepare('INSERT INTO credentials (firstname, lastname, username, password) VALUES (:fname, :lname, :username, :password)');
        $stmt->bindValue(':fname',$firstname);
        $stmt->bindValue(':lname',$lastname);
        $stmt->bindValue(':username',$username);
        $stmt->bindValue(':password',$password);
        $passwordHash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
        $stmt->bindValue(':password',$passwordHash);
        $stmt->execute();
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
?>

Thank You. Your Form Has Been Submitted.

<?php
}

Body:
I think you should one of these:

$stmt->bindValue(':password',$passwordHash);

Or

$stmt->bindValue(':password',$password);


问:
How to get selected date from inline datepicker on a servlet

Im trying to get the selected date of an inline jquery datepicker.I need to use selected date in Java code and not in JS.I tried to bind it to a hidden input but it didnt work, i only got null.

html:

 <input type="hidden" id="datepicker_send" name="datepicker_send">

Free Appointments on :

and js :

```<code>$(document).ready(function(){

$("#datepicker").datepicker({altField:'#datepicker_send'});

$("#datepicker").on("change",function(){
    var selected = $(this).val();
     $('#selectedDate').html(selected);
});
</code>```

I tried

```<code>request.getParameter("datepicker_send");
</code>```

and i only got null. Do you have any idea?

Thank you

答:
In your JS, try:
var selected = $('#datepicker').datepicker('getDate');

instead of: var selected = $(this).val();

this will trigger the getDate function in the datepicker class to actually get the date.

Body:
Im trying to get the selected date of an inline jquery datepicker.I need to use selected date in Java code and not in JS.I tried to bind it to a hidden input but it didnt work, i only got null.

html:

 <input type="hidden" id="datepicker_send" name="datepicker_send">

Free Appointments on :

and js :

$(document).ready(function(){

$("#datepicker").datepicker({altField:'#datepicker_send'});

$("#datepicker").on("change",function(){
    var selected = $(this).val();
     $('#selectedDate').html(selected);
});

I tried

request.getParameter("datepicker_send");

and i only got null. Do you have any idea?

Thank you


问:
Can't assign array element to class variable while overloading "=" operator
I am quite new in C++ programming, so maybe that's why I can't figure out why this assignment is not working.
In my class, I want to overload "=" operator.
I have specified a function, that outputs variables as an array. In overloading, I want to assign those variables to new object.

```<code> obj_new = obj_with_variables
</code>```

overloading:

```<code>  obj_new_x=obj_with_values_parameters()[0];
  obj_new_y=obj_with_values_parameters()[1];
</code>```

Here is a code:

```<code>// Test1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "string"

using namespace std;

class Vector2D
{
public:
Vector2D()
{

}
Vector2D(int& a, int& b)
    :x(a), y(b)
{

}
void Drukuj()
{
    cout << "wektor [" << x << ',' << y << "] \n";
}
void Wspolrzedne(int&a, int&b)
{
    x = a;
    y = b;
}
int* Wspolrzedne()
{
    int tab[2] = { x,y };
    return tab;
}
void operator = (Vector2D& obj)
{
    int* a = obj.Wspolrzedne();
    cout << a[0] << "\n";
    x = a[0];
    cout << x << " what? \n";
    y = a[1];
}

private:
int x, y;

};

int main()
{
int x1 = 2, x2 = 3;
Vector2D wektor(x1, x2);
wektor.Drukuj();
Vector2D wektor2;
wektor2 = wektor;
wektor2.Drukuj();
wektor.Drukuj();

return 0;
}
</code>```

The problem is that it assigns some strange values. However, if I don't use a reference, but declare 2 int values (j,k) and assign array element to them [0,1], it works fine.
Also, when using static numbers (for example, instead of a[0] ; use "2") it works fine too.

What is going on?

I would be glad if somebody could point me to right answer/ resources.

Regards,

答: In your member function int* Wspolrzedne(), you return the address of local variable tab. Accessing this variable once its life time has ended, as you do in your = operator, is undefined behaviour.

Body:
I am quite new in C++ programming, so maybe that's why I can't figure out why this assignment is not working.
In my class, I want to overload "=" operator.
I have specified a function, that outputs variables as an array. In overloading, I want to assign those variables to new object.

 obj_new = obj_with_variables

overloading:

  obj_new_x=obj_with_values_parameters()[0];
  obj_new_y=obj_with_values_parameters()[1];

Here is a code:

// Test1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "string"

using namespace std;

class Vector2D
{
public:
Vector2D()
{

}
Vector2D(int& a, int& b)
    :x(a), y(b)
{

}
void Drukuj()
{
    cout << "wektor [" << x << ',' << y << "] \n";
}
void Wspolrzedne(int&a, int&b)
{
    x = a;
    y = b;
}
int* Wspolrzedne()
{
    int tab[2] = { x,y };
    return tab;
}
void operator = (Vector2D& obj)
{
    int* a = obj.Wspolrzedne();
    cout << a[0] << "\n";
    x = a[0];
    cout << x << " what? \n";
    y = a[1];
}

private:
int x, y;

};

int main()
{
int x1 = 2, x2 = 3;
Vector2D wektor(x1, x2);
wektor.Drukuj();
Vector2D wektor2;
wektor2 = wektor;
wektor2.Drukuj();
wektor.Drukuj();

return 0;
}

The problem is that it assigns some strange values. However, if I don't use a reference, but declare 2 int values (j,k) and assign array element to them [0,1], it works fine.
Also, when using static numbers (for example, instead of a[0] ; use "2") it works fine too.

What is going on?

I would be glad if somebody could point me to right answer/ resources.

Regards,


问:
What is the proper way to block visitors from one specific folder, but allow my IP to see it (PHP)?
Let's say I have a site at www.example.com and I decide I want to have a French version of the same site at the URL www.example.com/fr

But at first, I only want myself to be able to see www.example.com/fr and anything within it (i'd like to block both "regular" visitors and any bots.

Can I block everyone except my IP from just that folder/section?  If so is it done via htaccess, robots.txt, a combo of both, some other way?

I know for visitors, I can add this to my htaccess:

```<code>order deny,allow
deny from all
allow from (my ip address)
</code>```

But can I tweak that to say everyone can go to everything EXCEPT the "fr" folder?

And I know for bots (i.e. google) this robots.txt file would be used at the root of my main site, if I wanted to keep bots from visiting:

```<code>User-agent: *
Disallow: /
</code>```

So do I create another robots.txt in the "fr" folder with that in it?  Or would it have to be done via the original robots.txt file in the main site root?

答:
You can have different .htaccess files in each folder, so just put a .htaccess in the /fr folder with the content:

```<code>order deny,allow
deny from all
allow from (your ip address)
</code>```

Regarding robots.txt, you can only have one which needs to be in the web root /. However, if you want to ask robots not to read a specific folder, all you need to do is to add a new row:

```<code>Disallow: /fr
</code>```

robots.txt can contain many Disallow-rows to different files/folders.

Just remember, robots doesn't have to respect your robots.txt-file. It's not a safe way to hide folders.

Note: If you have the above .htaccess in the /fr folder, you don't need to add it to robots.txt as well, since robots won't be able to read that folder anyway.

You can read more about .htaccess here (including why you should avoid using .htaccess if you have access to the main server config).

You can read more about robots.txt here

Body:
Let's say I have a site at www.example.com and I decide I want to have a French version of the same site at the URL www.example.com/fr

But at first, I only want myself to be able to see www.example.com/fr and anything within it (i'd like to block both "regular" visitors and any bots.

Can I block everyone except my IP from just that folder/section?  If so is it done via htaccess, robots.txt, a combo of both, some other way?

I know for visitors, I can add this to my htaccess:

order deny,allow
deny from all
allow from (my ip address)

But can I tweak that to say everyone can go to everything EXCEPT the "fr" folder?

And I know for bots (i.e. google) this robots.txt file would be used at the root of my main site, if I wanted to keep bots from visiting:

User-agent: *
Disallow: /

So do I create another robots.txt in the "fr" folder with that in it?  Or would it have to be done via the original robots.txt file in the main site root?

Body:
You can have different .htaccess files in each folder, so just put a .htaccess in the /fr folder with the content:

order deny,allow
deny from all
allow from (your ip address)

Regarding robots.txt, you can only have one which needs to be in the web root /. However, if you want to ask robots not to read a specific folder, all you need to do is to add a new row:

Disallow: /fr

robots.txt can contain many Disallow-rows to different files/folders.

Just remember, robots doesn't have to respect your robots.txt-file. It's not a safe way to hide folders.

Note: If you have the above .htaccess in the /fr folder, you don't need to add it to robots.txt as well, since robots won't be able to read that folder anyway.

You can read more about .htaccess here (including why you should avoid using .htaccess if you have access to the main server config).

You can read more about robots.txt here


问:
Javascript reduce() - What does the return line do?
I understand that it does reduce () in the most basic examples but not in one like this, especially the return line. It would be great if someone could explain how it works or put a more understandable example that returns the same result.</p>

```<code>var line = 'abazzzzax'
var obj = line.split('').reduce(function(p, c){
    return (p[c] = ++p[c] || 1, p);
}, {});
console.log(obj)
// Output => { a: 3, b: 1, z: 4, x: 1 }
</code>```

答:
The reduce function takes in 2 arguments in this example.

p  --> The initial state which is {}

c  --> the value of each iteration a , b , a .....

```<code>p[c] = ++p[c] || 1 //If the `key` is already available we increment it by 1 or set it to 1.
</code>```

So we first update it and return the p which contains the updated object, which is due to the comma operator.

Body:
I understand that it does reduce () in the most basic examples but not in one like this, especially the return line. It would be great if someone could explain how it works or put a more understandable example that returns the same result.

var line = 'abazzzzax'
var obj = line.split('').reduce(function(p, c){
    return (p[c] = ++p[c] || 1, p);
}, {});
console.log(obj)
// Output => { a: 3, b: 1, z: 4, x: 1 }

Body:
The reduce function takes in 2 arguments in this example.

p  --> The initial state which is {}

c  --> the value of each iteration a , b , a .....

p[c] = ++p[c] || 1 //If the `key` is already available we increment it by 1 or set it to 1.

So we first update it and return the p which contains the updated object, which is due to the comma operator.


答:
The inner part of the function can be rewritten like this:

```<code>var obj = line.split('').reduce(function(p, c){
    if (!p[c]) {
        p[c] = 1;
    } else {
        ++p[c];
    }
    return p;
}, {});
</code>```

Splitting out this expression:

p[c] = ++p[c] || 1

When p[c] doesn't exist yet, then the values is undefined. ++(undefined) returns NaN which is a falsy statement, so the value of p[c] will be 1. When p[c] does exist, then the value is incremented and then assigned back on to itself. Something like i = ++i, which is a little confusing in my opinion.

Finally, the comma operator allows you to run expressions in sequence from left to right, so the final expression is returned, which is the p object that keeps track of the occurrences.

Title: Javascript reduce() - What does the return line do?

Body:
The inner part of the function can be rewritten like this:

var obj = line.split('').reduce(function(p, c){
    if (!p[c]) {
        p[c] = 1;
    } else {
        ++p[c];
    }
    return p;
}, {});

Splitting out this expression:

p[c] = ++p[c] || 1

When p[c] doesn't exist yet, then the values is undefined. ++(undefined) returns NaN which is a falsy statement, so the value of p[c] will be 1. When p[c] does exist, then the value is incremented and then assigned back on to itself. Something like i = ++i, which is a little confusing in my opinion.

Finally, the comma operator allows you to run expressions in sequence from left to right, so the final expression is returned, which is the p object that keeps track of the occurrences.


问:
Identify groups of consecutive numbers in a list
I'd like to identify groups of consecutive numbers in a list, so that:

```<code>myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20])
</code>```

Returns:

```<code>[(2,5), (12,17), 20]
</code>```

And was wondering what the best way to do this was (particularly if there's something inbuilt into Python).

Edit: Note I originally forgot to mention that individual numbers should be returned as individual numbers, not ranges.

答:
more_itertools.consecutive_groups was added in version 4.0.

Demo

```<code>import more_itertools as mit

iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
[list(group) for group in mit.consecutive_groups(iterable)]
# [[2, 3, 4, 5], [12, 13, 14, 15, 16, 17], [20]]
</code>```

Code

Applying this tool, we make a generator function that finds ranges of consecutive numbers.

```<code>def find_ranges(iterable):
    """Yield range of consecutive numbers."""
    for group in mit.consecutive_groups(iterable):
        group = list(group)
        if len(group) == 1:
            yield group[0]
        else:
            yield group[0], group[-1]

iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
list(find_ranges(iterable))
# [(2, 5), (12, 17), 20]
</code>```

The source implementation emulates a classic recipe (as demonstrated by @Nadia Alramli).

Note: more_itertools is a third-party package installable via pip install more_itertools.

Body:
I'd like to identify groups of consecutive numbers in a list, so that:

myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20])

Returns:

[(2,5), (12,17), 20]

And was wondering what the best way to do this was (particularly if there's something inbuilt into Python).

Edit: Note I originally forgot to mention that individual numbers should be returned as individual numbers, not ranges.

Body:
more_itertools.consecutive_groups was added in version 4.0.

Demo

import more_itertools as mit

iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
[list(group) for group in mit.consecutive_groups(iterable)]
# [[2, 3, 4, 5], [12, 13, 14, 15, 16, 17], [20]]

Code

Applying this tool, we make a generator function that finds ranges of consecutive numbers.

def find_ranges(iterable):
    """Yield range of consecutive numbers."""
    for group in mit.consecutive_groups(iterable):
        group = list(group)
        if len(group) == 1:
            yield group[0]
        else:
            yield group[0], group[-1]

iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
list(find_ranges(iterable))
# [(2, 5), (12, 17), 20]

The source implementation emulates a classic recipe (as demonstrated by @Nadia Alramli).

Note: more_itertools is a third-party package installable via pip install more_itertools.


问:
Automatic date when specific cell contains text "YES"
I'm looking for help with this code:

```<code>function onEdit() {

  var s = SpreadsheetApp.getActiveSheet();

  if( s.getName() == "Trip Overview" ) { //checks that we're on the correct sheet

    var r = s.getActiveCell();

    if( r.getColumn() == 12 ) { //checks the column

      var nextCell = r.offset(0, 15);

      //if( nextCell.getValue() !==  ) //is empty?

      nextCell.setValue(new Date());
    }
  }
}
</code>```

The code is currently adding a date if column 12 contains ANY value, 1,2,3 or "Yes", "adf", "No" etc.

How to modify this code to only add a date if cell 12 contains "YES"?

答:
After checking if you are in the correct sheet and column, you need to check if the value of the cell is "YES"</p>

```<code>function onEdit() {

  var s = SpreadsheetApp.getActiveSheet();

  if( s.getName() == "Trip Overview" ) { //checks that we're on the correct sheet

    var r = s.getActiveCell();

    if( r.getColumn() == 12 ) { //checks the column

      if(r.getValue() == "YES") { //checksthe value of the cell

        var nextCell = r.offset(0, 15);

        nextCell.setValue(new Date());
      }

    }

  }

}
</code>```

Body:
I'm looking for help with this code:

function onEdit() {

  var s = SpreadsheetApp.getActiveSheet();

  if( s.getName() == "Trip Overview" ) { //checks that we're on the correct sheet

    var r = s.getActiveCell();

    if( r.getColumn() == 12 ) { //checks the column

      var nextCell = r.offset(0, 15);

      //if( nextCell.getValue() !==  ) //is empty?

      nextCell.setValue(new Date());
    }
  }
}

The code is currently adding a date if column 12 contains ANY value, 1,2,3 or "Yes", "adf", "No" etc.

How to modify this code to only add a date if cell 12 contains "YES"?

Body:
After checking if you are in the correct sheet and column, you need to check if the value of the cell is "YES"

function onEdit() {

  var s = SpreadsheetApp.getActiveSheet();

  if( s.getName() == "Trip Overview" ) { //checks that we're on the correct sheet

    var r = s.getActiveCell();

    if( r.getColumn() == 12 ) { //checks the column

      if(r.getValue() == "YES") { //checksthe value of the cell

        var nextCell = r.offset(0, 15);

        nextCell.setValue(new Date());
      }

    }

  }

}


问:
Radiobuttons set attribute checked is not working in function
Why is this not working with JQuery?
The property wont be checked to true so or with asnyc function... I tried everything, but it only will working if i set the attribute checked true in browser at console. Not even with outsourced async callback functions.

```<code>for (var i = 0; i < user.benutzer.length; i++)
                {
                    var user_var = user.benutzer[i].benutzer;
                    user_rep = user_var.replace(/ /g, '_');
                    $('#div_buttongroup').append('<label for="' + user_rep + '" class="btn btn-primary" id="label_'+user_rep+'"><input type="radio" class="user_radio" id="' + user_rep + '" value="' + user_var + '" name="radio" autocomplete="off"></input>' + user_var + '</label>');
                    if (i === 0)
                    {
                        t = user_rep;
                       $('#label_'+user_rep).addClass("btn btn-primary active");
                        $('#'+user_rep).prop("checked",true);
                    }
            }
</code>```

答:
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

```<code>$('#'+user_rep).attr("checked");
</code>```

Body:
Why is this not working with JQuery?
The property wont be checked to true so or with asnyc function... I tried everything, but it only will working if i set the attribute checked true in browser at console. Not even with outsourced async callback functions.

for (var i = 0; i < user.benutzer.length; i++)
                {
                    var user_var = user.benutzer[i].benutzer;
                    user_rep = user_var.replace(/ /g, '_');
                    $('#div_buttongroup').append('<input type="radio" class="user_radio" id="' + user_rep + '" value="' + user_var + '" name="radio" autocomplete="off"></input>' + user_var + '');
                    if (i === 0)
                    {
                        t = user_rep;
                       $('#label_'+user_rep).addClass("btn btn-primary active");
                        $('#'+user_rep).prop("checked",true);
                    }
            }

Body:
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

$('#'+user_rep).attr("checked");