ActiveMQ-Core 5.7.0 API causes "The lifecycle method [start] must not throw a checked exception"

Question: I have a EJB module, it use ActiveMQ-Core 5.7.0 as its dependency. When I deploy EJB Module alone to Glassfish server 4.1, it can be deployed successfully. But when I include this EJB module in an Enterprise Application and deploy this EAR to server, it throws error:
<code>[glassfish 4.1] [SEVERE] [] [javax.enterprise.system.core] [tid: _ThreadID=48 _ThreadName=admin-listener(4)] [timeMillis: 1460086777462] [levelValue: 1000] [[
  Exception while deploying the app [ATM.One-Ear-1.0] : The lifecycle method [start] must not throw a checked exception. Related annotation information: annotation [@javax.annotation.PostConstruct()] on annotated element [public void org.apache.activemq.broker.util.CommandAgent.start() throws java.lang.Exception] of type [METHOD]
The lifecycle method [start] must not throw a checked exception. Related annotation information: annotation [@javax.annotation.PostConstruct()] on annotated element [public void org.apache.activemq.broker.util.CommandAgent.start() throws java.lang.Exception] of type [METHOD]
    at org.glassfish.apf.impl.AnnotationProcessorImpl.process(AnnotationProcessorImpl.java:367)
    at org.glassfish.apf.impl.AnnotationProcessorImpl.process(AnnotationProcessorImpl.java:375)
    at org.glassfish.apf.impl.AnnotationProcessorImpl.processAnnotations(AnnotationProcessorImpl.java:289)
    at org.glassfish.apf.impl.AnnotationProcessorImpl.process(AnnotationProcessorImpl.java:217)
    at org.glassfish.apf.impl.AnnotationProcessorImpl.process(AnnotationProcessorImpl.java:134)
    at com.sun.enterprise.deployment.archivist.Archivist.processAnnotations(Archivist.java:626)
    at com.sun.enterprise.deployment.archivist.Archivist.readAnnotations(Archivist.java:462)
    at com.sun.enterprise.deployment.archivist.Archivist.readAnnotations(Archivist.java:446)
    at com.sun.enterprise.deployment.archivist.Archivist.readRestDeploymentDescriptors(Archivist.java:419)
    at com.sun.enterprise.deployment.archivist.Archivist.readDeploymentDescriptors(Archivist.java:396)
    at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:271)
    at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:280)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.readModulesDescriptors(ApplicationArchivist.java:611)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.openWith(ApplicationArchivist.java:229)
    at com.sun.enterprise.deployment.archivist.ApplicationFactory.openWith(ApplicationFactory.java:232)
    at org.glassfish.javaee.core.deployment.DolProvider.processDOL(DolProvider.java:193)
    at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:227)
    at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:96)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.loadDeployer(ApplicationLifecycle.java:881)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.setupContainerInfos(ApplicationLifecycle.java:821)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:377)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at org.glassfish.admin.rest.utils.ResourceUtil.runCommand(ResourceUtil.java:253)
    at org.glassfish.admin.rest.utils.ResourceUtil.runCommand(ResourceUtil.java:231)
    at org.glassfish.admin.rest.utils.ResourceUtil.runCommand(ResourceUtil.java:275)
    at org.glassfish.admin.rest.resources.TemplateListOfResource.createResource(TemplateListOfResource.java:133)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1028)
    at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.service(GrizzlyHttpContainer.java:365)
    at org.glassfish.admin.rest.adapter.RestAdapter$2.service(RestAdapter.java:316)
    at org.glassfish.admin.rest.adapter.RestAdapter.service(RestAdapter.java:179)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.portunif.PUFilter.handleRead(PUFilter.java:231)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.portunif.PUFilter.handleRead(PUFilter.java:231)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: The lifecycle method [start] must not throw a checked exception
    at com.sun.enterprise.deployment.annotation.handlers.AbstractResourceHandler.validateAnnotatedLifecycleMethod(AbstractResourceHandler.java:186)
    at com.sun.enterprise.deployment.annotation.handlers.PostConstructHandler.processAnnotation(PostConstructHandler.java:72)
    at com.sun.enterprise.deployment.annotation.handlers.AbstractResourceHandler.processAnnotation(AbstractResourceHandler.java:142)
    at com.sun.enterprise.deployment.annotation.factory.SJSASFactory$LazyAnnotationHandler.processAnnotation(SJSASFactory.java:148)
    at org.glassfish.apf.impl.AnnotationProcessorImpl.process(AnnotationProcessorImpl.java:344)
    ... 97 more
</code>
I found that the ActiveMQ-Core source code is
<code>@PostConstruct
public void start() throws Exception

@PreDestroy
public void stop() throws Exception
</code>
So, how can I fix this error. Any help would be greatly appreciated. Thanks!
Answer: remove throws Exception
and add try catch hope this will help
Comment: This is not a real solution for the problem.
Comment: try this=== https://github.com/mitreid-connect/OpenID-Connect-Java-Spring-Server/commit/88db457fc4ec1a9c8a4a8c187182466e47ae7be9


Finite measure of uncountably many disjoint sets implies at least one of them has measure zero?

Question: Given a probability space $(\Omega,\mathcal{F}, P).$  Suppose $\mathcal{A}$is a subclass of $\mathcal{F}$. Let $\mathcal{A}_{x,\epsilon}$ be the class of $\mathcal{A}-$sets satisfying $x\in A^{\circ}\subset A\subset B(x,\epsilon)$ and let $\partial \mathcal{A}_{x,\epsilon}$ be the class of their boundaries.
Claim: If $\partial\mathcal{A}_{x,\epsilon}$ contains uncountably many disjoint sets, then at least one of them mush have $P-$ measure zero.
This is in section 2 from the book " convergence of probability measures(Billingsley)".
I think  to proof this claim, we may need Borel-Cantelli lemma, but Borel-Cantelli lemma is for countably many sets.
Denote the metric on $\Omega$ by $\rho(x,y)$.
Since for any $A\in\mathcal{A}_{x,\epsilon}$, $x\in A^{\circ}\subset A\subset B(x,\epsilon)$,
then $\partial A\subset \partial B(x,\epsilon)\subset \{y:\rho(x,y)=\epsilon\}$.
Therefore $\cup_{A\in\partial\mathcal{A}_{x,\epsilon}} A\subset \{y:\rho(x,y)=\epsilon\}$. Thus
$P(\cup_{A\in\partial\mathcal{A}_{x,\epsilon}} A) \leq P(\{y:\rho(x,y)=\epsilon\})<\infty$
But then how can I get the conclusion?
Any help will be appreciated. Thanks
Comment: Yes, but the sets in the boundary of $\mathcal{A}_{x,\epsilon}$ may have a chance to be disjoint
Comment: Well, that was written when the $\partial$ was missing from the Claim.
Answer: You don't need anything fancy like Borel-Cantelli. Just the axioms of measure theory. In fact, a more general result is true, in your same probability space:

For any uncountable collection $\mathcal A\subset \mathcal F$ of disjoint subsets of $\Omega$, at most countably many elements of $\mathcal A$ have nonzero measure.

Proof: For any $n\in \mathbb N$, let $\mathcal A_n=\{A\in \mathcal A\mid P(A)>\frac1n\}$. Note that $\mathcal A_n$ has fewer than $n$ elements: if there were $n$ sets $E_1,E_2,\dots,E_n\in \mathcal A_n$, then you would have
$$
P(E_1\cup E_2\cup\dots\cup E_n)=P(E_1)+\dots+P(E_n)>\frac1n+\dots+\frac1n=1,
$$
contradicting that $P$ is a probability measure. Now, let $\mathcal A_0=\{A\in \mathcal A\mid P(A)>0\}$. Note that $\mathcal A_0=\bigcup_{n\ge 1}\mathcal A_n$, so $\mathcal A_0$ is a countable union of finite sets. This implies $\mathcal A_0$ is countable, as claimed.
Comment: This proof is so nice, thanks!


Drag and drop from ScrollView React Native

Question: I want to split the screen in two for a drag and drop list. When I use a View it works fine.
But I have to use ScrollView as second column has multiplay content.
How do I overlay Dropitem from ScrollView to View?
Snack https://snack.expo.io/@sitenative/two-columns-drag
Comment: I haven't looked at your code but my first hunch from looking at the screenshot is that it's a styling issue.  Make sure you don't have overflow=hidden and that the top elements are later in the code, or play with zIndex https://reactnative.dev/docs/layout-props#zindex
Answer: Even if this might not answer your question, I found a kind of solution/workaround for your issue which maybe is useful to you.
I moved the style from the scrollView style prop to contentContainerStyle, and basically used the space that remained from the whole scrollView as the view where the items will be dropped.

<code>  <SafeAreaView style={styles.container}>
                <ScrollView
                    style={{backgroundColor: 'brown'}}
                    scrollEnabled={this.state.scroll}
                    contentContainerStyle={styles.drag}
                    showsVerticalScrollIndicator={false}
                    disableScrollViewPanResponder={true}
                    nestedScrollEnabled={true}
                >
                    {sheet.map((object, i) =>
                        <DragItem
                            key={'top_'+i}
                            color={object.color}
                            first={!i}
                            name={object.name}
                            scrollUpdate={this.scrollUpdate}
                        />
                    )}
                </ScrollView>
            </SafeAreaView></code>


Design ideas for serving up high-frequency data

