AggCat Java Framework Cannot Read Certificate File

Question: I'm integrating the AggCat Java API into my webserver.  Unfortunately, the AggCat 1.0 Java framework cannot read my Java keystore (.jks) file correctly when I run it on a Tomcat (or GlassFish) web server.
I verified this by running the following identical code through a stand-alone Java program (where it worked perfectly), and then tried calling it in a Tomcat Servlet's method:
<code>public static void main(String[] args){
     AggCatTester aggcat = new AggCatTester();
     aggcat.testAggcat();
}

public void testAggcat() {
    Config.setProperty(Config.KEY_STORE_FILE, "./keystore.jks");
    Config.setProperty(Config.KEY_STORE_PASSWORD, "XXXXXXXX");
    Config.setProperty(Config.OAUTH_URL,
            "https://oauth.intuit.com/oauth/v1/get_access_token_by_saml");
    Config.setProperty(Config.CERT_ALIAS, "XXX");
    Config.setProperty(Config.KEY_PASSWORD, "XXXXXXXXX");

    OAuthAuthorizer oauth = new OAuthAuthorizer(consumerKey,
            consumerSecret, samlProviderId, userId);
    er.service = new AggCatService(new com.intuit.ipp.aggcat.core.Context(oauth));

    InstitutionDetail details = er.service.getInstitutionDetails(455);
    System.out.println(details.getInstitutionName());
}
</code>
When I call the testAggcat() method from a stand-alone command-line java program, it works no problem and prints the Institution defined by ID 455.  When I call the testAggCat() method from a servlet, I get an "UnrecoverableKeyException" that says my keystore password is invalid with the following stacktrace:
<code>    SEVERE: com.intuit.ipp.aggcat.exception.OAuthException: com.intuit.ipp.aggcat.exception.AggCatException: Exception while reading the certificate file
    at com.intuit.ipp.aggcat.util.OAuthUtil.getOAuthTokens(OAuthUtil.java:82)
    at com.intuit.ipp.aggcat.util.OAuthUtil.getOAuthTokens(OAuthUtil.java:57)
    at com.intuit.ipp.aggcat.core.OAuthAuthorizer.<init>(OAuthAuthorizer.java:85)
    at com.astar.zloty.webservice.rest.impl.EmployeeResource.initialize(EmployeeResource.java:97)
    at com.astar.zloty.webservice.rest.impl.EmployeeResource.testApi(EmployeeResource.java:72)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:680)
    Caused by: com.intuit.ipp.aggcat.exception.SamlAssertionException: com.intuit.ipp.aggcat.exception.AggCatException: Exception while reading the certificate file
    at com.intuit.ipp.aggcat.util.SamlUtil.createSignedSAMLPayload(SamlUtil.java:159)
    at com.intuit.ipp.aggcat.util.OAuthUtil.getOAuthTokens(OAuthUtil.java:72)
    ... 48 more
    Caused by: com.intuit.ipp.aggcat.exception.AggCatException: Exception while reading the certificate file
    at com.intuit.ipp.aggcat.util.SAMLCredentials.<init>(SAMLCredentials.java:60)
    at com.intuit.ipp.aggcat.util.SamlUtil.createSignedSAMLPayload(SamlUtil.java:155)
    ... 49 more
    Caused by: com.intuit.ipp.aggcat.exception.AggCatException: Exception when loading the cert.
    at com.intuit.ipp.aggcat.util.SAMLCredentials.loadCredential(SAMLCredentials.java:118)
    at com.intuit.ipp.aggcat.util.SAMLCredentials.<init>(SAMLCredentials.java:58)
    ... 50 more
    Caused by: java.io.IOException: Keystore was tampered with, or password was incorrect
    at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:771)
    at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:38)
    at java.security.KeyStore.load(KeyStore.java:1185)
    at com.intuit.ipp.aggcat.util.SAMLCredentials.loadCredential(SAMLCredentials.java:94)
    ... 51 more
    Caused by: java.security.UnrecoverableKeyException: Password verification failed
    at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:769)
    ... 54 more
</code>
Answer: Could you submit a support ticket (http://developer.intuit.com/Support.html) with the war file so I can verify the structure of the app and contents of the config ?
Answer: I was facing this issue. My problem went away by putting the keystore.jks file directly at the root of the classpath instead of placing it in some folder in the classpath.
keystore.jks


Como fazer os elementos aparecerem com o scrool do mouse?

Question:

Visibility.onVisible(function(){
 setTimeout(function(){
  $(".animar").addClass("animated fadeInDown"); }, 400);
 setTimeout(function(){
  $(".animar2").addClass("animated fadeInDown"); }, 800);
 setTimeout(function(){
  $(".animar3").addClass("animated fadeInDown"); }, 1200);
 setTimeout(function(){
  $(".animar4").addClass("animated fadeInDown"); }, 1600);
 setTimeout(function(){
  $(".animar5").addClass("animated fadeInDown"); }, 2000);
});
html,
body {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}
.animar,
.animar2,
.animar3,
.animar4,
.animar5 {
  opacity: 0;
}
.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}
@-webkit-keyframes fadeInDown {
  from {
    opacity: 0;
    -webkit-transform: translate3d(0, -100%, 0);
    transform: translate3d(0, -100%, 0);
  }
  to {
    opacity: 1;
    -webkit-transform: none;
    transform: none;
  }
}
@keyframes fadeInDown {
  from {
    opacity: 0;
    -webkit-transform: translate3d(0, -100%, 0);
    transform: translate3d(0, -100%, 0);
  }
  to {
    opacity: 1;
    -webkit-transform: none;
    transform: none;
  }
}
.fadeInDown {
  -webkit-animation-name: fadeInDown;
  animation-name: fadeInDown;
}

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

Este código utiliza uma biblioteca chamada VisibilityJS. Toda vez que eu recarregar a página ela faz com que conteúdo apareça de uma transição suave.
Eu quero fazer com que o conteúdo só apareça com o scrool/rolar do mouse.
Como neste exemplo
Como posso fazer isso?

Se houver outro plugin que faça isso também aceito. Meu objetivo é aprender a colocar essa animação em qualquer site.
Comment: É assim que queres? http://jsfiddle.net/Lt4ojtyp/
Comment: Acho que é duplicada de http://pt.stackoverflow.com/a/16479/129
Comment: Não é não. O efeito é diferente ;)
Comment: Podes explicar de que maneira é diferente? Ou seja, qual é a diferença que o outro link não mostra como fazer?
Comment: No outro link, ao acionar o scrool do mouse o conteúdo já está lá e tem seu tamanho expandido. Eu quero que o conteúdo esteja oculto e ao rolar o mouse ele apareça de uma forma suave
Comment: Exatamente assim: https://pages.github.com/
Answer: Fala, Zkk! Tudo bem?
Confere se esse artigo resolve seu problema.
A didática é simples e na minha opinião esse é o método mais fácil de reproduzir esses efeitos. Além de tudo ele explica sobre o viewport, que é parte importante na lógica pra criar isso.
Abraços!


How can I trigger 2 transforms one after the other with a delay in CSS?

Question: I'm making a menu button with 3 bars (sometimes referred to as a hamburger button) that turns into an X when clicked. I can't figure out how to trigger 2 transforms in one element without them triggering at the same time for the animation.
This script kind of works, but they both trigger at the same time:
transform: translate(10px, 10px) rotate(45deg);

My goal is for the translate to complete, and then the rotate to start after. (I need to use transitions because they are spam-proof, unlick keyframe animations.) One thing I've tried is putting something like this instead:
transform: translate(10px, 10px);
transform: rotate(45deg);

But only the bottom one activates. To fix this, I added this:
transition: transform 0.4s 0.4s, rotate 0.4s 0.4s;

to the mix, but that only added a delay to one of the transforms, still leaving the other broken. My last idea was to use rotate(deg) instead of translate(px) but there doesn't seem to be a way to center the rotation. I can post my full code if required.
Answer: Use translate and rotate as separate CSS properties:

.foo {
  transition: translate 1s 1s, rotate 1s 0s;
}

