text:
Q: How to manage JWT when Cookies are disabled I've been reading articles about JSON Web Token (which is completely new to me) and its safe mechanism to transmit information between parties in order to avoid server Sessions.
I'm building a web app from scratch using Java, Tomcat, Jersey framework for Web Services and JOSE4J for the JWT.
Many articles advice to use Cookies httpOnly instead of localStorage
I've already created a restful method like this with a cookie and the jwt
@GET
@Path("/authenticate")
@Produces(MediaType.APPLICATION_JSON)
public Response authenticate(
        @HeaderParam("username") String username,
        @HeaderParam("password") String password) throws JSONException,
        IOException, JoseException {
        Service service = Service.getInstance();
        EmployeeProfile employeeProfile = service.authenticate(username, password);
        // Temporarily httponly and secure as false to test
        NewCookie cookie = new NewCookie("jwt", service.getToken(), null, null, null, 900, false, false);
        return Response.status(200).cookie(cookie).entity(employeeProfile).build();
    }
    return Response.status(204).entity(null).build();
}

When I run my webapp in Chrome I can see that the cookie was saved correctly.
Now I can use this token to call further restful methods with no need to authenticate again, but what if Cookies are disabled? I cannot retrieve the cookie as I tested in incognito mode. In that case I can verify if cookies are enabled and warn the user to enable them in order to proceed with the login process.
To check cookies I do this:
$.cookie('test_cookie', 'cookie_value', { path: '/' });
if ($.cookie('test_cookie') !== 'cookie_value') {
    //Cookies are disabled. Show a modal.
}

But this is very restrictive. So I wonder what would be my alternative to retrieve the jwt from server? I am not very sure about this, but should I change the controller to send the jwt as a part of the response in json and keep it in the localStorage even if this can expose my token to XSS attacks? However, using cookies can be also susceptible to CRSF attacks but not if I set httpOnly and secure properties to true, but in that case I won't be able to read the cookie with javascript. I am confused about this.
Thanks in advance.

A: You are right , You need to change your controller and send the JWT is part of the response as well as the cookies with flag httpOnly due securities, but the question is are decrypting JWT in client side and using some value from there. if "No", then no need to send JWT as part of the response.. if "Yes", better take out all that values from the token and send a separate json object in response header.


text:
Q: joining sentences from a list in python3 I am trying to join a lists of appended sentences into a large a string text object so that I can use it as an input for the Gensim summarize module. However, when I try to do this, it says the input sentences are less than 2. But when I run a split on the text, I see multiple sentences but it counts each sentence once instead of the total of sentences together. And the variable r is a string type object. I would like to concatenate the sentences together into one large string so it can be read through the Gensim summarize module.
Sample Code:
import re
ruling_corpora  = re.findall("\.?([^\.].\*?I find[^\.]*\. |[^\.]*$In sum[^\.]*\. |[^\.]*$agree[^\.]*\.)", tokenized, re.I |re.DOTALL |re.M)[1:-1]

for r in ruling_corpora:
    print(type(r))
    rc= ''.join(r)
    print(summarize(rc))

SAMPLE OUTPUT:
raise ValueError("input must have more than one sentence")
ValueError: input must have more than one sentence

Here is an example of my input I want to summarize with the Gensim summarizer. The numbers underneath each string represent the count of sentences ending in periods:
####Beginning of File### LUMB65.BL23607963.xml
Background Content: ANDERSON INITIAL DECISIONOn January 13, 2015, the appellant filed this appeal arguing that the agency's decision not to renew his term limited appointment which expired on January 28, 2015, is in error.

 For the reasons discussed below, this appeal is DISMISSED for lack of jurisdiction without a hearing.
1
There is nothing in the agreement that curtails the agency's ability not to extend the term appointment.
 IdIn reviewing the appellant's arguments, the appellant fails to establish that the Board has jurisdiction to review the agency's decision not to renew his time-limited appointment at issue in this appeal.
 Following a review of the record evidence, I find that the appellant has failed to non-frivolously allege Board jurisdiction over this appeal on any basis.
 Accordingly, this appeal must be dismissed for lack of jurisdiction.
1
####End of File### LUMB65.BL23607963.xml

A: According to the documentation (emphasis mine):

The input should be a string, and must be longer than INPUT_MIN_LENGTH
  sentences for the summary to make sense. The text will be split into
  sentences using the split_sentences method in the
  gensim.summarization.texcleaner module. Note that newlines divide
  sentences.

Try using rc = '\n'.join(r).  You could also debug by calling gensim.summarization.texcleaner.split_sentences to check the result.
Additionally your regular expression does not match your given input and even if it did, you discard the only two results with [1:-1].  Try this instead:
>>> map(lambda x: x[0], re.findall('([^.]*?(I find|In sum|agree)[^.]*\.)', tokenized, re.I | re.DOTALL | re.M))
["\n1\nThere is nothing in the agreement that curtails the agency's ability not to extend the term appointment.", '\n Following a review of the record evidence, I find that the appellant has failed to non-frivolously allege Board jurisdiction over this appeal on any basis.']