Question: I want to build something to store and serve up time series data, which is coming in from a variety of sources at different time intervals. this includes both raw data and computed data. for example, let's say I want to log an every-30-seconds temperature reading, and a temperature forecast I'm calculating separately every 5 minutes.
I need to be able to query the data quickly, and I've found a relational database doesn't work well at all once it gets too big. so I was thinking about creating some sort of in-memory thing, but I'm sure it will crash at some point, so I'll need to persist the data to disk. so I was wondering, why not just make the whole thing disk-based, with some sort of caching for commonly requested data?
but I'm a bit clueless on how to go about this. I'm imagining data sources pushing update datasets to the server periodically, using some sort of string key/symbol to identify what the data is. the server gets the data, and then what? write it to some sort of binary file? could I write to one file per symbol? (assume over 100k symbols)
I think what I want is similar to google's BigTable, but on a much smaller scale. basically, a distributed hash table, mapping a string key to a time series of associated data, with very fast retrieval and the ability to retrieve a range query by time. and extra points for multidimensional data.
Oh, and this would (ideally) by a C#/windows project - it's doesn't need to be that high performance.
Answer: I have to tell you that no "file system" approach (that I'm aware of) is going to be any faster than a relational database. And it will probably be a lot worse.
The problem with relational databases is not that they are inherently slow but that placing data into them can be done very easily without regard to how the data are saved. A good index, even for millions of records, should produce sub-second results. It's more a matter of design than a problem of access. If you design it well, access will come.
edit: Also, if by "relational database" you mean Microsoft Access, then you're right; it is slow with lots of records. I would not go that route. Look into MySql if money is an issue or Oracle/Sql Server if money isn't.
Comment: Relational database do sit on top of a file system. Relational database can work for small SCADA systems, but they do not scale well at all. They simply use too much diskspace, and regardless of how good the index is tend to fall over far too soon.
Comment: @grieve Sorry, didn't mean to imply that relational databases were somehow divested of a storage medium. I meant that the mechanisms built into relational databases are better (to my knowledge) than trying to rig-up a similar system via a file-system by oneself. Wasn't aware of the scaling issues.
Comment: @grieve What else would you recommend besides relational databases if scaling is an issue?
Comment: @grieve Ah. Read your answer. Thanks.
Comment: @Michael Todd: No worries. It is actually a very difficult and interesting problem. Probably too much so to be easily answered here, rigging-up our system took three years. Of course we had a lot of constrainsts that bobsmith may not.
Comment: what about hdf5 files if the amount of data every 30sec/1min is quite big?
Answer: Sadly I am forbidden by NDA agreements to tell you how to do this. I worked on the team that created a non-relational database that does exactly what you are trying to do. It is called Citadel. I can however point you to the link for what is publicly available, and it should give you some ideas of how it works.
http://zone.ni.com/devzone/cda/tut/p/id/6579
You could just buy the product, but it is rather expensive.
Also as Karl points out this is generally Used in SCADA products like Wonderware, Lookout, and LabVIEW DSC.
A search for SCADA data storage turns up some interesting reading as well.

As an aside a relational databases can solve this problem if the amount of data is small. What tends to happen over time is that the data grows without bounds, and the relational database gets filled beyond its capacity. A good SCADA data storage system can easily handle 50000 points being polled at once a second. Though at some point even they start to get too large to handle easily.
Answer: I would agree with others that a database would be your best bet.
If you really are generating such a huge amount of data that it would cause a performance problem, you might want to create two tables - one as a "real time" source and another as an "archive".
Your system would insert new data into the real time table, and a batch job would periodically move data from there to the archive table.  When performance is a concern, you would query only the smaller real time table.  If you actually needed to query across all the data, you would query a view that UNIONs the real time and archive tables.
Answer: Sounds like a SCADA (System Control And Data Acquisition) type application, making use of the Data Acquisition part of the system.  Have you looked at off-the-shelf solutions.  Wonderware/IndustrialSQL or some competitor product?
Having said that my present employer (The MetService, New Zealand) logs readings each 30 seconds, 1 minute or 1 hourt from Automatic Weather Stations (temp, rainfall, wind, etc) and forecasts to an Oracle DB.  Minimal indexing; indexes slows down 3 out of 4 DML actions and speeds up Selects  Of course you need the 3 actions to be fast, in particular the Insert.  Fast IO system.  Very fast IO for Redo logs.  We are moving to partitioned tables so that the deletes are faster and generate less redo (drop the tablespace including contents rather than issue a delete)  Serious though given to light, fast transactions for Inserts.  Serious though given to performance of machines performing Inserts and network beteen them and the DB.
Answer: "RRDTool is the OpenSource industry standard, high performance data logging and graphing system for time series data."
It's in two parts, one which logs, stores and retrieves time series data, and a second part for graphing. There are many examples of it's use.
Even if you don't use it, it's design is definitely relevant.
Answer: If you use a database and take out indexing and the relational part you pretty much get what you described. However, I'm not sure how useful it would be. Could you give us a better idea why a database did not work for you? What did you try that didn't work?
Comment: I was using sql server 2005, and it was slow. I had data in the form of (timestamp, key1, key2, key3, data1, data2, data3) where the key was hierarchical. so I would say "give me data1 where key1=x, key2=y, and key3=z, in timestamp range [a,b].
Comment: I had indexes out to key3, but this made the index disk space very large, and made either inserts or deletes slow (don't remember). I guess I could revisit sql server, but it seemed sort of "wrong" to use a database as a data server, instead of just a data store...
Comment: How did you access the database each time? Creating new connections to the database can be slow, that is why most systems use a connection pool, or you can keep the connection alive.
Comment: I would recommend you try to make a small test program that you could share with us and see if we can help make it faster.
Comment: You cannot take out the indexing if you want the queries to be fast. You can of course throw away the relational aspect, since the data is not really relational.
Comment: @grieve
True, not if you want to efficiently get the data out, but it sure helps with the insert part :-)
Comment: @pbz: If he has no real time requirement he could: 1) turn off indexing, 2) insert data, 3) turn on indexing, 4) query. But that doesn't sound like what he wants. :)
Answer: I'm not sure why you're down on a database for this. I've done real-time statistics on tables with 10s of millions of rows. Further, you could batch up the readings periodically to turn hundreds of thousands of rows into hundreds of rows of compiled data--depending on your needs obviously.
As for in-memory persistence and key-value pair access, you may want to look at memcachedb. It's based on memcached and offers excellent performance.
Also, after thinking about it more, you could easily run the thing as a hashtable in memory and then periodically serialize it out to the file system for persistence.
Comment: Oh, yeah. That hash space would be huge.
Comment: The questioner stated that it would be key-value pairs. Given that (and his lack of specifics), I just suggested something that might fit. It may or may not be a good idea once details emerge.
Comment: If you read a bit more closely you can see that he is asking for key-data stream pairs. So the key gets him to the data stream, and then he has to index across the data stream. So it is really going to take more than one data structure to solve.


Function fails to return string

Question: I'm having problems in C with returning a string from this function:
char setup(){

    puts("Please select a size for the string");
    scanf("%d", &size);
    getchar();

    char sequence[size];

    printf("Please write any sequence of %d numbers\n", size);
    fgets(sequence, size+1, stdin);

return *sequence;
}