.foo:focus {
  transition: translate 1s 0s, rotate 1s 1s;
  translate: 10px 10px;
  rotate: 45deg;
}
<button class="foo">Focus me for a demo</button>
Comment: That worked, thanks! One more question: How can I reverse the movement back to the original position? For example if in your test the button rotated and then moved back into place after being unfocused. (Also I can't vote up because of new account, but pretend I did lol)
Comment: @TheDudeofDC sure, just invert the transition delays for the state. Edited my answer. You don't need to vote up, you can always read [tour].


On Apache how to switch off DirectorySlash only for requests to a specific subdomain?

Question: Served by Apache I'd like on one subdomain site of mine (say sub.mydomain.com) that URLs without trailing slashes point directly (without external redirect) to the index file in the underlying folder. The subdomain requests are internally redirected to a sub-folder. All other URLS should work in the normal Apache way with external redirect to the slashed version.
All the directives have to go in my .htaccess file. For this to work I am planning to do the following:

Switch off DirectorySlash for requests to sub.mydomain.com/...
Rewrite the sub.mydomain.com/… requests to /sub/...
Rewrite slashless directory URLs with  /sub/... to fetch the index.html inside the underlying directory

I have a good idea how to do 2. and 3., but how can I issue DirectorySlash off only for requests to sub.mydomain.com, but not to www.mydomain.com or other.mydomain.com?
Comment: Presumably the confusion is that the subdomain `sub` points to the same place as the main domain and all other subdomains?
Comment: @MrWhite The requests to the sub are redirected into the folder /sub. So I only want to switch Directory slash off for everything in that folder. Does that make sense?
Answer: By the sounds of it, your sub subdomain maps to the same directory as the main domain and all other subdomains (www and other, etc.)
However, if all requests to the sub subdomain are internally rewritten to the /sub subdirectory then you can presumably just create another .htaccess at /sub/.htaccess in which you set DirectorySlash Off - this then applies to all requests to the sub subdomain. (Assuming you don't also access the same subdirectory via a different hostname. You can prevent this if you wish.)
The /sub/.htaccess file is also where you would be implementing #3 in your requirements.
The root .htaccess file simply rewrites all requests to the sub subdomain to the /sub subdirectory.

Aside: Since you are asking this question on ServerFault it is generally assumed that you have full control of the server. In which case it would be preferable to configure this sub subdomain in its own vHost container that points directly to the /sub subdirectory (or somewhere outside of the main domains directory tree ideally). In this case, you would not need to implement #2 of your requirements and you just set DirectorySlash Off for the entire subdomain.
Comment: It works! As you suggest, the trick is to have a secondary `.htaccess` in the `/sub`. Super cool!


How to retrieve last update time of each document in MongoDB?

Question: I would like to know if there is a way to get the last update/modify time of data (i.e documents) in a collection in MongoDB. More clearly, I want to make a query to retrieve all documents updated after a particular time.
Is there any possible ways to retrieve this last modified timestamp in MongoDB?
Note: For newly created documents, I know that we can retrieve the timestamp from the objectId, but for an update, the id is going to be same. Does MongoDB store the last update time for each document anywhere?
I am using morphia as the java driver, so if there is any possible way from morphia, please let me know.
Comment: Possible dup of http://stackoverflow.com/questions/9462656/update-time-of-each-record-in-mongodb
Answer: You need to capture last update time yourself.
For my application, I keep an AuditTrail object, which captures AuditEvents. These events occur on any insert, update, or delete of an object (delete is virtual in my system, just setting a flag).
For each AuditEvent, I keep track of the date, authenticated user, db action, and a description filled in by the application. This is implemented in PersistentObject, so it is automatically called for any database action of any object saved in Mongo.
This actual took very little time to implement, but provides both the ability to get the last update time, and also any other information that you may need for security and customer support for everything in Mongo.
Comment: No - just in my DAO framework. I haven't looked at releasing my code to the community. I don't have any issues about, just never thought of it.
Answer: No, MongoDB by itself does not store either creation or update timestamps. You have to do that yourself (and as you have found out, if you use an ObjectID _id then you get the creation date already).
Comment: Not exacctly true. MongoDB does store the createdTime though.. we can access it via ObjectId("theIdofThedocumen").getTimeStamp()
Comment: Oh yes of course you're right. But I think it's always better if we dont overwrite _id...
Comment: **Object creation timestamp**,
As mentioned by @AminMohamedAjani,  [ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()](https://docs.mongodb.com/manual/reference/method/ObjectId.getTimestamp/#example) works, but it's Object creation timestamp.
Comment: @AminMohamedAjani: Only if you use an ObjectId created at document creation time for the `_id` field (you don't have to).
Comment: here is the tool for retrieving the date from the id
https://steveridout.com/mongo-object-time/
Answer: You can either use an audit trail entity as @user1530669 mentioned (I'm calling mine delta - the code is already available somewhere on StackOverflow).
Or you can simply save the last change time. I'm generally using a base entity to set that up and all other entities extend it (for your specific requirement you can probably remove the creationDate as the lastChange is enough for you):
protected Date creationDate;
protected Date lastChange;

// Getters and setters or final setters which don't do anything,
// if you only want to allow the entity to update the values

@PrePersist
public void prePersist() {
    creationDate = (creationDate == null) ? new Date() : creationDate;
    lastChange = (lastChange == null) ? creationDate : new Date();
}

And in your queries you can then add a filter so that the lastChange attribute is more recent than your retrieval limit.
Answer: You can do the following. With MongoDB version 4.2+, you can now perform aggregation operators like $toDate to extract the timestamp from ObjectId "_id" and update at the same time.
Here we use the aggregate query $toDate to extract the timestamp from MongoDB's ObjectId "_id" field and update the documents using {$replaceRoot: {newRoot: "$$ROOT"}} instead of explicitly stating $set
var collection = "person"

agg_query = [
    {
        "$addFields" : {
            "_last_updated" : {
                "$toDate" : "$_id"
            }
        }
    },
    {
        $replaceRoot: {
            newRoot: "$$ROOT"
        }
    }
]

db.getCollection(collection).updateMany({}, agg_query, {upsert: true})

Comment: How to find execution time for updateOne operation ?


If $Q$ is square matrix and $Q Q^T=I$, prove that $|\text{det}\:(Q)|=1$

Question: If $Q$ is square matrix and $Q Q^T=I$, prove that $|\text{det}\:(Q)|=1$
Any help is appreciated. Thanks!
Comment: How do $\det Q$ and $\det Q^T$ relate?
Comment: Well, I think det|QQ^T| = 1 . Am I righ?
Comment: Q^T is the transpose of Q
Comment: And what do you know about $det|Q  Q^T|$
Answer: Hints:

From $QQ^{T}=I$, how are $Q^{-1}$ and $Q^{T}$ related. Can you relate this to orthogonal matrices?.
Can you think about the Eigen values of orthogonal matrices?
What is the relation between eigenvalues and determinant for a square matrix?
Answer: We know that: det(Q) = det(${Q^T}$) ........(1)
From question
det(Q${Q^T}$) = det(I) = 1
det(Q)*det(${Q^T}$) = 1
${det(Q)^2}$ = 1 ...........(from (1))
So, det(Q) = +1 or -1
Hence |det(Q)| = 1
QED
Answer: $1=\text{det}\:I=\text{det}\:(QQ^T)=\text{det}\:(Q)\times\text{det}\:(Q^T)=[\text{det}\:(Q)]^2\implies \text{det}\:(Q)=\pm1$ so that $|\text{det}\:(Q)|=1$.


how to create a win32 application with Windows menus using c++ and using the visual studio 2017 menu editor

Question: After creating a win32 project using visual Studio 2017 community I have added to the menus pop downs that are already there. After I added below 'File' a popup item 'Mypop', I opened the properties of the new option and copied the ID; 'ID_FILE_MYPOP' into my WndProc WM_COMMAND loop.
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
...
case ID_FILE_MYPOP:
break;
It appears with error message "identifier ID_FILE_MYPOP is undefined".
I can only correct this by opening the resource.h file, it responds "this file is already open in another device do you want to close it?". If I reply yes, then I can see the contents of resource.h file and it includes ID_FILE_MYPOP. Then if I close the resource.h file the error message in WndProc disappears and the menu addition works correctly.
MY QUESTION IS:
Do I have to open and close the resource.h header file every time I add a menu item to resource.rc file?
What application might have the resource.h file open?
If anyone could help me I would really appreciate it.
ps I can also remove the error statement if I open and shut the project solution.
<code>LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM
lParam)
{
    switch (message)
{
    case WM_COMMAND:
    {
        int wmId = LOWORD(wParam);
        // Parse the menu selections:
        switch (wmId)
        {
        case  ID_FILE_MYPOP:
            break;
        case IDM_ABOUT:
            DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
            break;
        case ID_NEWEDITIDAPPROACH:
            break;
        case IDM_NEW7:
            break;
        case IDM_EXIT:
            DestroyWindow(hWnd);
            break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
    }
    break;
</code>
...}
Answer: Double click the resource file in the solution explorer - the resource editor should open (and this is the app opening the resource.h):
Comment: Thank you for your comment. I have always double clicked on, in my case, Win32test.rc and I can create a popup menu and obtain an ID. But when I close Win32test.rc the ID gives the error code  "this file is already open in another device do you want to close it?" and the problem remains as described above. ie Do I have to open and close the resource.h header file every time I add a menu item to resource.rc file?
Comment: Both the rc file and the related header can be either opened in the text editor OR in the resource editor. Opening the files in the text editor causes usually that questions from VS. I know that this is confusing and not properly solved (e.g. a "show definition" opens often the header file).
So usually both files should be closed -- then the resource editing should work.
Comment: Its surprising that something so basic as adding a resource is so clumsy. It is reassuring to hear that you have found the same clumsiness, thankyou for your comments.


Sequelize.js: how to sort query results based on values in where in closure ?

Question: I issue the next query:
<code>        Users.findAll({
            where : {
                user_id: {
                    in : [ data.user_id, data.user_id_to_replace ]
                }
            }
        }).then(function(results){})
</code>
I would like the results would be sorted by the order I have in the where in closure, i.e. first come for data.user_id and only then data.user_id_to_replace. I know how to do this in javascript, but I'm looking if there is a param in Sequelize that does this job for me. Thanks.
Answer: Ok, seems there is no sequelize built-in solution to my problem. Then here is a method using underscore I used for sorting finally. Hope this will be helpful someone looking to solve the same issue:
<code>_.sortBy(results, function(item) {
    return item.get('user_id') === data.user_id ? 0 : 1
})
</code>


Is there a name for the set of the pair/impair equivalence classes of the permutations of a set?

Question: In the theory of abstract simplicial complexes, a face of an abstract simplicial comples is a set, while an oriented face is one of the two equivalence classes of the permutations of this set under the equivelence relation based on the parity of the number of inversions. Is there a name for these equivalence classes?
Edit:
Sorry, I posed my question badly. Really, I am looking for a name of the set of these two equivalence classes. E.g., if the desired name is somename, then I'd like to say, that "Given a set $S$, an elements of somename of $S$ is called an oriented face."
Edit 2
Or, still it is good also, if the name refers to the equivalence classes itself, but simmetrically. E..g. "The othersomenames of $S$ are called oriented faces".
(The title also changed)
Comment: how about 'odd' and 'even'?
Answer: So one of the classes is called "alternating," and I guess the other could be called "non-alternating."  Or, alternately, "odd" and "even."
Edit: So you're essentially asking of there's a specific name for the group $S_n / A_n$?  I haven't heard of one; usually people call it by its isomorphism class, $C_2$.
It would follow a general pattern to refer to "a permutation, up to an even permutation," but that sounds horrible.  "A parity of permutations" would perhaps be a bit better.
Comment: or, perhaps the *parity class* of the permutations of the set (if it doens't interfere with other notions)?


Best practice for running an ansible role conditionally

Question: Is there a standard or best practice for running roles conditionally?
If I have the following basic playbook:
---
- hosts: prod
  gather_facts: false
  become: true
  become_method: sudo
  vars_files:
    - variables/vars.yml
  pre_tasks:
    - name: check app existence
      command: ls /data/myapp
      # Store the resuts here
      register: app_exists
      ignore_errors: yes
  roles:
    - os_base_setup
    - selinux_setup
    - libsemanage_install
    ...
    # Conditionally run this role
    - - { role: app_clean_install, when: app_exists|failed }
    - post_install_config
    - cleanup
...

Downsides I can see to this method:
This always reports the 'pre task' as having made a 'change'.
It also reports each individual task with the 'skipped' role as being skipping, instead of just skipping the entire role.
Comment: Typing a question mark somewhere does not necessarily make it a question.
Comment: Thanks for the feedback... the question was not stated clearly, so I've made an edit.
Answer:
This always reports the 'pre task' as having made a 'change'.

Use
changed_when: false

when you execute a shell command and you know, that it gathers just information, but does not change anything.

It also reports each individual task with the 'skipped' role as being skipping, instead of just skipping the entire role.

Set in your ansible.cfg
stdout_callback = skippy

to ignore skipped tasks.

Is there anyway to stop this pre_task from logging the error when the test fails?

It is not possible prevent the logging of an error. But it is possible to ignore an error with the following option:
failed_when: false

In this case the error is logged but the playbook does not stop the execution. This is necessary to handle the error in the playbook. See here for an example.
Comment: Is there anyway to stop this pre_task from logging the error when the test fails? atm the first task logs a bunch of red error text.


length of the tangent

Question: A Circle is inscribed in a triangle $ABC$, where $AB=10 cm$, $BC=9 cm$ and $AC=7 cm$ . $X$, $Y$, $Z$ are points of contact of the sides $AC$, $BC$ and $AB$ with the circle respectively. $BZ=?$
In the first look, question looked simple to me. But I am not able to get to the answer. I found the In-radius using $rs = \sqrt{s(s-a)(s-b)(s-c)}$. But that is not helping me to find the required length.
<code>In the above formula,
    r= indradius
    s=(a+b+c)/2
    a,b,c -> Lengths of the sides of triangle
</code>
I would be glad to see the answer of this question. Any Hints or answers are welcome. Thanks.
Sandy
Comment: The equations are easy to solve, but let's make it nicer. Let $BZ=p$, $CX=q$, $AZ=r$. Then $p+q+r=(10+9+7)/2=s$ (half-perimeter). So $p=s-b=13-7$.  Note the appearance of the term $s-b$, which will remind you of Heron's Formula.
Answer: It's much easier than you're making it.  XC = YC, XA = ZA and BZ = BY, because in each case, you've got two tangents up to the same point.
That gives you enough to solve for all of the lengths.  In particular (with all lengths in centimetres) BZ = 10  - AZ = 10 - AX = 3 + XC.  But because BY + YC = 9, this gives BZ = 6.
Comment: Hey thanks. Dint look at the problem that way.

length of the tangent


What is the correct way to handle caching with custom modules?

Question: I'm experimenting with creating a custom module in Drupal 8. I have created a module that has some custom database tables. One of these tables, "mymodule_tickets" gets populated via admin forms that I have created within the module.
On the public side of the website, I have another custom page setup ('/booking'), which displays a form containing the available 'tickets'. For the mostpart, this works really well, but I am having some trouble understanding caching.
The '/booking' page uses the drupal form api to create a 'number' field for each available ticket. The '#title' of each form field is the name of the ticket as setup in the admin area. When anonymous users view the /booking page, the titles of these form fields cache. If I change the title of the ticket in my admin area, this does not get reflected on the public site for anonymous users.
My first attempt at remedying this was to add this when building the form:
<code>$form['#cache']['max-age'] = 0;
</code>
But unfortunately this did not make any difference. Changes to the titles of form elements were still not reflected to the user.
In the end I had to add the following to my routing file:
<code>  options:
    no_cache: TRUE
</code>
While this did work and stopped the form titles from caching, it feels like a very heavy-handed way to fix the problem. To me the correct solution would be to cache these pages for anonymous users, but to correctly invalidate the cache after making changes in the admin area.
Are there any guides or code snippets or articles about how to do this? From searching the web I haven't been able to find any relevant information or examples.
Answer: In your page controller for /bookings, set a cache tag in the build array:
<code>$build['#cache'] = [
  'tags' => [
    'booking_page_settings',
  ],
];
</code>
Or since it's a form:
<code>$form['#cache'] = [
  'tags' => [
    'booking_page_settings',
  ],
];
</code>
Then when you submit the admin form that has the settings for the page, invalidate the tag:
<code>Cache::invalidateTags(['booking_page_settings']);
</code>
You can also add to your cache tags the nodes that display on your booking page, such as 'node:123', or you can add 'node_list' to invalidate the caching when any node is updated.
Answer: This is a bit adjacent to this specific question, but if folks land here from search engines looking for information on how to cache custom data, I've created a module to help with that:  https://www.drupal.org/project/cache_register


java/swing: gui froze, no thread suspended

Question: To start with it is a huge application and the problem concerns many lines so I can't really attach any code.
After a change that consists mainly of clearing and re-adding elements to some collection, swing GUI of the application freezes. That freeze doesn't happen while that added code is executed but some time afterwards. What makes it strange is that no thread is suspended.
My question is whether the infinite loop is the only explanation of this problem. It feels unlikely to me that this is the case because the added code finishes without problems.
There may be some unsynchronized collection access issue, but I don't see it leading to that situation. It doesn't look also like we are dealing with a deadlock coming from synchronization problem since no thread is suspended.
Comment: Have you tried using a debugger? If the GUI freezes, you should see something in the Event Dispatching Thread (in Eclipse you can pause any Thread on the fly and see where it is currently). Another option, is to use JConsole and look at the Threads and their current stack call.
Comment: GUI freeze ... take a thread dump and see what is blocking the AWT thread
Comment: Those were good tips, Guillaume and Robin. Thanks.
Answer: In the end it is a deadlock.
My team leader told me that threads waiting on monitor (on "synchronized") aren't shown in eclipse as suspended. He found some two threads and asked to pause them. Then I saw they are waiting for each other to release the occupied monitors.
The deadlock isn't fault of the code I entered. It's just that the change I made revealed wrong synchronization in some other place.
Thank you all for trying to help me, I really appreciate it. It is my first question on stackoverflow and I was surprised how fast had you reacted.
Answer: You might already know this, but just for the sake of it i would say that if you have not used a Swing worker in your long running processes within your app, this would be a ideal situation to use it.
Comment: This GUI implementation is based on listeners and swing worker is also used. The code I added finishes instantly.
Answer: Huge application + manipulating collections -> garbage collector kicks in?
Some related reading here at SO:
side effect for increasing maxpermsize and max heap size
And Oracle article about GC tuning:
http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html
Answer: It may be because of waiting (due to some heavy processing) in Event dispatcher thread in swing where events are executed. Ideally you should execute any resource intensive task in a separate thread so that UI doesn't freeze


.co.za Nameserver issue

Question: I am trying to change the nameservers on a .co.za domain to the private nameservers set up on my dedicated server, but I get the error below. The nameservers work fine for a .co.uk domain name.
Not sure what to do, any help will be more than appreciated.
The Error is:
Command failed; CheckDNS: ns1.wpserver.com not authoritative SOA.
If you wish to change the nameservers for your .co.za domain, please make sure that the domain has a valid zone in the new nameservers configuration. Please contact your new host if you are still having problems.
Comment: You did not give us enough information about your working environment like: OS, nameserver used, etc..
Answer: The nameserver you've specified (ns1.wpserver.com) is not authoritative for the domain. You need to configure your nameservers with your zone before you update the co.za delegation.
Answer: If it says not auth SOA, edit the dns SOA record for that domain and plop in the first nameserver you use. (want to use)

.co.za Nameserver issue


node process out of memory

Question: I want to understand why a simple node process run out of memory.
Out of fun, I tried to console.log 10 million times, after some time I got an error
<--- Last few GCs --->

  215529 ms: Scavenge 1485.5 (1532.7) -> 1485.5 (1532.7) MB, 43.9 / 0 ms (+ 1.8 ms in 1 steps since last GC) [allocation failure] [incremental marking delaying mark-sweep].
  216476 ms: Mark-sweep 1485.5 (1532.7) -> 1435.3 (1482.5) MB, 947.9 / 0 ms (+ 2.9 ms in 2 steps since start of marking, biggest step 1.8 ms) [last resort gc].
  217537 ms: Mark-sweep 1435.3 (1482.5) -> 1435.3 (1482.5) MB, 1060.2 / 0 ms [last resort gc].

<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x76575fe3ac1 <JS Object>
    1: _writeGeneric [net.js:645] [pc=0x1f0bf7164345] (this=0x6175737bfe9 ,writev=0x76575f04299 <false>,data=0x3d61a01691b9 <String[18]\: madan chutiya hai\n>,encoding=0x76575fed8d9 <String[4]: utf8>,cb=0x61757359889 <JS Function WritableState.onwrite (SharedFunctionInfo 0x61757359411)>)
    2: writeOrBuffer(aka writeOrBuffer) [_stream_writable.js:~255] [pc...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory
Abort trap: 6

The simple program I am executing is
for (var index = 0; index < 10000000; index++) {
        console.log('hello world');
}

What is the reason behind out of memory error?
Comment: My best guess would be that the garbage collection cannot run as this is blocking code. If you add something like `process.nextTick()` as some point it should be able to unblock, run gc, free up some memory and then continue execution.
Answer: Update:
Ben Noordhuis talks about console.log memory here: https://groups.google.com/forum/#!topic/nodejs/KtONbpVV68U
"Each console.log() statement allocates some memory that is not
reclaimed until the next tick of the event loop."
So that is why you run out of memory even though you aren't necessarily creating a bunch of objects.
Original:
Building on @Vasil's comment I think he is right. The event loop is blocked and cannot run garbage collection. FWIW I didn't have any issues running your example code on node v6.2.2. But if you play around with the allocated memory I can reproduce your issue by adding these flags: --max-executable-size=192 --max-old-space-size=256 --max-semi-space-size=2. To prove the process.nextTick() theory we can modify your test script to something like this:
// test.js
var BATCH_LIMIT = 250000;
var TEN_MILLION = 10000000;

var useNextTick = true; // switch to false to reproduce out of memory error

function log(start, end) {
  for(var index = start || 0; index<end; index++) {
    console.log('hello world', index);
    // if useNextTick is enabled we will call next tick every 250,000 iterations so GC can run
    if(useNextTick && index && index % BATCH_LIMIT === 0) {
      console.log('NEXT TICK');
      // bind the next start and end points to the log function that process.nextTick will call
      return process.nextTick(log.bind(this, index+1, index + (TEN_MILLION - index)));
    }
  }
}

// kick it off with 10,000,000 iterations
log(0, TEN_MILLION);

And run it with limited memory:
node --max-executable-size=192 --max-old-space-size=256 --max-semi-space-size=2 test.js
There is probably a cleaner way to code that but hopefully it gives you an idea of what is actually happening and why its important not to block the event loop.
Comment: I understand that there is no gc happening. But what is the need for gc. I am not creating any objects, there is no memory leak etc.
Answer: You could also use the --expose-gc Node.js flag like so:
https://simonmcmanus.wordpress.com/2013/01/03/forcing-garbage-collection-with-node-js-and-v8/
and then use
global.gc();

within the loop; try that in combination with process.nextTick()

node process out of memory


What is the equivalent of domain_get_domain()?

Question: I need the equivalent of domain_get_domain() in the Domain Access module for Drupal 8, but I can't find it.
I need to find the domain for the current request.
Answer: Finally worked out the following ...
$domainNegotiator = \Drupal::service('domain.negotiator');
$current = $domainNegotiator->negotiateActiveHostname();

There are other methods on the DomainNegotiator service that I thought should work, particularly getActiveDomain() and getActiveId(), but they didn't return the domain I was actually on like I thought they would.
It's still a bit confusing to me, but I made it work.
EDIT:
@berramou 's answer below helped as well. Originally, I was looking for the Domain object (from the Domain Access module), but it turns out the host was enough to match a Domain reference on my entity.
Answer: In drupal 8 there is \Drupal::request() to get request info.
For Example if your url something like https://example.com
If you want only the domain name example.com
$domain = \Drupal::request()->getHost();

if you want the domain name with schema http or https https://example.com use this:
  $domain_with_schema = \Drupal::request()->getSchemeAndHttpHost();


Transform $2^{2\log n}$, given that $\log$ is base 10, to $n^{2/\log_2 10}$

Question: Can anyone show me the step by step transformation? This is the answer given in a class but I'm getting tripped up over here. Thank you.
Comment: What did you try? Where exactly did you get stuck? It's a straightforward application of logarithm properties.
Answer: Note that
\begin{eqnarray}
n^{\frac{2}{\log_{2}{10}}}&=&n^{\frac{\log_{2} 2^2}{\log_{2}{10}}}=n^{\log 2^2}=2^{\log_{2}{n^{\log 2^2}}}=2^{\log 2^2\log_2{n}}=2^{2\log 2\log_2{n}}=2^{2\log 2\frac{\log{n}}{\log 2}}=2^{2\log{n}}
\end{eqnarray}


If an English qualified team is banned from the champions league, who takes over the vacant spot?

Question: As of the time of this question, there are talks that Manchester City may be banned from the UEFA Champions League 2019-20 competition.
If a top-four English Premier League team is banned, who takes the vacant slot?
Answer: Teams of the English Premier League can earn a maximum of five places between them in the UEFA Champions League, and a maximum of seven places in all European continental competition.
Those places are allocated as follows:

Winner of UCL 18-19, if any
Winner of UEL 18-19, if any
EPL 18-19 #1
EPL 18-19 #2
EPL 18-19 #3
EPL 18-19 #4 (gets dropped to UEL 19-20 if all five previous places are allocated already)

Thus for UCL 19-20, the allocation is currently held by

Liverpool or Tottenham Hotspur
Arsenal or Chelsea
Manchester City
& 5. Liverpool or Chelsea or Tottenham Hotspur (if not already qualified)
...
Arsenal (if not already qualified) (gets dropped to UEL 19-20 if placed here)

If Manchester City is removed, the remaining four teams between them are allocated four places, with the UCL place doubling up, and therefore England's allocation is done.
The exception to this is with Arsenal placed fifth, as they would not otherwise qualify, leaving an unallocated place, but it would be nonsensical to give it to a team ranked lower (e.g. Manchester United in sixth) instead, therefore Arsenal would likely go in place either way.
Comment: Thanks. This is what I figured, but I was watching a talkshow where one of the hosts stated that it was entirely POSSIBLE (but not likely), that United can potentially play UCL 19-20...
Comment: The only way to make that happen would be disqualify or ban two of the teams above them in EPL, or disqualify or ban virtually every other club in Europe, otherwise there is zero grounds for them to enter UCL.


How to add two feColorMatrix results? Just the sum of each RGB channel

Question: I can't seem to find this anywhere, but is there a way in an SVG filter to simply add two colors from 2 feColorMatrix's together? While there are many Porter-Duff operations available, the simple plus one doesn't seem to exist.
My color matrix's are built dynamically, so the values I send in to both will be different, but as a static example. Basically, I have a shape with a fill of rgb(68,114,196). I have two color matrix's that use that to get a new color. The result of the first one is RGB(43, 71,123) and the second one is RGB(8,13,22). Now I just want to add these together to get RGB(52, 88, 156). Simple, right? I can find anyway in feBlend, feComposite or other ways to do this.

    <svg x="50" y="20" width="144" height="144" overflow="visible">
              <defs>
          <filter id="newColorFilter" color-interpolation-filters="sRGB">

        <feColorMatrix in="SourceGraphic" result="color1" type="matrix" values="0.626095953 0 0 0 0 0 0.626095953 0 0 0 0 0 0.626095953 0 0 0 0 0 1 0"></feColorMatrix>
        <feColorMatrix in="SourceGraphic" result="color2" type="matrix" values="0.111116039 0 0 0 0 0 0.111116039 0 0 0 0 0 0 0.111116039 0 0 0 0 0 1 0"></feColorMatrix>

    </filter>
    </defs>
            <path d="M0,0 144,0 144,144 0,144 Z " fill="rgb(68,114,196)" filter="url(#newColorFilter)"></path>
 </svg>

Does anyone know a simple way to sum two colors in a filter?
Answer: <feComposite> has an arithmetic mode where you can define the composition formula by hand. If i1 and i2 are the input channels, you can set four parameters:
result = k1*i1*i2 + k2*i1 + k3*i2 + k4

A simple addition can be achieved with k2 = k3 = 1. (All other parameters are 0 by default.)
Yout second color matrix had an error (one value too much), btw.

<svg x="50" y="20" width="144" height="144" overflow="visible">
    <defs>
    <filter id="newColorFilter" color-interpolation-filters="sRGB">

        <feColorMatrix in="SourceGraphic" result="color1" type="matrix" values="0.626095953 0 0 0 0 0 0.626095953 0 0 0 0 0 0.626095953 0 0 0 0 0 1 0"></feColorMatrix>
        <feColorMatrix in="SourceGraphic" result="color2" type="matrix" values="0.111116039 0 0 0 0 0 0.111116039 0 0 0 0 0 0.111116039 0 0 0 0 0 1 0"></feColorMatrix>

        <feComposite operator="arithmetic" k2="1" k3="1" in="color1" in2="color2"></feComposite>
    </filter>
    </defs>
    <path d="M0,0 144,0 144,144 0,144 Z " fill="rgb(68,114,196)" filter="url(#newColorFilter)"></path>
 </svg>
Comment: so wonderful, that is exactly what I was looking for. thank you so much! and thanks for catching that error


Show that the set of the given vectors form a basis in $\mathbb R^3$ and represent the standard basis as a linear combination of these vectors

Question:
Show that the vectors $\langle 1,0,-1\rangle$,$\langle 1,2,1\rangle$,$\langle 0,-3,2\rangle$ from a basis in $\mathbb R^3$.
Represent standard basis in $\mathbb R^3$ as a linear combination of the given vectors.

By the definition a nonempty  linearly independent subset of vectors $S=\langle v_1,v_2,...,v_n \rangle$  from a vector space $V$ is a basis of $V$ if it spans $V$, in other words if every element of $V$ can be represented as a linear combination of the vectors in $S$.
We've given three vectors in $\mathbb R^3$,so we are allowed to use the fact that  The columns of an invertible  matrix are linearly independent ,thus the matrix is given by:
\begin{pmatrix}
1 & 1 & 0 \\
0& 2 & -3 \\
-1 & 1  & 2
\end{pmatrix}
With a nonzero determinant,so it follows that the vectors are linearly independent.
Now it's needed to show that every vector $\langle x,y,z \rangle$ in $\mathbb R^3$ can be defined as a linear combination of the given vectors,let $\lambda_1,\lambda_2,\lambda_3$ be some scalars,then :
$$  \begin{bmatrix} 1 & 1 & 0 \\
0& 2 & -3 \\
-1 & 1  & 2 \\  \end{bmatrix}  \left[ \begin{array}{c}  \lambda_1  \\
  \lambda_2  \\
 \lambda_3 \end{array} \right]=
\left[ \begin{array}{c}   x   \\
   y \\
   z  \end{array} \right] $$
Reduce it by elementary row operations gives:
$$  \begin{bmatrix} 1 & 0 & 0 \\
0& 1& 0 \\
0 & 0  & 1 \\  \end{bmatrix}  \left[ \begin{array}{c}  \lambda_1  \\
  \lambda_2  \\
 \lambda_3 \end{array} \right]=
\left[ \begin{array}{c}   x'   \\
   y' \\
   z'  \end{array} \right] $$
Where $x',y',z'$ are expressed as $x,y,z$.
Thus for every vector $\langle x,y,z \rangle$ in $\mathbb R^3$ it's possible to find scalars for which the vector can be defined as a linear combination of the given vectors which implies that the vectors span $\mathbb R^3$ and so the set containing them is a basis.
Another way would be using the fact that The set of three linearly independent vectors in $\mathbb R^3$ is a spanning set.

For the second part I thought that we need to find scalars and solve an equation ,but I guess for each one of the three standard basis we need to solve one system of equations which takes much time,so what else can I do? Does there exist a faster method?
Comment: Do the same row operations on the identity matrix, you'll receive the inverse of your matrix, and basically that's what you're looking for.
Comment: @  Berci ,Do you mean the second part? it would be appreciated if you post your solution with more details.
Answer: Let's call your matrix $A$.
Showing $\det A\ne 0$ is indeed enough to get linear independence of the column vectors, and since they are three, they form a basis of $\Bbb R^3$.
For the second part, you're basically looking for the inverse of $A$, as its $i$th column contains the coordinates of the $i$th standard basis vector in the given basis, as we can read it from the matrix product $AA^{-1}=I$.
If you already performed a full row reduction to obtain $I$ from $A$, then the exact same steps in the same order, but starting out from $I$ will produce $A^{-1}$.
This is because every elementary row operation can be expressed by a left multiplication of a corresponding elementary matrix $E_i$, and thus we have $E_k\dots E_2E_1A=I$, so $E_k\dots E_2E_1I=A^{-1}$.


Calling a procedure with objects as arguments

Question: Trying to save code.  I want to display text etc on an image on the form at OnActivate then print the same text on clicking button (Real program is more complicated).  To save writing code twice I tried the enclosed code but it won't compile at the "Obj.Canvas" line.  If I comment out this line and the enclosed line the program runs but the Obj value is ().
I've tried several other approaches but none work. Can anyone tell me where I'm going wrong.
Badger
unit Unit7;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, printers;

type
  TForm7 = class(TForm)
    Print: TButton;
    Image1: TImage;
    PrintDialog1: TPrintDialog;
    procedure FormActivate(Sender: TObject);
    procedure PrintClick(Sender: TObject);
  private
    { Private declarations }
  public
    DH,DW:Extended;
    Procedure DoLayout(Obj:TObject);
    { Public declarations }
  end;

var
  Form7: TForm7;

implementation

{$R *.dfm}

procedure TForm7.FormActivate(Sender: TObject);
begin
DoLayout(Image1);
end;

procedure TForm7.PrintClick(Sender: TObject);
begin
  if PrintDialog1.Execute then
  begin
    printer.BeginDoc;
      DoLayout(Printer);
    Printer.EndDoc;
  end;
end;

procedure TForm7.DoLayout(Obj:TObject);
begin
  if  Obj =Printer then         //when you run the program Obj is ()
  begin
    DW:=Printer.PageWidth/Image1.Width;
    DH:=Printer.PageHeight/Image1.Height;
  end
  else
  begin
    DH:=1;
    DW:=1;
  end;
  With Obj.canvas do          //Error here when compiled   - tried commenting it out
  begin
    TextOut(Int(DH*50),Int(DW*30),'This is the text');    //commented this out too
  end;
end;

end.

Comment: An instance of TObject does not have a canvas property, which explains the error; you need to pick the correct canvas object, rather than what you're doing.
Comment: FWIW, comments are merely comments, They are not meant to contain a solution to your problem. For that, there are answers.
Comment: I bow to your wisdom re TObject having no canvas.  However, it doesn't solve my problem. I need the DoLayout procedure to work for Image1 and Printer otherwise I would just have kept the doLayout as part of the print procedure.
Comment: Your problem is that you pass in a TObject, because TPrinter and TImage do not have a common ancestor. Object does not have a Canvas, and the compiler doesn't know what you actually pass in, so that doesn't work. But they have a Canvas in common, so pass that, together with the necessary data to perform the layout, IOW, do what Petesh's answer says.
Answer: The TPrinter class and the TImage class don't share a common ancestor class except for TObject, as a result that's what you're passing in.
A suggested refactoring is to change the DoLayout code to accept the canvas that you want to use, as well as an parameter to determine if it's a printer or an image that you're passing in e.g.
procedure TForm7.DoLayout(aCanvas : TCanvas; bPrinter : boolean);
begin
  if bPrinter then         //when you run the program Obj is ()
  begin
    DW:=Printer.PageWidth/Image1.Width;
    DH:=Printer.PageHeight/Image1.Height;
  end
  else
  begin
    DH:=1;
    DW:=1;
  end;
  With aCanvas do
  begin
    TextOut(Int(DH*50),Int(DW*30),'This is the text');
  end;
end;

then when you call it, use the printer canvas explicitly, or the image canvas:
DoLayout(Printer.canvas, true);

or
DoLayout(Image1.canvas, false);

this is just a rough estimation based on your code; I don't have a delphi compiler to hand to verify it.


How to improve performance of this counting program?

Question: Given a file looks like this:
1440927 1
1727557 3
1440927 2
9917156 4

The first field is an ID which is in range(0, 200000000). The second field represents a type , which is in range(1, 5). And type 1 and type 2 belong to a common category S1, while type 3 and type 4 belong to S2. One single ID may have several records with different type. The file is about 200MB in size.
The problem is to count the number of IDs which has a record of type 1 or 2, and the number
 of IDs which has a record of type 3 or 4.
My code:
def gen(path):
    line_count = 0
    for line in open(path):
        tmp = line.split()
        id = int(tmp[0])
        yield id, int(tmp[1])

max_id = 200000000
S1 = bitarray.bitarray(max_id)
S2 = bitarray.bitarray(max_id)
for id, type in gen(path):
    if type != 3 and type != 4:
        S1[id] = True
    else:
        S2[id] = True

print S1.count(), S2.count()

Although it gives the answer, I think it runs a little slowly. What should I do to make it run faster?
EDIT:
There are duplicated records in the file. And I only need to distinguish between S1(type 1 and type 2) and S2(type 3 and type 4). For example, 1440927 1 and 1440927 2 are counted only once but not twice because they belong to S1. So I have to store the IDs.
Comment: You could use a profiler. You could remove `id=int( ...` and use `yield int(tmp[0], ...` instead. You could use `if type <= 2` instead of two comparisons. And you could remove the generator entirely and inline the code in a `with open( ... ) as f:` block. Give it a try. And the comment below has a good point too, about the bitarray ^^
Comment: Is there any reason you use the bitarray to mark the indices? Otherwise you could simply increase a counter instead of setting the entries to "True". This should give you a performance increase.
Comment: +1 on using a profiler. Where is the bottleneck? Is it the allocation of S1 and S2? Also, consider these questions: Are (almost) all numbers in 0-200000000 present? If not, consider another datatype. Can each id be present multiple times? If not, consider ditching the arrays completely and just use a counter.

Or maybe this is a problem where you already have an optimal solution. For really large files your bottleneck may well be disk I/O which will require you to buy better disks to optimize.
Comment: @Boris I have to store the IDs because there are duplicated records. For example, in the file sample 1440927 should be counted only once but not twice. Because type 1 and 2 both belong to S1.
Answer: You're using a iterator over the file, this means that you only buffer a few lines at the time. Every time the buffer is empty the disk needs to seek and your program has to wait.
200MB easily fits into your memory, so getting all lines will speed things up:
def gen(path):
    # load all the lines,
    lines = open(path).readlines()
    split = (line.split() for line in lines)
    return ((int(x), int(y)) for x,y in split)

Comment: It looks as if you're using 600MB in your solution.
Comment: @hochl: Ok I changed the listcomprehension to a generator expression. Now it should use 200MB to store the `lines`.
Comment: you can't be certain what is faster `for line in f.readlines()` or `for line in f` unless a profiler says it. File iterator uses `READAHEAD_BUFSIZE` (`8192`) it means hundreds of lines at a time in this case.
Answer: Are you tied to Python?
egrep -e "[12]$" filename.txt | cut -d " " -f 1 | sort -u | wc -l

egrep -e "[34]$" filename.txt | cut -d " " -f 1 | sort -u | wc -l

These two commands count you the number of occurences of ("1" or "2") and ("3" or "4") at the end of each line in your filename.txt while ignoring duplicate first fields.
Probably faster than Python…
Comment: Are you tied to Python? vs. Are you tied to Linux? :)
Comment: `uniq` requires sorted input, which the OP doesn't have. You could add a `sort` to the pipeline...
Comment: @warvariuc: My windows desktop has a `grep -E` available on the commandline... what's your point?
Comment: @MattH, my point was: what's better - to be tied to a separate program, or do everything in Python?
Comment: @warvariuc: I'd be inclined to say that the right tool for the right job is the best approach.
Answer: If there is enough memory you could use dict instead of bitarray.bitarray. It could be faster:
S1, S2 = {}, {} # dicts are slightly faster than `set()`
with open(path) as f:
     for i, line in enumerate(f, 1):
         id, sep, type = line.partition(" ")
         if type == "1" or type == "2":
            S1[id] = True
         elif type == "3" or type == "4":
            S2[id] = True
         else:
            print "WARNING: unknown type: %r in line %d: %r" % (type, i, line)
print len(S1), len(S2)

Or you could try to sort the lines first:
def gettype(line):
    return line[-1]

S1, S2 = 0, 0
with open(path) as f:
     lines = f.read().splitlines()

lines.sort(key=gettype)
for type, group in itertools.groupby(lines, gettype):
    ids = (line.partition(" ")[0] for line in group)
    if type == "1" or type == "2":
       S1 += len(set(ids))
    elif type == "3" or type == "4":
       S2 += len(set(ids))
    else:
       assert 0, (type, list(ids))

print S1, S2

The asymptotic complexity of the second approach is worse.
You could use line_profiler to find out where your bottleneck is.


Impossible to update some modules via Composer

Question: I've updated a D8 website from 8.7 to 8.8.1 with SSH and composer.
For some modules (in SSH 3rd column is marked in yellow) it is not possible to update them. I understand that when they are marked in yellow some dependencies are missing?
The rest of the modules are updated successfully.
Below the list of modules that needs an update (3rd column is marked in yellow):
drupal/blazy         1.0.0-rc5 2.0.0-rc6 Provides basic bLazy integration for lazy loading and multi-serving images.
drupal/file_mdm      1.1.0     2.0.0     Provides a service to manage file metadata.
drupal/file_mdm_exif 1.1.0     2.0.0     Provides a file metadata plugin for EXIF image information.
drupal/file_mdm_font 1.1.0     2.0.0     Provides a file metadata plugin for TTF/OTF/WOFF font information.
drupal/slick         1.2.0     2.0.0     Slick carousel, the last carousel you'll ever need.
drupal/slick_views   1.0.0     2.1.0     Provides Slick carousel integration with Views.

In composer.json: slick and slick_views are added. Other above modules are not located in the composer.json:
{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "php": ">=5.6",
        ...,
        "drupal/field_group": "^1.0",
        "drupal/slick": "^1.1",
        "drupal/slick_views": "^1.0"
        ...,
    },
    "require-dev": {
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ],
        "files": ["load.environment.php"]
    },
    "scripts": {
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "enable-patching": true,
        "composer-exit-on-patch-failure": true,
        "patchLevel": {
            "drupal/core": "-p2"
        },
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/Commands/{$name}": ["type:drupal-drush"]
        },
        "drupal-scaffold": {
            "initial": {
                ".editorconfig": "../.editorconfig",
                ".gitattributes": "../.gitattributes"
            }
        },
        "patches": {}
    }
}

With these commands: nothing to install or update
composer update drupal/slick --with-dependencies
composer update drupal/slick

In the backoffice D8 (/admin/modules/update) it reports that field_group needs an major update.
That is not reported via SSH:
composer outdated "drupal/*"

I've tried to remove "field_group" to reinstall it:
composer remove drupal/field_group
...
composer require drupal/field_group
...
Using version ^1.0 for drupal/field_group

Why is it not using version: 8.x-3.0-rc2?
I've removed the vendor folder.
I've removed the composer.lock file.
What can I do to update the site to have the latest versions applied for the above list of modules? Simply removing and reinstalling is not working.
Answer: Major version changes contain breaking/incompatible changes in SemVer / Semantic versioning. If you would update them, it would break modules that depend on the old version. Therefore most projects lock composer entries to one specific major version number. Also doing a default composer require vendor/project - without denoting an explicit version number - will create an entry locked to the current major version number.
The common way for a major version change is to explicitly composer require a new major version, but this usually means manually doing extra upgrade/migration steps outside of composer.
Comment: Dependencies are usually updated indirectly by updating the source project. Packages listed directly in your composer.json must be updated directly by you. In any case try to update frequently, will make your life easier if there is a "must-have" update release due security issues.
Comment: I understand. What about the other updates? Those aren't major versions?
Comment: All entries you listed in your question are major updates. In all 6 lines the left most version number changes from 1.x.y to 2.x.y. Regarding Field group module: This might be due [minimum stability settings](https://getcomposer.org/doc/04-schema.md#minimum-stability) in your composer file. FieldGroup:3.0 is not yet marked as stable.
Comment: that is correct. I am sorry. Will I run into problems (in the future) if I do not update them to a new major version? Or is it just recommended to update them anyway?


Passing values from text field to a javascript function in Drupal 8

Question: i am new to Drupal and i am building a form (Drupal 8)that needs to calculate an amount based on the input in two text fields.
What i want to achieve is for the "calculate" button to be hidden until the two text fields have been filled but i'm not sure how to achieve this with behaviors.
Code example:
<code>    $form['weight'] = array(
        '#type'  => 'number',
        '#title' => t('Weight:'),
        '#required' => TRUE,
        '#attributes' => array(
            'id' => 'weight',
            ),
    );
    $form['number'] = array(
        '#type'  => 'number',
        '#title' => t('Number:'),
        '#required' => TRUE,
        '#attributes' => array(
            'id' => 'number',
            ),

    );
   // Here if weight and number are not empty, show button
</code>
Thanks
Answer: You do not need to use Drupal Behaviours for this, this can be done with States API which ultimately uses javascript.
e.g.
<code>$form['calculate'] = array(
  '#type' => 'submit',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="weight"]' => array(
        'filled' => TRUE,
      ':input[name="number"]' => array(
        'filled' => TRUE,
      ),
    ),
  ),
);
</code>
You can change the fields name as per your requirement. Hope this will help.
Thanks
Answer: Using jQuery you can achieve this
For example if you have input class for weight is input1 and for number it is input2
first hide both the classes using css then using jquery u can show it based on below condition.
<code>if($('.input1,.input2').length && $('.input1,.input2').val().length)){
//your code here showing calculate button
$('.calculate').show();
}
</code>
length evaluates to false in a condition, when the value is 0


How to aggregate two Strings and a List into a single byte[] and then extract them

Question: I need to aggregate 2 Strings and a List into a single byte[] in order to send it through the network (using a special library that has a function send(byte[]).
Then, on the other end, I need to get the 3 different objects back.
I've done an ugly implementation of it, but it is very slow. Basically, what I do is
        public byte[] myserializer(String dataA, String dataB, List<byte[]> info) {

        byte[] header = (dataA +";" + dataB + ";").getBytes();

        int numOfBytes = 0;
        for (byte[] bs : info) {
            numOfBytes += bs.length;
        }

        ByteArrayOutputStream b = new ByteArrayOutputStream();
        ObjectOutputStream o;
        try {
            o = new ObjectOutputStream(b);
            o.writeObject(info);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        byte[] data = b.toByteArray();

        int length = header.length + data.length;
        byte[] headerLength = (new Integer(header.length)).toString()
                .getBytes();
        byte[] pattern = ";".getBytes();
        int finalLength = headerLength.length + pattern.length + length;

        byte[] total = new byte[finalLength];enter code here
        total = // Copy headerLength, header and total into byte[] total

        return return;

In essence I'm creating kind of a frame that looks like this
      HEADER                    INFO

(-----------------------------------------------)(----------------------------------)
HEADER_LENGHT;DATA_A;DATA_B;SERIALIZED_LIST_OBJECT
Then, on the receiver side, I do the inverse process and that's "all". This works, but it is PRETTY inefficient and ugly.
Suggestions? Best practices? Ideas?
Oh...just one note more: this have to work for J2SE and Android too
Thanks so much in advanced!!
Comment: Probably, the serialization is a significant part of the performance cost.  So you may want to serialize the list yourself.  One obvious issue is delimiters between the byte arrays.  You could simplify this if there are any bytes you know will *not* be in the arrays.  Otherwise, you have to use some kind of escaping.
Comment: Yes, that's what I've trying to do, but it's kind of complex. I can't use any delimiters for the INFO chunk, because it can be binary data. I was thinking in adding the number of list elements and its length as part of the header... that way you don't need delimiters.
I tried this approach but it ended in spaghetti code.
The answer I picked, it tries to do this, but in a neater way!
Answer: Write it all to a ByteArrayOutputStream, with an ObjectOutputStream around it to serialize the Strings and the List, and then call the method that turns the BAOS into a byte[] array. At the other end, do the inverse.
Or define a serializable object that contains the {String, String, List} tuple and just serialize that with ObjectOutputStream, and deserialize that with ObjectInputStream. Much simpler.
Or just do three sends. TCP is a byte stream, there are no boundaries between the messages, the bytes all arrive sequentially. If you want to conserve writes to the network, interpose a BufferedOutputStream and flush it after writing the List.
Comment: wrapping the parameters inside an internal object would be more flexible and easier to maintain
Answer: Here is a simplistic method of serializing an array of bytes and deserialize it on the other side. Note that the method only accept one argument of type List<byte[]> and since your argument dataA and dataB are of type String, you can simply assume that the two first byte[] elements in the list are those two argument. I believe that this is a lot faster than object serialization through an ObjectOutputStream and will be faster to deserialize on the other side as well.
public class ByteListSerializer {
static private final int INT_SIZE = Integer.SIZE / 8;

    static public void main(String...args) {
        ByteListSerializer bls = new ByteListSerializer();

        // ============== variable declaration =================
        String dataA = "hello";
        String dataB = "world";
        List<byte[]> info = new ArrayList<byte[]>();
        info.add(new byte[] {'s','o','m','e'});
        info.add(new byte[] {'d','a','t','a'});
        // ============= end variable declaration ==============

        // ======== serialization =========
        info.add(0, dataA.getBytes());
        info.add(1, dataB.getBytes());
        byte[] result = bls.dataSerializer(info);

        System.out.println(Arrays.toString(result));

        // ======== deserialization ========
        List<byte[]> back = bls.dataDeserializer(result);

        String backDataA = new String(back.get(0));
        String backDataB = new String(back.get(1));
        back.remove(0);
        back.remove(0);

        // ============ print end result ============
        System.out.println(backDataA);
        System.out.println(backDataB);
        for (byte[] b : back) {
            System.out.println(new String(b));
        }
    }

    public byte[] dataSerializer(List<byte[]> data) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteBuffer lenBuffer = ByteBuffer.allocate(4);

        try {
            for (byte[] d : data) {
                lenBuffer.putInt(0, d.length);
                out.write(lenBuffer.array());
                out.write(d);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // wrap this
        byte[] dataBuffer = new byte[out.size() + 4];
        lenBuffer.putInt(0, out.size());
        System.arraycopy(lenBuffer.array(), 0, dataBuffer, 0, 4);
        System.arraycopy(out.toByteArray(), 0, dataBuffer, 4, out.size());

        return dataBuffer;
    }

    public List<byte[]> dataDeserializer(byte[] data) {
        if (data.length < INT_SIZE) {
            throw new IllegalArgumentException("incomplete data");
        }

        ByteBuffer dataBuffer = ByteBuffer.wrap(data);
        int packetSize = dataBuffer.getInt();

        if (packetSize > data.length - INT_SIZE) {
            throw new IllegalArgumentException("incomplete data");
        }

        List<byte[]> dataList = new ArrayList<byte[]>();
        int len, pos = dataBuffer.position(), nextPos;

        while (dataBuffer.hasRemaining() && (packetSize > 0)) {
            len = dataBuffer.getInt();
            pos += INT_SIZE;
            nextPos = pos + len;
            dataList.add(Arrays.copyOfRange(data, pos, nextPos));

            dataBuffer.position(pos = nextPos);
            packetSize -= len;
        }

        return dataList;
    }
}

The frame is constructed as
     - 4 bytes: the total bytes to read (frame size = [nnnn] + 4 bytes header)
    |      - 4 bytes: the first chunk size in bytes
    |     |          - x bytes: the first chunk data
    |     |         |
    |     |         |           - 4 bytes: the n chunk size in byte
    |     |         |          |         - x bytes: the n chunk data
    |     |         |          |        |
    |     |         |          |        |
[nnnn][iiii][dddd....][...][iiii][dddd...]

The example above will output
[0, 0, 0, 34, 0, 0, 0, 5, 104, 101, 108, 108, 111, 0, 0, 0, 5, 119, 111, 114, 108, 100, 0, 0, 0, 4, 115, 111, 109, 101, 0, 0, 0, 4, 100, 97, 116, 97]
hello
world
some
data

Note that the frame format is formed of byte[] chunks so as long as you know the order of the chunks, you can use these methods with virtually any set of data.
Comment: A `DataOutputStream` and `DataInputStream` could do all that much more 'simplistically'.
Comment: @EJP, I believe it will result in just about the same code as `DataOutputStream` does not "serialize" but simply output data as bytes (like in my example), and you still have to prepend the 4 bytes frame length before returning the resulting bytes.
Comment: Just a question: how in/efficient is ByteArrayOutputStream and ByteBuffer objects? Think that I create one instance of each per frame I send.
Comment: depends how often you are calling the methods. Object creation is usually cost effective, but having a class level instance will cause your class to be NOT thread safe. If you know for sure that your class will not have concurrent access, you can have a single instance of `ByteBuffer` and reuse `ByteArrayOutputStream` using `ByteArrayOutputStream.reset()` to reinitialize it. If you class will have concurrent access, you could have a synchronized pool of these objects... but this is going out of the question scope. I suggest you test as it is and improve if speed becomes more critical.


How can i call a my function in a qtslot?

Question: I'm trying to call my function as a function slot in Qt,But i don't know how to go about it.
it seems the following approach is wrong :
Update:
According to an answer i updated my source code,but still something is apparently wrong with it.Trying to compile this snippet of code causes these errors:

C2515:' no appropriate default constructor is available.'

And

C2665: QObject::connect':none of the 3 overloads could convert all the
  arguments.'

respectively in Visual studio 2010.
#include <QtGui/QApplication>
#include <QPushButton>
#include <QObject>
#include <QMessageBox>

class myclass;
int main(int argc,char *argv[])
{
    QApplication a(argc,argv);

    QPushButton btnshowmessage("show");
    myclass *my=new myclass();
    QObject::connect(&btnshowmessage,SIGNAL(clicked()),my,SLOT(warningmessage()));
    btnshowmessage.show();
    return a.exec();
}
//////////////////////////////////////////////////////////////////////////
class myclass: public QObject
{
Q_OBJECT
public:myclass(){}

        public slots:
            void warningmessage()
            {
                QMessageBox::warning(0,"Warning","Test Message!",QMessageBox::Ok);
            }
};

Comment: I am telling you the forward declaration will not work. Also the linker errors are probably caused by moc not running on your code. Remember moc always needs to be run if you have signals / slots in your class or use the Q_OBJECT macro. I am not sure how you are defining your project to invoke moc and I probably can not help with that since I generate my Qt projects for Visual Studio using CMake (which sets up moc for the files I specify) and not the qmake or the qtaddon.
Comment: Put the definition of myclass before int main() and see if that fixes things. With the forward declaration connect has no idea that myclass is a QObject derivative.
Comment: @drescherjm:I used a forward declaration to fix that.Even if i do what you told me i get bunch of other linker specific errors! which i have no idea of its cause!
Comment: Are you using the visual studio Qt Add-in and is it set up as a qt project?
Comment: @drescherjm +1 r.e. the fwd declaration - this is simply a c++ error and nothing to do with it being Qt
Comment: @Pete:Yes i am using Qt-Add-in.And yes it is set up as a qt project.
Comment: I believe for the Qt addin you need to add #include "main.moc" to the bottom of your main.cpp
Comment: @drescherjm:No ,I declared the class in a separate file and all went fine without even a warning:)thank you again for your time:)
Answer: You use signals and slots to connect one Object's signal to another Object's slot. Every signal or slot should be inside a class which must be also derived from QObject class and contain the Q_OBJECT macro.
So to make your code work, put the slot into some class of yours:
class MySlotClass:public QObject
{
Q_OBJECT
public slots:
void MyFunction()
    {
        QMessageBox::warning(0,"WarningTest","This is a waring text message",QMessageBox::Ok);
    }
}

and connect like this:
MySlotClass m = new MySlotClass();
Qobject::connect(&btnShowaMessageBox,SIGNAL(clicked()), &m ,SLOT(MyFunction()));

Comment: @Houssein: in main, the compiler had only seen the forward declaration to myclass so far and you were trying to a) create a new object of that class and b) convert it to a QObject*.  At this point the compiler only knew of myclass as an incomplete type.
Comment: The connect will compile but fail - SLOT(myFunction()) should be SLOT(MyFunction()) (or the function in the class should start with a lowercase letter).  The SLOT macro converts its argument to a string and the lookup is done a runtime.
Comment: @SingerOfTheFall:Thank you very much.By the way should it not be :
MySlotClass *m = new MySlotClass();
instead of the
MySlotClass m = new MySlotClass();
Comment: I still get errors doing that.I updated the first post to address the latest issues.
Comment: @Hossein, put your class in a separate unit. The class definition should be in a header file.
Comment: @SingerOfTheFall:Whats the difference?! I should be able to declare a class where ever i wish right?,I have done this and also seen it in lots of C++ books!.
Comment: @SingerOfTheFall:I did as told and it compiled just fine:)
Thank you.though i have no idea why it acted like that.
Answer: Currently Qt does not allow connection of signals to functions that are not declared as slots on some QObject derivative.  I believe Qt5 may offer this possibility, but connect will have different syntax to allow this.
basically your slot function must be in a QObject derived class and declared in a
public slots:

section.
Read the documentation on signals/slots.


Register Mapping Problem in STM32 Micro-controller

Question: I am using Micro-controller STM32-L476RG. I am facing a problem in RCC Register Mapping.
Please take a look at the picture. You will notice I declared a structured typedef struct of RCC_RegDef_t where all the register values are in the correct order. The Problem is when the code executing RCC->AHB2ENR  |= GPIOAEN;  this line of code in the main function, it should store the value in AHB2ENR register. But it is storing the value in APB2RSTR register. I am not finding why this is happening.
Comment: use CMSIS headers. Your hard work is rather useless
Comment: Since you tagged as C++, you don't need to use the `typedef struct` when declaring variables, parameters or return values from functions.
Answer: Your type definition lacks some entries, especially for the offsets 0x24, 0x34 and 0x44. See the snippet:

Correct your definition by inserting "unused" entries:
    _vo uint32_t CICR;
    _vo uint32_t unused1;
    _vo uint32_t AHB1RSTR;

Otherwise the compiler does not know that you want AHB1RSTR to be at offset 0x28.
Comment: @AbuSayed It doesn't explicitly say anything but it's supposedly some reserved addresses. You need to declare dummy variables at those locations. `_vo uint32_t dummy1;` etc. See 6.4.33 of the manual. Or better yet, write every single register in the MCU as an unique uint32_t declared at an absolute address. ST's way of writing register maps is error-prone and fishy in general.
Comment: But in reference Manual, there is nothing about these two offsets. Also IN SFRs view, it is also missing, what can I do, in that case?
Comment: @AbuSayed The expected way to say "Thank you" is to mark the best answer. You might want to take the [tour] to learn how this site works.
Comment: @ the busybee, I don't have 15 reputations to cast a vote.  But I already tried that. Thank you again.
Comment: Accepting an answer (to "mark") is different from casting a vote. AFAIK you should be able to accept without a certain reputation, perhaps after some time.


h5py order of dataset by dataset name

Question: I am creating an h5 files with 5 datasets ['a160'],['a1214']
How can I make it so that the datasets will be sorted by the dataset name..
For example when I do h5dump on my file I get:
HDF5 "jjjj.h5" {
GROUP "/" {
   DATASET "a1214" {
      DATATYPE  H5T_IEEE_F32BE
      DATASPACE  SIMPLE { ( 1, 19 ) / ( H5S_UNLIMITED, 19 ) }
      DATA {
      (0,0): 160, 0, 165, 4, 2.29761, 264, 4, 1.74368, 1, 0, 17, 193, 0, 0,
      (0,14): 0, 0, 0, 0, 0
      }
   }
   DATASET "a160" {
      DATATYPE  H5T_IEEE_F32BE
      DATASPACE  SIMPLE { ( 3, 19 ) / ( H5S_UNLIMITED, 19 ) }
      DATA {
      (0,0): 263, 0, 262, 7, 4.90241, 201, 34, 0.348432, 1, 0, 29, 11, 0, 0,
      (0,14): 0, 0, 0, 0, 0,
      }
   }

But I want it to be ordered by the dataset name, I need h5dump to output
HDF5 "jjjj.h5" {
GROUP "/" {
   DATASET "a160" {
      DATATYPE  H5T_IEEE_F32BE
      DATASPACE  SIMPLE { ( 3, 19 ) / ( H5S_UNLIMITED, 19 ) }
      DATA {
      (0,0): 263, 0, 262, 7, 4.90241, 201, 34, 0.348432, 1, 0, 29, 11, 0, 0,
      (0,14): 0, 0, 0, 0, 0,
      }
   }

   DATASET "a1214" {
      DATATYPE  H5T_IEEE_F32BE
      DATASPACE  SIMPLE { ( 1, 19 ) / ( H5S_UNLIMITED, 19 ) }
      DATA {
      (0,0): 160, 0, 165, 4, 2.29761, 264, 4, 1.74368, 1, 0, 17, 193, 0, 0,
      (0,14): 0, 0, 0, 0, 0
      }
   }
}

Answer: By default h5dump sorts HDF5 files' groups and attributes by their names in ascending order:
-q Q, --sort_by=Q    Sort groups and attributes by index Q
-z Z, --sort_order=Z Sort groups and attributes by order Z

Q - is the sort index type. It can be "creation_order" or "name" (default)
Z - is the sort order type. It can be "descending" or "ascending" (default)

The problem in this case is that "a160" is considered greater than "a1214" because that's how dictionary sorting works ('a12' < 'a16').
There's no change you can make to the internal structure of the HDF5 file to force h5dump to sort these data structures in a different order.  However, you could zero-pad your names like so:
a0040
a0160
a1214

and then the standard dictionary sort will output the file the way you want.

h5py order of dataset by dataset name


reverse ssh tunnel from server to laptop

Question: Question I would like to know how to tunnel requests made on a server (debian) to port 80 on my laptop using ssh tunneling.
Problem I can open up a tunnel with the following command that does not behave quite as I would like:
ssh -R 4445:localhost:80 email@example.com

After running this and getting a shell at example.com, the following command executes as expected returning the web page being hosted on my laptop:
wget localhost:4445

However, when trying to run this same command using example.com:4445 rather than localhost:4445, I get a connection refused.
Extra info: I also tried writing a forwarding rule using shorewall:
DNAT            net             $FW:127.0.0.1:4445        tcp     4446

and then tried
wget example.com:4446

When wget fails in any of the above cases, I get this:
--2011-02-16 13:48:26--  http://example.com:4446/
Resolving example.com... 70.90.XXX.XX
Connecting to example.com|70.90.XXX.XX|:4446... failed: Connection refused.

Any ideas on where to go from here? Also, if there is different / better way to achieve this effect I am completely open to the idea.
EDIT Thanks for the suggestions!
Tried the following:
ssh -R example.com:4445:localhost:80 firstname.lastname@example.com

and
ssh -R :4445:localhost:80 firstname.lastname@example.com

Then when running the same wget as above came back with the same error. I should maybe mention that this server has two interfaces (eth0 public eth1 private).
EDIT
I am a moron :( Had to set
GatewayPorts yes

in sshd_config. Thanks for the help everyone!
Answer: ssh is configured for security reasons to make the new tunnels to listen on localhost.
You have to use:
ssh -R :4445:localhost:80 firstname.lastname@example.com

From the man page of openssh:

 -R [bind_address:]port:host:hostport

Specifies that the given port on the remote (server) host is to
  be forwarded to the given host and
  port on the local side.  This works by
  allocating a socket to listen to port
  on the remote side, and whenever a connection is made to this port, the
  connection is forwarded over the
  secure channel, and a connection is
  made to host port hostport from the
  local machine.
Port forwardings can also be specified in the configuration
  file.  Privileged ports can be
  forwarded only when logging in as root
  on the remote machine.  IPv6 addresses
  can be specified by enclosing the address in square braces or using an alternative
  syntax:
  [bind_address/]host/port/hostport.
By default, the listening socket on the server will be bound to
  the loopback interface only.  This may
  be overridden by specifying a
  bind_address.  An empty bind_address,
  or the address
               '*', indicates that the remote socket should listen on all
  interfaces.  Specifying a remote
  bind_address will only succeed if the
  server's GatewayPorts option is
  enabled (see sshd_config(5)).
Comment: yea for man pages *slapping myself in the head*! However, for some reason this still did not work. Is there some log files I could be checking or something to get some more info? Actually still need to set the GatewayPorts option in sshd_config, I'll get back after I do this.
Answer: The first thing to keep in mind is that tunnels have a specific end point.  That end point doesn't have to be the client or the server, but the data is only encrypted while it's between the client and the server.
If you want a connection on the server to tunnel to example.com, you could run
 ssh -R 4445:example.com:80 email@example.com

When anyone on the server connects to localhost:4445 the packet will tunnel encrypted to your client. From your client, the packet will travel unencrypted to example.com:80.  SSH does not perform any analysis of your connection protocol, the packets simply go in one end and come out the other.
One tunnel can only go to one endpoint.  If you want to go somewhere else (say, example.org), you'll need to close the ssh connection and make a new one with -R 4445:example.org:80.  If you want to connect to both example.com and example.org, you'd need to set up two different tunnels with different local ports: -R 4445:example.com:80 -R 4446:example.com:80.
By (very good) default, tunnels can only "come from" one place (the server's localhost for -R tunnels, the client's localhost for -L tunnels).  For -R tunnels, if you enable GatewayPorts in the server's sshd_config file, then you can tell it to listen on the server's IP address for anyone who can connect to the server:
ssh -R server:4445:example.com:80 ...

Then, anyone who can reach server:4445 would have their packet travel unencrypted to the server, the server would tunnel it encrypted to the client, then the client would send it unencrypted to example.com:80.
Answer: Problem is you are trying to open port on example.com:4445 which is not really opened.
If you want to hit tunneled port 4445 on localhost when referencing example.com in wget command or in browser you will need to add entry to /etc/hosts file
127.0.0.1 example.com

which will then enable you to hit tunneled port on localhost when executing
wget example.com:4445

Other thing useful here to establish tunnel is, if you intend to use it on regular basis
is to setup .ssh/config file and make block like this.
Host example
Hostname example.com
User    someuser
LocalForward 4445 localhost:80

This will tunnel port 80 from example.com to localhost:4445 simply by invoking
ssh example


different form override for node/add and node/edit pages?

Question: Hia
I am using the following in a custom module to customise the form on the node/add/baby page for my BABY content type, however i want to make some slight modifications to this page when its the node/nid/edit page for the baby content type. is this possible?

<?php
function concept_theme() {
  return array(
    'baby_node_form' => array(
      'arguments' => array(
          'form' => NULL,
      ),
      'template' => 'templates/baby-node-form',
      'render element' => 'form',
    ),
  );
}
?>

thank u
Answer: In template.php
function my_theme_name_theme($existing, $type, $theme, $path)
$hooks['baby_node_form']=array(
    'render element'=>'form',
    'template'      =>'templates/node--baby-edit',
);
return $hooks;
}

In node--baby-edit.tpl.php
Hide fields like this:
<?php hide($form['title']); ?>

Manipulate fields like this:
<?php print render($form['field_image']); ?>

Use this to print all/rest of content:
<?php print drupal_render_children($form); ?>

Clear cache.
Answer: You can alter the node creation form by implementing this hook,
something similar to this:
hook_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'node_baby_form') {
     //do modification to form array $form
  }
}

Or if your node is defined by hook_node_info (which I believe is not the case), just changing the elements in hook_form()


Print a list as a table in jsp

Question: I have a list like this:
[[A,0,1],[A,0,0],[B,0,1],[C,1,1],[C,0,1]]

and i would like to print it in html like this:
-------------
| A | 0 | 1 |
-   -   -----
|   |   | 0 |
-------------
| B | 0 | 1 |
-------------
| C | 1 | 1 |
-   ---------
|   | 0 | 1 |
-------------

is there a way to do it in javascript or is there an easy way to do it in the jsp ?
Comment: I think there's a way in both JavaScript and in JSP.
Comment: @Mansuro no i just reversed them by accident, i'll fix that
Comment: shouldn't the last cells of the last two records be merged? Both contain '1'.
Comment: @isnot2bad no the merged cells go from left to right, if the cells on the lift are different we dont merge the cells
Comment: in JSP, you can use the JSTL with forEach or forTokens
Comment: It looks also JSON ready so you can do it in Javascript
Comment: @RachidO. just updated my answer.
Answer: Javascript:
Source:
var arr = [['A',0,1],['A',0,0],['B',0,1],['C',1,1],['C',0,1]];

Calculate merge depth for each cell:
var depth = arr.map(function(item){
    return item.map(function(){
        return 0;
    });
});

var arrLength = arr.length;
for(var index=0;index<arrLength;index++){

    var subArr = arr[index];
    var subLength = subArr.length;
    var tIndex;
    var maxtIndex = arrLength;

    if(index < arrLength -1) {
        for(var i=0;i<subLength;i++){
            tIndex = index + 1;
            while(depth[index][i] != -1 && tIndex<maxtIndex){
                if(subArr[i] == arr[tIndex][i]){
                    depth[index][i] = depth[index][i]+1;
                    depth[tIndex][i] = -1;
                } else {
                    break;
                }
                tIndex++;
                maxtIndex = tIndex;
            }

            if(depth[index][i] == 0){
                break;
            }
        }
    }
}

Result table:
var tableHtml = '
' + arr.map(function(subArr, index){
    var str = '
';
        for(var i=0;i<subArr.length;i++){
            var iDepth = depth[index][i];
            if(iDepth !== -1) {
                str += ' 0?' rowspan="'
                             + (iDepth + 1)+'"':'') + '>'
                             +subArr[i]
                     + '	';
            }
        }
    return str+'
';
}).join(' ') + '
';

