问:
How to run a zmq and other while True: at the same time independently?
I have this code for my server:

```<code>import time
import zmq

context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5000")

while True:
    message = socket.recv()
    socket.send(b"World")
    print "sent"

while True:
    print "done."
</code>```

I have a separate client script that sends a message through zmq to this one whenever i send a message. On the server (this code), if i only have the first while True:, it prints "sent" every time i send a message, and if i only have the second while True:, it prints "done." continuously. But if i put both, it never prints done (or if i switch their order and put both it never prints "sent" when i send a message").

As an output i want it to continuously print "done.", and also print "sent" when I get a message. So something like this:

```<code>done.
done.
done.
done.
done.
sent
done.
lots more done....
</code>```

Basically i want both loops to run continuously and completely independently of each other.

N.B. I have tried using multiprocessing (such as in the 3rd answer here How do I run two python loops concurrently?), but couldn't get that to work either. I tried it as below:

```<code>import time
import zmq
from multiprocessing import Process

context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5000")
i = time.time()

def zmq_loop():
    while True:
        message = socket.recv()
        socket.send(b"World")
        print "sent"

def done_loop():
    global i
    while True:
        i2 = time.time()-i
        if i2%2 == 0:
            print "done."

if __name__ == "__main__":
    Process(target=zmq_loop).start()
    Process(target=done_loop).start()
</code>```

答:
As was explained yesterday in this, the [CONCURRENT]-processing is technically achievable in several different ways in python, each with a way different cost.

Today, let's have a look onto another approach - using a framework, that was developed with the very same motivation - having the natural [CONCURRENT]-scheduling-already-in-DNA - originally intended for easy composing and smooth operating complex GUI Man-Machine-Interactions ( MMI ).

This framework may and will help you achieve a lot, right due to the fact, it has evolved with a lot of care for exactly the same scenarios, where more than one thing has to be monitored at once:

Welcome to Tkinter GUI framework, which we will use just for its smart concurrently operated event handlers.

I was many times positively surprised, how easy it comes to build a quite complex composition of Finite-State-Automata ( FSA ), that smoothly cooperate together ( a coalition of FSA-s ), using tools for both independent, isolated operations ( the inner-logic of each FSA ), yet being easily able to propagate signals / messages from one FSA towards another(s). Yes, they can actually operate in 1-event-source-FSA : N-consumer(s)-FSA(s)

There you can create ( with ZeroMQ always in a non-blocking manner ) handlers -- one "sniffer" for a regular checking ( best by a timeout-controlled .poll() method to { NACK | POSACK } anything to read ) -- another "reader" for actual reading from the ZeroMQ Socket() instance ( triggered by the POSACK-signal from the "sniffer", as was mentioned previously -- another "do-a-work-er" for any other task one may wish to operate

Tkinter .mainloop() method is the global controller, which orchestrates the dirty job for you.

The hich level concept of Tkinter-mediated agent's co-processing starts in main() as simple as:

```<code>def main():
    root = Tk()                      # INIT a Tk() instance
    root.lift()                      #      + make it visible
    app = myApplication( root )      # SET ( [HERE] are all your app gems )
    root.mainloop()                  # START the core event-handling orchestrator
</code>```

Tkinter might look as a garrage full of various GUI-gadgets, that have nothing to do with your problem, but don't panic.

Tkinter has incredibly well created tools right for your needs.

using control variables that will be used as a means for storing, signalling and propagating changes of values among otherwise independent and explicitly un-coordinated actors ( ref. "sniffer", "reader", "worker" and any others ... )

tools for handling events - real, abstract and even virtual

tools for handling timed-operations - in a form of an almost a  lightweight real-time system, using setups with preferred timing of what shall happen next, the .mainloop()-yet tasked to bear in mind

an explicitly specified timing .after( thisAmountOfMILLISECONDS, callThisFUNCTION ) or a liberal .after_idle( callAlwaysThatFUNCTION ).

One does not need indeed anything more to go and solve your task, using these already perfect tools.

So all the rest is just in principle under your creativity how to re-use these smart tools.

A small demo,
how to make two ( 3 ! ) things happen "at the same time independently"

Let's setup the case, when one wants to process ( here demonstrated by a printing ) several independent processes, all at the same time.

```<code>    >>> #-----------------------------------------------FAST MOCK-UP EXAMPLE
    >>> import Tkinter as tk                          # python27
    >>> root = tk.Tk()
    >>> root.protocol( "WM_DELETE_WINDOW", root.quit() )
    '3071841620Ldestroy'
    >>> #------VAR-------------------------------------IMPORTANT TOOL:
    >>> aStringVAR = tk.StringVar()
    >>> aStringVAR.set( "_init_" )

    >>> def aKeyPressEventHANDLER( anEvent ): # SIMPLE EventHANDLER,
            #                                 #        also ignites remote responsive processes
    ...     aTemplate = "[KEY]::{3: >10s}\n<s/n>::{0: >10d}\n(=@=)::{1: > 10d}\n^from::({5:})"
    ...     sString   = aTemplate.format( anEvent.serial,
    ...                                   anEvent.time,
    ...                                   anEvent.char,
    ...                                   anEvent.keysym,
    ...                                   anEvent.keysym_num,
    ...                               str(anEvent.widget )
    ...                               )
    ...     aStringVAR.set( sString )
    ...     print sString
    ...
    >>> #----VAR_TRACER----------------------------------------[#1]
    >>> def aVAR_TRACER_A( p1_quasiNAME, p2_indexOrEmptyString, p3_accessMODE ):
    ...     print "aVAR_TRACER_A()-called::(on){0:} traced_event({1:})".format( str( p1_quasiNAME ), str( p3_accessMODE ) )
    ...     # ###############=[A]#######
    ...     # < do some task =[A] here >
    ...     # ###############=[A]#######
    ...     print "aVAR_TRACER_A()         [{0:}]".format(   str( root.globalgetvar( p1_quasiNAME ) ).replace( " ", "" ) )
    ...

    >>> #----VAR_TRACER----------------------------------------[#2]
    >>> def aVAR_TRACER_B( p1_quasiNAME, p2_indexOrEmptyString, p3_accessMODE ):
    ...     print "aVAR_TRACER_B()-called::(on){0:} traced_event({1:})".format( str( p1_quasiNAME ), str( p3_accessMODE ) )
    ...     # ###############=[B]#######
    ...     # < do some task =[B] here >
    ...     # ###############=[B]######
    ...     print "aVAR_TRACER_B()         [{0:}]".format(   str( root.globalgetvar( p1_quasiNAME ) ).replace( " ", "" ) )
    ...

    >>> #-----VAR_A_tracer_ID------------------------------"w" EVENT SNIFFER
    >>> aTraceVAR_A_tracer_ID = aStringVAR.trace_variable( "w", aVAR_TRACER_A )

    >>> #-----VAR_B_tracer_ID------------------------------"w" EVENT SNIFFER
    >>> aTraceVAR_B_tracer_ID = aStringVAR.trace_variable( "w", aVAR_TRACER_B )

    >>> #-----------tracer_ID values for ev. theirs resp. de-activation:
    >>> aTraceVAR_A_tracer_ID
    '3071960124LaVAR_TRACER_A'
    >>> aTraceVAR_B_tracer_ID
    '3071961284LaVAR_TRACER_B'

    >>> #---.bind()-----------------------EventHANDLER with a system event <KeyPress>
    >>> root.bind( "<KeyPress>", aKeyPressEventHANDLER ) # <-since here LIVE (!)
    '3071841740LaKeyPressEventHANDLER'
    >>> #------------------------------------------------^^^ since here, it went live
    >>> #                                                 1: having put a mouse on tk-window,
    >>> #                                                 2: set-focus by click
    >>> #                                                 3: started keys:
    >>> #                                                    ( "a",
    >>> #                                                       6-on-<NumKeyPad>,
    >>> #                                                       *-on-<NumKeyPad>

    >>> # this happened "independently, at the same time" ( see time (=@=):: values )
    >>>

    aVAR_TRACER_B()-called::(on)PY_VAR0 traced_event(w)
    aVAR_TRACER_B()         [[KEY]::a<s/n>::832(=@=)::88486992^from::(.)]
    aVAR_TRACER_A()-called::(on)PY_VAR0 traced_event(w)
    aVAR_TRACER_A()         [[KEY]::a<s/n>::832(=@=)::88486992^from::(.)]
    [KEY]::         a
    <s/n>::       832
    (=@=)::  88486992
    ^from::(.)
    aVAR_TRACER_B()-called::(on)PY_VAR0 traced_event(w)
    aVAR_TRACER_B()         [[KEY]::KP_6<s/n>::832(=@=)::88509107^from::(.)]
    aVAR_TRACER_A()-called::(on)PY_VAR0 traced_event(w)
    aVAR_TRACER_A()         [[KEY]::KP_6<s/n>::832(=@=)::88509107^from::(.)]
    [KEY]::      KP_6
    <s/n>::       832
    (=@=)::  88509107
    ^from::(.)
    aVAR_TRACER_B()-called::(on)PY_VAR0 traced_event(w)
    aVAR_TRACER_B()         [[KEY]::KP_Multiply<s/n>::832(=@=)::88541180^from::(.)]
    aVAR_TRACER_A()-called::(on)PY_VAR0 traced_event(w)
    aVAR_TRACER_A()         [[KEY]::KP_Multiply<s/n>::832(=@=)::88541180^from::(.)]
    [KEY]::KP_Multiply
    <s/n>::       832
    (=@=)::  88541180
    ^from::(.)
</code>```

Body:
I have this code for my server:

import time
import zmq

context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5000")

while True:
    message = socket.recv()
    socket.send(b"World")
    print "sent"

while True:
    print "done."

I have a separate client script that sends a message through zmq to this one whenever i send a message. On the server (this code), if i only have the first while True:, it prints "sent" every time i send a message, and if i only have the second while True:, it prints "done." continuously. But if i put both, it never prints done (or if i switch their order and put both it never prints "sent" when i send a message").

As an output i want it to continuously print "done.", and also print "sent" when I get a message. So something like this:

done.
done.
done.
done.
done.
sent
done.
lots more done....

Basically i want both loops to run continuously and completely independently of each other.

N.B. I have tried using multiprocessing (such as in the 3rd answer here How do I run two python loops concurrently?), but couldn't get that to work either. I tried it as below:

import time
import zmq
from multiprocessing import Process

context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5000")
i = time.time()

def zmq_loop():
    while True:
        message = socket.recv()
        socket.send(b"World")
        print "sent"

def done_loop():
    global i
    while True:
        i2 = time.time()-i
        if i2%2 == 0:
            print "done."

if __name__ == "__main__":
    Process(target=zmq_loop).start()
    Process(target=done_loop).start()

Body:
As was explained yesterday in this, the [CONCURRENT]-processing is technically achievable in several different ways in python, each with a way different cost.

Today, let's have a look onto another approach - using a framework, that was developed with the very same motivation - having the natural [CONCURRENT]-scheduling-already-in-DNA - originally intended for easy composing and smooth operating complex GUI Man-Machine-Interactions ( MMI ).

This framework may and will help you achieve a lot, right due to the fact, it has evolved with a lot of care for exactly the same scenarios, where more than one thing has to be monitored at once:

Welcome to Tkinter GUI framework, which we will use just for its smart concurrently operated event handlers.

I was many times positively surprised, how easy it comes to build a quite complex composition of Finite-State-Automata ( FSA ), that smoothly cooperate together ( a coalition of FSA-s ), using tools for both independent, isolated operations ( the inner-logic of each FSA ), yet being easily able to propagate signals / messages from one FSA towards another(s). Yes, they can actually operate in 1-event-source-FSA : N-consumer(s)-FSA(s)

There you can create ( with ZeroMQ always in a non-blocking manner ) handlers -- one "sniffer" for a regular checking ( best by a timeout-controlled .poll() method to { NACK | POSACK } anything to read ) -- another "reader" for actual reading from the ZeroMQ Socket() instance ( triggered by the POSACK-signal from the "sniffer", as was mentioned previously -- another "do-a-work-er" for any other task one may wish to operate

Tkinter .mainloop() method is the global controller, which orchestrates the dirty job for you.

The hich level concept of Tkinter-mediated agent's co-processing starts in main() as simple as:

def main():
    root = Tk()                      # INIT a Tk() instance
    root.lift()                      #      + make it visible
    app = myApplication( root )      # SET ( [HERE] are all your app gems )
    root.mainloop()                  # START the core event-handling orchestrator

Tkinter might look as a garrage full of various GUI-gadgets, that have nothing to do with your problem, but don't panic.

Tkinter has incredibly well created tools right for your needs.

using control variables that will be used as a means for storing, signalling and propagating changes of values among otherwise independent and explicitly un-coordinated actors ( ref. "sniffer", "reader", "worker" and any others ... )

tools for handling events - real, abstract and even virtual

tools for handling timed-operations - in a form of an almost a  lightweight real-time system, using setups with preferred timing of what shall happen next, the .mainloop()-yet tasked to bear in mind

an explicitly specified timing .after( thisAmountOfMILLISECONDS, callThisFUNCTION ) or a liberal .after_idle( callAlwaysThatFUNCTION ).

One does not need indeed anything more to go and solve your task, using these already perfect tools.

So all the rest is just in principle under your creativity how to re-use these smart tools.

A small demo,
how to make two ( 3 ! ) things happen "at the same time independently"

Let's setup the case, when one wants to process ( here demonstrated by a printing ) several independent processes, all at the same time.

    >>> #-----------------------------------------------FAST MOCK-UP EXAMPLE
    >>> import Tkinter as tk                          # python27
    >>> root = tk.Tk()
    >>> root.protocol( "WM_DELETE_WINDOW", root.quit() )
    '3071841620Ldestroy'
    >>> #------VAR-------------------------------------IMPORTANT TOOL:
    >>> aStringVAR = tk.StringVar()
    >>> aStringVAR.set( "_init_" )

    >>> def aKeyPressEventHANDLER( anEvent ): # SIMPLE EventHANDLER,
            #                                 #        also ignites remote responsive processes
    ...     aTemplate = "[KEY]::{3: >10s}\n<s/n>::{0: >10d}\n(=@=)::{1: > 10d}\n^from::({5:})"
    ...     sString   = aTemplate.format( anEvent.serial,
    ...                                   anEvent.time,
    ...                                   anEvent.char,
    ...                                   anEvent.keysym,
    ...                                   anEvent.keysym_num,
    ...                               str(anEvent.widget )
    ...                               )
    ...     aStringVAR.set( sString )
    ...     print sString
    ...
    >>> #----VAR_TRACER----------------------------------------[#1]
    >>> def aVAR_TRACER_A( p1_quasiNAME, p2_indexOrEmptyString, p3_accessMODE ):
    ...     print "aVAR_TRACER_A()-called::(on){0:} traced_event({1:})".format( str( p1_quasiNAME ), str( p3_accessMODE ) )
    ...     # ###############=[A]#######
    ...     # < do some task =[A] here >
    ...     # ###############=[A]#######
    ...     print "aVAR_TRACER_A()         [{0:}]".format(   str( root.globalgetvar( p1_quasiNAME ) ).replace( " ", "" ) )
    ...

    >>> #----VAR_TRACER----------------------------------------[#2]
    >>> def aVAR_TRACER_B( p1_quasiNAME, p2_indexOrEmptyString, p3_accessMODE ):
    ...     print "aVAR_TRACER_B()-called::(on){0:} traced_event({1:})".format( str( p1_quasiNAME ), str( p3_accessMODE ) )
    ...     # ###############=[B]#######
    ...     # < do some task =[B] here >
    ...     # ###############=[B]######
    ...     print "aVAR_TRACER_B()         [{0:}]".format(   str( root.globalgetvar( p1_quasiNAME ) ).replace( " ", "" ) )
    ...

    >>> #-----VAR_A_tracer_ID------------------------------"w" EVENT SNIFFER
    >>> aTraceVAR_A_tracer_ID = aStringVAR.trace_variable( "w", aVAR_TRACER_A )

    >>> #-----VAR_B_tracer_ID------------------------------"w" EVENT SNIFFER
    >>> aTraceVAR_B_tracer_ID = aStringVAR.trace_variable( "w", aVAR_TRACER_B )

    >>> #-----------tracer_ID values for ev. theirs resp. de-activation:
    >>> aTraceVAR_A_tracer_ID
    '3071960124LaVAR_TRACER_A'
    >>> aTraceVAR_B_tracer_ID
    '3071961284LaVAR_TRACER_B'

    >>> #---.bind()-----------------------EventHANDLER with a system event <KeyPress>
    >>> root.bind( "<KeyPress>", aKeyPressEventHANDLER ) # <-since here LIVE (!)
    '3071841740LaKeyPressEventHANDLER'
    >>> #------------------------------------------------^^^ since here, it went live
    >>> #                                                 1: having put a mouse on tk-window,
    >>> #                                                 2: set-focus by click
    >>> #                                                 3: started keys:
    >>> #                                                    ( "a",
    >>> #                                                       6-on-<NumKeyPad>,
    >>> #                                                       *-on-<NumKeyPad>

    >>> # this happened "independently, at the same time" ( see time (=@=):: values )
    >>>

    aVAR_TRACER_B()-called::(on)PY_VAR0 traced_event(w)
    aVAR_TRACER_B()         [[KEY]::a<s/n>::832(=@=)::88486992^from::(.)]
    aVAR_TRACER_A()-called::(on)PY_VAR0 traced_event(w)
    aVAR_TRACER_A()         [[KEY]::a<s/n>::832(=@=)::88486992^from::(.)]
    [KEY]::         a
    <s/n>::       832
    (=@=)::  88486992
    ^from::(.)
    aVAR_TRACER_B()-called::(on)PY_VAR0 traced_event(w)
    aVAR_TRACER_B()         [[KEY]::KP_6<s/n>::832(=@=)::88509107^from::(.)]
    aVAR_TRACER_A()-called::(on)PY_VAR0 traced_event(w)
    aVAR_TRACER_A()         [[KEY]::KP_6<s/n>::832(=@=)::88509107^from::(.)]
    [KEY]::      KP_6
    <s/n>::       832
    (=@=)::  88509107
    ^from::(.)
    aVAR_TRACER_B()-called::(on)PY_VAR0 traced_event(w)
    aVAR_TRACER_B()         [[KEY]::KP_Multiply<s/n>::832(=@=)::88541180^from::(.)]
    aVAR_TRACER_A()-called::(on)PY_VAR0 traced_event(w)
    aVAR_TRACER_A()         [[KEY]::KP_Multiply<s/n>::832(=@=)::88541180^from::(.)]
    [KEY]::KP_Multiply
    <s/n>::       832
    (=@=)::  88541180
    ^from::(.)


来源: stackexchange

问:
Use R to reduce a dataset to only rows that have matching data in two separate columns
I am trying to reduce a massive data set to only the rows that match in the "FIRSTNAME" column and also the "SSN" column. In order to help clarify I made a small set.

Very small sample

```<code>CUSTNUM FIRSTNAME SSN
 1234     Matt    111
 4321     Mark    222
 5678     Mike    333
 9875     Matt    444
 1092     Matt    111
</code>```

I want it to return

```<code>CUSTNUM FIRSTNAME SSN
 1234     Matt    111
 1092     Matt    111
</code>```

Because they match in both columns.

My dataset has over 2 million rows of customer data in it so I need a way to id possible duplicate records.

答:
Alternatively, with dplyr:

```<code>library(tidyverse)

df %>%
  group_by(FIRSTNAME, SSN) %>%
  filter(n() > 1)

# A tibble: 2 x 3
# Groups:   FIRSTNAME, SSN [1]
  CUSTNUM FIRSTNAME   SSN
    <int>    <fctr> <int>
1    1234      Matt   111
2    1092      Matt   111
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to reduce a massive data set to only the rows that match in the "FIRSTNAME" column and also the "SSN" column. In order to help clarify I made a small set.

Very small sample

CUSTNUM FIRSTNAME SSN
 1234     Matt    111
 4321     Mark    222
 5678     Mike    333
 9875     Matt    444
 1092     Matt    111

I want it to return

CUSTNUM FIRSTNAME SSN
 1234     Matt    111
 1092     Matt    111

Because they match in both columns.

My dataset has over 2 million rows of customer data in it so I need a way to id possible duplicate records.

Body:
Alternatively, with dplyr:

library(tidyverse)

df %>%
  group_by(FIRSTNAME, SSN) %>%
  filter(n() > 1)

# A tibble: 2 x 3
# Groups:   FIRSTNAME, SSN [1]
  CUSTNUM FIRSTNAME   SSN
    <int>    <fctr> <int>
1    1234      Matt   111
2    1092      Matt   111


问:
report builder - queries returning incorrect results
I have set a reporting project where I would like to get stats for my tables and later integrate this into a webservice. For the following queries though, I am getting incorrect results and I will note where below:

1 - Get the number of new entries for a given day

```<code> SELECT COUNT(*) AS RecordsCount,CAST(FLOOR(CAST(dateadded AS float))
 AS datetime)as collectionDate
 FROM TFeed GROUP BY CAST(FLOOR(CAST(dateadded AS float))
 AS datetime) order by collectionDate
</code>```

works fine and I am able to put this in a bar graph successfully.

2 - Get the top 10 searchterms with the highest records per searchterm requested by a given client in the last 10 days

```<code>SELECT TOP 10 searchterm, clientId, COUNT(*) AS TermResults FROM TFeed
where dateadded > getdate() - 10 GROUP BY
searchterm,clientId order by TermResults desc
</code>```

does not work
If I do a query in the Database for one of those terms that returns 98 in the report, the result is 984 in the database.

3 - I need to get the number of new records per client for a given day as well.

Also I was wondering if it is possible to put these queries into one report and not individual reports for each query which is not a big deal but having to cut and paste into one doc afterwards is tedious.

Any ideas appreciated

答:
For #2,

```<code>WITH tmp as
(
 SELECT clientId, searchTerm, COUNT(1) as TermResults,
   DENSE_RANK() OVER (partition by clientId
    ORDER BY clientId, COUNT(1) DESC) as rnk
 FROM TFeed
 WHERE dateadded > GETDATE() - 10
 GROUP BY clientId, searchterm
)
SELECT *
FROM   tmp
WHERE rnk < 11
</code>```

USE RANK() if you want to skip a rank if there are two matches (if lets say term1 and term2 have the same number of count, they are both rank 1 and the following term will be ranked 3rd instead of 2nd

For #3,

you can define multiple datasets within one report. Then you would just create three charts / table and associate those with their respective datasets

ContentLicense: CC BY-SA 2.5

Body:
I have set a reporting project where I would like to get stats for my tables and later integrate this into a webservice. For the following queries though, I am getting incorrect results and I will note where below:

1 - Get the number of new entries for a given day

 SELECT COUNT(*) AS RecordsCount,CAST(FLOOR(CAST(dateadded AS float))
 AS datetime)as collectionDate
 FROM TFeed GROUP BY CAST(FLOOR(CAST(dateadded AS float))
 AS datetime) order by collectionDate

works fine and I am able to put this in a bar graph successfully.

2 - Get the top 10 searchterms with the highest records per searchterm requested by a given client in the last 10 days

SELECT TOP 10 searchterm, clientId, COUNT(*) AS TermResults FROM TFeed
where dateadded > getdate() - 10 GROUP BY
searchterm,clientId order by TermResults desc

does not work
If I do a query in the Database for one of those terms that returns 98 in the report, the result is 984 in the database.

3 - I need to get the number of new records per client for a given day as well.

Also I was wondering if it is possible to put these queries into one report and not individual reports for each query which is not a big deal but having to cut and paste into one doc afterwards is tedious.

Any ideas appreciated

Body:
For #2,

WITH tmp as
(
 SELECT clientId, searchTerm, COUNT(1) as TermResults,
   DENSE_RANK() OVER (partition by clientId
    ORDER BY clientId, COUNT(1) DESC) as rnk
 FROM TFeed
 WHERE dateadded > GETDATE() - 10
 GROUP BY clientId, searchterm
)
SELECT *
FROM   tmp
WHERE rnk < 11

USE RANK() if you want to skip a rank if there are two matches (if lets say term1 and term2 have the same number of count, they are both rank 1 and the following term will be ranked 3rd instead of 2nd

For #3,

you can define multiple datasets within one report. Then you would just create three charts / table and associate those with their respective datasets


问:
Dialogs are not being updated in AEM 6.3
Hi I am facing an issue in AEM 6.3, after doing some changes in our code, the author dialogs are not being updated after the build is done, every other code is succesfully updated (JS, CSS) but only dialogs (XML) are not being updated in CRXDE.

Please let me know if someone has face with this issue and if there is a way to fix it.

答: I found the solution, the problem was that I was doing the build with a component who only had two xmls (the dialog for touch UI and the other for classic UI), it was necessary to add the content.xml.</p>


问:
Randomly placing a string into a 2d array
I need to create a 2D array and then randomly generate two numbers which will be the row and column that an X will be . I need to place four of them and they need to be hidden since it is for a game where the user guesses where they are. </p>

```<code>char[][]gameBoard= new char [10][10];

int row= (int) (Math.random()*9+1);
int col=(int) (Math.random()*9+1);

for (int i = 0; i < 10; i++){
                for (int j = 0; j <     10; j++){

                      if(i==row&&j==col)
                            System.out.print("[X]");

                    else
                         System.out.print("[ ]");

                System.out.println();
}
</code>```

答:
```<code>const FILLED_FIELD = 'X'
function placeX(array) {
    const width = array.length - 1;
    const height = array[0].length - 1;
    const targetX = Math.round(Math.random() * width); //Pick a random number between 0, and the width of the array
    const targetY = Math.round(Math.random() * height); //Pick a random number between 0, and the height of the array
    if (array[targetX][targetY] === FILLED_FIELD) return placeX(array); //If the choosed place is already occupied, try again
    array[targetX][targetY] = FILLED_FIELD; //Otherwise fill a field
}
</code>```

Technically not a perfect implementation, but will do the job. Just pass your 2D array to the function and it will randomly place X, ignoring places where X is already placed.

Body:
I need to create a 2D array and then randomly generate two numbers which will be the row and column that an X will be . I need to place four of them and they need to be hidden since it is for a game where the user guesses where they are.

char[][]gameBoard= new char [10][10];

int row= (int) (Math.random()*9+1);
int col=(int) (Math.random()*9+1);

for (int i = 0; i < 10; i++){
                for (int j = 0; j <     10; j++){

                      if(i==row&&j==col)
                            System.out.print("[X]");

                    else
                         System.out.print("[ ]");

                System.out.println();
}

Body:
const FILLED_FIELD = 'X'
function placeX(array) {
    const width = array.length - 1;
    const height = array[0].length - 1;
    const targetX = Math.round(Math.random() * width); //Pick a random number between 0, and the width of the array
    const targetY = Math.round(Math.random() * height); //Pick a random number between 0, and the height of the array
    if (array[targetX][targetY] === FILLED_FIELD) return placeX(array); //If the choosed place is already occupied, try again
    array[targetX][targetY] = FILLED_FIELD; //Otherwise fill a field
}

Technically not a perfect implementation, but will do the job. Just pass your 2D array to the function and it will randomly place X, ignoring places where X is already placed.


问:
Android Application Keyboard Enter/Send Key
While using messaging services built inside different applications, I noticed that the Enter key on some applications is replaced by a send key. As an example, the attached 5 screenshots are from Facebook Messenger, Instagram, Snapchat, Twitter and my own application.

As you can see, Snapchat and Instagram have the bottom-right key of the keyboard set as send with the special icon. Rest of them, including mine, do not have that. I tried to look around but could not find any documentation or suggestions on how to achieve this.

Where do I even start to achieve something like this?

Footnote 1: I am using a Google Pixel 2 XL with Google Keyboard, but I have seen similar functionality on other devices.

Footnote 2: I have seen a question on overwriting the enter key's input to call a function but am looking for more traditional/sophisticated method (preferably with custom send icon).

Footnote 3: Order of images: My application, Snapchat, Messenger, Twitter, Instagram.

Footnote 4: I am not specifically looking to make an entire custom keyboard. I want to keep rest of the multimedia functions brought by Google Keyboard.

答:
try add this property on your EditText,

```<code>android:imeOptions="actionSend"
</code>```

good luck!

Body:
try add this property on your EditText,

android:imeOptions="actionSend"

good luck!


问:
storing variables in a field and using them to populate values
This is similar to this post storing code in a column and using it but has another twist to it

So, I have a column that has stuff like

```<code>"Ddddd " & color & " blah blah " & width & "kdndjnsnd"
</code>```

So, id like to run a query that will populate color and width from the values of those columns in a table. So each row will get populated with a value from those columns on that record.

For example

```<code>Color    Width    Code
Black    5        "Ddddd '" & color & "' blah blah " & width & " kdndjnsnd"
</code>```

Will produce the following for that record

```<code>Ddddd black blah blah 5 kdndjnsnd"
</code>```

I know that doing this isn't recommended. I'm open to suggestions on how to accomplish this. I have a bunch of fields that need to be populated with dynamic values. Those values are burried inside blocks of text.

ETA here's a link to an excel file with an example of what i'm trying to do
excel file with an example

答:
This is a very convoluted way to do a simple thing.

General rule: Data belongs in tables. Calculated fields / expressions belong in queries.

All your table should contain is the actual data columns:

```<code>ProductType  Length  Hardware   Color   Width
</code>```

Everything else belongs into a query:

SELECT
  "dddddd " & [Length] & " ft dddddd dog leash - dddddddd" AS ProductTitle,
  "https://blah.com/ddddddd-" & [Color] & "-" & [Width] & "-" & [Hardware] & "-dog-leash-1.png" AS MainImg,
  "https://blah.com/ddddddd-" & [Color] & "-" & [Width] & "-" & [Hardware] & "-ddddddd-1.png" AS Img1,
  -- etc.
FROM Product_Data
```

Body:
This is similar to this post storing code in a column and using it but has another twist to it

So, I have a column that has stuff like

"Ddddd " & color & " blah blah " & width & "kdndjnsnd"

So, id like to run a query that will populate color and width from the values of those columns in a table. So each row will get populated with a value from those columns on that record.

For example

Color    Width    Code
Black    5        "Ddddd '" & color & "' blah blah " & width & " kdndjnsnd"

Will produce the following for that record

Ddddd black blah blah 5 kdndjnsnd"

I know that doing this isn't recommended. I'm open to suggestions on how to accomplish this. I have a bunch of fields that need to be populated with dynamic values. Those values are burried inside blocks of text.

ETA here's a link to an excel file with an example of what i'm trying to do
excel file with an example

Body:
This is a very convoluted way to do a simple thing.

General rule: Data belongs in tables. Calculated fields / expressions belong in queries.

All your table should contain is the actual data columns:

ProductType  Length  Hardware   Color   Width

Everything else belongs into a query:

SELECT
  "dddddd " & [Length] & " ft dddddd dog leash - dddddddd" AS ProductTitle,
  "https://blah.com/ddddddd-" & [Color] & "-" & [Width] & "-" & [Hardware] & "-dog-leash-1.png" AS MainImg,
  "https://blah.com/ddddddd-" & [Color] & "-" & [Width] & "-" & [Hardware] & "-ddddddd-1.png" AS Img1,
  -- etc.
FROM Product_Data


问:
Overlay NSView over NSScrollView
I have an NSScrollView that fills an entire window and displays a huge image. Now I would like to overlay a custom NSView over parts of the Scroll View (eg. top 20 Pixels height and window width) to display additional information. As the user scrolls the scroll view, the custom NSView at the top should stay where it is.

I have tried the following:

Create an instance of NSView of the size of my window

Add NSScrollView as subview of the previously generated NSView

Add my custom view as subview to the NSView in step 1

This works in the beginning, the scroll view is displayed properly and my custom NSView as well. However, as soon as I start moving the scroll view (scrolling) the custom NSView is scrolled along with the content of the NSScrollView and eventually disappears when its moved outside of the bounds and the part of scroll view, where it was positioned, becomes redrawn. How could I effectively layer my custom NSView on top of the NSScrollView and make sure it stays put?

Thanks!

答:
You have two options:

First, turn off "Copy on Scroll". You can do this directly in IB or by setting the copiesOnScroll option on the contentView member of the NSScrollView. That option, which is on by default makes it so the scroll view "copies its existing rendered image while scrolling (only drawing exposed portions of its document view)". If turned off, "it forces its contents to be redrawn each time." So, if performance is not a big issue, it works to just turn that off.

However, making it so the content has to redraw every time can cause major performance issues if you are doing complex drawing within the scroll view.

The second option is to leave "Copy on Scroll" turned on and then create a borderless window containing your overlaid view. This is really not as hackish as it might sound as you can actually add an NSWindow instance as a child of your current window so that it automatically moves along with the main window when that is moved.

The RoundTransparentWindow sample will give you a great example to follow in creating the window that will contain your overlay. Then, simply use NSWindow's addChildWindow to attach it to your main window.

Note that with this approach you will need to handle the timing of the presentation and hiding of the overlay window. It also seems to be the case that when you maximize the parent window that the child window position does not automatically adjust. So, you'll have to handle that too. But, it's a great solution if you don't want to sacrifice what is sometimes a massive performance improvement when using "Copy on Scroll".

Title: Overlay NSView over NSScrollView


问:
Composing functions in python
I have an array of functions and I'm trying to produce one function which consists of the composition of the elements in my array.
My approach is:

```<code>def compose(list):
    if len(list) == 1:
        return lambda x:list[0](x)
    list.reverse()
    final=lambda x:x
    for f in list:
        final=lambda x:f(final(x))
    return final
</code>```

This method doesn't seems to be working, help will be appreciated.

(I'm reversing the list because this is the order of composition I want the functions to be)

答:
This is my version

```<code>def compose(*fargs):
    def inner(arg):
        if not arg:
            raise ValueError("Invalid argument")
        if not all([callable(f) for f in fargs]):
            raise TypeError("Function is not callable")
        return reduce(lambda arg, func: func(arg), fargs, arg)
    return inner
</code>```

An example of how it's used

```<code>def calcMean(iterable):
    return sum(iterable) / len(iterable)

def formatMean(mean):
    return round(float(mean), 2)

def adder(val, value):
    return val + value

def isEven(val):
    return val % 2 == 0

if __name__ == '__main__':
    # Ex1

    rand_range = [random.randint(0, 10000) for x in range(0, 10000)]

    isRandIntEven = compose(calcMean, formatMean,
                            partial(adder, value=0), math.floor.__call__, isEven)

    print(isRandIntEven(rand_range))
</code>```

Title: Composing functions in python

Body:
I have an array of functions and I'm trying to produce one function which consists of the composition of the elements in my array.
My approach is:

def compose(list):
    if len(list) == 1:
        return lambda x:list[0](x)
    list.reverse()
    final=lambda x:x
    for f in list:
        final=lambda x:f(final(x))
    return final

This method doesn't seems to be working, help will be appreciated.

(I'm reversing the list because this is the order of composition I want the functions to be)

Body:
This is my version

def compose(*fargs):
    def inner(arg):
        if not arg:
            raise ValueError("Invalid argument")
        if not all([callable(f) for f in fargs]):
            raise TypeError("Function is not callable")
        return reduce(lambda arg, func: func(arg), fargs, arg)
    return inner

An example of how it's used

def calcMean(iterable):
    return sum(iterable) / len(iterable)

def formatMean(mean):
    return round(float(mean), 2)

def adder(val, value):
    return val + value

def isEven(val):
    return val % 2 == 0

if __name__ == '__main__':
    # Ex1

    rand_range = [random.randint(0, 10000) for x in range(0, 10000)]

    isRandIntEven = compose(calcMean, formatMean,
                            partial(adder, value=0), math.floor.__call__, isEven)

    print(isRandIntEven(rand_range))


问:
Sum an a nested array in an array of objects
I have a react component with a state that looks like this:

```<code>this.state = {
            categoryGroups: [
                {
                    groupName: 'Immediate Obligations',
                    budgeted: '5,000.00',
                    activity: '3,275.76',
                    subcategories: [
                        {
                            category: 'food',
                            budgeted: '500.00',
                            activity: '300.76'
                        },
                        {
                            category: 'rent',
                            budgeted: '1,000.00',
                            activity: '1,000.00'
                        }
                    ]
                },
                {
                    groupName: 'True Expenses',
                    budgeted: '2,000.00',
                    activity: '1,000.33',
                    subcategories: [
                        {
                            category: 'Car Insurance',
                            budgeted: '60.00',
                            activity: '60.00'
                        },
                        {
                            category: 'Gas',
                            budgeted: '100.00',
                            activity: '34.50'
                        }
                    ]
                }
            ]
        }
</code>```

I want to find the total budgeted amount for all of the subcategories in each category group. How can I do this?

答:
You could map each subcategory and reduce the two as so:

const categoryGroups = [{
    groupName: 'Immediate Obligations',
    budgeted: '5,000.00',
    activity: '3,275.76',
    subcategories: [{
        category: 'food',
        budgeted: '500.00',
        activity: '300.76'
      },
      {
        category: 'rent',
        budgeted: '1,000.00',
        activity: '1,000.00'
      }
    ]
  },
  {
    groupName: 'True Expenses',
    budgeted: '2,000.00',
    activity: '1,000.33',
    subcategories: [{
        category: 'Car Insurance',
        budgeted: '60.00',
        activity: '60.00'
      },
      {
        category: 'Gas',
        budgeted: '100.00',
        activity: '34.50'
      }
    ]
  }
];

const subCategories = categoryGroups.map(({ subcategories }) => {
  return subcategories.reduce((prev, { budgeted }) => {
    return +prev['budgeted'].replace(/,/g, '') +  +budgeted.replace(/,/g, '');
  });
});

const total = subCategories.reduce((prev, next) => prev + next);

console.log(total);```

Body:
I have a react component with a state that looks like this:

this.state = {
            categoryGroups: [
                {
                    groupName: 'Immediate Obligations',
                    budgeted: '5,000.00',
                    activity: '3,275.76',
                    subcategories: [
                        {
                            category: 'food',
                            budgeted: '500.00',
                            activity: '300.76'
                        },
                        {
                            category: 'rent',
                            budgeted: '1,000.00',
                            activity: '1,000.00'
                        }
                    ]
                },
                {
                    groupName: 'True Expenses',
                    budgeted: '2,000.00',
                    activity: '1,000.33',
                    subcategories: [
                        {
                            category: 'Car Insurance',
                            budgeted: '60.00',
                            activity: '60.00'
                        },
                        {
                            category: 'Gas',
                            budgeted: '100.00',
                            activity: '34.50'
                        }
                    ]
                }
            ]
        }

I want to find the total budgeted amount for all of the subcategories in each category group. How can I do this?


问:
Select all folders with Automator
How can I create a custom Automator command to simply select all folders within a folder?

If I runned the action it would look like this.

Thanks!
Nicolas

答:
Add:

Get Folder Contents (this will get all items in the given input folder)

Filter Finder Items

and set Kind is Folder

For testing add Reveal Finder Items at the end. Screenshot:

The result will be the list of folders in the given input folder. This is simple but slow solution. (The Get Folder Contents action is very slow.

The fast solution could be written using some scripting. Actions:

Run Shell Script (set the Pass Input: as arguments) and add the following script:

```<code>for f in "$@"
do
    find "$f" -maxdepth 1 -mindepth 1 -type d -print
done
</code>```

The result is as above, just much-much faster.

Title: Select all folders with Automator

Body:
Add:

Get Folder Contents (this will get all items in the given input folder)

Filter Finder Items

and set Kind is Folder

For testing add Reveal Finder Items at the end. Screenshot:

The result will be the list of folders in the given input folder. This is simple but slow solution. (The Get Folder Contents action is very slow.

The fast solution could be written using some scripting. Actions:

Run Shell Script (set the Pass Input: as arguments) and add the following script:

for f in "$@"
do
    find "$f" -maxdepth 1 -mindepth 1 -type d -print
done

The result is as above, just much-much faster.


问:
Compiling Scss in Webpack
so I was trying to get my webpack config file to create a compiled css file so that later on when I added the webpack-dev-server I would be able to compile both my js and css and put it into a dist folder. I thought this would be simple enough so I had this so far in my webpack.config.js file

```<code>var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: ['./js/app.js', './scss/main.scss'],
  output: {
    filename: 'dist/bundle.js'
  },
  module: {

    rules: [
      /*
      your other rules for JavaScript transpiling go in here
      */
      { // regular css files
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          loader: 'css-loader?importLoaders=',
        }),
      },
      { // sass / scss loader for webpack
        test: /\.(sass|scss)$/,
        loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({ // define where to save the file
      filename: 'dist/[name].bundle.css',
      allChunks: true,
    }),
  ],
};
</code>```

But when running the webpack command I'm getting

```<code>throw new _ValidationError2.default(ajv.errors, name);
</code>```

I'm not sure why but I assumed it was maybe because I was using something outdated so I went searching and well I couldn't find anything that worked.

Oh also I'm on a windows computer and here is my package.json

```<code> {
  "name": "portfolio_site",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "start": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^0.28.7",
    "extract-text-webpack-plugin": "^3.0.2",
    "node-sass": "^4.7.2",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.19.0",
    "webpack": "^3.9.1",
    "webpack-dev-server": "^2.9.5"
  },
  "dependencies": {}
}
</code>```

Thanks in advance I just want to know why it's not working.

答:
in your webpack config you have :

```<code>{ // regular css files
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          loader: 'css-loader?importLoaders=',
        }),
      },
      { // sass / scss loader for webpack
        test: /\.(sass|scss)$/,
        loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
      }
</code>```

Instead it should be :

```<code>{ // regular css files
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: 'css-loader?importLoaders=',
        }),
      },
      { // sass / scss loader for webpack
        test: /\.(sass|scss)$/,
        use: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
      }
</code>```

"loader" has been deprecated.

ref : https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/569

Title: Compiling Scss in Webpack

Body:
so I was trying to get my webpack config file to create a compiled css file so that later on when I added the webpack-dev-server I would be able to compile both my js and css and put it into a dist folder. I thought this would be simple enough so I had this so far in my webpack.config.js file

var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: ['./js/app.js', './scss/main.scss'],
  output: {
    filename: 'dist/bundle.js'
  },
  module: {

    rules: [
      /*
      your other rules for JavaScript transpiling go in here
      */
      { // regular css files
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          loader: 'css-loader?importLoaders=',
        }),
      },
      { // sass / scss loader for webpack
        test: /\.(sass|scss)$/,
        loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({ // define where to save the file
      filename: 'dist/[name].bundle.css',
      allChunks: true,
    }),
  ],
};

But when running the webpack command I'm getting

throw new _ValidationError2.default(ajv.errors, name);

I'm not sure why but I assumed it was maybe because I was using something outdated so I went searching and well I couldn't find anything that worked.

Oh also I'm on a windows computer and here is my package.json

 {
  "name": "portfolio_site",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "start": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^0.28.7",
    "extract-text-webpack-plugin": "^3.0.2",
    "node-sass": "^4.7.2",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.19.0",
    "webpack": "^3.9.1",
    "webpack-dev-server": "^2.9.5"
  },
  "dependencies": {}
}

Thanks in advance I just want to know why it's not working.

Body:
in your webpack config you have :

{ // regular css files
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          loader: 'css-loader?importLoaders=',
        }),
      },
      { // sass / scss loader for webpack
        test: /\.(sass|scss)$/,
        loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
      }

Instead it should be :

{ // regular css files
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: 'css-loader?importLoaders=',
        }),
      },
      { // sass / scss loader for webpack
        test: /\.(sass|scss)$/,
        use: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
      }

"loader" has been deprecated.

ref : https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/569


问:
RCW Finalizer Access Violation
I am using COM interop for creating a managed plugin into an unmanaged application using VS2012/.NET 4.5/Win8.1. All the interop stuff seems to be going ok, but when I close the app I get an MDA exception telling me AV's have happened while Releasing COM objects the RCW's were holding onto during Finalizing.

This is the call stack:

```<code>clr.dll!MdaReportAvOnComRelease::ReportHandledException()  + 0x91 bytes
clr.dll!**SafeRelease_OnException**()  + 0x55 bytes
clr.dll!SafeReleasePreemp()  + 0x312d5f bytes
clr.dll!RCW::ReleaseAllInterfaces()  + 0xf3 bytes
clr.dll!RCW::ReleaseAllInterfacesCallBack()  + 0x4f bytes
clr.dll!RCW::Cleanup()  + 0x24 bytes
clr.dll!RCWCleanupList::ReleaseRCWListRaw()  + 0x16 bytes
clr.dll!RCWCleanupList::ReleaseRCWListInCorrectCtx()  + 0x9c bytes
clr.dll!RCWCleanupList::CleanupAllWrappers()  + 0x2cd1b6 bytes
clr.dll!RCWCache::ReleaseWrappersWorker()  + 0x277 bytes
clr.dll!AppDomain::ReleaseRCWs()  + 0x120cb2 bytes
clr.dll!ReleaseRCWsInCaches()  + 0x3f bytes
clr.dll!InnerCoEEShutDownCOM()  + 0x46 bytes
clr.dll!WKS::GCHeap::**FinalizerThreadStart**()  + 0x229 bytes
clr.dll!Thread::intermediateThreadProc()  + 0x76 bytes
kernel32.dll!BaseThreadInitThunk()  + 0xd bytes
ntdll.dll!RtlUserThreadStart()  + 0x1d bytes
</code>```

My guess is that the Application has already destroyed its COM objects, of which some references were passed to the managed plugin - and the call to the IUnknown::Release the RCW makes makes it go boom.

I can clearly see in the output window (VS) that the app has already started unloading some of it's dll's.

```<code>'TestHost.exe': Unloaded 'C:\Windows\System32\msls31.dll'
'TestHost.exe': Unloaded 'C:\Windows\System32\usp10.dll'
'TestHost.exe': Unloaded 'C:\Windows\System32\riched20.dll'
'TestHost.exe': Unloaded 'C:\Windows\System32\version.dll'
First-chance exception at 0x00000001400cea84 in VST3PluginTestHost.exe: 0xC0000005: Access violation reading location 0xffffffffffffffff.
First-chance exception at 0x00000001400cea84 in VST3PluginTestHost.exe: 0xC0000005: Access violation reading location 0xffffffffffffffff.
Managed Debugging Assistant 'ReportAvOnComRelease' has detected a problem in 'C:\Program Files\Steinberg\VST3PluginTestHost\VST3PluginTestHost.exe'.
Additional Information: An exception was caught but handled while releasing a COM interface pointer through Marshal.Release or Marshal.ReleaseComObject or implicitly after the corresponding RuntimeCallableWrapper was garbage collected. This is the result of a user refcount error or other problem with a COM object's Release. Make sure refcounts are managed properly.  The COM interface pointer's original vtable pointer was 0x406975a8. While these types of exceptions are caught by the CLR, they can still lead to corruption and data loss so if possible the issue causing the exception should be addressed
</code>```

So I though I would manage the lifetime my self and wrote a ComReference class that calls Marshal.ReleaseComObject. That did not work correctly and after reading up on it I have to agree that calling Marshal.ReleaseComObject in a scenrario where references are passed around freely, is not a good idea.
Marshal.ReleaseComObject Considered Dangerous

So the question is: Is there a way to manage this situation in order not to cause AV's when exiting the host application?

答:
This is a problem with the native COM reference counts. Your object is being Release()d from native code with refcount=1, it is destroyed, then the CLR comes along and tries Release() it. You need to track down where the reference count is going wrong. It crashes in the CLR because it runs cleanup after the native code is finished.

First step is to track down the type of object that isn't being counted properly. I did this by running gflags.exe against my .exe file and turn on "User mode stack traces". "Full page heap" may help also.

Run the application in windbg. Run .symfix. Run bp clr!SafeReleasePreemp "r rcx; gc"; g to log the interface pointers. When it crashes, the previous log entry should contain the interface pointer that was already destroyed. Run !heap -p -a [address of COM pointer] and it will print the stack of where it was released.

If you're unlucky, it won't crash right away, and the interface pointer that is causing problems won't be the most recent log. If you can run your native COM under the Debug configuration, it may help.

MS made the RCW header available. The members m_pIdentity (offset 0x88 on x64) and m_aInterfaceEntries (offset 0x8 on x64) are of interest. The RCW is in @rdx on entry to SafeReleasePreemp

Next step is to rerun with breakpoints on Interface::AddRef, Interface::QueryInterface, and Interface::Release to see which one is mismatched. _ATL_DEBUG_INTERFACES may help if you're using ATL.

Title: RCW Finalizer Access Violation

Body:
I am using COM interop for creating a managed plugin into an unmanaged application using VS2012/.NET 4.5/Win8.1. All the interop stuff seems to be going ok, but when I close the app I get an MDA exception telling me AV's have happened while Releasing COM objects the RCW's were holding onto during Finalizing.

This is the call stack:

clr.dll!MdaReportAvOnComRelease::ReportHandledException()  + 0x91 bytes
clr.dll!**SafeRelease_OnException**()  + 0x55 bytes
clr.dll!SafeReleasePreemp()  + 0x312d5f bytes
clr.dll!RCW::ReleaseAllInterfaces()  + 0xf3 bytes
clr.dll!RCW::ReleaseAllInterfacesCallBack()  + 0x4f bytes
clr.dll!RCW::Cleanup()  + 0x24 bytes
clr.dll!RCWCleanupList::ReleaseRCWListRaw()  + 0x16 bytes
clr.dll!RCWCleanupList::ReleaseRCWListInCorrectCtx()  + 0x9c bytes
clr.dll!RCWCleanupList::CleanupAllWrappers()  + 0x2cd1b6 bytes
clr.dll!RCWCache::ReleaseWrappersWorker()  + 0x277 bytes
clr.dll!AppDomain::ReleaseRCWs()  + 0x120cb2 bytes
clr.dll!ReleaseRCWsInCaches()  + 0x3f bytes
clr.dll!InnerCoEEShutDownCOM()  + 0x46 bytes
clr.dll!WKS::GCHeap::**FinalizerThreadStart**()  + 0x229 bytes
clr.dll!Thread::intermediateThreadProc()  + 0x76 bytes
kernel32.dll!BaseThreadInitThunk()  + 0xd bytes
ntdll.dll!RtlUserThreadStart()  + 0x1d bytes

My guess is that the Application has already destroyed its COM objects, of which some references were passed to the managed plugin - and the call to the IUnknown::Release the RCW makes makes it go boom.

I can clearly see in the output window (VS) that the app has already started unloading some of it's dll's.

'TestHost.exe': Unloaded 'C:\Windows\System32\msls31.dll'
'TestHost.exe': Unloaded 'C:\Windows\System32\usp10.dll'
'TestHost.exe': Unloaded 'C:\Windows\System32\riched20.dll'
'TestHost.exe': Unloaded 'C:\Windows\System32\version.dll'
First-chance exception at 0x00000001400cea84 in VST3PluginTestHost.exe: 0xC0000005: Access violation reading location 0xffffffffffffffff.
First-chance exception at 0x00000001400cea84 in VST3PluginTestHost.exe: 0xC0000005: Access violation reading location 0xffffffffffffffff.
Managed Debugging Assistant 'ReportAvOnComRelease' has detected a problem in 'C:\Program Files\Steinberg\VST3PluginTestHost\VST3PluginTestHost.exe'.
Additional Information: An exception was caught but handled while releasing a COM interface pointer through Marshal.Release or Marshal.ReleaseComObject or implicitly after the corresponding RuntimeCallableWrapper was garbage collected. This is the result of a user refcount error or other problem with a COM object's Release. Make sure refcounts are managed properly.  The COM interface pointer's original vtable pointer was 0x406975a8. While these types of exceptions are caught by the CLR, they can still lead to corruption and data loss so if possible the issue causing the exception should be addressed

So I though I would manage the lifetime my self and wrote a ComReference class that calls Marshal.ReleaseComObject. That did not work correctly and after reading up on it I have to agree that calling Marshal.ReleaseComObject in a scenrario where references are passed around freely, is not a good idea.
Marshal.ReleaseComObject Considered Dangerous

So the question is: Is there a way to manage this situation in order not to cause AV's when exiting the host application?


问:
How to create trigger when Insert and update table for checking if the inserted values respect case?
I want to create trigger to check if a value like age is up to 18 when insert and update table but I don't know syntax, if someone can give me the syntax or reference to great course, I will be appreciated!</p>

答:
If the requirement is to CHECK and allow only ages > 18 into the table. You can use CHECK Constraints.

Eg:

```<code>CREATE TABLE People(NAME VARCHAR(100),AGE TINYINT,CHECK (AGE>18))
</code>```

Success:

```<code>INSERT INTO People
SELECT 'A',20
</code>```

Failure:

```<code>INSERT INTO People
SELECT 'A',17
</code>```

Msg 547, Level 16, State 0, Line 2 The INSERT statement conflicted
  with the CHECK constraint "CK__People__AGE..". The conflict occurred
  in database "GraphExample", table "dbo.People", column 'AGE'.

Body:
If the requirement is to CHECK and allow only ages > 18 into the table. You can use CHECK Constraints.

Eg:

CREATE TABLE People(NAME VARCHAR(100),AGE TINYINT,CHECK (AGE>18))

Success:

INSERT INTO People
SELECT 'A',20

Failure:

INSERT INTO People
SELECT 'A',17

Msg 547, Level 16, State 0, Line 2 The INSERT statement conflicted
  with the CHECK constraint "CK__People__AGE..". The conflict occurred
  in database "GraphExample", table "dbo.People", column 'AGE'.


问:
Pandas rank method dense but skip a number
I have a sample data set that i'm trying to rank based on the values in the column 'HP':

```<code>import pandas as pd

d = {
 'unit': ['UD', 'UD', 'UD' ,'UC','UC', 'UC','UA','UA','UA','UB','UB','UB'],
 'N-D': [ 'C1', 'C2', 'C3','Q1', 'Q2', 'Q3','D1','D2','D3','E1','E2','E3'],
 'HP': [24, 24, 24,7,7,7,7,7,7,5,5,5]
}
df = pd.DataFrame(d)

df['rank']=df['HP'].rank(ascending=False, method='dense')

df
</code>```

it looks like:

```<code>    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   3.0
10   5  E2   UB   3.0
11   5  E3   UB   3.0
</code>```

the 'HP' is a calculated column based on other columns (i won't show it here, but it's necessary in my real dataset)

I also tried the method='min' but the outcome looks like this:

```<code>    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   4.0
4    7  Q2   UC   4.0
5    7  Q3   UC   4.0
6    7  D1   UA   4.0
7    7  D2   UA   4.0
8    7  D3   UA   4.0
9    5  E1   UB  10.0
10   5  E2   UB  10.0
11   5  E3   UB  10.0
</code>```

Units 'UC' and 'UA' tie for 2nd rank, what i'm looking for is to have the next rank which is unit 'UB' to be '4' instead of '3'. :

```<code>    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   4.0
10   5  E2   UB   4.0
11   5  E3   UB   4.0
</code>```

答:
One option would be to calculate the ranks by dropping the duplicates first:

```<code>temp = df[['HP', 'unit']].drop_duplicates()
temp.assign(rank=temp['HP'].rank(method='min', ascending=False)).merge(df)
Out[48]:
    HP unit  rank N-D
0   24   UD   1.0  C1
1   24   UD   1.0  C2
2   24   UD   1.0  C3
3    7   UC   2.0  Q1
4    7   UC   2.0  Q2
5    7   UC   2.0  Q3
6    7   UA   2.0  D1
7    7   UA   2.0  D2
8    7   UA   2.0  D3
9    5   UB   4.0  E1
10   5   UB   4.0  E2
11   5   UB   4.0  E3
</code>```

Added (antonvbr) a slight modification to assign directly:

```<code>df['rank']= (df[['HP', 'unit']].drop_duplicates()['HP']
            .rank(method='min', ascending=False)
            .reindex(range(len(df)),method='pad'))
</code>```

Body:
I have a sample data set that i'm trying to rank based on the values in the column 'HP':

import pandas as pd

d = {
 'unit': ['UD', 'UD', 'UD' ,'UC','UC', 'UC','UA','UA','UA','UB','UB','UB'],
 'N-D': [ 'C1', 'C2', 'C3','Q1', 'Q2', 'Q3','D1','D2','D3','E1','E2','E3'],
 'HP': [24, 24, 24,7,7,7,7,7,7,5,5,5]
}
df = pd.DataFrame(d)

df['rank']=df['HP'].rank(ascending=False, method='dense')

df

it looks like:

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   3.0
10   5  E2   UB   3.0
11   5  E3   UB   3.0

the 'HP' is a calculated column based on other columns (i won't show it here, but it's necessary in my real dataset)

I also tried the method='min' but the outcome looks like this:

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   4.0
4    7  Q2   UC   4.0
5    7  Q3   UC   4.0
6    7  D1   UA   4.0
7    7  D2   UA   4.0
8    7  D3   UA   4.0
9    5  E1   UB  10.0
10   5  E2   UB  10.0
11   5  E3   UB  10.0

Units 'UC' and 'UA' tie for 2nd rank, what i'm looking for is to have the next rank which is unit 'UB' to be '4' instead of '3'. :

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   4.0
10   5  E2   UB   4.0
11   5  E3   UB   4.0

Body:
One option would be to calculate the ranks by dropping the duplicates first:

temp = df[['HP', 'unit']].drop_duplicates()
temp.assign(rank=temp['HP'].rank(method='min', ascending=False)).merge(df)
Out[48]:
    HP unit  rank N-D
0   24   UD   1.0  C1
1   24   UD   1.0  C2
2   24   UD   1.0  C3
3    7   UC   2.0  Q1
4    7   UC   2.0  Q2
5    7   UC   2.0  Q3
6    7   UA   2.0  D1
7    7   UA   2.0  D2
8    7   UA   2.0  D3
9    5   UB   4.0  E1
10   5   UB   4.0  E2
11   5   UB   4.0  E3

Added (antonvbr) a slight modification to assign directly:

df['rank']= (df[['HP', 'unit']].drop_duplicates()['HP']
            .rank(method='min', ascending=False)
            .reindex(range(len(df)),method='pad'))


问:
What's an example of an NSString for which -UTF8String returns NULL?
I see crash reports from which I can infer that -UTF8String returns NULL, but I haven't found any string which does so. Can anyone provide an example of a string that, at least for some OS version greater than or equal to 9.0, returns NULL for -UTF8String? It would be nice for unit tests, etc.</p>

答:
Here's an example of a high surrogate without a low surrogate that does it.</p>

```<code>unichar c = 0xd800;
NSString *s = [[NSString alloc] initWithCharacters:&c length:1];
assert(s.UTF8String == NULL);
</code>```

Body:
Here's an example of a high surrogate without a low surrogate that does it.

unichar c = 0xd800;
NSString *s = [[NSString alloc] initWithCharacters:&c length:1];
assert(s.UTF8String == NULL);


问:
curl no url specified // Text to Speech IBM Bluemix
I start using Text to Speech with curl and i'm in trouble. I copy the code from the exemple in the command line with my credentials but there is an error i can't solve : curl : no URL specified!

Here is the code i try :

```<code>curl -X POST -u {username}:{password} \
--header "Content-Type: application/json" \
--header "Accept: audio/wav" \
--data "{\"text\":\"hello world\"}" \
--output hello_world.wav \
"https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize"
</code>```

Here the code in the command line (win10) :

Curl in command line no url specified

Can i have any help please ? :)

答: You left no space in between the (unnecessarily quoted) URL and the value of the --output switch.

Body:
I start using Text to Speech with curl and i'm in trouble. I copy the code from the exemple in the command line with my credentials but there is an error i can't solve : curl : no URL specified!

Here is the code i try :

curl -X POST -u {username}:{password} \
--header "Content-Type: application/json" \
--header "Accept: audio/wav" \
--data "{\"text\":\"hello world\"}" \
--output hello_world.wav \
"https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize"

Here the code in the command line (win10) :

Curl in command line no url specified

Can i have any help please ? :)


问:
Submit an HTML form with empty checkboxes
I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.

However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.

How can I get around this? Thanks.

答:
Unchecked radio or checkbox elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.

```<code>if (isset($_POST['checkbox'])) {
    // checkbox has been checked
}
</code>```

OwnerDisplayName: Tray

LastEditorDisplayName: fmsf

Body:
Unchecked radio or checkbox elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.

if (isset($_POST['checkbox'])) {
    // checkbox has been checked
}

OwnerDisplayName: Gumbo


问:
Registering a COM server to have admin privileges
I have an application that relies on a COM server.

```<code>string exePath = "path\\to\\exe.exe";

string regString = String.Format("SOFTWARE\\Classes\\CLSID\\{{{0}}}\\LocalServer32", someGuid);

var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(regString);

key.SetValue(null, exePath);
</code>```

However, when the exe is fired by the com server, the exe does not have admin privileges, and therefore cannot do things like silent install an msi, create a text file in the ProgramFiles directory, etc.

How can I configure my com server to have admin privileges?

答:
In order to accomplish this, you need to use the COM Elevation Moniker.

https://msdn.microsoft.com/en-us/library/ms679687(VS.85).aspx

Body:
I have an application that relies on a COM server.

string exePath = "path\\to\\exe.exe";

string regString = String.Format("SOFTWARE\\Classes\\CLSID\\{{{0}}}\\LocalServer32", someGuid);

var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(regString);

key.SetValue(null, exePath);

However, when the exe is fired by the com server, the exe does not have admin privileges, and therefore cannot do things like silent install an msi, create a text file in the ProgramFiles directory, etc.

How can I configure my com server to have admin privileges?


问:
Change function of the pgdown key
Is there a way to change the function of the pgdown key so that, when users are on your site, pressing pgdown takes the user to a particular anchor on the page?</p>

答:
You can do it with JS like this:

```<code>window.addEventListener("keydown", function(e){
    if (e.which === 40) {
        window.location.href = "#" + ancohr;
    }
})
</code>```

Adding the event listener to the window will catch any keydown event, 40 is arrow down key code, then you send the client where you want with adding the anchor to the current root location.

Title: Change function of the pgdown key

Body:
You can do it with JS like this:

window.addEventListener("keydown", function(e){
    if (e.which === 40) {
        window.location.href = "#" + ancohr;
    }
})

Adding the event listener to the window will catch any keydown event, 40 is arrow down key code, then you send the client where you want with adding the anchor to the current root location.


问:
How do I get inputs from a user and find the highest, lowest, and average of them?
I am in the process of writing code that asks the user for their name, how many jobs they have, and the income of those jobs. Then the code finds the highest and lowest paying incomes, and the average of the jobs they entered.

Im having issues with the highest and lowest paying portion, along with finding the average, while still maintaining what the user entered in order to recite it later.

Ex:
Inputs: 10000  30000  50000
"Hello Audrey. You have had 3 jobs. The highest paying job paid $50000. The lowest paying job paid $10000. The average pay for the jobs entered is $30000

**** heres the code I have edited, but it is not running properly. I believe it has to do with int and double. Im not sure which code should be double and which ones should be int.****

```<code>import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class JobIncome {

public static void main(String[] args) throws FileNotFoundException {

Scanner input = new Scanner (System.in);
System.out.println("What is your first name? ");
String firstName = input.nextLine();

Scanner scan = new Scanner (System.in);
System.out.println("How many jobs have you had? ");
int jobNum = scan.nextInt();

//Declarations
int total = 0;
int average = 0;

//for loop asks for the incomes of the user's previous
//jobs and stores them into an array
int arrayOfIncomes[] = new int[jobNum];
for(int i = 1; i <= arrayOfIncomes.length; i++){
    System.out.println("Enter the income of job #" + i + " : ");
    arrayOfIncomes[i] = scan.nextInt();
    total = total + arrayOfIncomes[i];
}

average = total/jobNum;

//Start of the code that will find the min and max
int min = arrayOfIncomes[0];
int max = arrayOfIncomes[0];

for (int i = 1; i < arrayOfIncomes.length; i++) {
    if (arrayOfIncomes[i] > max) {
        max = arrayOfIncomes[i];
    }
}

for (int i = 1; i < arrayOfIncomes.length; i++) {
    if (arrayOfIncomes[i] < min) {
        min = arrayOfIncomes[i];
    }
}

//Print statement that gives the user all their information
System.out.println("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");

//Prompt asking the user if they would like to print their info into a text file
System.out.println("Would you like to output your information into a text file, yes or no? ");
String yesNo = input.nextLine();
if(yesNo.equals("yes")){
    System.out.println("");
} else {
    System.out.println("Goodbye.");
}

//Output code
Scanner console = new Scanner(System.in);
System.out.print("Your output file: ");
String outputFileName = console.next();
PrintWriter out = new PrintWriter(outputFileName);

//This code prints the information into the output text file
out.print("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");

out.close();
}
</code>```

答:
Create an int variable sum. Add the sum as you get input from the user then divide the sum with the variable jobNum while casting at least one variable to double.

Example:

```<code>double ave = (double) sum / jobNum;
</code>```

Body:
I am in the process of writing code that asks the user for their name, how many jobs they have, and the income of those jobs. Then the code finds the highest and lowest paying incomes, and the average of the jobs they entered.

Im having issues with the highest and lowest paying portion, along with finding the average, while still maintaining what the user entered in order to recite it later.

Ex:
Inputs: 10000  30000  50000
"Hello Audrey. You have had 3 jobs. The highest paying job paid $50000. The lowest paying job paid $10000. The average pay for the jobs entered is $30000

**** heres the code I have edited, but it is not running properly. I believe it has to do with int and double. Im not sure which code should be double and which ones should be int.****

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class JobIncome {

public static void main(String[] args) throws FileNotFoundException {

Scanner input = new Scanner (System.in);
System.out.println("What is your first name? ");
String firstName = input.nextLine();

Scanner scan = new Scanner (System.in);
System.out.println("How many jobs have you had? ");
int jobNum = scan.nextInt();

//Declarations
int total = 0;
int average = 0;

//for loop asks for the incomes of the user's previous
//jobs and stores them into an array
int arrayOfIncomes[] = new int[jobNum];
for(int i = 1; i <= arrayOfIncomes.length; i++){
    System.out.println("Enter the income of job #" + i + " : ");
    arrayOfIncomes[i] = scan.nextInt();
    total = total + arrayOfIncomes[i];
}

average = total/jobNum;

//Start of the code that will find the min and max
int min = arrayOfIncomes[0];
int max = arrayOfIncomes[0];

for (int i = 1; i < arrayOfIncomes.length; i++) {
    if (arrayOfIncomes[i] > max) {
        max = arrayOfIncomes[i];
    }
}

for (int i = 1; i < arrayOfIncomes.length; i++) {
    if (arrayOfIncomes[i] < min) {
        min = arrayOfIncomes[i];
    }
}

//Print statement that gives the user all their information
System.out.println("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");

//Prompt asking the user if they would like to print their info into a text file
System.out.println("Would you like to output your information into a text file, yes or no? ");
String yesNo = input.nextLine();
if(yesNo.equals("yes")){
    System.out.println("");
} else {
    System.out.println("Goodbye.");
}

//Output code
Scanner console = new Scanner(System.in);
System.out.print("Your output file: ");
String outputFileName = console.next();
PrintWriter out = new PrintWriter(outputFileName);

//This code prints the information into the output text file
out.print("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");

out.close();
}

Body:
Create an int variable sum. Add the sum as you get input from the user then divide the sum with the variable jobNum while casting at least one variable to double.

Example:

double ave = (double) sum / jobNum;


问:
Openlayers 3: Select a feature programmatically
I am trying to upgrade my system from Openlayers 2 to Openlayers 3 and I have having one particular issue that I cannot seem to figure out.

My application has a grid and a map and when a user clicks on the grid I want to select the relevant point on the map.

In Openlayers 2 I used the following:

```<code>self.selectControl.select(feature[0]);
</code>```

I cannot find or understand how to do the same in Openlayers 3.

So to be clear, I have a feature which I have found programmatically and I want to select that feature on a map (programmatically)!

I cannot seem to find anything in the APIs but that might be due to my lack of understanding as I am new to Openlayers.

答:
```<code>var selectInteraction = new ol.interaction.Select(});
map.addInteraction(selectInteraction);

function highlightFeature(feat){
   selectInteraction.getFeatures().push(feat);
   selectInteraction.dispatchEvent({
      type: 'select',
      selected: [feat],
      deselected: []
   });
}
</code>```

works like a char on latest openlayers 4.5

Body:
I am trying to upgrade my system from Openlayers 2 to Openlayers 3 and I have having one particular issue that I cannot seem to figure out.

My application has a grid and a map and when a user clicks on the grid I want to select the relevant point on the map.

In Openlayers 2 I used the following:

self.selectControl.select(feature[0]);

I cannot find or understand how to do the same in Openlayers 3.

So to be clear, I have a feature which I have found programmatically and I want to select that feature on a map (programmatically)!

I cannot seem to find anything in the APIs but that might be due to my lack of understanding as I am new to Openlayers.

Body:
var selectInteraction = new ol.interaction.Select(});
map.addInteraction(selectInteraction);

function highlightFeature(feat){
   selectInteraction.getFeatures().push(feat);
   selectInteraction.dispatchEvent({
      type: 'select',
      selected: [feat],
      deselected: []
   });
}

works like a char on latest openlayers 4.5


问:
Integrating Twilio-js in Angular.js?
Can anyone please guide me how do I integrate/require twilio.js file in the my application? I have to do it with angular.js app. I can't require/include it and can't get the Twilio object to call it's methods. I'm really new to it!

By just adding following script tag do not makes me able to use Twilio object:

```<code><script type="text/javascript" src="//media.twiliocdn.com/sdk/js/client/v1.4/twilio.js"></script>
</code>```

Results:

Update:

As per @philnash help I've resolved the previous error and now this is how my code looks like is:

```<code><script type="text/javascript" src="//media.twiliocdn.com/sdk/js/client/v1.4/twilio.js"></script>
<script>
Twilio.Device.setup(@token, { debug: true, region: "ie1" });
Twilio.Device.ready(function(device) {
    // The device is now ready
    alert("Twilio.Device is now ready for connections");
});
</script>
</code>```

But I'm getting the below error:

Any help will be appreciated!

答:
Twilio developer evangelist here.

When using the Twilio Client JavaScript, there is no Twilio.setup function.

Instead, you should use Twilio.Device.setup.

Let me know if that helps at all.

Title: Integrating Twilio-js in Angular.js?

Body:
Can anyone please guide me how do I integrate/require twilio.js file in the my application? I have to do it with angular.js app. I can't require/include it and can't get the Twilio object to call it's methods. I'm really new to it!

By just adding following script tag do not makes me able to use Twilio object:

Results:

Update:

As per @philnash help I've resolved the previous error and now this is how my code looks like is:

But I'm getting the below error:

Any help will be appreciated!


问:
Edit JavaScript blocks of web page... live
I know you can use Firebug in the DOM view to edit JavaScript variables BUT... is there a way I can use (anything else) to edit live JavaScript that is embedded in a HTML page?

Like this kind that is in a .html page:

```<code><script type="text/javascript>
// code here
</script>
</code>```

Thanks.

答: Eloquent javascript has a console type window in the bottom (click the small arrow on the bottom right side). This might be what you're looking for. The exact term for what you means is an REPL, a Read-Evaluate-Print loop.</p>

Body:
I know you can use Firebug in the DOM view to edit JavaScript variables BUT... is there a way I can use (anything else) to edit live JavaScript that is embedded in a HTML page?

Like this kind that is in a .html page:

Thanks.


问:
Provide arguments with a method
Is there a way in Java to create a method that would return the list of parameters of another method such that I am able to call

```<code>anotherMethod(method())
</code>```

where anotherMethod has arbitrary arguments like

```<code>public void anotherMethod(int a, int b, String c)
</code>```

And what is if the types stay the same, like with

```<code>public int add(int a, int b, int c)
</code>```

If there is no such way, how could I model the list of parameters such that it would work? Is it a List or an array or something else?

答:
If the number of parameters is fixed at the call site, you could use varargs

```<code>int add(int... numbers)
</code>```

otherwise you'd use an array or collection

```<code>int add(int[] numbers)
</code>```

You can then of course have another method provide the value of these parameters:

```<code>add(someOtherMethod())
</code>```

Title: Provide arguments with a method

Body:
Is there a way in Java to create a method that would return the list of parameters of another method such that I am able to call

anotherMethod(method())

where anotherMethod has arbitrary arguments like

public void anotherMethod(int a, int b, String c)

And what is if the types stay the same, like with

public int add(int a, int b, int c)

If there is no such way, how could I model the list of parameters such that it would work? Is it a List or an array or something else?

Body:
If the number of parameters is fixed at the call site, you could use varargs

int add(int... numbers)

otherwise you'd use an array or collection

int add(int[] numbers)

You can then of course have another method provide the value of these parameters:

add(someOtherMethod())