Size is set as a global variable.
And the main:
int main(){

    int program=0;
    char sequence_alt[size];

    puts("Please select the number of the program to test:");
    scanf("%d", &program);
    getchar();

    switch(program){
    case 1:
        sequence_alt[size]=setup();
        break;

The switch goes on, but nothing else is added on this case. Instead of getting the full string, like 12345 if i choose size 5, i get only the first character.
I've searched for a lot of guides but i still can't understand if the problem is actually in my function, or my main when i print the value of the sequence. Any tip and help would be awesome and i've be forever thankful. Sorry if the code is too rudimentary, but im still taking my first baby steps in learning C.
Thanks!
Comment: `char` means a single character. Your function returns `char`.
Answer: Your function must return a char * (not a single char)
char setup(){
    ...
    return *sequence;
}

should be
char *setup(void){
    ...
    return sequence;
}

char sequence[size];

sequence is a local array, his lifetime ends when the function ends, use dynamic memory:
char *sequence = malloc(size);

Using size+1 in fgets you can write outside the bounds of the array, change
fgets(sequence, size+1, stdin);

to
fgets(sequence, size, stdin);

Comment: Thanks, it worked perfectly! I had no idea char in a function only returns a single char and not the full string. Always learning!
About the size+1, if i dont add that, and i have a size 5 for example, the 5th position will be replaced by the null character, so ill only get space for 4 chars. I think its a setback of fgets.
Comment: You are welcome, if you need 5 characters then you need to reserve space for 6 (one more for the trailing `\0`)
Answer: Like the above answer explained, your function should return char* to get a string (char pointer) back and you should also know whatever you create in a function block disappears when you return from the function. so sequence can only return the first character even if it was char* since there was no memory allocated for a string of that size. The following will work fine
char* setup(){

    puts("Please select a size for the string");
    scanf("%d", &size);
    getchar();

    char *sequence = malloc(sizeof(int) * size);

    printf("Please write any sequence of %d numbers\n", size);
    fgets(sequence, size+1, stdin);

    return sequence;
}

Comment: `sizeof(int) * size`?
Comment: Thanks for the help, it solved my problem!
Comment: sizeof(int) returns 4bytes if 32-bit machine or something else, but you just need 'size' amount of integers so we need size * 4 bytes (or whatever bytes represent an int on the machine)

Function fails to return string


Alternative to SIMILE Timeline for timeline visualization?

Question: So I have been having lots of fun playing with SIMILE Timeline, but unfortunately, it appears to be all but abandoned (most recently closed ticket May 2009) and riddled with memory leaks, especially when you are dynamically loading and unloading events (which is especially true in my case).
I am a novice in JavaScript, so debugging these leaks is going to be more than a little complicated. Before I dive head-first into fixing a problem in a language I don't understand or a codebase I have never looked at, I want to know if there is anything out there that compares to the feature-set that I can get with Timeline:

Multiple events on one band

instead of having 10, 100, 1000 rows of data, use the space available to fit multiple events on one line when possible

Scrollable
CSS styling down to the specific event

I can specify a specific icon, font, etc., for each event if I need to.  This is great for highlighting error events or interesting events

filtering/searching/highlighting
highlighting a band of time or point in time

This would be a vertical band that shows a 'now' moment, or a band that covers a time period's start and end time

I know that alot of these features can probably be put into things such as Flot or HighCharts, but these things were next to free for me to use in Timeline, so I'm weighing the cost/benefit of whether it is easier to fix a memory leak or roll out 3 - 4 features on some library that doesn't have it.  My gut says "fix the leak, it's easier", but I would like to know if anyone can show me something that might be 90% of the way there with a low barrier of entry to getting that other 10%.
Comment: I have also worked with Simile Timeline (see http://innl.nl) and and I found it a nightmare. Almost no documentation and often outdated documentation, outdated/undocumented code, lots of browser bugs. -- It's not just problems with memory leakage. But yes, it's the only open source thing out there and it is extendable.
Comment: I'm glad I ran across this question, I'm just starting with SIMILE timeline and was finding it a huge pain too, I can now predictably crash firefox with it!
Comment: I'm offering a bounty, even though I think timeglider is already a *brilliant* answer to this question, because I have a personal interest in this question and I'd like to see somebody get a nice rep bonus for answering it.
Comment: is Anyone had tried with this widget in HTTPS ??
Comment: Been using it over HTTPS for a few years, no specific issues relating to that I'm aware of.
Comment: look at http://time.graphics
Answer: Maybe you can use the Timeline from the (open source) CHAP Links Library, developed by Almende.
http://almende.github.com/chap-links-library/timeline.html
Have a look at the examples to see what you can do with the Timeline. It is quite flexible, you can choose your create your own layout and use your own CSS/HTML in each individual event.
Comment: +1 for an excellent link, I would +2 if I could! Anyone looking for a JavaScript timeline should consider this. I've worked with Simile and Timeglider before and always found that I was having to battle with some of the code. Timeline on the other hand appears to be very comprehensive. If you have used it, what were your experiences with it?
Comment: CHAP Links Library now has a successor: [vis.js](http://visjs.org/). Consider using that instead.
Comment: This should be the accepted answer, can't believe people pay money to Timeglider when this one is available for free.
Comment: +1 Looks great .. definitely going to consider it as a Simile replacement
Comment: If you can use the same e-mail / openid on both accounts, we'll be happy to merge.
Comment: What an amazing perfect library indeed.
light weight and fully customizable.
+1 for this link
Comment: +1 - this is by far the best solution yet, which also works in IE8! The successor http://visjs.org/ is also great, but does not work in IE8.
Comment: Why is this not at the top?! I am flabbergasted, as it's perfect for the question.
Answer: Check out Timeglider (see http://timeglider.com/jquery/) which is an open source (MIT), JavaScript (uses jQuery) scrolling timeline under active development.  It meets your first 4 requirements I believe but I am unclear about the specifics of your 5th requirement.  I have only done some simple experiments with Timeglider and don't know it very well but maybe this is a potential solution for you.
Comment: It's no longer under MIT licence unfortunately.
Comment: Not my question, but I gave you an upvote.  Thanks for the simile alternative!
Comment: That is unfortunate.  Not much consolation, but I believe versions prior to the license change ([here and earlier](https://github.com/timeglider/jquery_widget/tree/345442fa3dc7c66b23c36031a6569693ecf309bd)) remain MIT licensed.
Comment: The 5th requirement can be seen in that picture above with the orange band.  I've more-or-less used it to highlight a small 10px band that says "this is the current time", and then every minute or so, I move the band and the highlight to the new time.  It recenters, too.

That being said, this seems pretty awesome, and I would rather give up that feature if it meant a snappy doesn't-crash-your-browser experience.  I'll definitely have to give this a go.
Comment: look at http://time.graphics its better
Answer: We needed the Simile Timeline at Lab 21k so we took the source code, cleaned it up and published it using bower. So you don't need an alternative anymore.
https://github.com/Lab21k/standalone-timeline/
Answer: The Timeline project is very much alive, they just don't use Google Code anymore. The Simile widgets are now hosted on a dedicated homepage, here is the homepage and documentation of Timeline. Keep in mind that the links on the page are not consistent, many pages still link to the outdated wikis on Google Code and the mit.edu wiki pages. Keep that in mind when checking the wiki.
There is also an active mailing list on Google Groups.
Comment: From the Simile tag wiki itself: "As of Spring 2012, Exhibit is the only Simile widget seeing active development." So, the TimeLine control has not been updated since 2009.
Comment: I was just looking at this the other day. Those recent commits are for the other SIMILE widgets, not the timeline one.
Comment: Where's the source code hosted?  Google Code shows the last commit sometime in mid-2009, so if they have a new repo, then maybe the issues I had before (memory leaks, somewhat kludgy API) would be fixed...
Comment: In looking at their new site, it doesn't appear that they are using GoogleCode for **documentation**, but they still link to their downloads and examples on googlecode.com, so I think my original statement (Timeline's code hasn't been updated since 2009) still holds true.
Comment: It looks like they're updating their code again - most recent closed issue was July 2011, most recent [change](http://code.google.com/p/simile-widgets/source/list) September 7 2011.
Answer: This is probably the best one around right now:
http://timeline.verite.co/
Comment: I don't know if you read the question or saw how I'm using it.  Yes, I'll say that Timeline JS is pretty, but it's completely outside of how I need to use it and lacks almost any customizations outside of css styling.  And one part of it that makes it almost useless from the [FAQ](http://timeline.verite.co/#faq-04):
Comment: and the part that says that it shouldn't handle more than 100 elements, of which I would have several hundred.  "Timeline is optimized for up to 100 entries preferably more like 20-30. Anything else may cause a loading issue."  So while it'd be nice, it's unfortunately a no-go, even by their standards.
Comment: I found this link useful, so I redeemed it with an upvote. Thank you!
Answer: I'm actually working with the Simile Timeline in a project of my called Event Viewpoint.  I've fixed quite a lot of bugs and enhanced it with many contributions that I have found online including images for the event, a zoom bar, and some additional events.
It is a brilliant piece of work just needs someone to take the time to update it and make it more current.  That is currently out of scope for my project, but if I have time in the next year or so I will start to enhance it.
It would really be great if people could revive the project, add touch events and so on.
If someone needs the source I am willing to provide it.
Comment: Perhaps use a fork of https://github.com/simile-widgets/timeline to share these improvements with the world?
Comment: When I get farther along I will, right now I'm still trying to get my features into it.  I'm fiddling with adding a Zoom bar like Google Maps.  I have updated it with latest version of JQuery and have a Grunt build task to build it.
Answer: They're still very active. David Karger makes frequent updates. Now they have the version 3.0.
You can find reference documentation here:
http://simile-widgets.org/wiki/Reference_Documentation_for_Exhibit.
The code is here: https://github.com/simile-widgets/exhibit
Answer: I don't know exactly what you want, but i'm working on this jquery plugin that it's being used in a website with dynamically managed events.
Comment: You don't know what the OP wants... but you are going to post a link to your own project, anyway?


Choices of priors for time-varying-parameter VAR in Primiceri (2005)

Question: The main idea of the question is how to choose priors' parameters for the time-varying-parameter VAR model.
I am really confused in the way Primiceri (2005) constructed priors in his paper under the title "Time varying structural vector autoregressions and monetary policy". If I understood the idea of the prior correctly, it should reflect our believe for the parameters so we can calculate our posterior distribution. However, how the author identity the matrices' priors in Q, W, and S (in pg. 13) and, for example, choosing the value 40 (the training sample) as the variance for our prior?
The same inquiry apply for the paper: Nakajima, J., M. Kasuya, and T. Watanabe (2011). "Bayesian analysis of time-varying parameter vector autoregressive model for the Japanese economy and monetary policy". However, in this paper, the justification of the prior choice is really vague and not straightforward.
Answer: Primiceri (2005) writes on p. 830 bottom that the first 10 years (40 obs.) are used to calibrate the prior distributions. He estimates a constant parameter VAR model on the first 40 obs. and uses these point estimates to calibrate the prior distributions. Note that he calibrates the variance as four times the estimated variance from the constant parameter VAR.
Nakajima and Kasuya follow Primiceri (2005) when calibrating their prior distribution. They discuss this in sections 3.2 (p. 228-229) and 4.1 (p. 229-231).
The reason for choosing this prior is discussed by both Primiceri (2005) and Nakajima and Kasuya, see section 3.2: "The priors should be carefully chosen because the TVP–VAR model has many state variables and their process is modeled as a non-stationary process. The TVP–VAR model is so flexible that the state variables can capture both gradual and sudden changes of the underlying economic structure. As mentioned by Primiceri (2005), the tight prior for the covariance matrix of the disturbance in the random walk process avoids implausible behaviors of the time-varying parameters. A tighter prior should sometimes be avoided in empirical econometrics for its arbitrary choice, although the TVP–VAR model needs slightly tighter priors to provide reasonable identification."
Nakajima, J. (2011) Time-Varying Parameter VAR Model with Stochastic Volatility: An Overview of Methodology and Empirical Applications and Koop, G. and Korobilis, D. (2009). BAYESIAN MULTIVARIATE TIME SERIES METHODS FOR EMPIRICAL MACROECONOMICS provide more details on the TVP-VAR model. There is an improved MCMC algorithm for estimating the TVP-VAR model in Primiceri (2005). A discussion of this is found in TIME VARYING STRUCTURAL VECTOR AUTOREGRESSIONS AND MONETARY POLICY: A CORRIGENDUM.
Comment: Dear Plissken, thank you for answering, I understand the choice of Primiceri (2005) and Nakajima et al. (2011) when using the OLS estimation for the training period get the priors for B0, A0, and log (sigma). However, in Primiciri the prior for the covariance matrix is really confusing where it include the dimension of the matrices Q,S, and W. in addition, for the case of Q, the author choose the training period as prior variance for the IW distribution. For W, the author choose to multiply the (1+dimension of the matrix W) with uncertainty coefficient (kq)....
Comment: Nakajima et al (2011) use OLS estimation, similar to Primiciri, however, for the covarinace matrix, the prior distribution choice was gamma. The parameters arbitrary choice was build on the convenience of tighter prior for B. The authors did not  indicate for the initial training period nor the dimension of the matrix similar to Primiceri.. Did I get this part wrong? this is the part from Nakajima et al paper, ".set a tighter prior for the time-varying coefficient (β) than the simultaneous relations (a) and the volatility (h) of the structural shock for the variance of time-varying process"...
Comment: Have you looked at Cogley and Sargent (2001): "Evolving Post-World War II U.S. Inflation Dynamics", Cogley and Sargent (2003): "Drifts and Volatilities: Monetary Policies and Outcomes in the Post WWII
U.S." and Cogley (2003): "How Fast Can the New Economy Grow? A Bayesian Analysis of the Evolution of Trend Growth" ? I will be able to help you more in a week or so. Sorry that I couldn't be of more help.
Comment: Dear Plissken, thank you for the suggested literature. Hope it will solve my inquiry... I will keep this post alive if I could not understand this issue...
Comment: Returning to this question after a while, There are stil the following unclear points,:The first point: when Primiceri (2005) set the prior distribution for Q with variance =40 (on pg. 13), Nakaijma(2011) set the same prior with variance=0.02 (pg. 129). Although they both chose difference distribution, still, the parameters are so much different. There is something I am missing and I could not comprehend the difference.
Comment: The second point: in Primiceri (2005), the choice of 40 as a prior parameter for matrix, Q , do not make sense for me, I expected that the prior's variance is 40 % but not 40. Please correct my misunderstanding to these points.
Comment: Did you solve your issues regarding the model? I have estimated and used the model and would be happy to assist you in any questions you may have.
Comment: Hello, thanks for the comment. Unfortunately no,still stuck in the same previous points about how the authors relate their prior parameter choices with the used data!
Comment: Okay. I will try to edit my answer tomorrow or the day after.
Answer: Let me try and answer the question: "However, how does the author identify the matrices' priors in Q, W, and S (in pg. 13) and, for example, choosing the value 40 (the training sample) as the variance for our prior?" Specifically, let me try to explain the the prior for Q.
The author states that his choice for the prior of the state error variance, Q, is an inverse Wishart distribution: $Q \sim IW(\Sigma,T)$, where $\Sigma$ is the scale matrix and $T$ the degrees of freedom. Two things are crucial in this distribution: (i) its interpretation and (ii) how to use pre-sample information in order to parameterize the prior.
(i) The inverse Wishart, like the Wishart, can be interpreted as generating sums of squares from samples of size $T$ of observations drawn from the multivariate normal distribution (check Nydick, 2012, for a quick read on these distributions.) $\Sigma$, as Primiceri hints at on the first paragraph of page 831, can be interpreted as the population value of the variance/covariance matrix of the multivariate normal. So if $T\rightarrow\infty$, by the Law of Large Numbers, your sample sum of squares should be equal to the population sum of squares. Hence, the higher is $T$, the tighter is your prior. What is the relationship of the IW with $Q$? Note that the expected value of a variable $X$ distributed according to IW is $E(X) = \frac{\Sigma}{T - p -1}$, where p is the dimension of $X$. As you can see, if $\Sigma$ is a sum of squares, $E(X)$ is a variance, which is what we are trying to model (Primiceri, 2005, actually clears this up in footnote 20 on page 842.)
(ii) To set the value of $\Sigma$, the scale matrix for the prior of the state error covariance, Primiceri (2005) uses the OLS estimate of the VCV of parameters, $Var(\hat{B}_{OLS})$. Since $\bf{Var(\hat{B}_{OLS})}$ is a variance, he must multiply it by the pre-sample size, in order to obtain the pre-sample sum of squares. Since he used a pre-sample of 40, in my view, the number of degrees of freedom should be $40-p-1$, where $p$ is the number of parameters he is estimating, just like he does for the other two matrices (although I assume that this is of little consequence for the results.) Therefore, the expected value of his prior is $\frac{Var(\hat{B}_{OLS})\times(T-p-1)}{T - p -1} = Var(\hat{B}_{OLS})$.
Hope this helps


How to get and/or set the link key when pairng bluetoth devices using Android(Java)?

Question: I'm really new on this of Android development, so I have many questions. Right now I'm trying to connect two devices via Bluetooth. So far I was able to do this, I have connected two tablets, but now I'm asked to save the LinkKey and use some bytes of it to create a PIN. So, how can I get that LinkKey? I've read that it's saved on both devices for future connections, but I don't know how to get it.
Also, I've read that this devices can delete those LinkKey, what happens then? If they try to connect with each other again, will they use the same LinkKey or a new one is created?
And the last thing. I have to connect a tablet to a device that has neither a display nor a keypad, a normal bluetooth connection is enough? I'm doing this to stablish the connection:
final UUID MY_UUID = UUID.randomUUID();
        //tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        Method m = null;
        try {
            m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        tmp = (BluetoothSocket) m.invoke(device, 1);
        mmSocket = tmp;

    Thread connectionThread = new Thread(new Runnable(){

    public void run() {
        // Cancel discovery because it will slow down the connection
        mBluetoothAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
        manageConnectedSocket(mmSocket);
    }

Thanks.
Answer: Link key creation is done on the stack/LMP(Link Manager) level, not on the app level. Bluetooth devices check if the link key exist or not, if exist, it will not go for pairing and bluetooth connection will proceed, if no link key is found on the bluetooth stack, LMP(Link Manager) will initiate a new pairing process , once pairing completed, bluetooth connection will proceed. If link key is deleted, a new link key will be generated for a connection.
Try checking in adb shell (/data/misc/bluetoothd or data/misc/bluetooth) for link key , it will be available in the paired device info.


Multiprocessing Pool.apply executing n-1 times

Question: Im having an issues with multiprocessing.Pool.apply.
My objective is to have 5 processes, each filling an array with 100 elements (100 for this test), and then merging then arrays into a single one with length 500. Problem is, it ends up with only 400 elements for any reason i cant understand.
I have tried changing the amount of processes created by the pool but that didn't change anything at all besides the execution time.
import torch.multiprocessing as mp
import itertools

pool = mp.Pool(processes=5)
split = int(500/5)
lst =  pool.apply(RampedGraph, (split,[]))    #each foo returns a list of 100 elements
lst = list(itertools.chain.from_iterable(lst)) #merging the lists into one

len(lst)
>>>400

The expect output of len(lst) should be 500.
Can anyone enlighten me on what Im doing wrong?
EDIT Foo method explained:
def RampedGraph(popsize, graph_lst):
    cyclic_size = int(math.ceil(popsize/2))
    acyclic_size = popsize - full_size
    append = graph_lst.append
    for _ in range(cyclic_size):
        t = c.Node().cyclic()
        nn = c.number_of_nodes()
        c = c.calculate(0, False)
        append((t,nn,c))
    for _ in range(acyclic_size):
        t = c.Node().acyclic()
        nn = c.number_of_nodes()
        c = c.calculate(0, False)
        append((t,nn,c))
    return graph_lst

Comment: `pool.apply(RampedGraph, (split,[]))` only calls `RampedGraph(split, [])` once. Are you trying to call `RampedGraph` 5 times? All with the same argument?
Comment: @unutbu done , added the full method
Comment: @unutbu im trying to call it one time for each process, so i can merge 5 arrays of 100 elements. All with the same argument
Answer: import torch.multiprocessing as mp
# import multiprocessing as mp
import itertools

def RampedGraph(popsize, graph_lst):
    print(mp.current_process().name)
    return list(range(100))

num_workers = 5
pool = mp.Pool(processes=num_workers)
split = int(500/num_workers)
lst =  pool.starmap(RampedGraph, [(split,[])]*num_workers)
lst = list(itertools.chain.from_iterable(lst))
print(len(lst))
# 500

pool.starmap(RampedGraph, [(split,[])]*5) sends 5 tasks to the task pool.
It causes RampedGraph(split, []) to be called 5 times concurrently.
The 5 results returned by RampedGraph are collected into a list, lst.
Note that calling RampedGraph 5 times concurrently does not guarantee that all 5 processors are used. For example, if RampedGraph were to finish very quickly, it is possible that one processor handles more than one task, and perhaps another processor never gets used at all.
However, if RampedGraph takes a non-trivial amount of time, in general you can expect all 5 worker processes to be used.
Note: I ran the above code with import multiprocessing as mp rather than import torch.multiprocessing as mp. But since torch.multiprocessing is supposed to be a drop-in replacement for multiprocessing, that shouldn't make a difference.

Using multiprocessing comes with both costs and benefits.
The benefit, of course, is the ability to use multiple processors concurrently.
The costs include the time required to launch additional processes, and the cost of interprocess communication. multiprocessing uses Queues to transport arguments to the function run by the worker processes, and to transport the returned value back to the main process. To transport the  returned values through the Queues, the objects are serialized into bytes via pickling. If the pickled objects being sent through the Queues are large, this can add a significant overhead cost when using multiprocessing. Notice that all these costs are not incurred by an equivalent sequential version of the same code.
Particularly when the function run by the worker processes finishes quickly, overhead costs can dominate the total run time of the program, making code which uses multiprocessing slower than a sequential version of the same code.
Thus, a key to speed when using multiprocessing is to try to minimize interprocess communication and to make sure the worker processes do a lot of work so the overhead costs become a relatively small part of the total run time.
Comment: much appreciated !
Comment: Hum. Any idea why this approaches takes about 3x more time to execute than simply filling the array with 500 elements? I Assumed it would cut the execution time, not triple it :/
Comment: I added a few words about why `multiprocessing` can sometimes be slower than a sequential version of the same code. Whether it applies in your case I don't know. We might have to see your actual runnable code to investigate.


Getting error "code will never execute" when using do-while loop for password checking function in c++e

Question: I put a do/while loop in my password function but it doesn't work. I use xcode10 to code c++ and when I use a semicolon after the while statement it shows an error saying code will never execute
string password (string g)
{
    string ch = "hello" ;
    cout << "Enter password";
    getline(cin, g);
    do {
        if (ch.compare(g) != 0) {
            cout << " INCORRECT PASSWORD";
            return (0);
        } else {
            cout << "correct password";
            return (string(g));
        }
    } while (ch.compare(g) == 0);  //this is where it shows the error that the code will never exec
}

I wanted to put this loop and a few other things so I can make this a infinite loop till you enter the correct password.
Comment: So when do you think that `while` condition will be executed? Also, `return (0);` for constructing `std::string` has undefined behavior.
Answer: Well in your if statement you will return in both cases causing the function to stop so it will never get to the while condition to test it
  string password(string g)
{
    string ch = "hello";
    cout << "Enter password\n";
    do
    {
        getline(cin, g);

        if (ch.compare(g) != 0)
        {
            cout << " INCORRECT PASSWORD\n";
        }
        else {
            cout << "correct password";
            return (string(g));
        }
    } while (ch.compare(g) != 0);
}

Comment: hey! so I removed the return function from if and else, its still not working. the do while loop. if I enter the correct password it continues, it I enter the wrong password then the output displays incorrect password and stops. it displays incorrect password and its like this.
Enter password no
Incorrect Password (11db).
I am using Xcode for c++.
Answer: There is Return statement in the "if" and also in the "else".
You can see that no matter what will be the result of ch.compare(g), the function will return to it's caller.
That's why it will never do the "while".
Try to set the Return statements in different place in the code :)
Answer: You need to check if you get input at all too, in case of EOF.
string password() { // you don't need g as parameters in, your overwriting it
    string const ch = "hello"; // make ch const to show it not supposed to change
    cout << "Enter password";
    string g; // defining g here since now you need it
    while (getline(cin, g)) { // check that the read from cin is OK
        if (ch != g) { // simple notation for comparing two strings. There's also == available
            cout << "INCORRECT PASSWORD. Please try again\n"; // no return if you want to try again
        } else {
            cout << "correct password";
            return g; // you could also return ch here since they have the same content
        }
    }
    cout << "Unable to read line. aborting\n"; // not really a lot you can do if there is no input to read.
    return string(); // returning empty string.
}


Oracle SQL: What is the best way to select a subset of a very large table

Question: I have been roaming these forums for a few years and I've always found my questions had already been asked, and a fitting answer was already present.
I have a pretty generic (and maybe easy) question now though, but I haven't been able to find a thread asking the same one yet.
The situation:

I have a payment table with 10-50M records per day, a history of 10 days and hundreds of columns. About 10-20 columns are indexed. One of the indices is batch_id.
I have a batch table with considerably fewer records and columns, say 10k a day and 30 columns.

If I want to select all payments from one specific sender, I could just do this:
Select * from payments p
where p.sender_id = 'SenderA'

This runs a while, even though sender_id is also indexed. So I figure, it's better to select the batches first, then go into the payments table with the batch_id:
select * from payments p
where p.batch_id in
(select b.batch_id from batches where b.sender_id = 'SenderA')
--and p.sender_id = 'SenderA'

Now, my questions are:

In the second script, should I uncomment the Sender_id in my where clause on the payments table? It doesn't feel very efficient to filter on sender_id twice, even though it's in different tables.
Is it better if I make it an inner join instead of a nested query?
Is it better if I make it a common table expression instead of a nested query or inner join?

I suppose it could all fit into one question: What is the best way to query this?
Comment: https://docs.oracle.com/cd/B10500_01/server.920/a96533/ex_plan.htm
Comment: Are the two tables **partitioned**? this would help a lot... also, you could try to materialize one of the two subset (`payments` or `batches` fildered for `sender_id`) using `with` construct... anyway you have to compare the execution plans to choose the form of the query.
Comment: How many rows are returned by the query?
Comment: Short answers to questions:
1) If both columns(batch_id and sender_id) are indexed same way, then first simple query is more efficient.
2) Depends. In most cases Oracle will create same explain plan, so it doesn't matter.
3) Same as 2nd answer.

Few things, which might improve performance:
keep table and index statistics up-to-date
For this kind of queries single column indexes will be most efficient
Comment: Thank you. Rows returned are usually 4M or so.
Comment: Your "per day" numbers are a bit confusing since the queries don't have a day column and you didn't mention any partitioning. I think you're saying the PAYMENTS table has 300M rows with 100K distinct batch IDs (so 3000 rows per batch ID), but you don't say how many distinct sender IDs there are. Three? A million?
Comment: The question makes no sense, because the queries are quite different.  One uses a single table; one uses two tables.
Answer: In the worst case the two queries should run in the same time and in the best case I would expect the first query to run quicker. If it is running slower, there is some problem elsewhere. You don't need the additional condition in the second query.
The first query will retrieve index entries for a single value, so that is going to access less blocks than the second query which has to find index entries for multiple batches (as well as executing the subquery, but that is probably not significant).
But the danger as always with Oracle is that there are a lot of factors determining which query plan the optimizer chooses. I would immediately verify that the statistics on your indexed columns are up-to-date. If they are not, this might be your problem and you don't need to read any further.
The next step is to obtain a query execution plan. My guess is that this will tell you that your query is running a full-table-scan.
Whether or not Oracle choses to perform a full-table-scan on a query such as this is dependent on the number of rows returned and whether Oracle thinks it is more efficient to use the index or to simply read the whole table. The threshold for flipping between the two is not a fixed number: it depends on a lot of things, one of them being a parameter called DB_FILE_MULTIBLOCK_READ_COUNT.
This is set-up by Orale and in theory it should be configured such that the transition between indexed and full-table scan queries should be smooth. In other words, at the transition point where your query is returning enough rows to just about make a full table scan more efficient, the index scan and the table scan should take roughly the same time.
Unfortunately, I have seen systems where this is way out and Oracle flips to doing full table scans far too quickly, resulting in a long query time once the number of rows gets over a certain threshold.
As I said before, first check your statistics. If that doesn't work, get a QEP and start tuning your Oracle instance.
Tuning Oracle is a very complex subject that can't be answered in full here, so I am forced to recommend links. Here is a useful page on the parameter: reducing it might help: Why Change the Oracle DB_FILE_MULTIBLOCK_READ_COUNT.
Other than that, the general Oracle performance tuning guide is here: (Oracle) Configuring a Database for Performance.
If you are still having problems, you need to progress your investigation further and then come up with a more specific question.
EDIT:
Based on your comment where you say your query is returning 4M rows out of 10M-50M in the table. If it is 4M out of 10M there is no way an index will be of any use. Even with 4M out of 50M, it is still pretty certain that a full-table-scan would be the most efficient approach.
You say that you have a lot of columns, so probably this 4M row fetch is returning a huge amount of data.
You could perhaps consider splitting off some of the columns that are not required and putting them into a child table. In particular, if you have columns containing a lot of data (e.g., some text comments or whatever) they might be better being kept outside the main table.
Remember - small is fast, not only in terms of number of rows, but also in terms of the size of each row.
Comment: Thanks, I think this answer explains the problem and next steps to take well. I've been getting better at getting the information I need from a database, but I have very little knowledge about statistics and execution plans; and how to improve those. I'm always told I should ask a DBA, but those people are rare!
Comment: Reply on your edit: Indeed, there is a lot of data in the table. In my select, I'm only asking for the sender, receiver, and status. I also count the records and sum the amount. I suppose a full table scan is unavoidable. That being said, I will still have a look at the statistics.

Sadly, I don't think I have enough pull to move some columns into a child table.
Answer:
SQL is an declarative language. This means, that you specify what you like not how.
Check your indexes primary and "normal" ones...
Comment: This question deserves a wider response, since the OP clearly has a genuine performance problem.
Comment: The question was: "What is the best way to query this?" and the answer to that is: 1. SQL is an declarative language. This means, that you specify what you like not how.


Can we integrate, the indefinite integral $\int 2aye^{ay^2}dy$ by parts?

Question: Can we integrate, the indefinite integral $\int 2aye^{ay^2}dy$ by parts ?
If we let, $ay^2= t$, we have $(2ay)dy=dt$ and the integral can be integrated. This process is known as integration by substitution.
Comment: why do you want to do this by parts if you can do it by a simple substitution?
Answer: Yes, but you're not going to like it.
Let $u=1$, $dv=2aye^{ay^2}\,dy$. Then $du=0dy$, and (by the substitution technique that you already know about) $v=e^{ay^2}$. So $$\int2aye^{ay^2}\,dy=\int u\,dv=uv-\int v\,du=e^{ay^2}-\int0dy=e^{ay^2}$$
Comment: Awww, beat me to the punch.
Answer: You can do it directly. Observe that
$$\left(e^{ay^2}\right)'=2aye^{ay^2}\Longrightarrow\int\,2ay\,e^{ay^2}dy=\int d\left(e^{ay^2}\right)=e^{ay^2}+K(=\text{ constant})$$
Comment: Well done, @Tharsis. Thanks


Set a parameter for added method to element object?

Question: I wrote the method fadeIn and fadeOut and I know it's in jQuery, but this is some kind of a practice, so I want to add a parameter to the fadeIn method:

function fadeIn(e, time) {
  // e.style.opacity = 1;
  var op = Number(getComputedStyle(e).opacity).toPrecision(2);
  e.style.opacity = op;
  if (op >= 1) {
    return;
  }
  e.style.opacity = Number(op) + 0.01;
  setTimeout(function() {
    fadeIn(e)
  }, time)
}

function fadeOut(e) {
  // e.style.opacity = 0;
  var op = Number(getComputedStyle(e).opacity).toPrecision(2);
  e.style.opacity = op;
  if (op <= 0) {
    return;
  }
  e.style.opacity = Number(op) - 0.01;
  setTimeout(function() {
    fadeOut(e)
  }, 10)
}

Element.prototype.fadeIn = function(time) {
  fadeIn(this, time);
};
Element.prototype.fadeOut = function() {
  fadeOut(this);
};
Comment: And what is the problem?
Answer: You have to pass in the time at the ongoing calls:
setTimeout(function () {
    fadeIn(e, time); // <<<
}, time)

Now this is the interval time for increasing the opacity by 1/100, so you might wanna divide the time too:
Element.prototype.fadeIn = function (time) {
   fadeIn(this,time / 100);
};

So now
 el.fadeIn(1000);

will take one second to fade in.


Erro ao acessar instância do objeto através da interface

Question: Estou fazendo testes unitários para C# usando o framework MOQ e estou utilizando EF core para acesso a dados. Estou escrevendo um método de teste para uma de minhas classes de repositório, a minha classe de repositório espera no construtor uma instância do meu ApplicationDbContext.
Dessa forma, tenho os seguintes arquivos:
IpplicationDbContext.cs
public interface IApplicationDbContext
{
    DbSet<T> Set<T>() where T : class;
}

ApplicationDbContext.cs
public class ApplicationDbContext : DbContext, IApplicationDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
    : base(options)
    {}

    public DbSet<ContactModel> Contact { get; set; }
    public DbSet<LoginModel> Login { get; set; }
    public DbSet<UserModel> User { get; set; }
    public DbSet<UserRoleModel> UserRole { get; set; }
    public DbSet<RoleModel> Role { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfiguration(new ContactMap());
        modelBuilder.ApplyConfiguration(new LoginMap());
        modelBuilder.ApplyConfiguration(new UserMap());
        modelBuilder.ApplyConfiguration(new UserRoleMap());
        modelBuilder.ApplyConfiguration(new RoleMap());
    }
}

Até aqui tudo certo, eu criei a interface IApplicationDbContext.cs e implementei ela na minha classe ApplicationDbContext.cs, na interface IApplicationDbContext.cs eu tenho somente uma assinatura e a classe DbContext.cs já possui esse método implementado, dessa forma a classe ApplicationDbContext.cs passa a implementar o método pelo fato de herdar de DbContext.
O problema entra quando eu não consigo acessar a instância do objeto de IApplicationDbContext.cs mesmo tendo implementando em uma classe e fazendo o mapeamento da injeção de dependência. Método onde faço o mapeamento das injeções:
 public static IServiceCollection GetInjectionConfig(this IServiceCollection services) =>
            services
                .GetApplicationDbContextConfig()
                .GetTokenConfig()
                .GetEmailConfig()
                .GetValidationsConfig()
                .GetServicesConfig()
                .GetRepositoriesConfig();

    private static IServiceCollection GetApplicationDbContextConfig(this IServiceCollection services) =>
            services
                .AddScoped<IApplicationDbContext>(provider => provider.GetService<ApplicationDbContext>())

Em meu método de teste está sendo acusado o seguinte erro:
cannot convert from 'Hospital.WebApi.Domain.Interfaces.ApplicationDbContext.IApplicationDbContext' to 'Hospital.WebApi.Infra.Data.Context.ApplicationDbContext'
Método de teste:

Isso é estranho, porque eu estou seguindo o padrão, de criar um mock através de uma interface e depois acessar o objeto desse mock (classe que implementa a interface), e conforme mencionado, eu criei a interface, implementei ela no meu AplicationDbContext, fiz o mapeamento e mesmo assim não estou conseguindo.
Comment: Não é mais fácil configurar o seu EF pra usar um banco em memória ou sqlite?
Comment: como o @BrunoWarmling comentou, mockar o DbContext não é facil, e usar um inmemory database funciona bem e é o mais simples. Instale o package `Microsoft.EntityFrameworkCore.InMemory` e use ele para fazer isso. Basicamente seria algo como `var options = new DbContextOptionsBuilder().UseInMemoryDatabase("NomeDaSuaConfigComAStringDeConexao").Options` e depois `var dbContext  = new IApplicationDbContext(options)`
Comment: Nesse caso os testes não vai ficar dependentes do banco né? vai ser tipo o que eu tentei fazer ali, mas de outra forma? Porque não quero deixar os testes presos no banco, tipo, não quero que nenhum teste chegue até o banco real. Perguntando porque vi que você mencionou que devo colocar o nome de minha config com a string de conexão.
Answer: Existem diversos providers necessários pra fazer o ApplicationDbContext funcionar desta forma, acho que essa abordagem não é a melhor, a menos que seja extremamente necessária.
Uma forma mais fácil é adotar a solução InMemory. A Microsoft implementou exatamente para este propósito.
Este link abaixo contém a documentação explicando como realizar os testes InMemory:
https://docs.microsoft.com/en-us/ef/core/testing/
Tem bastante conteúdo sobre o assunto disponível.
Se ainda assim, quiser continuar com esta abordagem e acreditando que o restante está funcionando corretamente, dentro das suas classes de teste você utilizaria injeção de dependência da sua interface, algo como:
public class Teste
{
   private readonly IApplicationDbContext _context

   public Teste(IApplicationDbContext context)
   {
     _context = context;
   }
}

Depois, para fazer o mock do seu context:
var contextMock = new Mock<IApplicationDbContext>();
contextMock.Setup(x=> x.Set<ContactModel>()).Returns(contextMock.Object);


Creating a survey weights variable

Question: I'm a survey weight novice, and I'm trying to implement survey weights in an analysis for the first time.
Let's say I have some variable of interest, X, in a dataset but that dataset provides no weight variable that I can quickly implement in the analysis.
But, I do have the following crosstab for X that I can use in creating a weight variable.
<code>|--------------|------|---------|
| Age in Years | Male |  Female |
|--------------|------|---------|
| 18-29        |  0.1 |    0.15 |
| 30-44        |  0.2 |    0.19 |
| 45-59        |  0.1 |    0.11 |
| 60 +         |  0.1 |    0.13 |
|--------------|------|---------|
</code>
I'm sure it's not a very difficult procedure to create a weight variable out of this information, but I'm not entirely sure where to begin.
Is it that for every row of X that corresponds to "60 +" years and "Female", I code a weight value of 0.13? And for every row of X that corresponds to "60 +" years and "Male", I code a weight of 0.1? And so on? Or is it something else entirely?
Answer: The point of survey weights is to make your sample closer in distribution to the target population. You need to know what the corresponding table for the whole population would look like.
Suppose that in the population 12.32% of people are Male aged 18-29. In your sample there fewer people in this category, so you want to give them extra weight. Each person in this category would get a weight of 12.32%/10% = 1.232.  And so on.
Strictly speaking, these are calibration (post-stratification) weights rather than sampling weights, but they get used in basically the same way.

Creating a survey weights variable


Regression: Interpretation of decreasing slope with positive average growth

Question: I have performed a linear fit on the following series using np.polyfit in python, where y is the net difference between inflow and outflow and x is month of year:
x   y
1   0
2   24
3   3
4   1
5   1
6   1

The regression equation comes out as:
y = -1.89x + 9.71

So this is saying that the overall slope of the line is decreasing with each unit increase in x. I can see this is being driven by one month having a spike in inflows (Month 2 = 24) and the rest of the months having minimal positive changes.
But, when we calculate the average of y, it comes out as 5 ((0+24+3+1+1+1)/6 = 5), which is saying on average you are gaining 5 each month, which again is being driven by that spike in month 2.
So my question is, what's a logical way of explaining a trend that is decreasing but has positive average unit growth? And the same goes for the opposite, when the slope of the equation is positive, but on average each month there is a net loss.
Comment: You're confusing growth and changes in growth.  On average you are gaining each month.  The amount you gain each month decreases each month.
Comment: You are right, and that makes so complete sense. Thanks for pointing it out
Answer: It appears that you have outlier which is significantly impacting your model. You need to decide how you are going to proceed. Below is a picture with added regression lines with and without the outlier. The difference is significant.


Java script básico

Question: Gostaria de fazer uma verificação no meu código, um "if else", que quando eu não coloque nada pra calcular e clique no botão, ele dê um alerta avisando que não tem nada nos campos de valor.
Não peguei muito bem a lógica, alguém poderia me ajudar?
document.getElementById("btn-calcular").onclick = function(){

    var valorA = document.getElementById("valor-a").value;
    var valorB = document.getElementById("valor-b").value;

    alert(parseInt(valorA) + parseInt(valorB));

    document.getElementById("resposta").value = parseInt(valorA) + parseInt(valorB);

}

Answer: Não sei se entendi muito bem sua pergunta, mas se for o que eu percebi pode fazer da seguinte forma:
document.getElementById("btn-calcular").onclick = function(){

var valorA = document.getElementById("valor-a").value;
var valorB = document.getElementById("valor-b").value;

if (valorA == "" || valorB == ""){
   alert("Por favor introduza os dados necessários");
}
else{
    alert(parseInt(valorA) + parseInt(valorB));

 //aqui ja nao precisa de usar o parseInt, uma vez que ja converteu os valores para inteiros acima

    document.getElementById("resposta").value = valorA + valorB;

 }

}

Comment: Cara, era isso mesmo. Valeuuuuuuuuuuuu de verdade! Abraço
Comment: Valeu ;) Força aí, pratique muito!

Java script básico


What is the correct way to apply word embeddings to new data?

Question: Consider the words "banana" and "split". Assume that a pre-trained word embedding (say, word2vec GoogleNews) has the vectors like so:
banana_vec = array([[1.56, -2.46, 6.13, ... , -2.81]])
split_vec = array([[3.56, 9.45, -2.43, ... , 5.32]])
Now consider a completely new data set consisting of documents (sentences). Assume that one of the documents is the sentence "banana split".
How does one represent that sentence with the pre-trained word embeddings?
Things I've considered include:
Sum word embedding elements for each word
So this would give something like
bananana split = array([[v1, v2]])
where v1 is the sum of elements in banana_vec, and v2 is the same for split_vec.
L2 norm of word embedding elements for each word
So this would be the same, but the L2 norm instead of the sum.
Sum word embedding elements across words
So this would be:
banana split = array([[v1, v2, v3, ... , v100]])
where v1 = 1.56 + 3.56
L2 norm of embedding elements across words
Same as above except v1 = sqrt(1.56^2 + 3.56^).
Or is it something completely different?
Thanks in advance.
Answer: In the pre-trained word embeddings that have been loaded, each word will have a vector of the same length, $n$.
doc_vectors = []
for doc in documents:
    doc = tokenize(doc)
    feature_vector = zeros_array(n)
    for word in document:
        vec = vector (embedding) for the word
        feature_vector += vec
    feature_vec = feature_vec / len(doc)
    doc_vectors.append(feature_vector)

So for the example in the question:
vec("banana") = array([[1.56, -2.46, 6.13, ... , -2.81]])
vec("split") = array([[3.56, 9.45, -2.43, ... , 5.32]])

feature_vec("banana split") = vec(banana) + (split) = array([[5.12, 6.99, ..., 2.51]])
feature_vec("banana split") = feature_vec("banana split") / length

And that is how feature vectors are achieved for documents embeddings, which was one of the suggestions in the question.


Using Knockout JS, update a table cell on a screen from Javascript

Question: I am using Knockout JS to work with an editable grid.  Updates work fine when typing values into the table cells.  However, I need to set a date as a result of clicking a "set complete date" button.  The Javascript update sets the value in the view model, but does not update the table cell on the screen.  Based on web searches, this should work if the cell is observable.  For some reason, it doesn't.  The attached code is self contained, and illustrates the problem.
The following code is a simplified version of what I'm trying to accomplish.  By clicking on the name field, the view model is updated with "a new name".  I want this to update the cell on the html display as well.
<!DOCTYPE html>

         <meta charset="utf-8" />
         <title> - Fresh Water Buoy data maintenance</title>
         <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
         <meta name="viewport" content="width=device-width" />
         <link href="/Content/site.css" rel="stylesheet"/>

Fresh Water Buoys

Home

About

Contact

Your seat reservations ()

             Passenger name
             Meal
             Modified name
             Surcharge

             <input data-bind="value: name, click: $root.nameClick" />
             <select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select>

             Remove

 <button data-bind="click: addSeat, enable: seats().length < 5">Reserve another seat</button>

 0">
     Total surcharge: $

© 2016 - My ASP.NET MVC Application

Answer: I copied and pasted your code into JSFiddle.  The issue is in the nameClick() function.  You are setting the seat.name value to a new observable, when it should just update the observable.
Change the following:
seat.name = ko.observable("a new name");

To this:
seat.name("a new name");

And the code should work.
Comment: Thank you Eric!  You have been a real blessing to me.


jQuery not working in zen theme

Question: Ive put this code before the closing head tag in my html.tpl.php but nothing is happening. Im using the zen theme. Ive tried clearing my cache.
Im I somehow missing a syntax error or is this a Zen/ Drupal qwerk?

Answer: It would be helpful to know what version of drupal you are using.
Modifying html.tpl.php to add Javascript like this is really a bad choice as it is a very brittle way of coding something.
Jquery in Drupal 7 is loaded using the noConflict mechanism. This avoids javascript namespace collisions:

Many JavaScript libraries use $ as a function or variable name, just
  as jQuery does. In jQuery's case, $ is just an alias for jQuery, so
  all functionality is available without using $. If we need to use
  another JavaScript library alongside jQuery, we can return control of
  $ back to the other library with a call to $.noConflict():

If you wanted to use code like you've written you would write:

You're better off adding a scripts[] entry into your theme_name.info file and placing such code in its own javascript file in your theme directory. Drupal will load it into the HTML  for you and aggregate your javascript files for you if you have aggregation turned on.
# In YOURTHEME.info
scripts[]= js/example.js

/* Example /sites/all/themes/YOURTHEME/js/example.js */
jQuery(document).ready(function($) {
  $('nav ul.primary-menu').append('

');
});

Comment: html.tpl.php is not used before Drupal 7. I hope the OP is not using that with Drupal 6. `:)`

jQuery not working in zen theme


Erro em programa para fazer uma lista de mercado

Question: O problema: Ao executar no Google Chrome, o navegador acusa ter um erro na função lerLista embora eu não tenha conseguido resolver acredito que seja um problema a captura do campo produto.

<!DOCTYPE html>

 <title>Lista de Compras</title>
 <meta charset="UTF-8"/>

Item lista de compra

<form name="entradaDaLista">

  Produto: <input type="text" id="produtoId" name="produto" >
  Quantidade:<input type="text" id="quantidadeId" name="quantidade"  >
  Preço:<input type="text" id="precoId" name="preco" >
  <button type="button" onclick="criaLista()">Incluir</button>

</form>

Erro retornado:

Uncaught SyntaxError: Invalid or unexpected token
Comment: O erro é porque tem quebra de linha no código em: `document.getElementById("output").innerHTML +="Lista de compras  Produto
Quantidade  Preço  Total";` também em: `document.getElementById("output").innerHTML +="
"+parse.int(lista[i].quantidade);` e `document.getElementById("output").innerHTML +="
"+parse.int(lista[i].quantidade*lista[i].preco);`
Comment: Veja o snippet, agora da para perceber a quebra de linha no código.
Comment: Oi NoobSaibot(nome estiloso kk). Me desculpa mas poderia dizer o que é snippet?
Answer: Sua funçao criaLista() nunca vai preencher o array lista pois a propriedade lista.length sempre é zero uma vez que você acabou de criar o array na linha de cima.

<!DOCTYPE html>

 <title>Lista de Compras</title>
 <meta charset="UTF-8"/>

Item lista de compra

<form name="entradaDaLista">

  Produto: <input type="text" id="produtoId" name="produto" >
  Quantidade:<input type="text" id="quantidadeId" name="quantidade"  >
  Preço:<input type="text" id="precoId" name="preco" >
  <button type="button" onclick="adicionaItem()">Incluir</button>

</form>


PL/SQL Oracle 11g Record Groups

Question: Upgrading from 6i to Oracle 11g Fusion Middleware.  How can a record group be passed from a form to the report?  We were using DATA_PARAMETER but I understand that that is no longer an option.
Comment: Assuming you are talking about a record group in Oracle Forms, wouldn't it just be easier to copy the sql used to generate this group into the Reports parameter. Then you could pass any parameters for the record group from forms using bing variables - see http://docs.oracle.com/cd/E23943_01/bi.1111/b32122/orbr_howto011.htm#RSBDR1028
Comment: it looks like just adding a bind variable to a query in Oracle reports e.g. :parm1 will prompt for a parameter to be created and added to the parameter form
Answer: Here's an example code to invoke a report refer to the for loop. It's kind of an example breaking your parameter and passing it to run_report_object.
https://www.oracle.com/technetwork/developer-tools/forms/frmrepparamform-128021.pdf
<code>PROCEDURE RUN_REPORT_OBJECT_PROC(
report_id REPORT_OBJECT,
report_server_name VARCHAR2,
report_format VARCHAR2,
report_destype_name NUMBER,
report_file_name VARCHAR2,
report_otherparam VARCHAR2,
reports_servlet VARCHAR2) IS
report_message VARCHAR2(100) :='';
rep_status VARCHAR2(100) :='';
vjob_id VARCHAR2(4000) :='';
hidden_action VARCHAR2(2000) :='';
v_report_other VARCHAR2(4000) :='';
i number (5);
c char;
c_old char;
c_new char;
BEGIN
 VHWWLQJ 5HSRUWV UXQWLPH SDUDPHWHUV
SET_REPORT_OBJECT_PROPERTY(report_id,REPORT_COMM_MODE,
SYNCHRONOUS);
SET_REPORT_OBJECT_PROPERTY(report_id,REPORT_FILENAME,
report_file_name);
SET_REPORT_OBJECT_PROPERTY(report_id,REPORT_SERVER,
report_server_name);
SET_REPORT_OBJECT_PROPERTY(report_id,REPORT_DESTYPE,
report_destype_name);
SET_REPORT_OBJECT_PROPERTY(report_id,REPORT_DESFORMAT,
report_format);
 FUHDWLQJ VWULQJ IRU SIDFWLRQ SDUDPHWHU
hidden_action := hidden_action ||'&report='||
GET_REPORT_OBJECT_PROPERTY(report_id,REPORT_FILENAME);
hidden_action := hidden_action||'&destype='||
GET_REPORT_OBJECT_PROPERTY(report_id,REPORT_DESTYPE);
hidden_action := hidden_action||'&desformat='||
GET_REPORT_OBJECT_PROPERTY (report_id,REPORT_DESFORMAT);
hidden_action := hidden_action ||'&userid='
||get_application_property(username)||'/'||
get_application_property(password)||'@'||
get_application_property(connect_string);
c_old :='@';
FOR i IN 1..LENGTH(report_otherparam) LOOP
c_new:= substr(report_otherparam,i,1);
IF (c_new =' ') THEN
c:='&';
ELSE
c:= c_new;
END IF;
-- eliminate multiple blanks
IF (c_old =' ' and c_new = ' ') THEN
null;
ELSE
v_report_other := v_report_other||c;
END IF;

c_old := c_new;

hidden_action := hidden_action ||'&'|| v_report_other;

hidden_action := reports_servlet||'?_hidden_server='||report_server_name
|| encode(hidden_action);
SET_REPORT_OBJECT_PROPERTY(report_id,REPORT_OTHER,'pfaction='||
hidden_action||' '||report_otherparam);
-- run Reports
report_message := run_report_object(report_id);
rep_status := report_object_status(report_message);
IF rep_status='FINISHED' THEN
vjob_id :=substr(report_message,length(report_server_name)+2,length
(report_message));
WEB.SHOW_DOCUMENT(reports_servlet||'/getjobid'||vjob_id||'?server='||
report_server_name,' _blank');
ELSE
--handle errors
null;
END IF;
END;
</code>

PL/SQL Oracle 11g Record Groups


How to display the views page title in a custom fieldable block

Question: Goal:
To create a custom fieldable block as available out of the box in D8, which also shows the page title of a a views page, if the page it is displayed on is a views page.
I created a custom block type, and added an image field for the block background.
I then copied and modified the block template to include:
{% if title %}

{{ title }}

{% endif %}

But the views title does not show up. The page source shows nothing rendered. I enable theme debugging and the new block template is being used.
Answer: Views sets the title configured in a Views page statically in the route definition. Get this title from the current route in a preprocess hook for your specific block content UUID. Add a routecache context, so that the block changes the title when you visit different pages:
function mytheme_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'block_content:12345678-1234-5678-90ab-1234567890ab') {
    $variables['title'] = \Drupal::routeMatch()->getRouteObject()->getDefault('_title');
    $variables['#cache']['contexts'][] = 'route';
  }
}

Comment: When you place the block in the block layout the UUID is also visible in the url of the  button "Place block".
Comment: Thank you! The plugin_id is something different from the block machine name, right? Where can I find the plugin_id ?
Comment: You've said you want to use a custom (fieldable) block. Then the plugin id is composed like in the example, you only need to find the UUID (the longer version of the block content id), for example with the help of Twig Debug or install the Devel module and click on the tab Devel when editing the block.


filtering event logs with specific TIME range of ANY day

Question: How can I query windows server events between two times of any day?
I have tried with PowerShell...
Get-EventLog -Logname xxxx -After 04:00:00 -Before 04:00:30

...but just returns today's events
Answer: To find events between two times at any day we'll want to use a regex. Example code to find any event that happened between 04:00:00 and 04:29:59 of any day in the System log:
Get-EventLog -LogName System | ?{$_.TimeGenerated -match "04:[0-2][0-9]:[0-5][0-9]"}

Comment: Thanks Mikael, but how can I ask the same query for ANY day (if possible) in an elegant way?
Comment: Initial reply updated to actually answer the question.
Comment: @MikaelH, That's great. Can you explain more about the regex part (`04:[0-2][0-9]:[0-5][0-9]`)? for example if my time range is `04:00:55 - 05:12:03` then how to modify the regex?
Comment: @Tom, Each bracket represents the allowed range for a single character in the TimeGenerated field. For the first example given, I knew that we'll always want to look within hour number 4, i.e. "04". To also include events from hour number 5, we'd replace "04:" with "0[4-5]:". The next part of your request gets significantly more hairy: We'd need to program our "where" query ("?") to include only the last five seconds of the minute "4:00:", and only the first three seconds of the minute "5:12:".I'd define these non-general qualifications in "or", or "and not" clauses next to the main one.
Comment: @Tom, Just to illustrate my point, the first part of your query would look something like this:

Get-EventLog -LogName System | ?{$_.TimeGenerated -match "04:00:5[5-9]" -or $_.TimeGenerated -match "04:0[1-9]:\d\d" -or $_.TimeGenerated -match "04:[1-5][0-9]:\d\d"}
Comment: @Tom, Someone who is more fluent in regex could probably shorten that to a lovely unreadable chunk-o-chars, but I'm a simple man. :)


Connect a balanced mono output - to - an unbalanced stereo input?

Question: I am looking at purchasing this line mixer: https://www.monoprice.com/product?p_id=615108
    Here is the manual: https://downloads.monoprice.com/files/manuals/615108_Manual_160818.pdf
At the output stage, I need to send to:
 1. A stereo receiver that has dual female RCA
 2. A laptop line input jack, 1/8" unbalanced stereo (to record into GarageBand)
EDIT:{the entire mixer is mono!}
The mixer provides: "Balanced XLR and TRS outputs carrying the mixed signal after the Master Volume Control."
I am 99% sure I can use an XLR to dual male RCA cable to send to the receiver.
What I can't figure out is if I will be able to use the 1/4" output to send to the laptop. The mixer sends balanced mono, but the laptop is expecting unbalanced stereo. How can I make them communicate?
I've tried searching a lot, and this article asks basically the same question - TS vs TRS cables to connect mixer to audio interface - but the conclusive answer seems to be "it depends on your specific equipment," and I don't know how to apply that to the pieces I'm looking at.
Can you help? Thank you!
Comment: do you *really* want mono? If you go for a 2-channel output mixer, you can, say input a mono instrument or mic, pan hard to one channel and arm your track for that as mono in garage band. You can use the tape out to control levels to the laptop and the main outs for monitoring on your receiver. etc
Comment: Sure, it's not that I specifically want mono, just that it really doesn't matter in this situation. This is for a small meditation center that's just using mics for talking and iTunes for playing recorded prayers. No instruments, no music performance, no panning or effects needs.
Comment: And most of the people who will run this have *no idea* about audio, so it's been stressed to me by the decision makers that the board has to be "very simple," meaning as few EQ, effects, sends, etc. knobs as possible. If I send them a Yamaha MG10, they'll freak out - they basically want one volume knob per channel, nothing else. There are some simple, small mic mixers, but we need to have inputs for 3 mics and a feed from iTunes, and then the two separate outs for the receiver and back into GarageBand.
Comment: I have spent many hours looking at mixers and I've found it exceedingly difficult to find something with that input and output capability that isn't also a complete mixer with EQ, sends, pans, etc. And finally, budget is a concern, $100 was the target.
Answer: A normal balanced TRS output is automatically "degraded" to an unbalanced one simply by connecting a TS jack. The way this works is, it forces the ring to ground level, then the tip voltage is
Utip = Uring + Usignal = 0 + Usignal = Usignal
i.e. the same as with an unbalanced output (which simply sets Utip = Usignal right away).
So to connect this mixer to the laptop, simply use a 2×mono-TS to 1×stereo-TRS cable. The mono plugs convert the outputs to unbalanced, the cable combines those two signals to a stereo one.
Comment: Thank you! I understood the first idea, that balanced TRS gets downgraded to unbalanced via TS. But then it looks like your conclusion is to use a dual mono TS 1/4" to single TRS 1/8", but the mixer only has one balanced 1/4" TRS out, not two. Can you clarify?
Comment: There's a comment from the linked thread that says: "If you had a stereo output socket (TRS) and plugged in a mono plug with only the tip and the sleeve, you'd be grounding one of the channels (probably the right, which is usually wired to the ring) which is not a great thing to do."
Comment: and this thread: https://sound.stackexchange.com/questions/25577/stereo-and-mono-cables-and-jacks-what-happens-when-you-cross-them - says: "Plugging a mono cable into a stereo jack will not work well. If it's unbalanced mono, the result will come out only on the left channel; if it's balanced it will come out L/R in opposite phase. Neither is usually acceptable."
Comment: Only _one_ balanced TRS out? That seems unlikely. Normally there are two balanced outputs for L and R channel, as well as a stereo, unbalanced headphone output.
Comment: Aha, that entire mixer is mono! Then obviously you need a split cable / y-box.
Comment: yes, entire mixer is mono. I was actually just thinking about that... but could you explain your solution more? It might sound like I know what I'm talking about, but I really don't lol. Could I run a 1/4" TRS male to dual 1/4" TS female adapter, and then just run out of only one of the females using a 1/4" TS to 1/8" TRS into the laptop? Or did you mean something different?


WCF Windows authentication with AspNetRoles

Question: Is it possible to configure WCF to use Windows credentials to authenticate users and the SQL AspNet Roles provider to store roles and authorizations?
Answer: You need to activate the ASP.NET Compatibility Mode because as you know WCF could be hosted outside of an ASP.NET context. Obviously by doing this you realize that your service now becomes tied to ASP.NET.
Comment: In what sense would it be tied to ASP.NET?  Can't I self-host the WCF service? or would I need to use IIS?

EDIT: Just read it from the article (This mode requires that the bindings use the HTTP transport and the service itself must be hosted in IIS.)
Comment: I currently have a self-hosted service with a net.tcp binding. I am using the AspSqlMembership and AspSqlRole providers without enabling ASP.NET compatibility mode.  The thing I am interested in is just replacing the membership provider with windows credentials while keeping the sql roles provider intact.


Python pandas - Join with substitution

Question: I am trying to update a dataframe df_1 with values contained in a dataframe df_2.
df_1
ID    B    val    val2
0     1     2      2
1     1     2      3
1     2     1      1
1     3     1      1
1     4     1      1

df_2
ID    B    val    val2
0     1     1      3
1     1     3      3
1     3     3      3

The result I want is reported below in df_3:
df_3
ID    B    val    val2
0     1     1      3
1     1     3      3
1     2     1      1
1     3     3      3
1     4     1      1

As you can the join columns are ID and B, and when there is a match in df_2 I substitute the values. Regarding values, df_2 contains the exact same columns of df_1.
There are two questions that mention that problem: Python pandas join on with overwrite and Python pandas - particular merge/replacement. These questions mention the exact same problem that I have, however when I try the solutions reported the join takes to much time, I have a huge dataset and I personally think that the mentioned solutions are suitable for small chunks of data. Furthermore, these questions are old, so I was wondering if there is any news in pandas that can speed-up this process.
Answer: You need using cumcount create the additional keys since the ID is not unique , then we do concat  with drop_duplicates
df1['keys']=df1.groupby('ID').cumcount()
df2['keys']=df2.groupby('ID').cumcount()
pd.concat([df1,df2]).drop_duplicates(['ID','keys'],keep='last').drop('keys',1).sort_index()
Out[31]:
   ID  B  val  val2
0   0  1    1     3
1   1  1    3     3
2   1  2    1     1

Update
df1.set_index(['ID','B'],inplace=True)
df1.update(df2.set_index(['ID','B']))
df1=df1.reset_index()
df1
Out[258]:
   ID  B  val  val2
0   0  1  1.0   3.0
1   1  1  3.0   3.0
2   1  2  1.0   1.0
3   1  3  3.0   3.0
4   1  4  1.0   1.0

Comment: What about B? As I wrote in the question ID and B identifies the lines to substitute. @W-B
Comment: I tried this approach and in actual fact is not working. I have modified the example to make it more precise.

Python pandas - Join with substitution


How to deal with non-normal heterocedastic data from a factorial experiment?

Question: I ran an experiment with two factors each with two levels, 5 replicates each combination and one response variable. My data are non-normal and heterocedastic. Transformations didn't help. I ran a permutation ANOVA (aovp - package lmperm - R), but I am not sure this is the right way to go and I don't know what to do about a post hoc test, because I have a significant interaction. This is what my data look like:
F1 F2 BIOMASS
A C 0.66
A C 0.31
A C 0.88
A C 0.55
A C 0.81
A D 0.39
A D 0.21
A D 0.17
A D 0.15
A D 0.18
B C 0.00
B C 0.18
B C 0.05
B C 0.00
B C 0.02
B D 0.16
B D 0.04
B D 0.21
B D 0.15
B D 0.06

Comment: What is your response variable? Is it a continuous variable that just happens to fall between 0 & 1? Is it the proportion of successes from some number of Bernoulli trials? Is it a continuous proportion?
Comment: Your permutation test will assume equal distributions under the null. If you're after a location-shift alternative that won't be suitable (but it might work for a scale-shift). My first instinct would be to consider something like a GLM but it partly depends on what your response is.
Answer: Your response variable is suspicious.  If it is a continuous proportion, you may want to pursue beta regression (I have an example of a BR in R here: Remove effect of factor on continuous proportion data using regression in R.  If it is the outcome of some number of Bernoulli trials (and you know the number), you should disaggregate and use logistic regression (or use a weighted LR).  The following assumes the data are simply from a continuous variable, and happen to be within the (0, 1) interval.
I think most of this may be covered by my answer here: Alternatives to one-way ANOVA for heteroscedastic data.  In general, permutation tests are not recommended when you have heteroscedasticity.  In your case, I might suggest using ordinal logistic regression.  Since you have a 2x2, the post-hoc tests are just two 2-group comparisons, which could be done by repeating the original analysis on the stratified data.  Under the assumption that the global test of the initial model is significant, I wouldn't even worry about multiple comparisons.
Comment: My response variable is plant biomass... it just happened to be between 0 and 1. I took a look at the alternatives to one-way ANOVA, but I have two factors to analyse. I also checked the ordinal logistic regression but I don't think it makes sense for my data. I'll keep searching. Thanks anyways!
Comment: I recognize that that question was about one-way ANOVA & you have a two-way ANOVA, but most of the methods will generalize to >1 factor. OLR is the most general non-parametric approach. All you need is for your data to be ordinal in nature, ie you need to be able to confidently say .66>.31, if you can say that, you can use OLR.