Demo: JSFiddle
Answer: updated
it is working now but still not as you want

Answer: In JavaScript you can do in following way
 var numbers = [['A','0','1'],['A','0','0'],['B','0','1'],['C','1','1'],['C','0','1']];

 var rows = "";

 for(var i=0; i < numbers .length; i++){

    rows = rows  + "
"

    for(var j=0; j < 3; j++){

         if(i != '0' && numbers[i][j]==numbers[i-1][j]){
              rows = rows  + ""+"-"+"	"
         }else{
              rows = rows  + ""+numbers[i][j]+"	"
         }
    }

    rows = rows  + "
"
 }

 var table ="
" + rows  +"
"
//you can append it to DIV or any element in JSP

Print a list as a table in jsp


flash lite memory management

Question: I'm having a hard time managing my memory in flash lite.
are there any pointers i should care about ? or best practices?
ive been reading every 60 seconds the garbage collector runs.
i'm deleting my objects/movieclips like
mc = null;
delete mc;
and making sure every listeners is deleted on it.
still nothing seems to happen..
Answer: Flash's garbage collector isn't deterministic - it runs when it can run and while it may check to see if it can run at a regular interval, there's no guarantee it will run. If your SWF is constantly chewing CPU the GC will never have time run.
Flash Lite uses ActionScript 2 which does have one "nuke" option for visual assets - MovieClip.unloadMovie(). If you've got a movieclip, running unload on it will kill everything within it.