You may want to process out the stand-alone numbers first since they show up in the match.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pandas: Creating new Dataframe and writing to new CSV I think I know how to do this but I'm experiencing a bug where I get the dataframe I want but when I write the new dataframe to a csv, the original dataframe is written instead of the new one.
Goal: read csv into dataframe, pull out all rows filtered by values in two different columns (I'm good on this).  Then I want to write this new dataframe to a new csv.
To create the new dataframe, I have done:
df_new = df.loc[(df['column1'] == 0.0) & (df['column2'] != 1)]
df_new.describe()
#this yields the correct results

df_new.to_csv('new_csv.csv')

The new csv has the original dataframe's data in it.
Can someone help me here?


text:
Q: Why is my hover function working, but my onmouseleave function is not? (calling the function in the console works) here's my codepen:

https://codepen.io/squishyboots19996/pen/BaoQjPL

I'm trying to create a navigation menu that slides in when you hover on the arrow and then slides away when your mouse leaves the menu.
I have UIController.showMenu and UIController.closeMenu.
If I call either one of them in the console, they work as expected.
However the event listener for the closeMenu is not working. It just doesn't detect the mouse leaving the menu and doesn't close.
If i add a console.log("Hello") to the function, it will trigger when the page first loads. But won't work when I need it to.
app.js:
var Controller = (function() {
    UIController.updateNav;
    setInterval(UIController.moveArrowDown, 3000);
    //UIController.addBodyMargin();
 document.querySelector('#menuArrow').addEventListener("mouseover", UIController.openMenu);
      document.querySelector('#sideMenu').addEventListener("onmouseleave", UIController.closeMenu);
});
//-----------------------------------------------------------
var UIController = (function() {

    return {
        openMenu: (function(){
          document.getElementById('sideMenu').style.marginLeft = '0';
          document.getElementById('menuArrow').style.marginLeft = '250px';
          document.body.style.marginLeft = '25px'
        }),
        closeMenu: (function(){
          document.getElementById('sideMenu').style.marginLeft = '-250px';
          document.getElementById('menuArrow').style.marginLeft = '0';
          document.body.style.marginLeft = '0';
        })
        }

})();

document.addEventListener('DOMContentLoaded', (event) => {
  Controller();
})

navbar.css:
.sidemenu {
  height: 100vh;
  width: 250px;
  position: fixed;
  top: 0;
  left: 0;
  background-color: red;
  z-index: 5001;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-left: -250px;
  transition: .5s;
  cursor: pointer;
}

.sidemenu ul {
  list-style: none;
  padding: 0;
}

.sidemenu a {
  text-decoration: none;
  font-size: 2rem;
}

.expand-arrow {
  z-index: 4999;
  position: fixed;
  transition: .5s;
  bottom: 50%;
}

HTML:

Home

About

Questionnaire

        SHOW MENU BUTTON >

About Us

                        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi, soluta magni exercitationem consectetur natus assumenda dignissimos quasi porro non doloremque labore odit quae accusantium excepturi, dicta recusandae possimus. Necessitatibus, ipsam.
                        Esse dolorem porro quo velit odit quam, rerum, non optio, labore aliquam ducimus totam molestias ipsa quasi explicabo voluptates. Quas eius dolor harum optio corrupti quo impedit dolorem sunt porro?
                        Eaque officia vero, facere possimus exercitationem sint magnam aliquam veniam, ipsam soluta eveniet ex iusto perferendis blanditiis a repellendus assumenda dolores natus dolorum. Cumque vero deserunt fuga autem reprehenderit dignissimos.

A: When using the addEventListener() method, it's "mouseleave" not "onmouseleave"

A:
you shouldn't use "on" while adding the event, just use the name of
  the function

document.querySelector('#sideMenu').addEventListener("mouseleave", UIController.closeMenu);

instead of

document.querySelector('#sideMenu').addEventListener("onmouseleave", UIController.closeMenu);


text:
Q: Tuning Neo4j for Performance I have imported data using Michael Hunger's Batch Import, through which I created:-
4,612,893 nodes
14,495,063 properties
    node properties are indexed.
5,300,237 relationships

{Question} Cypher queries are executing too slow almost crawling, simple traversal is taking > 5 mins to return resultset, Please let me know how to tune the server to get better performance and what I am doing wrong.
Store Details:-
-rw-r--r-- 1 root root 567M Jul 12 12:42 data/graph.db/neostore.propertystore.db
-rw-r--r-- 1 root root 167M Jul 12 12:42 data/graph.db/neostore.relationshipstore.db
-rw-r--r-- 1 root root  40M Jul 12 12:42 data/graph.db/neostore.nodestore.db
-rw-r--r-- 1 root root 7.8M Jul 12 12:42 data/graph.db/neostore.propertystore.db.strings
-rw-r--r-- 1 root root  330 Jul 12 12:42 data/graph.db/neostore.propertystore.db.index.keys
-rw-r--r-- 1 root root  292 Jul 12 12:42 data/graph.db/neostore.relationshiptypestore.db.names
-rw-r--r-- 1 root root  153 Jul 12 12:42 data/graph.db/neostore.propertystore.db.arrays
-rw-r--r-- 1 root root   88 Jul 12 12:42 data/graph.db/neostore.propertystore.db.index
-rw-r--r-- 1 root root   69 Jul 12 12:42 data/graph.db/neostore
-rw-r--r-- 1 root root   58 Jul 12 12:42 data/graph.db/neostore.relationshiptypestore.db
-rw-r--r-- 1 root root    9 Jul 12 12:42 data/graph.db/neostore.id
-rw-r--r-- 1 root root    9 Jul 12 12:42 data/graph.db/neostore.nodestore.db.id
-rw-r--r-- 1 root root    9 Jul 12 12:42 data/graph.db/neostore.propertystore.db.arrays.id
-rw-r--r-- 1 root root    9 Jul 12 12:42 data/graph.db/neostore.propertystore.db.id
-rw-r--r-- 1 root root    9 Jul 12 12:42 data/graph.db/neostore.propertystore.db.index.id
-rw-r--r-- 1 root root    9 Jul 12 12:42 data/graph.db/neostore.propertystore.db.index.keys.id
-rw-r--r-- 1 root root    9 Jul 12 12:42 data/graph.db/neostore.propertystore.db.strings.id
-rw-r--r-- 1 root root    9 Jul 12 12:42 data/graph.db/neostore.relationshipstore.db.id
-rw-r--r-- 1 root root    9 Jul 12 12:42 data/graph.db/neostore.relationshiptypestore.db.id
-rw-r--r-- 1 root root    9 Jul 12 12:42 data/graph.db/neostore.relationshiptypestore.db.names.id

I am using
neo4j-community-1.9.1
java version "1.7.0_25"
Amazon EC2 m1.large instance with Ubuntu 12.04.2 LTS (GNU/Linux 3.2.0-40-virtual x86_64)
RAM ~8GB.
EBS 200 GB, neo4j is running on EBS volume.

Invoked as ./neo4j-community-1.9.1/bin/neo4j start
Below are the neo4j server info:
neostore.nodestore.db.mapped_memory                 161M
neostore.relationshipstore.db.mapped_memory         714M
neostore.propertystore.db.mapped_memory              90M
neostore.propertystore.db.index.keys.mapped_memory    1M
neostore.propertystore.db.strings.mapped_memory     130M
neostore.propertystore.db.arrays.mapped_memory      130M
mapped_memory_page_size                               1M
all_stores_total_mapped_memory_size                 500M

{Data Model} is like Social Graph :-
User-User
    User-[:FOLLOWS]->User
User-Item
    User-[:CREATED]->Item
    User-[:LIKE]->Item
    User-[:COMMENT]->Item
    User-[:VIEW]->Item
Cluster-User
    User-[:FACEBOOK]->SocialLogin_Cluster
Cluster-Item
    Item-[:KIND_OF]->Type_Cluster
Cluster-Cluster
    Cluster-[:KIND_OF]->Type_Cluster

{Some Queries} and time:
START u=node(467242)
MATCH u-[r1:LIKE|COMMENT]->a<-[r2:LIKE|COMMENT]-lu-[r3:LIKE]-b
WHERE NOT(a=b)
RETURN u,COUNT(b)

Query took 1015348ms. Returned 70956115 result count.
START a=node:nodes(kind="user")
RETURN a,length(a-[:CREATED|LIKE|COMMENT|FOLLOWS]-()) AS cnt
ORDER BY cnt DESC
LIMIT 10

Query took 231613ms

From the suggestions, I upgraged the box to M1.xlarge and M2.2xlarge

*

*M1.xlarge (vCPU:4,ECU:8,RAM:15 GB,Instance Storage:~600 GB)

*M2.2xlarge (vCPU:4,ECU:13,RAM:34 GB,Instance Storage:~800 GB)

I tuned the properties like below, and running from instance storage (as against EBS)
neo4j.properties
neostore.nodestore.db.mapped_memory=1800M
neostore.relationshipstore.db.mapped_memory=1800M
neostore.propertystore.db.mapped_memory=100M
neostore.propertystore.db.strings.mapped_memory=150M
neostore.propertystore.db.arrays.mapped_memory=10M

neo4j-wrapper.conf
wrapper.java.additional.1=-d64
wrapper.java.additional.1=-server
wrapper.java.additional=-XX:+UseConcMarkSweepGC
wrapper.java.additional=-XX:+CMSClassUnloadingEnabled
wrapper.java.initmemory=4098
wrapper.java.maxmemory=8192

but still the queries (like below) run in minutes ~5-8 minutes, which is not acceptable from recommendation point of view.
Query:
START u=node(467242)
MATCH u-[r1:LIKE]->a<-[r2:LIKE]-lu-[r3:LIKE]-b
RETURN u,COUNT(b)

{Profiling}
neo4j-sh (0)$ profile START u=node(467242) MATCH u-[r1:LIKE|COMMENT]->a<-[r2:LIKE|COMMENT]-lu-[r3:LIKE]-b RETURN u,COUNT(b);
==> +-------------------------+
==> | u            | COUNT(b) |
==> +-------------------------+
==> | Node[467242] | 70960482 |
==> +-------------------------+
==> 1 row
==>
==> ColumnFilter(symKeys=["u", "  INTERNAL_AGGREGATEad2ab10d-cfc3-48c2-bea9-be4b9c1b5595"], returnItemNames=["u", "COUNT(b)"], _rows=1, _db_hits=0)
==> EagerAggregation(keys=["u"], aggregates=["(  INTERNAL_AGGREGATEad2ab10d-cfc3-48c2-bea9-be4b9c1b5595,Count)"], _rows=1, _db_hits=0)
==>   TraversalMatcher(trail="(u)-[r1:LIKE|COMMENT WHERE true AND true]->(a)<-[r2:LIKE|COMMENT WHERE true AND true]-(lu)-[r3:LIKE WHERE true AND true]-(b)", _rows=70960482, _db_hits=71452891)
==>     ParameterPipe(_rows=1, _db_hits=0)

neo4j-sh (0)$ profile START u=node(467242) MATCH u-[r1:LIKE|COMMENT]->a<-[r2:LIKE|COMMENT]-lu-[r3:LIKE]-b RETURN count(distinct a),COUNT(distinct b),COUNT(*);
==> +--------------------------------------------------+
==> | count(distinct a) | COUNT(distinct b) | COUNT(*) |
==> +--------------------------------------------------+
==> | 1950              | 91294             | 70960482 |
==> +--------------------------------------------------+
==> 1 row
==>
==> ColumnFilter(symKeys=["  INTERNAL_AGGREGATEe6b94644-0a55-43d9-8337-491ac0b29c8c", "  INTERNAL_AGGREGATE1cfcd797-7585-4240-84ef-eff41a59af33", "  INTERNAL_AGGREGATEea9176b2-1991-443c-bdd4-c63f4854d005"], returnItemNames=["count(distinct a)", "COUNT(distinct b)", "COUNT(*)"], _rows=1, _db_hits=0)
==> EagerAggregation(keys=[], aggregates=["(  INTERNAL_AGGREGATEe6b94644-0a55-43d9-8337-491ac0b29c8c,Distinct)", "(  INTERNAL_AGGREGATE1cfcd797-7585-4240-84ef-eff41a59af33,Distinct)", "(  INTERNAL_AGGREGATEea9176b2-1991-443c-bdd4-c63f4854d005,CountStar)"], _rows=1, _db_hits=0)
==>   TraversalMatcher(trail="(u)-[r1:LIKE|COMMENT WHERE true AND true]->(a)<-[r2:LIKE|COMMENT WHERE true AND true]-(lu)-[r3:LIKE WHERE true AND true]-(b)", _rows=70960482, _db_hits=71452891)
==>     ParameterPipe(_rows=1, _db_hits=0)

Please let me know the configuration and neo4j startup arguments for tuning.
Thanks in advance

A: Okay, so first of all, for only 8GB of memory that's a very large graph. You should seriously consider getting a larger box. Neo4j actually provides an extremely nice hardware calculator that will let you determine exactly what is appropriate for your needs:
http://neotechnology.com/calculatorv2/

In a contrived way (since there are more relevant metrics to determining size) their calculator estimates should should be dedicating about 10GB at a minimum.
Secondly, Neo4j and any graph database will have issues with nodes that have a large number of connections. If you're looking to tune your instance to perform better (after getting a bigger box) I would suggest looking for any massive nodes with a large number of connections as those will seriously impact performance.
After seeing your examples I'm quite certain you've got a graph with a number of nodes that have a much larger number of connections that other nodes. This will inherently slow down your performance. You might also try more narrow queries. Especially when you're already working on a server that's too small you don't want to run the kind of extremely taxing large return queries you've got there.
There are some things about your queries that could be cleaned up, but I really urge you to get the appropriately sized box for your graph and actually do some introspection into the number of connections your most connected nodes have.
It also looks like you have an artificial cap on your Java Heap size. If you try starting up java with a command like:
java -Xmx8g //Other stuff

You'll allocate 8 gigs instead of the standard ~500 Megs, which would also help.

A: Running this on my macbook air with little RAM and CPU with your dataset.
You will get much faster than my results with more memory mapping, GCR cache and more heap for caches. Also make sure to use parameters in your queries.
You are running into combinatorial explosion.
Every step of the path adds "times rels" elements/rows to your matched subgraphs.
See for instance here: you end up at 269268 matches but you only have 81674 distinct lu's
The problem is that for each row the next match is expanded. So if you use distinct in between to limit the sizes again it will be some order of magnitutes less data.
Same for the next level.
START u=node(467242)
MATCH u-[:LIKED|COMMENTED]->a
WITH distinct a
MATCH a<-[r2:LIKED|COMMENTED]-lu
RETURN count(*),count(distinct a),count(distinct lu);

+---------------------------------------------------+
| count(*) | count(distinct a) | count(distinct lu) |
+---------------------------------------------------+
| 269268   | 1952              | 81674              |
+---------------------------------------------------+
1 row

895 ms

START u=node(467242)
MATCH u-[:LIKED|COMMENTED]->a
WITH distinct a
MATCH a<-[:LIKED|COMMENTED]-lu
WITH distinct lu
MATCH lu-[:LIKED]-b
RETURN count(*),count(distinct lu), count(distinct b)
;
+---------------------------------------------------+
| count(*) | count(distinct lu) | count(distinct b) |
+---------------------------------------------------+
| 2311694  | 62705              | 91294             |
+---------------------------------------------------+

Here you have 2.3M total matches and only 91k distinct elements. So almost 2 orders of magnitude.
This is a huge aggregation which is rather a BI / statistics query that an OLTP query.
Usually you can store the results e.g. on the user-node and only re-execute this in the background.
THESE kind of queries are again global graph queries (statistics / BI ), in this case top 10 users.
Usually you would run these in the background (e.g. once per day or hour) and connect the top 10 user nodes to a special node or index that then can be queried in a few ms.
START a=node:nodes(kind="user") RETURN count(*);
+----------+
| count(*) |
+----------+
| 3889031  |
+----------+
1 row

27329 ms

After all you are running a match across the whole graph, i.e. 4M users that's a graph global, not a graph local query.
START n=node:nodes(kind="top-user")
MATCH n-[r?:TOP_USER]-()
DELETE r
WITH distinct n
START a=node:nodes(kind="user")
MATCH a-[:CREATED|LIKED|COMMENTED|FOLLOWS]-()
WITH n, a,count(*) as cnt
ORDER BY cnt DESC
LIMIT 10
CREATE a-[:TOP_USER {count:cnt} ]->n;

+-------------------+
| No data returned. |
+-------------------+
Relationships created: 10
Properties set: 10
Relationships deleted: 10

70316 ms

The querying would then be:
START n=node:nodes(kind="top-user")
MATCH n-[r:TOP_USER]-a
RETURN a, r.count
ORDER BY r.count DESC;

+--------------------------------------------------------------------------------------------------------------------------------------------------------------+
| a                                                                                | r.count |
+--------------------------------------------------------------------------------------------------------------------------------------------------------------+
….
+--------------------------------------------------------------------------------------------------------------------------------------------------------------+
10 rows

4 ms

A: You don't need:
WHERE NOT(a=b)

Two different identifiers are never the same node in a Pattern matcher.
Can you use profile with your queries?
profile START u=node(467242)
MATCH u-[r1:LIKE|COMMENT]->a<-[r2:LIKE|COMMENT]-lu-[r3:LIKE]-b
RETURN u,COUNT(b)

It would also be interesting to see how many nodes are touched:
profile START u=node(467242)
MATCH u-[r1:LIKE|COMMENT]->a<-[r2:LIKE|COMMENT]-lu-[r3:LIKE]-b
RETURN count(distinct a),COUNT(distinct b),COUNT(*)

You can also reduce your MMIO settings to the real values:
neostore.nodestore.db.mapped_memory=180M
neostore.relationshipstore.db.mapped_memory=750M

If you declare all of your machine's RAM as heap it will compete with FS-buffers and the mmio buffers.
wrapper.java.initmemory=5000
wrapper.java.maxmemory=5000

Are you measuring the first run or subsequent runs of your queries?


text:
Q: Recursive descent parser that counts the number of 'a' and 'b' characters not counting correctly I'm writing a simple recursive descent parser that takes standard input and counts the number of 'a' and 'b' characters. The grammar for this is as follows:
S -> A B '\n'
A -> a A | empty
B -> b B | empty
int lookahead;

int nontermA();
int nontermB();

void match (int terminal){

   if (lookahead == terminal){
      lookahead = getchar();
      } else {
      printf("Syntax error at %c\n", lookahead);
      exit(0);
      }

}

void nontermS(){
   int a,b;
   switch(lookahead){
      default:
      a = nontermA();
      b = nontermB();
      printf("Match! Number of A's is %d and number of B's is %d", a,b);
      match('\n');
     }

}

int nontermA(){
   int countA = 0;
   switch(lookahead){

      case 'a': match('a'); countA++; nontermA(); break;
      case 'A': match('A'); countA++; nontermA(); break;
      default: break;

   }

   return countA;

}

int nontermB(){
   int countB = 0;
   switch(lookahead){
      case 'b': match('b'); countB++; nontermB(); break;
      case 'B': match('B'); countB++; nontermB(); break;
      default: break;
   }
   return countB;

}

Basically, if I type in something like "aA", "bB", or "abAB", it should just output the number of a's and b's, but the actual output for my program is just 1 for a and b. I also get a syntax error when I type in "ba", as well as if I input "B".

A: Both of the nontermA and nontermB functions exhibit the same logical flaw. The following describes only nontermA's bug, but the same bug also occurs in nontermB.
 int countA = 0;

This declares a new int variable that's local to nontermA.
  case 'a': match('a'); countA++; nontermA(); break;

This increments countA, and recursively invokes itself.
However each recursive invocation of nontermA works exactly like any other function call to nontermA: it creates a new local variable named countA and initializes it to 0.
The obvious intent here is for the counter to persist across all recursive invocations. But recursion does not work this way.
Each recursive call creates a new countA local int variable for that recursive function call only, and that's the only thing that gets incremented. That's how C++ works.
The solution is very simple: just return the counter value, have both nontermA and nontermB return the counter value directly.
  case 'a': match('a'); return nontermA()+1;

And, otherwise,
return 0;

when no match occurs.


text:
Q: P(x) is x-special??? Beforehand, I apologize for my complete inability to write any sort of TeX commands; fortunately, my question shouldn't require this. (If anyone knows a good reference for me to start learning, I would greatly appreciate it.)  Also, any occurrence of "0" below refers to the empty set.
I'm reading Smullyan and Fitting's "Set Theory and the Continuum Problem," and the authors are trying to show that for a fixed progressing function g, (i.e., a function g on the universal class V such that x is a subset of g(x) for all x in V) the existence of the class of all g-sets (x is a g-set if x belongs to every class superinductive under g) is derivable without the axiom of substitution.  In particular, when g is the successor function x |--> x U {x} , this shows that the class of all ordinals exists.
Now, the authors approach this through a series of lemmas.  First, they define:
For sets S and x, "S is closed (under g) relative to x" iff for all z in S, if z is a subset of x, then g(z) is in S.
A set S is "x-special" iff 0 is in S, S is closed relative to x, and S is closed under chain unions.
Then they write "Lemma 7.4: P(x) is x-special. Proof: Obvious."
But I don't believe that's even true! For example, if we let x = 0 and g be the successor function, then P(x) = {0} = 1, so if we take z = 0, we see that z is in S, z is a subset of x, and clearly g(z) = 0 U {0} = {0} = 1 is not in P(x), so that P(x) is NOT closed under g relative to x, hence, P(x) is NOT x-special.
Am I misunderstanding something? Please help clarify this for me...it's been driving me crazy.  It seems so simple, yet I can't understand why the authors would write something like this if it were so "obviously" false.
Thank you!  (Sorry for the long read)

A: I took a look at the errata for the 2010 Dover edition, and found a listing for one of the definitions you provided. It is the Page 66 listing.
I quote:

Definition 7.1 is incorrect as stated. It should read as follows.For any sets $y$ and $x$, we will say that $y$ is closed (under $g$) relative to $x$ provided, for any
  $z \in y$, if $g(z) \in P(x)$ then $g(z) \in y$.

Using this definition, the lemma is indeed obvious.


text:
Q: How would I translate numbers to words in Scheme? We just started with scheme at the university and I need some help doing my task.
We shall write a program that translates numbers into words, EG: 1 to "one".
It must work for all numbers up to 10 ^ 9. I've got no real clue how to do this.
My basic idea would be to create some sort of array or list where I define those numbers as words like this:
('ZERO', 0) ('ONE', 1) ('TWO', 2) ('THREE', 3) ('FOUR', 4) ('FIVE', 5) ('SIX', 6)
('SEVEN', 7) ('EIGHT', 8) ('NINE', 9) ('TEN', 10) ('ELEVEN', 11) ('TWELVE', 12)
('THIRTEEN', 13) ('FOURTEEN', 14) ('FIFTEEN', 15) ('SIXTEEN', 16)
('SEVENTEEN', 17) ('EIGHTEEN', 18) ('NINETEEN', 19) ('TWENTY', 20) ('THIRTY', 30)
('FORTY', 40) ('FIFTY', 50) ('SIXTY', 60) ('SEVENTY', 70) ('EIGHTY', 80)
('NINETY', 90) ('HUNDRED', 100) ('THOUSAND', 1000) ('MILLION', 1000000)
('BILLION', 1000000000) ('TRILLION', 1000000000000)
('QUADRILLION', 1000000000000000)

Then somehow check the input value with this list and substitute the numbers with the words.
But implementing this is giving me some trouble.
The main question that buggers me is if Scheme can do substrings and if I can make a list in which I define those numbers as words (so define 1 as one).

A: *

*You can't "cheat" and do (define 1 one) as 1 is already defined to be a number :)

*I don't think you need to worry about substring in this problem, you are building up a string from substrings, not the opposite...

*

*You do need an operation for string concatenation though. I don't remember how they do strings in scheme though...

The only "hard" problem here is that you need to encode the arbritrary rules from the english language so...
//pseudocode, doing things the "dumb way" tons of ifs, aka cond
define to_str n =
    if n == 1 then "one"
    ...
    if n == 3 then "thirteen"
    ..
    if 20 <= n < 30 then
       'twenty-' concatenated to  (to_str (n - 20))
    ...

After you get a version like this to work you can think about abstracting the repetitive control-flow via a dictionary or association list similar to the one you mentioned in the question.


text:
Q: Resampling netcdf from daily to monthly keeping nan values I have many daily NetCDF resulted from a hydrological model and I want to convert them to monthly/yearly level both by summing or averaging them. For this, I use the following code:
import xarray as xr

nc_file = r'J:\RESULTS\WB_PRECIPITATION.nc'
ds = xr.open_dataset(nc_file)
monthly_data=ds.resample(time='Y',skipna=True).sum()
output = r'J:\RESULTS\WB_PRECIPITATION_YEARLY.nc'
monthly_data.to_netcdf(output, engine="netcdf4")

The problem is that my original daily file has several zones with nan (_FillValue=-9999) and that when they pass to the new NetCDF they pass to have the value 0. In this case, that is distorting all the calculations.
I already check "skipna" parameter with True and False values and I got the same result.
In pandas, when I have had the same problem I have used the following code, however, I have not been able to adapt it for this situation.
import numpy as np
import pandas as pd

def very_sum(array_like):
    if any(pd.isnull(array_like)):
        return np.nan
    else:
        return array_like.sum()

df = ...
df_yearly = df.resample('Y').apply(very_sum)

How can I resample my data without losing the zones with nan. ?

A: I think you only misplaced the skipna keyword, it belongs in the method rather than in the resample. This is basically a duplicate of: xarray resampling with certain nan treatment
So instead of:
monthly_data=ds.resample(time='Y',skipna=True).sum()

Just do:
monthly_data=ds.resample(time='Y').sum(skipna=False)

As a runnable example:
import numpy as np
import pandas as pd
import xarray as xr

time = pd.date_range("2000-01-01", "2000-12-31")
da = xr.DataArray(data=np.ones(time.size), coords={"time": time}, dims=["time"])
da.data[:45] = np.nan

Default:
da.resample(time="m").sum()

<xarray.DataArray (time: 12)>
array([ 0., 15., 31., 30., 31., 30., 31., 31., 30., 31., 30., 31.])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-31 2000-02-29 ... 2000-12-31

skipna=False:
da.resample(time="m").sum(skipna=False)

<xarray.DataArray (time: 12)>
array([nan, nan, 31., 30., 31., 30., 31., 31., 30., 31., 30., 31.])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-31 2000-02-29 ... 2000-12-31


text:
Q: In ASP.NET MVC5 how do I retrieve the Selected Value chosen by a user in a View from a DropDownListFor and pass it to the Controller Action? In ASP.NET MVC 5 Please could someone help me with how I determine the value that has been selected from a Select List (implemented as a @Html.DropDownListFor) in a View so I can pass it back to the Controller Method in order to select a modified list of data please? I have spent a few days browsing and trying things to no avail:
Here is what I have. I have a parent Model:
public class ParentEndorsementViewModel
{
    // Child Models:
    public List<VW_CMA_PRODUCT_ENDORSEMENT> VW_CMA_PRODUCT_ENDORSEMENTS { get; set; }

    // This property will hold all available Products for selection:
    public IEnumerable<SelectListItem> Product_DropDownList { get; set; }

}

And the relevant "child" model is:
public class Product_DropDownList
{
    private Product_DropDownList(int id, string name)
    {
        Id = id;
        Name = name;
    }

    public int Id { get; set; }
    public string Name { get; set; }
}

The View has:
@model App_Endorsement.Models.ParentEndorsementViewModel
….
    @using (Html.BeginForm("Manage_Endorsement", "Endorsement", new { ParentEndorsementViewModel = @Model }, FormMethod.Post, null))
{
    @*@Html.AntiForgeryToken()*@
    @Html.DropDownListFor(m => m.Product_DropDownList, new SelectList(Model.Product_DropDownList, "Value", "Text", Model.Product_DropDownList), "Show All Products")
    <input type = "submit" value = "Send" />
}

The Controller method starts:
    [HttpPost]
    //[ValidateAntiForgeryToken]
    public IActionResult Manage_Endorsement(ParentEndorsementViewModel In_ParentEndorsementViewModel)
    {
        var ParentEndorsementViewModel = In_ParentEndorsementViewModel;

As I say I want to retrieve the Selected Value that the User has chosen from within the Product_DropDownList but when the model (ParentEndorsementViewModel) arrives in the Controller it is empty.

A: I think you have overcomplicated this somewhat. Your views main model needs both a list to populate the control and a variable to contain the selected value.
For example your model:
public class ParentEndorsementViewModel
{
    public int SelectedId { get; set; }
    public List<SelectListItem> ProductList { get; set; }

    public ParentEndorsementViewModel() {
        // Do this just in case you forget to instantiate the list in your first call to the view.
        ProductList = New List<SelectListItem>();
    }
}

On your view:
@Html.DropDownListFor(x => x.SelectedId, Model.ProductList)

When the user sends this data to back to your controller via a form POST for example, the model binder should marry up to the view model. The value selected by your user is contained in SelectedId variable.
[HttpPost]
public ActionResult MyPostBack (ParentEndorsementViewModel model) {
    var myselectedid = model.SelectedId;
    //Do whatever
}

A: You need another property on your ParentEndorsementViewModel, which is what will hold the selected value from the drop down list.  Currently your code is attempting to set the selected value to the property that contains the available items.
e.g. in the view model
public class ParentEndorsementViewModel
{
    // Child Models:
    public List<VW_CMA_PRODUCT_ENDORSEMENT> VW_CMA_PRODUCT_ENDORSEMENTS { get; set; }

    // This property will hold all available Products for selection:
    public IEnumerable<SelectListItem> Product_DropDownList { get; set; }

    // NEW PROPERTY
    public int SelectedProductId { get; set; }
}

In the view:
@model App_Endorsement.Models.ParentEndorsementViewModel

@using (Html.BeginForm("Manage_Endorsement", "Endorsement", new { ParentEndorsementViewModel = @Model }, FormMethod.Post, null))
{
    @*@Html.AntiForgeryToken()*@

    @* CHANGE THE TARGET PROPERTY HERE *@
    @Html.DropDownListFor(m => m.SelectedProductId, new SelectList(Model.Product_DropDownList, "Value", "Text", Model.Product_DropDownList), "Show All Products")
    <input type = "submit" value = "Send" />
}

In the Controller:
[HttpPost]
//[ValidateAntiForgeryToken]
public IActionResult Manage_Endorsement(ParentEndorsementViewModel In_ParentEndorsementViewModel)
{
    var ParentEndorsementViewModel = In_ParentEndorsementViewModel;
    var selectedProductId = ParentEndorsementViewModel.SelectedProductId;


text:
Q: Why are there automatic moderator flags (autoflags) from the Community User, and what are they for? Occasionally as a moderator I've noticed flags from the Community user.  I've got a few questions:

*

*Why do they exist?

*What events trigger them?

*How might moderators act on them?

A: When you look at the Community user's flag history you are seeing all the flags from deleted users which are assigned to Community.  But there are also 10 flag types that are generated by the system in order to bring to moderator attention situations that might be missed by a site's users.  These flags don't always indicate a problem (otherwise the system would take action directly).  Their purpose is to serve as a canary in the coal mine.
The complete list of automated flags and their descriptions is:

*

*low quality (auto)—"Failed low quality algorithms upon creation"

*

*This flag will also result in the post being placed in the Low quality posts queue, or, on certain sites, the Triage queue for questions or the Low quality answers queue for answers. Dismissing this flag will remove it from those queues.

*disputed low quality review (auto): There are three reasons why this flag will be raised, all of which result from the Low quality posts or Low quality answers review queues:

*

*A post was dismissed with a Looks OK outcome, but "Looks OK" did not constitute a majority of the reviews. (Due to the way the review queue works, it's possible for tasks to be dismissed with fewer Looks OK reviews than close/delete reviews - this flag is to indicate that that happened.)

*An answer was deleted in review, but it was undeleted by the author.

*An answer with a positive score was reviewed as Recommend Deletion.

*consecutive closed questions (auto)—"User has had multiple questions closed back-to-back"

*post is excessively long (auto)—"Post body is much larger than usual"

*too many comments (auto)—"Post has more comments than usual"

*too many answers (auto) -- "more than 10 answers posted in 7 days" (15 answers on Software Engineering)

*possible rollback war (auto)—"Post is being rolled back more than usual"

*question closed without explanatory comment (auto)—"A question on a private/public beta site has been closed without any explanation"

*duplicate answer (auto)—"Many of a user's latest answers are similar/identical"

*possible vandalism: deletions (auto)—"Possible vandalism of own posts; multiple deletions in a short time"

*possible vandalism: edits (auto)—"Possible vandalism of own posts; multiple edits in a short time"

*possible vandalism: comments (auto)—"Possible vandalism of own comments; multiple deletions in a short time"

*possible comment abuse: too many rude/NC (auto)— Too many comments with "harassment" or "unfriendly" flags

Each flag's description gives an idea about what caused the flag to be raised.  Of note, the "question closed without explanatory comment" is not raised on sites that are not in beta.
I've linked a meta-question that asks for guidance on how to respond to each flag.  In general, treat automated flags as you would any other.  Feel free to decline Community flags if they aren't helpful.


text:
Q: How to redirect traffic/packets on one port to another port or server:port? I found similar questions but couldn't get them to work for my use case. I have a linux server running memcached that is listening to traffic on its local network ip, which is on eth1. I would like to allow a specific external IP to access memcached (has to be specific as there is no auth on memcached, and I don't want to restart the service and lose the cache.)
So I would like to do two things:

*

*On the memcached server, allow a specific external IP "A" to connect to the server on eth0, the public net, and forward the packets to eth0 with access to memcached. There should be no interference with existing traffic to memcached on eth1. This can probably be done with iptables.

*Use the server with IP "A" as a proxy for other servers on its LAN. How can I set up all traffic on "A":1234 to forward to eth0 on the memcached server? Can this be done with iptables?
Any help would be appreciated.


text:
Q: Determine when $T(S^n \times S^k)$ is a trivial tangent bundle. My partial answer is that , to make $T(S^n \times S^k)$ trivial, a neccessary condition is that $n$ or $k$ is odd.
My argument is as follows:
Suppose $T(S^n \times S^k)$ is trivial, that is, $S^n \times S^k$ is parallelizable. In particular, there exists a global non-vanishing vector field, say $X$. It follows from Poincare-Hopf index theorem that $$\chi (S^n \times S^k)=0$$
On the other hand, by Kunneth formula,
$H_*(S^n \times S^k)=H_*(S^n)\otimes H_*(S^k)$; and it follows that
$$\chi (S^n \times S^k)=1+(-1)^n+(-1)^k+(-1)^{n+k}=(1+(-1)^n)(1+(-1)^k)$$
Hence, a necessary condition should be  "$n$ or $k$ is odd".
Question   (1) Is the condition "$n$ or $k$ is odd" a sufficient condition too?
(2) Are there some systematical methods to solve this kind of problem---determing tangent bundle or even fibre bundles over a specific manifold?
(3)Concerning the reference books related to "bundle theory", I only know Hatcher's book "Vector bndles and K-theory" and Bott's book "Differential forms in algebraic topology". , are there any other more comprehensive reference books else?
Please help! Thank you very much!

A: (1) Yes. Use the fact that the $TS^n$ are stably trivial. (Explicitly, embed $S^n$ in $\mathbb{R}^{n+1}$ and note that the normal bundle is trivial, since it clearly admits a nowhere-vanishing section. Now note that $T(S^n\times S^m) = TS^n \oplus TS^m$ and induct on $n, m$.)
(2) There are certainly a lot of results about classifying bundles by characteristic classes, up to stable trivialization, for specific classes of manifolds (e.g., closed, oriented $3$-manifolds), etc., but I don't know of a convenient algorithm.
(3) Hatcher's and Bott's books are exceptional, but I like Husemoller's "Fiber Bundles".


text:
Q: DocuSign IP addresses The following pdf gives a list of IP addresses of DocuSign servers:
https://www.docusign.co.uk/sites/default/files/Post_API_Certification20130522.pdf
Based on the information in this document:
1) to call the REST API in a production environment we have to use the hostname www.docusign.net
2) this server has the IP 209.67.98.12
Can we rely on this ? I need to be sure that the server to call will be always www.docusign.net and I need to know its IP address to properly configure firewalls.
Thank you

A: The URL you have listed is accurate as long as your account resides on that instance in Production. Your question about the IP addresses is a good one - I believe the version of this document you are looking at is a bit stale. Please refer to this post (http://community.docusign.com/t5/Announcements/Additional-IP-Addresses-for-DocuSign-Service/td-p/29702) regarding the IP ranges of the DocuSign service.


text:
Q: Non-trivial extensions with trivial connecting homomorphism in long exact sequence? Let $X$ be a smooth projective curve over an alg. closed field $k$. Consider an exact sequence of locally free sheaves:
$$0 \to \mathcal{E}_1 \to \mathcal{E}_2 \to \mathcal{E}_3 \to 0$$
This sequence gives rise to a long exact sequence in cohomology:
$$0 \to H^0(\mathcal{E}_1) \to H^0(\mathcal{E}_2) \to H^0(\mathcal{E}_3) \to H^1(\mathcal{E}_1) \to H^1(\mathcal{E}_2) \to H^1(\mathcal{E}_3) \to 0$$
For a trivial extension $\mathcal{E}_2\cong\mathcal{E}_1 \oplus \mathcal{E}_3$ the connecting homomorphism $\delta: H^0(\mathcal{E_3}) \to H^1(\mathcal{E}_1)$ is forced to be trivial ($Im(\delta)=0$).

What about implication in the other direction? Can there be a
  non-trivial extension of locally free sheaves whose connecting homomorphism $\delta$ is
  trivial?

A: If you take any non-split short exact sequence of locally free sheaves over $\mathbb{P}^1$ and take the tensor product with $\mathcal{O}(-n)$ for sufficiently large $n$, then you'll get a sequence on which $H^0$ vanishes, and so necessarily the connecting homomorphism will be zero.


text:
Q: How to generate a random number that is not the same as the last Before I say anything, please note that this is not a duplicate of:
**
This Question
Because I have tried using all the answers from that question, but they all come up as errors because of the UINT32.
So, how can I generate a random number using arc4random but not making it the same number as last time?

A: Here's a solution without using UINT32
var previousNumber: Int? // used in randomNumber()

func randomNumber() -> Int {
    var randomNumber = Int(arc4random_uniform(10))
    while previousNumber == randomNumber {
        randomNumber = Int(arc4random_uniform(10))
    }
    previousNumber = randomNumber
    return randomNumber
}


text:
Q: Register non-static C++ methods in Lua I'm trying to make a small C++/Lua system where I would create my objects and attach behaviors to them in Lua. Right now I'm using LuaWrapper (a small header with basic C++ to Lua stuff), my problem is that as far as I can see Lua only let me register static class methods (or non-static functions), a little research and I figured its because the Lua typedef expects a method with only one parameter lua_State* L and non-static methods have the implicit this.
I was hoping for a way to solve this without dependency on other libraries, all I need is non-static classes/properties in Lua, so I see no reason to use LuaBind+Boost or other heavy-dependant wrappers.

A: LuaWrapper isn't meant to hook up directly to non-static functions in a class. I suppose it could be with some special trickery, but this is how I designed it to be used:
static int Widget_AddChild(lua_State* L)
{
    Widget* parent = luaW_check<Widget>(L, 1);
    Widget* child = luaW_check<Widget>(L, 2);
    if (parent && child)
    {
        lua_pushboolean(L, parent->AddChild(child));
        return 1;
    }
    return 0;
}

// ...

static luaL_reg Widget_metatable[] =
{
    { "AddChild", Widget_Addchild },
    // ...
    { NULL, NULL }
};

I usually keep the non-lua stuff in a separate file. In this case Widget.cpp/hpp. Then I have a LuaWidget file which just contains bindings like these which I write as needed. (I also have a number of snipmate snippets to make writing these functions quick and painless. If you're using vim I'd be happy to share them)

A: You can make a static function that will accept an instance of the class and an argument and call that function on the instance:
void func_static(MyClass* inst, T arg) {
    inst->func(arg);
}

Then register a function to call that function as a metafunction so you can do in lua
blah:x(y)

which will call the function that will receive the userdata that blah contains, as well as the argument y, and call func_static with blah and y.

A: You may want to look into using toLua++ (http://www.codenix.com/~tolua/).
It can parse class definitions and output a c++ code file to make the non-static class members available in Lua.

A: You could also take a look at LuaCppWrapper. It's intended for simple bindings only. If you want a full fledged solution, maybe OOLua or Simple Lua Binder are what you need.


text:
Q: Is $SU(n)$ a CW group? A CW-group $G$ is a topological group with a CW structure such that both the multiplication and the inversion are cellular. It is known that $O(n)$, $U(n)$, and $Sp(n)$ can be given CW-group structures: for the CW structures given in Steenrod and Epstein, Cohomology Operations, Chap. IV, it is not hard to check that the relevant maps are cellular.
$SU(n)$ can be given a CW structure, via the homeomorphism $SU(n) \approx G_{\mathbb C}(n,1) := U(n)/U(1)$. This is what was done in Cohomology Operations, as well as "On the cell structures of $SU(n)$ and $Sp(n)$," but my understanding is that this does not make $SU(n)$ a CW-group.
Can $SU(n)$ be given a CW-group structure? Is there any theorem addressing the question as to when a topological group can be given a CW-group structure?


text:
Q: how to automatically restart a node server? We are finishing development of a project, the client is already using it but occasionally some errors occur - crashing the server.
I know I could register a service as 'upstart' script on linux, in order to have my node service restart when it crashes.
But our server is running other stuff, so we can't restart it.
Well, actually, while writing, I realize I have two questions then:

*

*Will 'upstart' work without having to reboot? Something is just whispering yes to me :)

*If not, what other option would I have to 'respawn' my node server when it crashes?

A: Yes, upstart will restart your process without a reboot.
Also, you should look into forever.

A: If your focus for automatic restart is an always running application, I suggest to use a process manager. Process manager, in general, handles the node process(es if cluster enabled), and is responsible for the process/es execution. PM leans on the operative system: your node app and the OS are not so strinctly chained because the pm is in the middle.Final trick: put the process manager on upstart. Here is a complete performance improvement path to follow.

A: PM2 is a Production process manager for Node.js app.

A: Using a shared server and not having root privileges, I can't download or install any of the previously mentioned libraries. What I am able to do is use a simple infinite bash loop to solve my issue. First, I created the file ./startup.sh in the base directory ($ vim startup.sh):
#!/bin/bash
while:
do
    node ./dist/sophisticatedPrimate/server/main.js
done

Then I run it with:
$ bash startup.sh

and it works fine. There is a downside to this, which is that is doesn't have a graceful way to end the loop (at least not once I exit the server). What I ended up doing is simply finding the process with:
$ ps aux | grep startup.sh

Then killing it with
$ kill <process id>
example
$ kill 555555


text:
Q: typescript calling function results with undefined Having an issue with regard to calling the function in typescript
I have a class
 export class Test{
     constructor(){}

     public func1(req:request,res:Response) {
 // call method
        let func2 =  this.Func2();

     }

     private Func2():string{
       return "Hello";
   }
}
export default new Test();

I have an express Router class
import {Router} from "express";
import Test from '../Handlers/Test';
export class UserRouter {

router: Router;

constructor() {
    this.router = Router();

}

Routes() {
    this.router.route('/user').post(Test.Func1);
    return this.router;
}

}

export default new UserRouter().Routes();

The issue is when I try to call the method Func2 using this.Func2() in Func1() method i get an error stating cannot call Func2 of undefined. I either have to call it in 2 ways
1) `new Test().Func2() inside Func1() method as
public Func1(req:request,res:Response){
   let func2 = new Test().Func2();
}

2) make Func2() as static and then call it using Test.Func2()
public Func1(req:request,res:Response){
   let func2 = Test.Func2();
}

private static Func2():string{
   return "Hello";
}

why can't I just call it using this.Func2() ?
Is it because I am exporting new of Test() to the router method and that object is no longer in memory?

A: 1) new Test().Func2()
This will not work in Typescript level, because your method is private, so it is not accessible from the outside.
2) Test.Func2()
This will keep the function inside the Test itself, so the function will not been attached to any object ( this ).
What about your code?
Your code is working. Is this the same code you have tried?

 class Test{
     constructor(){}

     func1(req,res) {
        let func2 =  this.func2();
        console.log(func2);
     }

     func2(){
       return "Hello";
   }
}

const t = new Test();
t.func1();

A: Your problem is this:
this.router.route('/user').post(Test.Func1);

You are passing Test.Func1 to be invoked later as a callback, when that function is finally invoked the scope of this won't be the instance (Test) but something else, and so you have two options:
(1) Bind it:
this.router.route('/user').post(Test.Func1.bind(Test));

(2) Arrow function:
this.router.route('/user').post(() => Test.Func1());


text:
Q: IntelliJ beginning of file keyboard shortcut Is there a keyboard shortcut to move to the beginning of a file? I checked IntelliJ's Keymap for Mac OS X and it doesn't list anything for navigating to the start of a file.

A: The accepted answer is not correct. To move to the beginning/end of a file, use ctrl+home/ctrl+end on Windows/Unix or command-home and command-end on the Mac, as @jackrabbit suggested.
ctrl+pageup (Move Caret to Page Top) moves the caret to the top of the viewable portion of the file (page, viewport). It also does not move the caret to the first column, it tries to stay in the same column that it was previously

A: Just as an addition for clarity
For Windows,
Ctrl + Home => Top
Ctrl + End => Bottom
Ctrl + PgUp => Page Up
Ctrl + PgDn => Page Down

A: command+home or fn+command+left arrow

A: Search the Keymap preference settings, and set your own key combination for "Move Caret to Text Start" and "Move Caret to Text End".  This has the behavior the OP intends, where the caret is moved to the very top of the text in file, and the very end.  :D
I am using IntelliJ 12, and LOVING IT!

A: On Mac, command+home and command+end move to the top and bottom of the file.
On a Mac laptop, there are no home or end keys. Many key combinations with option/function keys produce missing keys and do other neat things. For instance, using function+left and function+right will provide windows-style home and end behaviour while function+up and function+down will provide page up and page down behaviour. Superuser has more information.
Also, if you open the Keyboard preferences pane and look at the Input Sources tab, you will find that the displayed keyboard changes as you press modifier keys such shift, option and function. Your keyboard probably does way more than you thought.

A: Edit the Intellij Preferences -> KeyMap -> Editor Actions entries for "Move Caret to Text Start" and "Move Caret to Text End".  If you set those to Command+UpArrow and Command+DownArrow, it'll work like a normal text editor.  I have no idea why that isn't the default in Intellij instead of the seemingly pointless "scroll one line" feature.

A: You're looking for:
Page Up => fn + up

Page Down => fn + down


text:
Q: How to group records by date when date is in UNIX Timestamp format? I'm getting two dates from PHP form in the dd-mm-yyyy format.
(Say 01/06/2013 and 30/06/2013)
Now I'm using following code to display the datewise result among the date range as given above, but it's not working for me as the dates stored in DB are in UNIX Timestamp format(transaction_date    bigint(12)). How should I display the datewise results then? Can anyone help me in resolving this issue?
if($form_data['from_date']!='' && $form_data['to_date']!='') {
        $from_time  = explode("/", $form_data['from_date']);
        $to_time    = explode("/", $form_data['to_date']);

        $start_date = mktime( 0,0,0,$from_time[1],$from_time[0],$from_time[2] ) ;
        $end_date   = mktime( 23,59,59,$to_time[1],$to_time[0],$to_time[2] ) ;

        $sql  =" SELECT COUNT(*) `total count`, SUM(transaction_status = 'success') `success`, ";
        $sql .=" SUM(transaction_status = 'inprocess') `inprocess`, SUM(transaction_status = 'fail') `fail`, ";
        $sql .=" SUM(transaction_status = 'cancelled') `cancelled` FROM user_transaction ";
        $sql .=" WHERE  transaction_date >= '".$start_date."' AND transaction_date <=  '".$end_date."' GROUP BY transaction_date ";

        $this->mDb->Query( $sql);

        $queryResult = $this->mDb->FetchArray();
    }

Thanks in advance.

A: Use FROM_UNIXTIME(transaction_date) to get it as date type. Info

A: Make change in your last line of query and replace with below code:
$sql .=" WHERE  DATE_FORMAT(transaction_date,'%d-%m-%Y') >= '".$start_date."' AND DATE_FORMAT(transaction_date,'%d-%m-%Y') <=  '".$end_date."' GROUP BY FROM_UNIXTIME(transaction_date)";

And this link will be more helpful to you MySQL convert datetime to Unix timestamp.


text:
Q: Find the source of (eval:...) code I've got code which produces a stack trace at some point:
fileA.rb:1670:in `flow_completed_for'
(eval):58:in `on_success_res_for_register'
fileB:312:in `send'
fileC:312:in `request_specific_response_dispatch'
...

How can I find the source where on_success_res_for_register was defined? The code is called from some timer and I have problems localising the function code. Is there any way I can get the source of that command?
Also - is such stacktrace line generated only by eval(), or is it possible in some other way (some side effects of send()? or something catching all method calls?)

A: That means the method was created by eval, so it doesn't have a file associated with it. Your best bet is just to grep for "def flow_completed_for".


text:
Q: Doesn't change coordinate child After Scale Layout Android Java Problem: I have Custom Layout When I Scale it with following method all Child draw in right position but when i get their coordinate still they are in primary location or when i touch previous location then onClick child call it.
Question: I want know is there any easy way i can fix it by some method
or it must fix it with manual way .(anyway I haven't any idea for solve this problem)
protected void dispatchDraw(Canvas canvas) {
    canvas.save();
    canvas.scale(mScaleFactor, mScaleFactor, mPivotX, mPivotY);
    super.dispatchDraw(canvas);
    canvas.restore();
}

Near one week i stuck in this problem ,any help or suggestion can be grateful.

A: When you scale using the canvas, you are changing the appearance of the view but not the underlying view. That is why when you touch what appears to be one location, the code reports a different location.
Take a look at this question and the accepted answer. It will give you an idea about how to proceed in mapping your coordinates.
I hope this helps.


text:
Q: Best solutions for tree in doctrine with extension I am finding Best solutions for tree in doctrine with extension.
I need tree:

*

*in one table

*with multiple roots

*add onne root item to another root item

*tree items need order (weight) also roots

*create list with one select and without recursion

I try from this extension: https://github.com/Atlantic18/DoctrineExtensions/blob/v2.4.x/doc/tree.md
nested
- I can not order root items
closure
- not good idea , need 2 tables
materializedPath
- maybe bes way but do not have order (weight)
Does anyone have experience how to solve it?


text:
Q: Solving this inequality Question:

Solve: $$\frac{5x-6}{x+6}<1$$

My attempt:
$$\frac{5x-6-x-6}{x+6}<0$$
$$\Rightarrow \frac{4x-12}{x+6}<0$$
$$\Rightarrow \frac{x-3}{x+6}<0$$
$$\Rightarrow (x-3)(x+6) < 0$$
Thus, it implies that the answer is $-6 < x < 3$. However, in my textbook, it is given as wrong answer.
Can please someone tell what is the correct procedure for this.
Thanks.

A: Your answer is correct, the textbook is wrong.

A: If you're really unsure when something like that happens, you can always graph your rational function.  But consider that in $ \ \frac{x-3}{x+6} \ $ , there is a vertical asymptote at $ \ x \ = \ -6 \ $ and an $ \ x-$ intercept at $ \ x = 3 \ $ .  So the real numbers are divided into intervals by these points, $ \ x \ < \ -6 \ , \ -6 \ < \ x \ < \ 3 \ , $ and $ \ x \ > \ 3 \ $ .  Also, your rational function has a horizontal asymptote of $ \ y \ = \ 1 \ $ .
So the function is positive for "a lot" of the real numbers to start with.  We can also use what we know about working with signed numbers. For large negative numbers, both the numerator and denominator are negative, and for large positive numbers, they are both positive.  So for $ \ x \ < \ -6 \ $ and $ \ x \ > \ 3 \ $ , we can conclude that the ratio is positive.  It will only be in the interval $ \ -6 \ < \ x \ < \ 3 \ $ that the numerator is negative, while the denominator is positive, so the ratio is negative in this interval.
So you are correct.  Large introductory course textbook answers can be wrong anywhere from about $ \ \frac{1}{3}   $ %  to $ \ 2  $ % of the time, depending upon how carefully the submitted answers (of multiple authorship) have been combed through...

A: Hint: There are two cases, either $x < -6$ or $x > -6$. You can multiply both sides of the inequality by $x + 6$ and depending on which case you are considering, either it will reverse the inequality or leave it intact. Then you can rewrite the inequality with $x$ on one side and a number on the other side by adding/subtracting/dividing.


text:
Q: How to make this data control reusable for different content and data? I'm using ASP.NET Web Forms, and I've got a Repeater control to display some data. Currently it looks like this:
<asp:Repeater runat="server" ID="blah" OnItemDataBound="blah" OnItemCommand="blah">
    <HeaderTemplate>

    </HeaderTemplate>
    <ItemTemplate>

            <asp:LinkButton runat="server" ID="btn_select" CommandName="Select" Text="Select" style="display: none;"></asp:LinkButton>
            Date/Time: <%# DataBinder.Eval(Container.DataItem, "date") %>

            Details: <%# DataBinder.Eval(Container.DataItem, "details") %>

            Status: <%# DataBinder.Eval(Container.DataItem, "status") %>

    </ItemTemplate>
    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>

This list has hover behaviour, etc. and I'd like to reuse the same style of list across my project, just with different data (really just replacing the three lines with  tags in). However, I obviously don't want to copypaste and change it every time it's used, so I thought I'd try and make it into a User Control:
<asp:Repeater runat="server" ID="blah" OnItemDataBound="blah" OnItemCommand="blah">
    <HeaderTemplate>

    </HeaderTemplate>
    <ItemTemplate>

            <asp:LinkButton runat="server" ID="btn_select" CommandName="Select" Text="Select" style="display: none;"></asp:LinkButton>
            <%= DataString %>

    </ItemTemplate>
    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>

And in my corresponding class in CodeBehind:
public string DataString { get; set; }

So my main aim was to do this:
<uc:MyUserControl runat="server" ID="blah" DataString="Date/Time:<%# DataBinder.Eval(Container.DataItem, "date") %> ETC..." />

But it seemed that ASP.NET wanted to evaluate the <% %> in the string there and then, and I tried different ways to get around it such as this:
<% string theDataString = "Date/Time: <%# DataBinder.Eval(Container.DataItem, "date") %>"; %>
<uc:MyUserControl runat="server" ID="blah" DataString='<%= theDataString %>' />

But I ran into trouble again with the closing %> in theDataString, and even after replacing it with something like {0: %} (to escape the % sign: can't remember the exact syntax), which did escape it correctly, I discovered that you can't actually use the <%= %> inside an attribute, which was annoying.
My last-ditch attempt was to set DataString in my page's CodeBehind, and the HTML  rendered correctly, but ASP.NET didn't evaluate the <%# %> and just spat it out literally. So I'm kind of stuck as I can't think of anything else... (by the way I'm still relatively new to ASP.NET)
I'm not even sure this is a good way to go about it - previously I thought about making it into a templated user control but this method seemed simpler and it was something I already knew how to do, or so I thought. So any help with this would be greatly appreciated, thanks!
EDIT: Just to be clear, my emphasis here is on the re-usability of this particular control - so I will be able to display different types of data records in this style of list (clickable, highlight behaviour etc).

A: If your goal is to have three lines appear as bold instead of normal text, then your best bet is to use something more geared towards website-display than something programmatic and heavy-handed like a dynamic server-side user control. For example:
<asp:Repeater runat="server" ID="blah" OnItemDataBound="blah" OnItemCommand="blah">
    <HeaderTemplate>

    </HeaderTemplate>
    <ItemTemplate>

            <asp:LinkButton runat="server" ID="btn_select" CommandName="Select" Text="Select" style="display: none;"></asp:LinkButton>
            Date/Time: <%# DataBinder.Eval(Container.DataItem, "date") %>

            Details: <%# DataBinder.Eval(Container.DataItem, "details") %>

            Status: <%# DataBinder.Eval(Container.DataItem, "status") %>

    </ItemTemplate>
    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>

And then, programmtically show:

Use the right tool for the job, in this case, I don't feel as though server-side code is the right way to accomplish this task. If, on the other hand, you need to change the content of the insides of your
 tags, then yes you would have to do it in C#. However, if that were the case you could easily bind it to a different object or use a different control or inherit the control or any number of other methods. For your specific case, just use standard HTML manipulation techniques.


text:
Q: ruby version is not installing <= 2.2.5 or 2.2.0 I'm having trouble installing ruby 2.2.0 on my Linux system using rvm as my ruby version manager:
Searching for binary rubies, this might take some time.
No binary rubies available for: kali/kali-rolling/x86_64/ruby-2.2.0.
Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.
Installing Ruby from source to: /root/.rvm/rubies/ruby-2.2.0, this may take a while depending on your cpu(s)...
ruby-2.2.0 - #downloading ruby-2.2.0, this may take a while depending on your connection...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 12.6M  100 12.6M    0     0   9223      0  0:24:02  0:24:02 --:--:--  8338
ruby-2.2.0 - #extracting ruby-2.2.0 to /root/.rvm/src/ruby-2.2.0.....
ruby-2.2.0 - #applying patch /root/.rvm/patches/ruby/2.2.0/fix_installing_bundled_gems.patch.
ruby-2.2.0 - #applying patch /root/.rvm/patches/ruby/2.2.0/openssl3.patch.
ruby-2.2.0 - #configuring.........................................................
ruby-2.2.0 - #post-configuration..
ruby-2.2.0 - #compiling..............................................................................................................................................................................-
Error running '__rvm_make -j4',
please read /root/.rvm/log/1612011949_ruby-2.2.0/make.log

There has been an error while running make. Halting the installation.


text:
Q: How to handle a change in the published abstract base class? I have developed a "Kennel" application which takes care of various kinds of Dogs. My clients are expected to admit their Dogs to my application to avail the services.
So, I had defined a generic "Dog" interface. The clients need to implement the interface to create a concrete Dog type (Say Labrador, Poodle, etc), instantiate them and admit them to my kennel application(using say, kennel::admitDog(dog *dog).
Here is the Dog abstract base class:
class Dog {
public:
    Dog()
    {

    }

    virtual ~Dog()
    {

    }

    virtual void eatFood() = 0;
    virtual void takeBath() = 0;
    virtual void play() = 0;
    virtual void sleep() = 0;
};

I published this Interface and my clients already started using it to create their own concrete Dog types. In the next version of the application, I am planning to support robotic dogs in the kennel.
Here comes the problem. The robotic dogs needs Dog::rechargeBattery() in the above abstract base class. And, it doesnt need the existing Dog::eatFood() function. Adding the Dog::rechargeBattery() to the above abstract base class would affect all the existing clients who are already using this interface. They will be forced to implement the Dog::rechargeBattery() and recompile. This may not be desirable.

*

*What is the solution at this point?

*What should I have been done in the initial design to have this problem prevented?

A: Both questions can be answered the same, i.e. you still can implement a design to solve the problem now and prevent it for the future. In order to handle different classes (dogs in your example) which implement different subsets of operations, simply add an API to find out what they can/need. The handler/client (kennel in your example) is then able to find out what they can/need and call accordingly.
This is a more transparent design than determining the needs/capabilities based on being aware of all possible derived classes and what each of them can/need.
Consider this approach. "I can tell that you are a robot (because you reek of oil), so I will charge your battery. You (other) have salivated all over me, so you seem to be a biological dog, that is why I will feed you."
Compare it to "Do you want food? Nice sausage? Ah, you beg, so obviously you want it. Here, nice doggy." and "Your low battery indicator flashes, so I will show you the power outlet. Nice robby."
The point is that if something begs for a sausage AND has a low battery indicator, then you can charge AND feed it - without first being told that there are not only biological dogs and robodogs, but newly invented cyborgdogs.
(Sorry if this is scary, but it is for illustrating.)
The indicators of whether food or electricity is needed can be implemented in the base class, avoiding any changes to existing dog code. The API is meaningful for anything you can hold in a kennel (and can be abstracted to any class hierarchy with sets of potentially meaningful/-less operations).
To implement this concept, you can add virtual checker methods to the base class, which allow the kennel to find out what the dog needs. With a default implementation of those methods, all existing biological dogs will learn to give the right info on their needs, without the necessity to change their implementation.
For robots (which have not yet been implemented by anybody) you can require behavior of the needs-checkers which is different from the default.
class Dog {
public:
    Dog()
    {

    }

    virtual ~Dog()
    {

    }

    virtual void eatFood() = 0;
    virtual void takeBath() = 0;
    virtual void play() = 0;
    virtual void sleep() = 0;

    virtual bool boNeedsFood(void)
    {return true; /* standard dog */
    }

    virtual bool boNeedsElectricity(void)
    {return false; /* standard dog */
    }

    virtual void rechargeBattery(void)
    {    /* optional exception handling, in case kennel is malfunctioning */;
         /* sorry for the mental image... */
    }
};

class robodog
: public dog
{

public:

    /* ... */

    virtual bool boNeedsFood(void)
    {    return false; /* standard dog */
    }

    virtual bool boNeedsElectricity(void)
    {    return true; /* standard dog */
    }

    virtual void eatFood(void)
    {/* optional exception handling, in case kennel is malfunctioning */;}

    virtual void rechargeBattery(void)
    {
        /* actual code */
    }

}

/* ... somewhere in kennel ... */

if (doginstance.needsFood())
{doginstance.eatFood();
} /* intentionally no "else", could be cyborg dog, which needs both */
if (doginstance.needsElectricity())
{ doginstance.rechargeBattery();
}

A: Here's what I'd do:
#include <iostream>

using namespace std;

class Dog {
public:
    virtual ~Dog()
    {
    }

    virtual void eatFood() = 0;
    virtual void takeBath() = 0;
    virtual void play() = 0;
    virtual void sleep() = 0;
};

class RoboticDog : public Dog {
public:
    virtual void rechargeBattery() = 0;
};

class Pug : public Dog {
private:
    void eatFood()
    {
    }

    void takeBath()
    {
    }

    void play()
    {
        cout << "Pug::play()" << endl;
    }

    void sleep()
    {
    }
};

class Robo1 : public RoboticDog {
private:
    void eatFood()
    {
    }

    void takeBath()
    {
    }

    void play()
    {
        cout << "Robo1::play()" << endl;
    }

    void sleep()
    {
    }

    void rechargeBattery()
    {
        cout << "Robo1::rechargeBattery()" << endl;
    }
};

int main()
{
    Pug pug;
    Robo1 robo1;

    Dog *dogs[] = { &pug, &robo1 };

    for(unsigned i = 0; i < sizeof(dogs) / sizeof(Dog *); ++i) {
        dogs[i]->play();

        RoboticDog *robo = dynamic_cast<RoboticDog *>(dogs[i]);
        if(robo) // If dynamic_cast<> returned != nullptr, this is a RoboticDog
            robo->rechargeBattery();
    }
}

This code allows for binary compatibility with your existing clients. Their code will continue to work as-is, and new code can implement the RoboticDog interface, which is backwards-compatible with Dog.
dynamic_cast<> safely converts pointers and references to classes up, down, and sideways along the inheritance hierarchy. What that means is that if the object you have an interface pointer to implements another interface as well, dynamic_cast<SecondInterface *>(pointerToFirstInterface) will return nullptr if the underlying object does not implement SecondInterface.
So you can simply modify your code to check if the Dog * pointers you were previously working with happen to point to objects that are really RoboticDogs, and if they are, then you're free to use the full RoboticDog interface with them.
That's pretty much how they're extending interfaces in COM+ (where you can see a bunch of SomeInterfaceEx and ThatInterface2 abstract classes).

A: This:
class Dog {
    virtual void eatFood() = 0;
    virtual void takeBath() = 0;
    virtual void play() = 0;
    virtual void sleep() = 0;
};

class Kennel {
    void admit (Dog*);
}

Becomes this:
class DogLike {
    // virtual void eatFood() = 0; <-- removed
    virtual void takeBath() = 0;
    virtual void play() = 0;
    virtual void sleep() = 0;
};

class Dog : public DogLike {
    virtual void eatFood() = 0; // <-- added
};

class RoboticDog : public DogLike {
    virtual void rechargeBatteries() = 0;
};

class Kennel {
    void admit (DogLike*);
};

Existing clients should be source-compatible (but almost certainly not binary-compatible) with your modified library. Achieving binary compatibility may or may not be possible, but that's the case with any change to the published Dog class.
Since clients supposedly know what kind of dog they are handing to the kennel, it is possible to modify the kennel interface to separate live dogs from robotic dogs:
class Kennel {
  public:
    void admit (Dog*);
    void admit (RoboticDog*);
};

Other kinds of dogs will not be admitted.
What's next? Supposedly the kennel has facilities to serve all who answer the DogLike interface, and separate facilities for live dogs and for robotic dogs.
void Kennel::admit (Dog* dog) {
    commonFacilities.admit(dog);
    messHall.admit(dog);
}

void Kennel::admit (RoboticDog* dog) {
    commonFacilities.admit(dog);
    chargingStation.admit(dog);
}

Still no cast in sight. If it is undesirable to have two public admit methods, one can hide them behind a façade that inspects dynamic types behind the scenes.
class Kennel {
    void admit (Dog*);
    void admit (RoboticDog*);
  public:
    void admit (DogLike* dog) {
      if (auto d = dynamic_cast<Dog*>(dog))
        admit (d);
      else if (auto d = dynamic_cast<RoboticDog*>(dog))
        admit (d);
      else
        throw UnknownDogTypeError;
    }
};


text:
Q: Unwanted line chart ''shadow" using chart.js I am using ng2-charts which is an Angular charting module based on Chart.js. I am facing an issue where there are unwanted "shadow" kind of while rendering the chart as shown in the screen shot. I wonder if there is any chart option that I need to tweak on in order to remove it.
Thanks]1

A: I managed to get rid of it by setting stacked option to false


text:
Q: How to access array of nested hashes using ruby results = [
   {"day"=>"2012-08-15", "name"=>"John", "calls"=>"5"},
   {"day"=>"2012-08-15", "name"=>"Bill", "calls"=>"8"},
   {"day"=>"2012-08-16", "name"=>"Bill", "calls"=>"11"},
]

I can access the hash using the following code
results.find {|i| i["day"] == "2012-08-15" and i["name"] == "Bill"}["calls"]

How can I access email in the following code
results = [
   {"name"=>"John", "address"=>{"email"=> "john@example.com"}},
   {"name"=>"Bill", "address"=>{"email"=> "bill@example.com"}},
]

A: To access John's email:
results[0]["address"]["email"]
=> "john@example.com"

To print all the emails:
results.each do |result|
  p result["address"]["email"]
end

A: results.find {|i| i["name"] == "Bill"}["address"]["email"]

Although you should verify that the result is not null.
See this fiddle

A: If
results = [
   {"name"=>"Irma", "address"=>{"email"=> "irma@example.com"}},
   {"name"=>"John", "address"=>{"email"=> "john@example.com"}},
   {"name"=>"Bill", "address"=>{"email"=> "bill@example.com"}},
]

and you wish to get John's email address today and perhaps Irma's tomorrow, you may wish to crate a new hash:
addresses = results.map { |h| [h["name"], h["address"]["email"]] }.to_h
  #=> {"Irma"=>"irma@example.com", "John"=>"john@example.com", "Bill"=>"bill@example.com"}


text:
Q: Access connection string in data layer I'm currently developing a web API in .NET core. I have three projects in my solution with the following references:
Web -> Services -> DataAccess
So the web layer does not have a direct reference to the DataAccess layer.
My question is: What is the right way to get the connectionstring in this type of architecture with three layers? I have read around, but can't find any nice solution where I can access my connectionstring in the third layer, just because the web layer does not have a reference to the third layer.
I came accross this approach:
services.Configure<ConnectionConfig>(Configuration.GetSection("ConnectionStrings"));
services.AddScoped<IQueryHelper>(c => new QueryHelper(cn));

This work well if I just have two layers, where the QueryHelper is in the service-layer.
But I want to access one or multiple connectionstrings in my DataAccess-layer.

A: Edit: Injecting the configuration might not be the smartest idea as you can read here. Better way would be to configure options for each connection string that can be accessed by the DAL aswell.
services.Configure<MyConnectionInfo>(options => Configuration.GetSection("MyConnectionInfo").Bind(options));

Now in your repository just inject IOptions<MyConnection> and use the values.
Old Answer: Just inject your configuration into your datalayer-classes. Before you have to register the configuration with the ioc-container.
services.AddSingleton(typeof(IConfiguration), Configuration);

Now access the connectionstrings you need by injection the instance of IConfiguration. You could also configure more options instead, but injecting the configuration is fine aswell.


text:
Q: Joomla, Zoo, Category renderer I am trying to find where I can customise the view of automatically generated Joomla Zoo categories.
Someone has created a new application within the Zoo called Human Resources.
It has a category structure setup as per:
Category 1
   Sub Category 1
   Sub Category 2
   Sub Category 3
Category 2
   Sub Category 1
   Sub Category 2
   Sub Category 3
Category 3
   ...

Etc...
Once you get through to an item (i.e. clicking on an item from a sub category page I can edit the layout within full.php.
Category 1 for instance seems to be mapped to teaser.php and I can modify the layout here too.
However category 2 and the sub categories of category 2 render, but I can't for the life of me find what renderer they are using.
I have gone through all the files int he application asking them to die(); to no avail.
Any help as to how I can find out how and where these category pages are being rendered would be greatly appreciated.
Many thanks,
Dan.

A: Try these few sample steps to create the category and sub-category menu Items through Joomla admin control panel.
1)Create a new Menu in the Menu Manager called "Pets".
2)Add a new Menu Item called "Dogs". For this example, we don't really care what the type of the Menu Items is. For example, you can just create one article called "Pet Menu Test" and then create all of the Menu Items as type Article → Article Layout and point to this article.
3)Add a second Menu Item called "Collies" (again, Menu Type of Article Layout as above). In the Parent Item box, select "Dogs", as shown below:
4)Add a third Menu Item called "Greyhounds", again making "Dogs" the Parent Item. (Remember, these can all point to the same article.)
5)Add the "Cats" Menu Item. Be sure to make the Parent Item for this "Top".
6)Add the last two Menu Items, "Tabbies" and "Siamese", making "Cats" the Parent Item for both.

try to get more details here,
https://docs.joomla.org/Creating_a_submenu


text:
Q: Template for ViewBag I want to create a template to format some ViewBags.
Up to now, I had only the case of property of of a class, which I could easily modify with
[UIHint("MYTemplate")]
public virtual float Foo { get; set; }

Every selction of the property will consider "MyTemplate" and formate the output correctly.
How am I able to transfer this 'structure' to a ViewBag, which is defined in a certain controller?

A: Actuall, you can't. The contents of the ViewBag is Dynamically Resolved at Runtime. As opposed to Model properties. You can only use Templates for properties of a Model.
The only other option would be to add it to your model. The reason behind this is that, Your model (or View Model to be precise) ought to have everything that your view needs to display data. The ViewBag was intended to add some flexibility for data that doesn't necessarily need to be in your model like the contents of a DropDownList. Therefore, if you need to display content from the ViewBag like properties in your page, then you should consider promoting that property to your model.
Alternatively, you could use Partial Views. like so @Html.Partial("_MyTemplate",ViewBag.Data)


text:
Q: How are we supposed to find F-statistic when we have 2 model? in the model y=B0+b1x1+bpxp+e, p=23, n=206
Sum square Reg =400, SS TOT= 1000
assume B1=B2=0 and  deleting the predictor with these slopes ereased of the model.
Sum square= 100, SStot=1000
find F statistic.
I know this formula:
(SSreg1-SSreg2)/(p2-p1)/(ssReg/n-p2)
however the problem is I only have one P what should I do? or is it any other way?

A: By setting $\beta_1=0$ and $\beta_2=0$, you are removing two of your $p=23$ variables. Therefore, your $p_1 = 23-2=21$.
By the way, there is a mistake in your formula.
$$F=\dfrac{\dfrac{RSS_{1}-RSS_{2}}{p_2-p_1}}{\dfrac{RSS_{2}}{n-p_2}}$$
Model $2$ has all $p_2=23$ parameters, while model $1$ only has $p_1 = 21$ parameters.
You might be interested in reading a good answer on the partial F-test, which is a particular type of chunk test.


text: Q: Inertial mass and gravitational mass I would like to ask about gravitational mass. I know inertial mass is changing by motion (speed) according to $m=\frac{m_o}{(1-v^2/c^2)^{1/2}}$ And also that is inertial mass which sits in $E=mc^2$. If the statements above is correct, now how about gravitational mass? Does it change with motion (speed)? And what mass should be used for general gravitational formula $F=\frac{GmM}{r^2}$? should we use $m_o$ (rest mass) regardless of speed of the object? Or should we use $m=\frac{m_o}{(1-v^2/c^2)^{1/2}}$ to substitute in $F=\frac{GmM}{r^2}$? In other words does mass equivalence principle (inertial mass=gravitational mass) hold in high speeds?


text:
Q: AutoLayout - Visual Format Language not working iOS8 I'm trying to learn how to use autolayout and write constraints using the visual format language. for a simple test I have a test view and want it to expand the full size.  So top, bottom, trailing, leading to superview would all be zero.
If I run in iOS 7, it seems to mostly work, but get black bars on the top and bottom of iPhone 5 simulator with no ambiguous layout errors.
In iOS 8, I get ambiguous layout errors.  Can anyone show me where my problem is?
Here's my code:
- (void)viewDidLoad {
    [super viewDidLoad];

    testView = [UIView new];
    testView.backgroundColor = [UIColor blueColor];
    testView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:testView];

    [self.view needsUpdateConstraints];
}
- (void)updateViewConstraints
{
    [super updateViewConstraints];
    [self.view removeConstraints:self.view.constraints];

    NSDictionary *viewsDictionary =
    NSDictionaryOfVariableBindings(testView);
    NSArray *constraints = [NSLayoutConstraint
                            constraintsWithVisualFormat:@"|[testView]|"
                            options:0
                            metrics:nil
                            views:viewsDictionary];
    [self.view addConstraints:constraints];

    constraints = [NSLayoutConstraint
                   constraintsWithVisualFormat:@"V:|[testView]|"
                   options:0
                   metrics:nil
                   views:viewsDictionary];
    [self.view addConstraints:constraints];
}

Thanks!
-- Update - the issue seems to be with    [self.view removeConstraints:self.view.constraints];
If I comment that out, it works fine.  Not sure why though.

A: Try calling [self.view setNeedsUpdateConstraints].  You are calling [self.view needsUpdateConstraints], which just asks whether setNeedsUpdateConstraints has been called.


text:
Q: All observations for some variables is zero, which regression model to use? I have an assignment to create a regression model using leave-one-out cross validation.
Due to specific biological nature, the variables cannot be negatively correlated to the response variable.
There are 12 variables and 66 observations in total. 1 of the variable had observations that are either numeric or zero, while another 2 variables were zeros for all observations. The remaining 9 variables were numeric.
I have ran the following and ended up with a warning that says "In predict.lm(modelFit, newdata) : prediction from a rank-deficient fit may be misleading".
set.seed(2)

install.packages('caret')

library(caret)

#Define training control
train.control <- trainControl(method = 'LOOCV')

#Train the model
train.model <- train(Y ~., data = OSbiome, method = 'lm', trControl = train.control)
summary(train.model)
print(train.model)
warnings()

Not sure if the warning received was due to the fact that 2 of the variables were zero for all observations? Any suggestions on what model to use then? Thanks!


text:
Q: What to think of a missing man? I'm trying to get info on mktemp.
MKTEMP(1) contains these two lines:
SEE ALSO
       mkstemp(3), mkdtemp(3), mktemp(3)

Ok, let's see.
tomasz@E4200:~$ man 3 mkstemp
No manual entry for mkstemp in section 3
tomasz@E4200:~$ man 3 mkdtemp
No manual entry for mkdtemp in section 3
tomasz@E4200:~$ man 3 mktemp
No manual entry for mktemp in section 3
See 'man 7 undocumented' for help when manual pages are not available.

I didn't know this is possible. Do I need to install them separately? What's the best way? Is this a release bug?

A: Just search for the debian package that contains those extra development man pages (should be manpages-dev) and install it.
It is quite common nowadays for distributions to not install development manpages by default.
You can use apt-file search to search for other missing man pages.


text:
Q: Java, delimiter I have this code for delimiters: (":|\\s+").
I want the sign allowed like this: (":"), but if I use this the program does not work - it stops after the first question.
Can anyone see where I have gone wrong?
import java.util.Scanner;
public class Salary
{
    public static void main(String[] args)
    {
        int hour1, hour2, minute1, minute2, salary;
        double totaly, totSalary, totHours, totMinutes, totDecMinutes;

        salary = 190;

        Scanner scan = new Scanner(System.in);

        scan.useDelimiter(":|\\s+");

        System.out.println("Write the time when you startet working."
            + "Use the format (hh:mm).");

        hour1 = scan.nextInt();
        minute1 = scan.nextInt();

        System.out.println("Write the time when you stopped working."
            + "Use the formatet (hh:mm).");

        hour2 = scan.nextInt();
        minute2 = scan.nextInt();

        // Counts the number of workinghours.
        totHours = (hour2 - hour1);

        // Counts the number om workingminutes, decimal number
        totMinutes = (minute2 - minute1);
        totDecMinutes = totMinutes/60;

        // Counts the salary: total hours.
        totaly = totHours + totDecMinutes;
        totSalary = totaly*salary;

        System.out.printf("Din lön för idag blir: %.2f kr.", totSalary);
    }
}

A: I think (not sure though) a newline is interpreted as some combination of space. The delimiter used above delimits on either the : or one or more spaces. If I wrote 2:34 and then click enter to go to a newline, the scanner would delimit on the : giving 2 for the hour and then delimit on the newline character giving 34 for the minute. I am not sure how a newline gets translated to ASCII, and in any rate it varies with the Operating System.
That is why I prefer to use Scanner.nextLine() which returns the input from the rest of the line, excluding any line separator at the end. It is also easier to sanitize the user input (see example code below) as I can repeatedly ask for the user to provide a time if the previous time is not well-formed.
public class Salary
{
public static void main(String[] args)
{
    int hour1, hour2, minute1, minute2, salary;
    double totaly, totSalary, totHours, totMinutes, totDecMinutes;

    salary = 190;

    Scanner scan = new Scanner(System.in);

    System.out.print("Write the time when you startet working."
            + "Use the format (hh:mm).\n>> ");
    while (true) {
        String s = scan.nextLine();
        String[] parsed = s.split(":");
        if (s.split(":").length == 2) {
            try {
                hour1 = Integer.parseInt(parsed[0]);
                minute1 = Integer.parseInt(parsed[1]);
                break;
            } catch (NumberFormatException e) {
            }
        }
        System.out.print("Invalid input. Try again\n>> ");
    }

    System.out.print("Write the time when you stopped working."
            + "Use the formatet (hh:mm).\n>> ");
    while (true) {
        String s = scan.nextLine();
        String[] parsed = s.split(":");
        if (s.split(":").length == 2) {
            try {
                hour2 = Integer.parseInt(parsed[0]);
                minute2 = Integer.parseInt(parsed[1]);
                break;
            } catch (NumberFormatException e) {
            }
        }
        System.out.print("Invalid input. Try again\n>> ");
    }

    // Counts the number of workinghours.
    totHours = (hour2 - hour1);

    // Counts the number om workingminutes, decimal number
    totMinutes = (minute2 - minute1);
    totDecMinutes = totMinutes/60.0;

    // Counts the salary: total hours.
    totaly = totHours + totDecMinutes;
    totSalary = totaly*salary;

    System.out.printf("Din lön för idag blir: %.2f kr.", totSalary);
}

}


text:
Q: Refreshing Sandbox and Reconnecting Marketing Cloud environment (We have all live BU's in Marketing Cloud) Are there any watch outs for when refreshing a Salesforce Sandbox Environment that is linked to a 'test' (Production type BU) in the Marketing Cloud. These environments represent our Sandbox set up.
I have refreshed the Salesforce Sandbox environment and I am now no longer able to connect the clouds from within Marketing Cloud in the Salesforce Integrations tab. I get the following error message: An exception occurred while saving the integration.

A: When doing a Sandbox Refresh, you must disconnect the integration prior to the refresh.
The connector bases its connection on the ORG ID.  A sandbox refresh changes the ORGID and therefore the system is incorrectly attached to the previous integration.
You will need to make a case with support to have the back end team correct the integration.
Steps BEFORE a sandbox refresh.
https://help.salesforce.com/articleView?id=000249278&type=1
Check your recycling bin for the Tokens.
Also, you must clear the API USER by using a different method.
Look under the January 2nd release to find the details on the API USER.
https://help.salesforce.com/articleView?id=mc_co_latest_releases.htm&type=5


text:
Q: Word frequency using C programming and Linked-List but frequency count is wrong I am stuck and searched all over spending days on this. I need to create a word frequency program using C. For keeping track of collisions I use a linked list, but my code does not give the right frequency (for example, frequncy of "the" should be 25, but instead it's 18). What am I doing wrong?. Here is my code:
void addToArr( char *str, HASH_ARR_ELEM hashArr[]){
int homeAddress = 0;
int addResult = 0;
WORD *tempWord;
homeAddress = hashFunct(str);

if(!(tempWord = (WORD*)malloc(sizeof(WORD))))
    printf("Memory Allocation Error\n"),
        exit(100);

strcpy(tempWord->str,str);
tempWord->count = 1;

if(hashArr[homeAddress].wordPtr == NULL){
    // allocate memory
    if(!(hashArr[homeAddress].wordPtr = (WORD*)malloc(sizeof(WORD))))
        printf("Memory Allocation Error\n"), exit(100);

    strcpy(hashArr[homeAddress].wordPtr->str,tempWord->str);
    hashArr[homeAddress].wordPtr->count = 1;

} else if(hashArr[homeAddress].wordPtr != NULL && hashArr[homeAddress].headPtr == NULL){

    if(strcmp(hashArr[homeAddress].wordPtr->str,tempWord->str))
        hashArr[homeAddress].wordPtr->count++;
    else{
        hashArr[homeAddress].headPtr = createList(cmpWord);
        if(!hashArr[homeAddress].headPtr)
            printf("\aCannot create list\n"),
            exit(100);

        addNode(hashArr[homeAddress].headPtr,tempWord);
        }
}else
    if(strcmp(hashArr[homeAddress].wordPtr->str,tempWord->str))
        hashArr[homeAddress].wordPtr->count++;
    else
    {
        addResult = addNode(hashArr[homeAddress].headPtr,tempWord);
        if(addResult != 0)
            if(addResult == -1)
                printf("Memory Overflow adding node\n"),
                    exit(120);
            else
            {
                retrieveNode(hashArr[homeAddress].headPtr,tempWord,(void**)&tempWord);
                tempWord->count++;
                    printf("%s %d\n\n", tempWord->str, tempWord->count);
            }
    }
 } // end addToArr

A: At least one of your problems is in the string comparison line.
strcmp returns 0 if the two strings are equal, which means that you're incrementing counts only when the strings are different.

A: If I am reading this correctly you expect if(strcmp(...)) to be true if the strings are equal. But it returns 0 if the strings are equal.
So this:
if(strcmp(hashArr[homeAddress].wordPtr->str,tempWord->str))

Should be this:
if(!strcmp(hashArr[homeAddress].wordPtr->str,tempWord->str))

strcmp will tell you the position of the first difference, so any number greater than zero is going to be a difference, so 0 is all that is left for the strings being equal.


text:
Q: Extract line of text from .txt file using CMD? was wandering if there is a way to extract a line of text which contains certain value from a .txt file using CMD. For example using "type filepath\example.txt" will open the whole file and in my case I am working trough a software which doesn't allow CTRL+F option and .txt files are massive.
Is there any way I could specify certain word in order to get that whole line of text or to open only .txt files which have that word within them. For example I have 1000 .txt files and all of them contain the same text but only one of them has a word "EXAMPLE" in it. Could I use some command to find and open that file using CMD.
Thank you.

A: I have 1000 .txt files and all of them contain the same text but only one of them has a word "EXAMPLE" in it. Could I use some command to find and open that file using CMD.
a) find the file(s) that have the desired string:
findstr /m "EXAMPLE" *.txt

b) find the file (assuming, only one contains the string; else it will open all matching files) and open the file in notepad:
for /f "delims=" %a in ('findstr /m "EXAMPLE" *.txt') do "%a"

c) find the one line that has the string:
findstr "EXAMPLE" *.txt

A: The findstr.exe solution from Stephen would be less typing. But, using Select-String allows the use of a much more complete implementation of regex. All supported Windows systems have PowerShell available. This works in a batch-file run by cmd on windows and at the command prompt. Given that this would likely be put into a batch-file, the amount of typing is not very significant.
@powershell.exe -NoLogo -NoProfile -Command ^
    Get-ChildItem -Path '.\*.txt' ^| ^
        ForEach-Object { Select-String -Pattern 'example' -Path $_ } ^| ^
        Select-Object -Property Filename,Line

A: Not the most elegant alternative, I agree, and I am certain someone will tell me how it could be bettered. The key is it uses basic find a string (you can set as I have to be case insensitive) in a file then reports filename and line number, Line [9] in this case.

@forfiles /m *.txt /C "cmd /c (find /n /i \"For example\" "@file"1>nul) &&if %errorlevel%==0 (find /n /i \"For example\" "@file"2>nul)"

When used in a batch file it could look something like this, but see caveats below
Finder$.cmd
@echo off & Title Find wally String in a file
set "string=where's Wally"
if not "%1"=="" set "string=%~*"

forfiles /m *.txt /C "cmd /c (find /n /i \"%string%\" "@file"1>nul) &&if %errorlevel%==0 (find /n /i \"%string%\" "@file")"

echo/ & pause & exit /b

It is not perfect but note its not case sensitive (using /i), it can readily fail if *.txt files are not plain text and as written will only accept a short unquoted string of up to 9 words ( avoid " or other punctuation). It works in local directory with *.txt, but you could alter those as require to first say cd /d f:\mylogs and search *.log files.
Finally you asked to open the file thus we can simplify for that task to call an editor like notepad or with some fetteling one that accepts line numbers (but that is another question)
forfiles /m *.txt /C "cmd /c (find /n /i \"%string%\" "@file"1>nul) &&if %errorlevel%==0 (notepad.exe "@file")"

A: Everything below is related to unix bash terminal, so please install Linux Subsystems if you are using Windows. Or even Linux itself :)

*

*You can open specific file in a text editor like Vim or Nano in terminal. They offer the "CTRL+F" function.

Below you can see me searching for the "gameId" keyword in the file game_stats.js, which I opened via $ vim game_stats.js.

P.S. To quite vim you need to type :q :)

*Use grep command as advised in this answer https://stackoverflow.com/a/16957078/13212398
Example for the command that recursively searches for any .js or .txt files that contains "let" in the current directory (.).
$ grep  --include=\*.{js,txt} -rnw -e "let" .

./this_test.js:18:let bob = new Person('Bob');
./this_test.js:19:let bill = new Person('Bill', bob);
./TUD-2Q-WDB/checkers-in-delft/public/javascripts/game_state.js:99:        let pieces = []