flash lite memory management


Page not found when working with apiResource

Question: I have the following simple project:
App\Http\Controllers\ProductController.php which includes all the API methods (store, show, update, destroy)
App\Http\Resources\ProductResource.php which returns a JSON
App\Models\Product.php which just has the protected fillable array
and finally App\routes\api.php with the following code:
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;

Route::apiResource('products', ProductController::class);

But when I try to POST some example product using Postman, I get 404 Not Found.
The URL I post to is localhost:8000/api/products.store, because from what I understand is that apiResource simply creates all the named routes in the form of products.method_name
*By the way, the URL localhost:8000/api/products returns an empty {"data":[]}
I'm clearly doing something wrong - what is it?
Comment: Can you please run the command php artisan route:list and send the snap shot of routes
Answer: you can't use the route name in the URL like this,
the request should be like:
localhost:8000/api/products/store

try this command
 php artisan route:list

and you will see all your routes and the URL that you should use for each one
Answer: Please try to add Accept: application/json in header.


Cisco ASA not allowing DNS traffic to pass?

Question: I have an ASA 5515 as my internet firewall. It is not allowing me to do NS Lookups from any internal DNS Servers, or clients. If I set my nslookup server to 18.104.22.168 (google DNS), I can resolve public DNS names. If I am on the internal network, breaks.
I have the following in my ASA:
<code>policy-map type inspect dns preset_dns_map
 parameters
  message-length maximum client auto
  message-length maximum 8192
policy-map global_policy
 class inspection_default
  inspect ftp
  inspect h323 h225
  inspect h323 ras
  inspect ip-options
  inspect netbios
  inspect rsh
  inspect rtsp
  inspect skinny
  inspect esmtp
  inspect sqlnet
  inspect sunrpc
  inspect tftp
  inspect sip
  inspect xdmcp
  inspect pptp
  inspect ipsec-pass-thru
  inspect icmp
  inspect dns preset_dns_map
</code>
Any ideas as to why its not working?
Comment: More likely the breakage is related to an ACL or NAT problem.. do you have an internal DNS server that's handling the DNS requests for the internal network now?
Comment: I'd guess that's a problem with firewall ACLs, then - can you provide the relevant config for those - probably an inbound rule set on the inside interface?
Comment: My internal DNS server can resolve its records, but it can not forward lookups. When I am in my network, I can not lookup external hosts either. Im using 188.8.131.52 and 22.214.171.124 DNS servers from NSLOOKUP
Comment: It turned out to be a NAT inside, outside DYNAMIC problem. Not sure how that rule disappeared on the reboot, but I guess it did. All traffic was being blocked. Thanks you the input :)
Answer: As per the mentioned notes when you are sending a DNS query internally is it going through the firewall or not. If it is run a packet for the concerned traffic and see if the traffic is getting dropped at any stage. If due to any reason ASA is dropping the traffic collect the output of ASP capture. ASP capture will help us to isolate the reason due to which ASA is dropping the packet.