text:
Q: Given an infinite number of monkeys and an infinite amount of time, would one of them write Hamlet? Of course, we've all heard the colloquialism "If a bunch of monkeys pound on a typewriter, eventually one of them will write Hamlet."
I have a (not very mathematically intelligent) friend who presented it as if it were a mathematical fact, which got me thinking... Is this really true?  Of course, I've learned that dealing with infinity can be tricky, but my intuition says that time is countably infinite while the number of works the monkeys could produce is uncountably infinite.  Therefore, it isn't necessarily given that the monkeys would write Hamlet.
Could someone who's better at this kind of math than me tell me if this is correct?  Or is there more to it than I'm thinking?

A: Let me be the one who says NO.
It is a bit hard to handle an infinite number of monkeys (because you will need an infinite number of bananas to feed them), but if you agree to have a finite number of monkeys and infinite time, I would guess that considering the time it should take for this to happen, it is likely that the universe would die before it actually does.
To quote a chat of one of my friends with my first year "intro to CS" professor:

Professor: "So there is no chance that a fair coin would fall with the head side up $50$ times in a row."
My friend: "No!, there is such a chance it's just very small...."
Professor: "Well yes, it's like the chance for all the nitrogen molecules in the air to gather around your head and have you die from lack of oxygen."

A: For some reason I want to attribute this reasoning to Douglas Hofstadter, though I couldn't tell you which of his books it's from. Here goes:
If you could get sufficient randomness from an infinite number of monkeys (this is trivial if you assume that by mere chance, a infinite subset will fit the bill – or you could follow Arjang's approach and aggregate across monkeys for more entropy, which has the benefit of getting results much faster), you already have every variation of every story ever told. You'll even have every story that ever could be told. Just get an infinite number of monkeys (or a slightly smaller number of computers) and opening a publishing business. Make a million bucks and retire.
But this rings false, especially since modern computing power (relative to the difficulty of the task) is practically infinite, putting the practice of this philosophy within reach. Just imagine trying it yourself. It's not the monkeys or the computers or the printers doing all of the work. Suddenly, you are wading through millions of pages of gibberish text looking for the book that will make you rich. Good luck. (It is the fact that the filtering process is much slower than the production process that makes me say that computer power is practically infinite.)
It's not the characters on the page that make Hamlet. Hamlet is a synthesis of information, a composition that can only be guided by intelligence. In a sea of random characters, the sequence that maps isomorphically to Hamlet is just more noise.
This may sound like a qualified "yes" in response to the question, but in reality it is an empathic "no." It is not the act of producing the character sequence of Hamlet in a random string that writes Hamlet – it is the act of finding Hamlet in a random string that writes Hamlet. The distinction may sound subtle, but the two tasks are profoundly different.

A: If you have an infinite number of monkeys, then an infinite subset of them will just sit and type out Hamlet, letter-for-letter, straight away. So after a few hours you will have an infinite number of copies of Hamlet.
If you have a finite number of monkeys then you may have to wait. But given in infinite amount of time (and immortal monkeys, etc.), you'll get your Hamlet. Eventually.

A: NOTE: By probability, I mean the chance of it happening per iteration, and starting with a new page each time.
Let's take a step back, shall we? (Not too many, because there's a cliff behind you.) Let's think of what the probability is of producing the following randomly:

A

Assuming there are only 26 characters (A-Z, uppercase), the probability would be $\frac{1}{26}$.
What about this:

AA

It'd be $(\frac{1}{26})^2$. This:

AAA

It'd be $(\frac{1}{26})^3$. And this:

XKCD

It'd be $(\frac{0}{26})^4$. [Just kidding, it's: $(\frac{1}{26})^4$].
So, for every character we add to the quote, it will be: $(1/26)^c)$, where $c$ represents the number of characters.
Basically, it would be a probability of $(\frac{1}{26*2+12})^c$ since the characters used could be: A-Z, a-z, .!?,;: "'/() Of course, there could be more characters, but that's just an example. :)

A: The answer is yes, With infinite time and all of the infinite monkeys will produce hamlet and every other works infinitely many times.
After the first keystroke of the infinitely many monkeys, there will be infinitely many hamlets if you just grabbed the first letter from each one of them.
Also at the first keystroke, infinitely of monkeys would have types the first letter of the entire hamlet already, this shows that if you have infinite number of monkeys you only each one of them to type just as many letters as the number of letters in hamlet to have already infinitely many copies of hamlet, so there is no need for infinite time to have one of them produced hamlet, infinitely many of the monkeys would produce infinitely many hamlets in finite amount of time as long as the finite amount of time is equal or greater than the time to type a single copy of hamlet. (this was already mentioned in Bennett McElwee's answer)
If you rephrase the question to : Would an infinite random sequence of letters in 2 dimensions contain at least one hamlet in every and each one of it's columns/rows? then the answer is yes, but there would be infinite number of hamlets contained in each row/column, As an infinite random sequence will contain all it's possible finite sub sequences, infinitely many times. ( Reference needed ).

A: Monkeys don't produce a proper random distribution on keystrokes. Not even a Markov-chain of keystrokes.
Given infinite time (and an undying support of monkeys) or just infinite monkeys, they will produce infinite text. But that does not need to imply that Hamlet will be part of this infinite long text.

[edit]
There is empirical evidence from such an experiment, reported by the BBC.
The actual text produced is obviously not that random at all.
(@Henry: Thx for these links.)
[/edit]

A: I found online the claim (which we may as well accept for this purpose) that there are $32241$ words in Hamlet.  Figuring $5$ characters and one space per word, this is $193446$ characters.  If the character set is $60$ including capitals and punctuation, a random string of $193446$ characters has a chance of $1$ in $60^{193446}$ (roughly $1$ in $10^{344000}$) of being Hamlet.  While very small, this is greater than zero.  So if you try enough times, and infinity times is certainly enough, you will probably produce Hamlet.  But don't hold your breath.  It doesn't even take an infinite number of monkeys or an infinite number of tries.  Only a product of $10^{344001}$ makes it very likely.  True, this is a very large number, but most numbers are larger.

A: Here's a rather interesting  article  discussing the probability of a monkey producing Shakespeare's works and uses a random letter generator to demonstrate some results.

A: If there truly was an infinite amount of time and monkey, yes, it could happen. However, we know that time and monkeys are both limited. Let's say that the universe will be gone when there are no more neutrons. According to this article, that will be about 10^40 years. There are approximately 4*10^78 atoms. And let's just say that an atom monkey can type at 10^15 keys per second. Let's also assume that there are 40 keys on a typewritter (26 A-Z, numbers, period, comma, semicolon, and space). That'll give the following:
There will be 4e78*365*24*3600*1e15 key strokes per atom, giving a total of 1.26e101. There would then be 5.05e177 key strokes. 40^108=1.0531e+173. That means that there would be segments of around 108 characters of Hamlet around, but certainly not the whole work.

A: You don't even need an infinite number of monkeys!  For any $\epsilon > 0$ and $k \geq l(\text{Hamlet})$, there is some number $N$ such that $N$ monkeys at typewriters, each typing for $k$ keystrokes, will produce a copy of Hamlet with probability greater than $1-\epsilon$.  (This holds under some quite weak conditions on our model of monkey typing.)
This is an example of the general "soft analysis to hard analysis" principle, championed by Terry Tao among others: most any proof in analysis may be transformed into a proof of a quantitative statement such as the one above.
This can be made precise in some generality using various rather beautiful proof-theoretic methods, such as variants of Gödel's Dialectica translation; lovely results along these lines have been obtained by e.g. Avigad, Gerhardy and Towsner.  In this particular case, the bounds we get will of course depend on the model of monkey typing used.
For instance, if we assume that the keystrokes are independently uniformly distributed, if our Hamlet-recognition criterion is case-, punctuation- and whitespace-insensitive, then for the case $k = l(\text{Hamlet})$,
$$N = \left\lceil \frac{\log \epsilon}{\log \left(1 - \frac{1}{26^{l(\text{Hamlet})}}\right)}\right\rceil$$
will work.  (The proof is an exercise for the reader.)
Project Gutenberg's copy of Hamlet (first folio) weighs in at 117,496 alphanumeric characters.  So if we want to produce Hamlet (first folio) with probability 1/2, in the minimal number of keystrokes, then by some quick slapdash estimating (rounding up a little to be on the safe side), something like $10^{170,000}$ monkeys should certainly suffice!
I guess empirical testing is out — ethical controls are so tricky.  Anyone want to run some simulations?

A: It would probably be faster to apply selective pressure to breed intelligent, literary monkeys.  Our common ancestor with chimps lived only 4 million years ago, and by design I'm sure we could make something similar happen faster starting with chimps, bonobos, or whatever.
We could probably get orcas and other whales up to speed very quickly, too!

A: Some references (I am mildly surprised that no one has done this yet).  This is called the infinite monkey theorem in the literature.  It follows from the second Borel-Cantelli lemma and is related to Kolmogorov's zero-one law, which is the result that provides the intuition behind general statements like this.  (The zero-one law tells you that the probability of getting Hamlet is either zero or one, but doesn't tell you which.  This is usually the hard part of applying the zero-one law.)  Since others have addressed the practical side, I am telling you what the mathematical idealization looks like.

my intuition says that time is countably infinite while the number of works the monkeys could produce is uncountably infinite.

This is a good idea!  Unfortunately, the number of finite strings from a finite alphabet is countable.  This is a good exercise and worth working out yourself.
Edit: also, regarding some ideas which have come up in the discussions on other answers, Jorge Luis Borges' short story The Library of Babel is an interesting read.

A: [Note that in my answer I am actually assuming that there are only a finite number of monkeys.  I don't see what is gained by having both the number of monkeys and the time frame be infinite: mathematically speaking $\aleph_0 \times \aleph_0 = \aleph_0$, and it is somewhat confusing to contemplate infinitely many monkeys typing simultaneously: too much is happening at once.  In fact, there might as well be only one monkey, or at any rate only one typewriter.]
Let me take the unusual (for me) step of considering the practical aspects of this question as well.
As Ross Millikan has explained, there is a simple mathematical model of monkey keyboard pounding under which it is easy to see that the claim is true: the probability that at least one of the monkeys will type out Hamlet approaches $1$ as the time $n$ approaches infinity.
However there is an assumption here: namely, that the pounding on the typewriter is random or sufficiently close to random.  One way to formalize this is to say that after typing any $n$ characters, the probability of hitting any given key as the $n+1$st character is at least $P$, where $P$ is positive and independent of $n$.
The problem is that for actual typewriter banging, this is a very unlikely assumption.  The issue is similar here to what happens if you ask someone to produce a random sequence of digits, say from $0$ to $9$, or even a random sequence of $H$'s and $T$'s (for "heads" and "tails"). Just closing your eyes and banging away will produce something very far from being random.
If the question is meant to apply to actual monkeys with their nonrandom motor behavior, then it is something else entirely.  I would be tempted to say that the probability of producing Hamlet does not approach $1$ as time approaches infinity, but I'm not sure off the top of my head how to justify this.


text:
Q: Disable complete log trace for Mobile application in Rhomobile I referred to the Rhomobile documentation it mentions
log level
0-trace, 1-info(app level), 3-warnings, 4-errors
I want to disable log trace completely for production. Which level should I set it to?

A: For production, as wrote in the comments in rhoconfig.txt, the suggestion is to put it a level 3 (errors), there's no level 4:
# Rhodes log properties
# log level
# 0-trace, 1-info(app level), 2-warnings, 3-errors
# for production set to 3

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why am I getting a StringIndexOutOfBoundsException when I try to replace `\\` with `\`? I have to replace \\ with \ in Java. The code I am using is
System.out.println( (MyConstants.LOCATION_PATH + File.separator + myObject.getStLocation() ).replaceAll("\\\\", "\\") );

But I don't know why it is throwing StringIndexOutOfBoundsException.
It says String index out of range: 1
What could be the reason? I guess it is because the first argument replaceAll accepts a pattern. What could be the possible solution?

Stacktrace
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
    at java.lang.String.charAt(String.java:558)
    at java.util.regex.Matcher.appendReplacement(Matcher.java:696)
    at java.util.regex.Matcher.replaceAll(Matcher.java:806)
    at java.lang.String.replaceAll(String.java:2000)

Answer Found
asalamon74 posted the code I required, but I don't know why he deleted it. In any case here it is.
There is a bug already filed in Java's bug database. (Thanks for this reference, asalamon.)
yourString.replaceAll("\\\\", "\\\\");

Amazingly, both search and replace string are the same :) but still it does what I require.

A: Well, i tried
    String test = "just a \\ test with some \\\\ and others \\\\ or \\ so";
    String result = test.replaceAll("\\\\", "\\\\");
    System.out.println(test);
    System.out.println(result);
    System.out.println(test.equals(result));

and got, as expected
just a \ test with some \\ and others \\ or \ so
just a \ test with some \\ and others \\ or \ so
true

What you really need is
string.replaceAll("\\\\\\\\", "\\\\");

to get
just a \ test with some \\ and others \\ or \ so
just a \ test with some \ and others \ or \ so
false

You want to find: \\  (2 slashes)
which needs to be escaped in the regex: \\\\  (4 slashes)
and escaped in Java: "\\\\\\\\"  (8 slashes)
same for the replacement...

A: For the regex, if you want to change \ to \\, you should do this:
if (str.indexOf('\\') > -1)
    str = str.replaceAll("\\\\", "\\\\\\\\");
str = "\"" + str + "\"";

Where \\\\ means \ and \\\\\\\\ means \\.

A: Use String.replace instead of replaceAll to avoid it using a regex:
String original = MyConstants.LOCATION_PATH + File.seperator
    + myObject.getStLocation();
System.out.println(original.replace("\\\\", "\\"));

Personally I wouldn't do it this way though - I'd create MyConstants.LOCATION_PATH_FILE as a File and then you could write:
File location = new File(MyConstants.LOCATION_PATH_FILE,
                         myObject.getStLocation());

which will do the right thing automatically.

A: File.seperator is already escaped as is any string object so you are escaping them twice.
You only need to escape values that you are entering as a string literal.

A: Try this
cadena.replaceAll("\\\\","\\\\\\\\")

A: The best way is :
str.replace(**'**\\**'**, **'**/**'**); //with char method not String

A: I suspect the problem is that replaceAll() uses regexps and the backslash is an escape character in regexps as well as in Java - it might be necessary to double the number of backslashes.
In general you should always post the full stack trace of exceptions, it is much easier to diagnose the problem that way.

A: I believe what you need to do is:
System.out.println( (MyConstants.LOCATION_PATH + File.separator + myObject.getStLocation() ).replaceAll("\\\\\\\\", "\\\\") );

The regular expression String is actually four backslashes, which is a regular expression that matches two backslashes.
The replacement String has to be four slashes as per Java documentation, from:
http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#replaceAll(java.lang.String)

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

A: final StringBuilder result = new StringBuilder();
final StringCharacterIterator iterator = new StringCharacterIterator(str);
char character =  iterator.current();
while (character != CharacterIterator.DONE )
{
  if (character == '\\\\') {
     result.append("\\");
  }
  else {
    result.append(character);
  }

  character = iterator.next();
}

System.out.print(result);


text:
Q: java - can't use log4j in project explorer of eclipse I updated eclipse version to 4.9.0
my project used log4j library in maven.
but maven build raise error that block maven dependencies in project explorer of eclipse.
please teach me how to do this problem.
thanks.
[capture screen] https://i.stack.imgur.com/8MjfC.jpg
I used code below in pom.xml
<org.slf4j-version>1.7.5</org.slf4j-version>
<dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>

A: I moved the Eclipse version to Neon 4.6.3.
so I resolved that shown block to log4j.
but raise error below:
please how to resolve this error
thank you for reply.
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for com.joins::war:1.0.0-BUILD-SNAPSHOT
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.mybatis:mybatis:jar -> duplicate declaration of version 3.2.2 @ line 249, column 15
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @  ---
[INFO] Deleting joongangClickCountDashboard\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @  ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @  ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 188 source files to D:\sean-workspace-neon\ClickCountDashboard\target\classes
[INFO] -------------------------------------------------------------
[WARNING] COMPILATION WARNING :
[INFO] -------------------------------------------------------------
[WARNING] ClickCountDashboard/src/main/java/com/joins/innovation/campaign/excel/InnovationCampaignDataExcelBuilder.java:[10,17] jxl.write.Font in jxl.write has been deprecated
[WARNING] ClickCountDashboard/src/main/java/com/joins//facebook/service/impl/FacebookServiceImpl.java:[56,104] unchecked cast
  required: java.util.HashMap<java.lang.String,org.bson.Document>
  found:    java.lang.Object
[WARNING] ClickCountDashboard/src/main/java/com/joins//facebook/service/impl/FacebookServiceImpl.java:[57,130] unchecked cast
  required: java.util.HashMap<java.lang.String,java.util.HashMap<java.lang.String,java.lang.Integer>>
  found:    java.lang.Object
[WARNING] ClickCountDashboard/src/main/java/com/joins//common/db/MongoDBConnectionManager.java:[199,17] found raw type: java.util.List
  missing type arguments for generic class java.util.List<E>
[WARNING] ClickCountDashboard/src/main/java/com/joins//common/db/MongoDBConnectionManager.java:[201,126] unchecked method invocation: method aggregate in interface com.mongodb.client.MongoCollection is applied to given types
  required: java.util.List<? extends org.bson.conversions.Bson>

I has settings in maven below
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <compilerArgument>-Xlint:all</compilerArgument>
        <showWarnings>true</showWarnings>
        <showDeprecation>true</showDeprecation>
    </configuration>
</plugin>


text:
Q: Which one sounds more natural: "agree to a price" or "agree at a price"? Which one sounds more natural: agree to a price or agree at a price? Here's some examples:

We agreed at/to the price with the customer, but then he changed his mind.
I offered $1000 for the car and she agreed to/at that.
We agreed at/to $100 for the job.

I have heard both used with the word "agree" but can't figure out which one is more correct and natural.

A: I would recommend the following three:

*

*"We agreed on the price with the customer, but then he changed his mind."

*"I offered $1000 for the car and she agreed to that."

*"We agreed on $100 for the job."

In the first and third cases, the word "to" could be used instead of "on", but it would just sound more awkward, especially for the first sentence (and not as much for the third sentence).
In all three of these cases, using the word "at" as you suggested, would make the sentence sound a lot more awkward. The phrase "agree at a price" seems to imply to me that there was some back-and-forth bargaining that ended at some final value, and in that case the sentence would look like this (for example):
"After several hours of back-and-forth negotiation, we agreed at the final price of $100".

A: "agree on a price" is idiomatic in the US.


text:
Q: Parameters not being passed through Request in NodeJs I am trying to make a request with the request package and can't seem to be able to pass through a simple parameter.
Anyone know what would be the best way to pass it through?
asyncRefreshToken()
  .then(function(token){
    console.log('Got the token! ' + token);
    for(var k=0; k<2; k++){
      var url= 'https://www.googleapis.com/analytics/v3/data/realtime?ids=ga:'+brandsConfig.brands[k].profileId+'&metrics=rt%3AactiveUsers&dimensions=rt%3ApagePath&sort=-rt%3AactiveUsers&access_token='+token;
      var options = {
        url: url,
        method: 'GET'
      }
      request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          // Print out the response body
          var parsed = JSON.parse(body);
          var activeUsers = parsed.totalResults;
          console.log(brandsConfig.brands[k].title + ': ' + activeUsers);
        }
      })
    }
  })

Sorry, I should be more specific - brandsConfig.brands[k].title will only return the last value i.e. brandsConfig.brands[1].title
What I am trying to achieve:

*

*Once a token has been obtained (from asyncRefreshToken), use the request package to query the Google Analytics API for a list of brands.

*The brands are in an array brandsConfig.brands[k], the corresponding title can be obtained from brandsConfig.brands[k].title

*The result for now, during the time I'm trying to learn can just be in the console.

*So ideal result:
* Got the token! 1234567890
* Brand 1 : 582432
* Brand 2 : 523423

*Current output:
* Got the token! 1234567890
* Brand 2 : 582432
* Brand 2 : 523423

A: Your problem is caused by the combination of a for loop and an asynchronous request.  What's happening is that your loop begins, and kicks off the first request.  The request is asynchronous (since it's over ye olde interwebs).  This means that the code in the callback will not be executed right away, it will be "skipped" until the asynchronous request returns.  The important thing is that your for loop keeps executing, incrementing k, and kicking of a new request.  Now your code has finished except for the callbacks to the two requests.
Now the first one comes back.  It executes the code in the callback.  What is the value of k?  Well since the loop kept going, the value is now 1.  Same thing happens to the second request, k is still 1.
The important thing is that a callback does not create it's own context that only it can touch.
There are 3 ways out of this: figure out a way that does not put an async operation in the for loop, use the async library, or learn about closures (read 3 different explanations to get a good intuition on this one).


text:
Q: non-keyword arg after keyword arg I can't figured out why is this working :
T1 = tree.insert("", 'end', text=BO[2],tags = (BO[3]),values=(strftime(" %d-%m-%Y", gmtime()),BO[5],BO[6],BO[7],BO[8]))

while this one is not working :
T1 = tree.insert("", 'end', text=BO[2],tags = (BO[3]),values=(BO[4]),BO[5],BO[6],BO[7],BO[8]))

I get the following error :

non-keyword arg after keyword arg

A: you have an extra parenthesis after BO[4], so it thinks B[5] through BO[8] are arguments to insert(), not part of the values tuple
T1 = tree.insert("", 'end', text=BO[2],tags = (BO[3]),values=(BO[4],BO[5],BO[6],BO[7],BO[8]))


text:
Q: How can I get invoices with one loc only? I have table ( aztrd)  it contains invoice deatils like itm_code , date, loc_cd ... ect

*

*in each in invoice they are items from loc_cd "1" and loc_cd "2" and some invoices has loc_cd   "1" only or loc_cd  "2" only

i use this query:
SELECT tr_no,loc_cd FROM AZTRD
WHERE LOC_CD = 1 and tr_ty = 102 and loc = 01  AND LOC_CD NOT IN (SELECT itm_cd WHERE LOC_CD = 2)
GROUP BY TR_NO,LOC_CD
ORDER BY TR_NO
So how can I get invoices that has LOC_CD  (1) - any LOC_CD  has (1,2) I don't want them - I try it as you see but this invoice has items from 1 and have items from 2 - so I don't want it it just want only invoice has one LOC_CD not both ?

A: That SQL won't even work. Please post the actual SQL you are using.
Making a lot of assumptions you might be after this:
SELECT tr_no,loc_cd
FROM AZTRD WHERE LOC_CD = 1
AND  tr_ty = 102
AND  loc = 01
AND  itm_cd NOT IN
    (SELECT itm_cd FROM AZTRD WHERE LOC_CD = 2)
ORDER BY TR_NO

A possibly faster way is like this:
SELECT tr_no,loc_cd
FROM AZTRD D
WHERE LOC_CD = 1
and tr_ty = 102
and loc = 01
AND NOT EXISTS (
    SELECT 1 FROM AZTRD E WHERE E.itm_cd = D.itm_cd AND E.LOC_CD = 2)
ORDER BY D.TR_NO

A: Your description is a little hard to read, and as ElecticLlama pointed out, the SQL code you provided will not run...
But, building on ElecticLlama's interpretation, and code cleanup, (so if this helps you, UPVOTE HIS TOO), I thought these logic changes (esp. adding a HAVING clause), might give you your goal: "just want only invoice has one LOC_CD not both".
SELECT tr_no, location_code = MIN(loc_cd)
FROM AZTRD
WHERE tr_ty = 102
GROUP BY tr_no
HAVING MIN(loc_cd) = MAX(loc_cd)
ORDER BY tr_no

Hope that helps! ...let us know.


text:
Q: Como logar somente usuários ativos? Na autenticação além dos dados necessários para logar o usuário, quero que somente os que estão com status ativo = 1 faça login, mas não sei como fazer esta verificação.
table user:
id
username
email
password
ativo

UserController
public function store()
{
      $userdata = array(
          'email'    => Input::get('email'),
          'password' => Input::get('password')
      );
      $rules = array(
          'email'    => 'required',
          'password' => 'required'
      );
      $message = array(
         'email.required'    => 'O :attribute é obrigatório.',
         'password.required' => 'A senha é obrigatória.'
        );
      $validator = Validator::make($userdata, $rules, $message);

     if ($validator->passes())
      {
       if (Auth::attempt($userdata))
          {
           return Redirect::to('')->with('success', 'You have logged in successfully');
          }
          else
          {
           return Redirect::route('admin.create')->withErrors(array('password' => 'Senha inválida'))->withInput(Input::except('password'));
          }
      }

  // Something went wrong.
  return Redirect::route('admin.create')->withErrors($validator)->withInput(Input::except('password'));

}

A: Passa o terceiro parametro que é correspondente a sua coluna de status (ativo ou inativo, exemplifiquei como activated):
 $userdata = array(
      'email'     => Input::get('email'),
      'password'  => Input::get('password'),
      'activated' => 'A'
  );

O Laravel adicionará o activated ao where no momento de localizar o usuário, caso o mesmo esteja inativo não trará.

A: Outra maneira seria assim:
        if (Auth::attempt(array('username' => Input::get('username'), 'password' => Input::get('password')), Input::has('lembar') ? true : false)) {
            if(Auth::user()->status == TRUE) {
                return Redirect::intended('dashboard');
            } else {
                Auth::logout();
                return Redirect::route('entrar')->withErrors('Desculpe, mas o Usuário está desativado.');
            }

        } else {
            return Redirect::route('entrar')->withErrors('Usuário ou Senha Inválido.');
        }


text:
Q: Read Data From Xml and Assign the values in Variable section in Yaml File in Azure DevOps I was trying to read the data from the xml file and take backup of the each file from the location in azure DevOps and Create a artifact
I have a xml with this format and have to read the files data from the file
<?xml version="1.0" encoding="utf-16"?>
<configdatastorage>
  <Files>
    <configfile filename="File1.zip"/>
    <configfile filename="File2.zip"/>
<!--<configfile filename="File3.zip"/>
    <configfile filename="File4.zip"/>
    <configfile filename="File5.zip"/>-->
  </Files>
 </configdatastorage>

I have created a PowerShell script for extracting the value
$XMLfile = "$(Build.SourcesDirectory)\Test.xml"
[XML]$empDetails = Get-Content $XMLfile
$FileNames = ''
foreach($empDetail in $empDetails.configdatastorage.Files.configfile)
{
    $Solution=$empDetail.filename.split(".")
    $FileNames =$FileNames + $Solution[0] + ","
}

Write-Host $fulllength
$FilesRequired = $FileNames.Substring(0,$FileNames.Length-1)
Write-Host "##vso[task.setvariable variable=FileNames;]$FilesRequired"

Now i want to use these values into iterating for each value to take backup of each file from the location
I have created a variable in the pipeline with
# Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml

trigger:
- none

pool:
  vmImage: ubuntu-latest

steps:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      $XMLfile = "$(Build.SourcesDirectory)\Test.xml"
      [XML]$empDetails = Get-Content $XMLfile
      $FileNames = ''
      foreach($empDetail in $empDetails.configdatastorage.Files.configfile)
      {
          $Files=$empDetail.filename.split(".")
          $FileNames =$FileNames + $Files[0] + ","
      }
      $FilesRequired = $FileNames.Substring(0,$FileNames.Length-1)
      Write-Host "##vso[task.setvariable variable=FileNames;]$FilesRequired"

- ${{ each file in split(variables.FileNames, ',')}}:
  - script: echo backup ${{ file }}

This will not provide any output. I came to know the compile type and runtime variable section. where the values are set at different section. How to use the iteration in this case. Do we have any other approach to access the value from the Xml and iterate through the DevOps pipeline
Couldnt find a workaround for this


text:
Q: Poderia este código fazer com que a a webview não "liga-se" ao center_horizontal do xml? Tenho este codigo para carregar um video para a webview  , já tinha feito um post mas tinha me esquecido de apresentar o código .
 mWebView.getSettings().setJavaScriptEnabled(true);
            mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
            mWebView.loadUrl(Vid[0]);
            mWebView.setLayoutParams(new LinearLayout.LayoutParams(350, 350));
            mWebView.setWebChromeClient(new WebChromeClient());

o meu xml completo
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#f0f0f0"
    android:orientation="vertical"
    android:layout_gravity="center_horizontal"
    android:gravity="center_horizontal">
<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="3000dp"
    >
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center_horizontal"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:cropToPadding="false"

            android:layout_gravity="center_horizontal"
            android:layout_alignParentTop="true"
            android:scaleType="fitXY"
            android:id="@+id/imgcabecalho"

            />
        <TextView
            android:id="@+id/tvinformacoes"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:textColor="#FFFFFF"
            android:textSize="12dp"
            android:textStyle="bold"
            android:background="#00BFFF"

            android:text="nome" />

        <TextView
        android:id="@+id/tvdescricao"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:textColor="#333"
        android:textSize="12dp"
        android:textStyle="bold"
        android:text="nome" />

        <ImageView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
              android:id="@+id/img1"

               />

        <TextView
          android:id="@+id/tvdescricao2"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"

          android:textColor="#333"
          android:textSize="12dp"
          android:textStyle="bold"
          android:text=""

          />

           <ImageView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:id="@+id/img2"
               android:layout_gravity="center_horizontal"

                />

        <TextView
           android:id="@+id/tvdescricao3"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"

           android:textColor="#333"
           android:textSize="12dp"
           android:textStyle="bold"
           android:text=""

          />

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:id="@+id/img3"

                   />

        <TextView
                    android:id="@+id/tvdescricao4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"

                    android:textColor="#333"
                    android:textSize="12dp"
                    android:textStyle="bold"
                    android:text=""

                   />

                                                                       <ImageView
                                                                           android:layout_width="wrap_content"
                                                                           android:layout_height="wrap_content"
                                                                           android:layout_gravity="center_horizontal"
                                                                           android:id="@+id/img4"

                                                                           />

        <TextView
                                                                       android:id="@+id/tvdescricao5"
                                                                       android:layout_width="wrap_content"
                                                                       android:layout_height="wrap_content"

                                                                       android:textColor="#333"
                                                                       android:textSize="12dp"
                                                                       android:textStyle="bold"
                                                                       android:text=""

                                                                     />

                   <ImageView
                       android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                       android:layout_gravity="center_horizontal"
                       android:id="@+id/img5"

                        />

        <TextView
                   android:id="@+id/tvdescricao6"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"

                   android:textColor="#333"
                   android:textSize="12dp"
                   android:textStyle="bold"
                   android:text=""

                   />

                   <ImageView
                       android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                       android:layout_gravity="center_horizontal"
                       android:id="@+id/img6"

                      />

        <TextView
                   android:id="@+id/tvdescricao7"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"

                   android:padding="10dp"
                   android:textColor="#333"
                   android:textSize="12dp"
                   android:textStyle="bold"
                   android:text=""
                    />

        <WebView
        android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true"
            android:scaleType="fitXY"
            android:layout_gravity="center_horizontal"
        android:id="@+id/webView"

        android:background="#f0f0f0" />
        <WebView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true"
            android:scaleType="fitXY"
            android:layout_gravity="center_horizontal"
            android:id="@+id/webView2"

            android:background="#f0f0f0" />
        <WebView
            android:layout_width="match_parent"
            android:layout_gravity="center_horizontal"
            android:layout_height="match_parent"
            android:id="@+id/webView3"

            android:background="#f0f0f0" />
        <WebView
            android:layout_width="match_parent"
            android:layout_gravity="center_horizontal"
            android:layout_height="match_parent"

            android:id="@+id/webView4"

            android:background="#f0f0f0" />

        <WebView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:id="@+id/webView5"

            android:background="#f0f0f0" />

    </LinearLayout>
    </ScrollView>

</RelativeLayout>

Código da webview
 <WebView
            android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_alignParentTop="true"
                android:scaleType="fitXY"
                android:layout_gravity="center_horizontal"
            android:id="@+id/webView"

            android:background="#f0f0f0" />

Imagem como estão a aparecer os vídeos na minha app :


text:
Q: Munit 4: Is there a way to mock a payload from the same cache-scoped HTTP Request in different test cases for a suite? I am trying to Mock a response payload from HTTP request like this:
        <munit-tools:mock-when doc:name="doc-name"
            doc:id="doc-id" processor="http:request">
            <munit-tools:with-attributes>
                <munit-tools:with-attribute
                    attributeName="doc:name" whereValue="#['DOCNAME']" />
            </munit-tools:with-attributes>
            <munit-tools:then-return>
                <munit-tools:payload mediaType="application/json"
                    value="#[MunitTools::getResourceAsString('testPayloadA.json')]" />
            </munit-tools:then-return>
        </munit-tools:mock-when>

Then in another test case, I mock the same HTTP request like this:
        <munit-tools:mock-when doc:name="doc-name"
            doc:id="doc-id" processor="http:request">
            <munit-tools:with-attributes>
                <munit-tools:with-attribute
                    attributeName="doc:name" whereValue="#['DOCNAME']" />
            </munit-tools:with-attributes>
            <munit-tools:then-return>
                <munit-tools:payload mediaType="application/json"
                    value="#[MunitTools::getResourceAsString('testPayloadB.json')]" />
            </munit-tools:then-return>
        </munit-tools:mock-when>

Basically the mock has the same structure for at least 4 cases where I am trying to evaluate the behavior that varies depending on the content of the payload that comes from the Http Request with name DOCNAME. The fact is that this request is enclosed in a Cache scope. This means that if I try to run the test cases individually, they will do it successfully, but when all the suite is run, the first case executes OK but the subsequent ones fail.
Does anyone have an idea about how a response payload from a cache-scoped request should be mocked in a way that does not affect all the test suite?

A: So im guessing the tests are failing because the previous value is cached. This could be down to the caching strategy and maybe using different data per test so the cache always misses.
But in case you need to use similar data, you can clear the cache before each test. For example:
Given this flow, setup a named object store and caching strategy that uses said object store:
<os:object-store name="myObjectStore" doc:name="Object store"
        doc:id="25cec35b-2680-4754-8073-633f3e60a34f" />
    <ee:object-store-caching-strategy
        name="Caching_Strategy" objectStore="myObjectStore" doc:name="Caching Strategy"
        doc:id="fd059f4f-d3be-4971-a36c-374506e2db49" />

    <flow name="httpCache">
        <ee:cache cachingStrategy-ref="Caching_Strategy"  doc:name="Cache"  doc:id="0dcabdb4-d6fc-41d5-aebd-77d015e02dd7" >
            <http:request method="GET" doc:name="Request" doc:id="366184e9-6c0b-41d4-8414-3dfdd047ecb2" url="http://google.com"/>
            <logger level="ERROR" message="CACHE MISS" />
        </ee:cache>
        <logger level="ERROR" message="After cache: #[payload]" />
    </flow>

Then is your tests, setup a before action to clear that store:
<munit:before-test name="clearOS" description="clears OS">
            <os:clear objectStore="myObjectStore" doc:id="cd931ce7-6945-4dc9-919a-3ff9b158d746" />
    </munit:before-test>

    <munit:test name="new-test-suite-httpCacheTest" description="Test" doc:id="b8e299ea-d191-4c0a-ac71-27a12b28d275" >
        <munit:behavior >
            <munit-tools:mock-when doc:name="Mock when" doc:id="8bf1468d-c9c1-48a1-9009-bae02bf8e788" processor="http:request">
                <munit-tools:with-attributes >
                    <munit-tools:with-attribute attributeName="doc:name" whereValue="Request" />
                </munit-tools:with-attributes>
                <munit-tools:then-return >
                     <munit-tools:payload value="#['mockPayload']"/>
                </munit-tools:then-return>
            </munit-tools:mock-when>
        </munit:behavior>
        <munit:execution >
            <flow-ref doc:name="Flow-ref to httpCache" doc:id="2dd44c7b-f250-4852-9e53-f4eee3b5ad84" name="httpCache"/>
        </munit:execution>
        <munit:validation >
            <munit-tools:assert-that doc:name="Assert that" doc:id="6521459d-04dd-4e59-8a2e-16a27f51c091" expression="#[payload]" is="#[MunitTools::notNullValue()]"/>
        </munit:validation>
    </munit:test>

    <munit:test name="new-test-suite-httpCacheTest2" description="Test" doc:id="d6ea0d83-f943-450e-948c-26596bf41207" >
        <munit:behavior >
            <munit-tools:mock-when doc:name="Mock when" doc:id="8688876f-144e-4f7f-8ef0-98a8e6caeca0" processor="http:request">
                <munit-tools:with-attributes >
                    <munit-tools:with-attribute attributeName="doc:name" whereValue="Request" />
                </munit-tools:with-attributes>
                <munit-tools:then-return >
                     <munit-tools:payload value="#['mockPayload2']"/>
                </munit-tools:then-return>
            </munit-tools:mock-when>
        </munit:behavior>
        <munit:execution >
            <flow-ref doc:name="Flow-ref to httpCache" doc:id="b4a1d37a-f0e4-4fa1-9c78-084ed3f6faf8" name="httpCache"/>
        </munit:execution>
        <munit:validation >
            <munit-tools:assert-that doc:name="Assert that" doc:id="46febad5-d557-4152-829e-db61aa6ef409" expression="#[payload]" is="#[MunitTools::notNullValue()]"/>
        </munit:validation>
    </munit:test>

Both of these will log:
LoggerMessageProcessor: CACHE MISS

And then:
LoggerMessageProcessor: After cache: mockPayload

LoggerMessageProcessor: After cache: mockPayload2

Where as, without the os:clear it would only miss the cache first time, and print out the same payload from the cache:
 LoggerMessageProcessor: CACHE MISS
 LoggerMessageProcessor: After cache: mockPayload

 LoggerMessageProcessor: After cache: mockPayload

Or alternatively, you could move the cache and http processors to their own flow and mock the flow instead so cache is never used in your tests.


text:
Q: Struggling with Swift Protocol and `some` Keyword I have a Processor protocol:
protocol OutputProvider<OutputType>: AnyObject {
    associatedtype OutputType
    var cachedOutput: OutputType? { get set }
}

protocol Processor: OutputProvider {
    associatedtype InputType
    associatedtype InputProvider: OutputProvider<InputType>

    func process(input: InputType) -> OutputType

    var inputProvider: InputProvider { get }
}

extension Processor {
    func process() {
        if let nextProcessor = inputProvider as? any Processor {
            nextProcessor.process()
        }
        guard let input = inputProvider.cachedOutput else {
            cachedOutput = nil
            return
        }
        self.cachedOutput = self.process(input: input)
    }
}

Each object which conforms to the Processor protocol has a (type safe) reference to an inputProvider (which conforms to the OutputProvider protocol with matching OutputType for the processors InputType).
So the idea is, that by calling the process() function in the last of a chain of Processor objects, each Processor can process the output of its inputProvider, down the chain until the initial input is reached (the real setup would be more complex and more dynamic):
final class Input: OutputProvider {
    var cachedOutput: String?
}

final class P1: Processor {
    ...
}

final class P2: Processor {
    ...
}

let input = Input()
input.cachedOutput = ...

let chain = P2(inputProvider: P1(inputProvider: initialInput))
chain.process()
print(chain.cachedOutput)

But now I've go stuck at the implementation of a concrete Processor:
final class P1: Processor {
    init(inputProvider: some OutputProvider) {
        self.inputProvider = inputProvider // ERROR 1
    }

    func process(input: String) -> Int {
        input.count
    }

    var cachedOutput: Int?

    let inputProvider: some OutputProvider<String> // ERROR 2
}

*

*Error 1: Cannot assign value of type 'some OutputProvider' to type 'some OutputProvider & AnyObject'

*Error 2: Property declares an opaque return type, but has no initializer expression from which to infer an underlying type
I already tried many things, but nothing seems to satisfy the swift compiler.
I thought, that the some keyword is exactly for a use case like this. But now I'm not so sure anymore :)
Am I on a completely wrong path here or did I just get some obscure detail wrong?

A: You have to resolve the generics; every type must be known absolutely at compile time. Thus, in your class P1, you must define inputProvider as a specific type that adopts OutputProvider.
Looking at the same matter from a different direction, the Processor requirement
var inputProvider: InputProvider { get }

can be satisfied only by a declaration that starts
var inputProvider: InputProvider

You cannot arbitrarily insert some; that's not what the requirement says.
Here's a working example of the kind of chain you're trying to create (omitting the entire process method, which is a red herring for purposes of the issue):
protocol OutputProvider: AnyObject {
    associatedtype OutputType
    var cachedOutput: OutputType? { get set }
}

protocol Processor: OutputProvider {
    associatedtype InputType
    associatedtype InputProvider where InputProvider: OutputProvider, InputProvider.OutputType == InputType

    var inputProvider: InputProvider { get }
}

class P1: OutputProvider {
    var cachedOutput: String?
}

class P2: Processor {
    typealias InputType = String

    var inputProvider: P1

    var cachedOutput: Int?

    init(inputProvider: P1) {
        self.inputProvider = inputProvider
    }
}

I should just add that if you want to see this kind of chaining in action, you have no further to look than the Combine framework; this sort of thing is exactly how it works.


text:
Q: understanding the convolution in signals and systems Hi : I've been reading introductions to signals and systems but my background is probability and statistics. In probability, the concept of convolution makes perfect sense to me. If $t$ is a random variable with density $g(t)$ and $g(t) = f(x)h(y)$, then $P(T = t) = \int f(\tau)h(t-\tau) d \tau$. This is because the integral represents all the various ways that $x$ and $y$ can add to become the value $t$. A similar argument holds for the discrete case.
But when I'm reading the various "intros to signals and systems texts", they describe a step by step process where you flip the h function over the y-axis, so that its  $h(-\tau)$, add t, and then keep moving it over to the right step by step and calculating the area ( i.e.: the value of the integral at each time $\tau$ )  by calculating the area covered by the overlapped values of $f$ and $h$. This doesn't make sense to me. In other words, is there some analog in signals and systems to the "various ways that $x$ and $y$ can add to become the value $t$ in probability . Clearly, in the signals and systems framework, $t$ is not a random variable so the interpretation has to be totally different. But I'm wondering if there is some way of REALLY understanding why this is done. Maybe there is some physical reason due to what the function $h$ actually represents. They keep referring to it as the impulse response function so maybe my lack of understanding is because  I'm not understanding what the impulse response function really represents ? I just don't get why you do the flip over the y-axis thing and then move it slowly to the right step by step and keep figuring out the overlapped areas.
My take is that it's really essential to understand convolution in signals and systems or else you cannot go an further. So I stopped and decided to ask here because every book seems to give the same step by step overlap explanation and I'm continuously stumped by it. I realize it's a lot to ask for an explanation but maybe someone knows of a text that explains the WHY part of the process or possibly relates it to the convolution in probability. Thank you very much for any help, wisdom, references, links etc.
                                                                   Mark

A: It might help to look at a discrete time system.
Suppose you have a linear time-invariant system with 'impulse' response $t \mapsto h_t$, that is, with input $u = 1_{\{0\}}$ (that is, one for $t = 0$ and zero everywhere else).
By linearity, if the input is $u = \sum u_k 1_{\{k\} }$ (that is, $u=(u_0,u_1,...)$), then the output will have the combined responses from each separate $ u_k 1_{\{k\} }$, appropriately delayed.
At time $t$, the input $ u_0 1_{\{0\} }$ will contribute $u_0 h_{t-0}$.
At time $t$, the input $ u_1 1_{\{1\} }$ will contribute $u_1 h_{t-1}$.
At time $t$, the input $ u_k 1_{\{k\} }$ will contribute $u_k h_{t-k}$.
Etc, etc.
Combining gives the response $y_t = \sum h_{t-k} u_k$.
For continuous systems, we can informally think of $u(t) = \int u(\tau) \delta(t-\tau) d \tau$. For a fixed $\tau$, the 'input' $t \mapsto u(\tau) \delta(t-\tau)$ results in a contribution $t \mapsto u(\tau) h(t-\tau)$, hence the total combined response is $y(t) =\int u(\tau) h(t-\tau) d \tau$.

A: $\def\nR{\mathbb{R}}\def\rmC{{\mathrm C}}\def\rmu{{\rm u}}\def\sS{{\Sigma}}\def\sF{{\mathcal{F}}}\def\l{\left}\def\r{\right}\def\di{d}\def\sinc{\operatorname{sinc}}\def\ltag#1{\tag{#1}\label{#1}}$
We speak of signals as time functions $x:\nR\rightarrow\nR$ (defined on the whole time axis).
Actually, they are not just any real functions but must have some nice properties (such as square integrability, else we had difficulties with convolution).
We do not go deeper into that here. We just collect all admissible signals into a signal set $\sS$.
A system $S$ maps input signals $x$ uniquely to output signals $y$, we write $y=S(x)$.
We concentrate here on the special class of time-invariant linear systems.
Linear means not only that for two signals $x_1,x_2\in \sS$ and a scalar $\lambda\in\nR$ there holds $S(x_1+\lambda x_2)=S(x_1)+\lambda S(x_2)$ but also if we have a parameterized set of signals $\l(x_\tau\r)_{\tau\in\nR}\in\sS$ and a coefficient function $\lambda(\tau)$ then
$$
S\l(\int_\nR \lambda_\tau x_\tau \di\tau\r) = \int_\nR \lambda_\tau S(x_\tau)\di\tau
$$
For time invariance we need the notion of shifted time signals. For a given time-shift $\tau\in\nR$ and a signal $x\in\sS$ we denote with $x(\bullet-\tau)$ the shifted signal defined by $x(\bullet-\tau)(t)=x(t-\tau)$ for all $t\in\nR$.
Time invariant systems respond to a shifted input signal with a shifted output signal, i.e., $S(x(\bullet-\tau)) = S(x)(\bullet-\tau)$.
Beside linearity this time invariance is the special property of
models for physical systems that makes convolution such a useful tool.
And the set of linear time-invariant systems is large. All systems
that can be described through linear ordinary and partial differential
equations with constant coefficients belong to this set.
Now, suppose we have a family of base functions $\l(\delta(\bullet-\tau)\r)_{\tau\in\nR}$ for our signal space $\sS$
which just differ by a shift.
Just to recap: Base functions of $\sS$ means that we can represent every signal $x\in\sS$ as linear combination
\begin{align}
  \ltag{base}
  x(t) &= \int_{-\infty}^\infty \lambda_\tau \delta(t-\tau) d\tau
\end{align}
of the base functions $\delta(\bullet-\tau)$ with a corresponding family of coefficients $\lambda_\tau$ which represent the signal $x$ uniquely.
The nice thing with base functions which just differ by shift is that
because of the time-invariance of the considered physical systems $S$
the system responses to these base functions also just differ by a
shift:
$$
S(\delta(\bullet-\tau))= S(\delta)(\bullet-\tau)
$$
Let us denote the system repsonse to our unshifted base function $\delta$ as $g:=S(\delta)$.
To calculate the answer of the linear operator we just need the mapped
base functions (just like in linear algebra).
\begin{align}
  y=S(x) &= S\l(\int_\nR \lambda_\tau \delta(\bullet-\tau) d\tau \r)\\
  &= \int_\nR\lambda_\tau S(\delta(\bullet-\tau)) d\tau&&\text{ just using linearity}\\
  &= \int_\nR\lambda_\tau S(\delta)(\bullet-\tau) d\tau&&\text{ using time invariance}\\
  &= \int_\nR\lambda_\tau g(\bullet-\tau) d\tau
\end{align}
The system response at a certain time $t$ can be computed as
\begin{align}
  \ltag{impulseResponse}
  y(t) &= \int_\nR \lambda_\tau g(t-\tau)d\tau.
\end{align}
Now, the only problem remains to find the appropriate base
functions. Hm..., we would have to extend our signal space
$\sS$ to a space of distributions for that purpose and we would have to define the linear system
$S$ on this extended signal space.
We do not want to go into these details here.
Instead we switch to Rieman-Stieltjes integrals in \eqref{base}. That
means we use a family of base functions $\bar h(\bullet-\tau)$ (left-continuous, with
bounded variation) that only differ in a shift such that we can
represent our signal as
\begin{align}
  \ltag{baseStieltjes}
  x(t) &= \int_{\tau=-\infty}^\infty \lambda_\tau d \bar h(t-\tau).
\end{align}
with a family of coefficients $\lambda_\tau$ continuously depending on $\tau\in\nR$.
Riemann Stieltjes integrals are known from distribution functions in
statistics. Especially, discontinuities in the integrator function $h$
result to sum terms
\begin{align}
  x(t) &= \sum_{\scriptsize\begin{matrix}\tau\in\nR\\h(t-(\tau-))\\\neq h(t-(\tau+))\end{matrix}} \lambda_\tau\cdot (\bar h(t-(\tau+))-\bar h(t-(\tau-)) +\\
  \ltag{sumStieltjes}
&\phantom{= \sum_{\scriptsize\begin{matrix}\tau\in\nR\\h(t-(\tau-))\\\neq h(t-(\tau+))\end{matrix}}\lambda_\tau\cdot  \bar h(t-(\tau+))
}+ \int_{\tau=-\infty}^\infty \lambda_\tau (-\bar h'_\rmC(t-\tau))d\tau.
\end{align}
where $h_\rmC$ is the continuous part of $h$, i.e.,
\begin{align}
  \bar h_\rmC(t)&=\bar h(t)-\sum_{\scriptsize\begin{matrix}\tau\leq t\\h(\tau-)\\\neq h(\tau+)\end{matrix}}\bar h(\tau+)-\bar h(\tau-).
\end{align}
Note, that the differentiation of $\bar h_\rmC$ in \label{sumStieltjes} is
carried out w.r.t. $\tau$.  This explains the negative sign.
With the help of \label{sumStieltjes} it is easy to construct nice
base functions. We just choose $\bar h'_\rmC=0$, i.e. a piecewise constant
function and let $h$ have one jump of height -1 from 0 to -1 for $\tau=t$.
Such a signal would be the negative Heaviside function
\begin{align}
  \bar h(t) &=\l\{\begin{matrix}
    0&\text{ for }t<0\\
    -1&\text{ for }t\geq 0
  \end{matrix}
  \r\} = -h(t)
\end{align}
with the Heaviside function $h$.
This way we get just $\lambda_\tau = x(\tau)$ and the
representation \label{baseStieltjes} reads as
\begin{align}
  x(t) =\int_{\tau=-\infty}^\infty x(\tau)\cdot d\bar h(t-\tau).
\end{align}
Applying the linear time invariant system to this signal means
\begin{align}
  y(t) &= S\l(\int_{\tau=-\infty}^{\infty} x(\tau)d\bar h(\bullet-\tau)\r)(t)\\
  &=\int_{\tau=-\infty}^{\infty} x(\tau)d S\l(\bar h(\bullet-\tau)\r)(t)&&\text{ using linearity}\\
  &=\int_{\tau=-\infty}^{\infty} x(\tau)d S\l(\bar h\r)(t-\tau)&&\text{ using time invariance}
\end{align}
We have again one signal $\bar G:= S(\bar h)$ that
characterizses the system completely.
Often the system has smoothing properties such that $\bar G$ is
continuous even with the discontinuous input $\bar h$.
In that case one can derive the integrator function in the
Riemann-Stieltjes integral w.r.t. $\tau$ and obtains
\begin{align}
  y(t) &= \int_{\tau=-\infty}^\infty x(\tau) (-\bar G'(t-\tau))d\tau.
\end{align}
There is the connection to \label{impulseResponse}.
We can choose
\begin{align}
  \lambda_\tau &= x(\tau)\\
  g(t) &=-\bar G'(t)\\
  &= - S(-h)'(t) = S(h)'(t)
\end{align}
and write
\begin{align}
  y(t) &= \int_{\tau=-\infty}^\infty x(\tau)g(t-\tau)d\tau.
\end{align}

Mark Leeds asked some good questions in the comments to this Answer which I want to address here:

*

*At the point where you introduce the stieltjes integral, what was the integral called before that point? I know reimann and lebesgue but that's it.

*If you had to give intuition for why it's the second term is g(t−τ) rather than just g(t), what would it be?

Answer to 1.: One could at first try Lebesgue integrals. But, pityingly there is
no family of Lebesgue integrable base functions $\delta(\bullet-\tau)$
$(\tau\in\nR)$ which only differ by shifts. The problem is that the
convolution integral
$y(t)=\int_{-\infty}^{+\infty}x(\tau)\delta(t-\tau)d\tau$ "smears" the
support of the integrands. This leads relatively fast to the
conclusion that the base functions $\delta(\bullet-\tau)$ should have
a single point as support to satisfy $y(t)=x(t)$. This in turn would
mean that $\delta$ would be the zero function in the Lebesgue
sense. Therefore, there are no such base functions in $L^2$. I have
shown one relatively simple way around this difficulty with
Stieltjes-Riemann integrals.
Another general way would be to start with the space of piecewise
smooth L2-functions which form a ring with the convolution product as
multiplication. The algebraic structure of this set is like that one
of the ring of
integers. This ring
can be extended to a field. This method is known from the extension of
the ring of integers to the field rational numbers). The unit element
in that field is called Dirac-delta distribution. You find this
approach in the book Differential Algebraic Equations of Kunkel and
Mehrmann.
A further alternative would be to reduce the signal space to the space of
frequency-limited signals. This way even works with classical
integrals. I think you know the Fourier transformation $X(\omega) =
\sF(x)(\omega) = \int_{-\infty}^\infty x(t) e^{-i\omega t} dt$ from
statistics or at least from the
video.
Furthermore, you know that convolution in the time-domain
$(x*y)(t)=\int_{\tau=-\infty}^\infty x(\tau)y(t-\tau)d\tau$ translates
to multiplication $\sF(x*y)(\omega) = X(\omega)\cdot Y(\omega)$ in the
frequency domain.
We are looking for the decomposition of signals $x$ in linear combinations $x(t) = \int_{-\infty}^\infty x(\tau) \delta(t-\tau) d\tau = (x*\delta)(t)$.
That means that $\delta$ should retain the signal under
convolution. In the frequency domain the spectrum
$\Delta:=\sF(\delta)$ of $\delta$ should retain the spectrum $X$ of
the signal $x$ under multiplication. If our signal space $\sS$
contains signals $x$ whose spectra $X$ have unbounded support this implies that the spectrum of $\Delta$ must be the unit function, i.e., $\Delta(\omega)=1$ for all $\omega\in\nR$. But, if there exists an upper limit frequency $\omega_\rmu>0$ such that the spectra $X$ for all signals $x\in\sS$ are zero outside of $[-\omega_\rmu,\omega_\rmu]$ then $\Delta(\omega)$ must only be 1 for $\omega\in[-\omega_\rmu,\omega_\rmu]$. We can construct an appropriate generator for our base as inverse Fourier transformed of
\begin{align}
  \Delta(\omega) &=
  \begin{cases}
    1 &\text{ for } \omega \in [-\omega_\rmu,\omega_\rmu]\\
    0 &\text{ else }
  \end{cases}
\end{align}
\begin{align}
  \delta(t) &:= \frac1{2\pi}\int_{-\infty}^\infty \Delta(\omega)e^{i\omega t} d\omega\\
  &= \frac1{2\pi}\int_{-\omega_\rmu}^{\omega_\rmu} e^{i\omega t} d\omega\\
  &= \begin{cases}
    \frac{\omega_\rmu}{\pi} &\text{ for } t=0\\
    \frac1{t\pi} \sin(\omega_\rmu t)&\text{ for } t\neq 0
  \end{cases}\\
  &= \frac{\omega_\rmu}{\pi} \sinc(\omega_\rmu t)
\end{align}
with the sinc function.
So, for frequency-bounded signals you can use normal Lebesgue
integration and you have an explicit representation of the base functions $\delta(\bullet-\tau) = \frac{\omega_\rmu}{\pi} \sinc(\omega_\rmu (\bullet-\tau))$.
Pityingly, this is a rather restricted signal space only suited for educational purposes. You do not have a step signal since this is not frequency limited and not $L^2$. Furthermore, all those signals are acausal since their support is unlimited in both directions.
Note, that for increasing upper frequency bound $\omega_\rmu$ the
sequence $\delta_{\omega_\rmu}$ $(\omega_\rmu\rightarrow\infty)$
represents in the limit the Dirac delta distribution. This limit is
one way to understand the Dirac delta distribution.

Answer to 2.: The intuitive picture is already contained in the text. The LTI
system responses to a time-shifted input signal by a time-shifted
output signal. That is the reason why we represent our signal $x$ as
superposition of time-shifted basis signals
$x(t)=\int_{\tau=-\infty}^\infty x(\tau)\delta(t-\tau) d\tau.$ Under
the integral only $\delta$ is dependent on the real time $t$ and $x$
only appears as a weighting function which ist "indexed" through
$\tau$. Thus, the system $S$ only acts on the shifted time signals
$\delta(t-\tau)$ with the shifted system response $g(t-\tau)$. One
obtains the system response on the input signal $x$ as superposition
$y(t) = S(x)(t) = \int_{-\infty}^\infty x(\tau)g(t-\tau) d\tau$ of the
system responses $g(t-\tau)$ on the shifted $\delta(t-\tau)$. Notably,
the impulse response starting at time $\tau$ is weighted with the
value $x(\tau)$ of the input signal at time $\tau$. It contributes to
the output $y(t)$ at time $t$ with the $x(\tau)$-weighted impulse response of
the system after the elapsed time $t-\tau$ of the time interval from $\tau$ to $t$.
You compose your input signal as a sequence of shifted "special signals" and look what the system delivers for the shifted special signals after the elapsed time from the start time of the special signal to the current time.


text:
Q: Rock Paper Scissors Always Lets Me Win I'm a new programmer and am trying to familiarize myself with if else statements by creating a rock paper scissors game. My problem is that the code always lets me win. In addition, my while loop won't actually loop so any help with this stuff would be greatly appreciated. Thanks! :)
The code:
from random import randint

t = ["Rock", "Paper", "Scissors"]

computer = t[randint(0, 2)]

player = False

while player == False:
    player = input("Rock, Paper, or Scissors: ").lower()
    if player == computer:
        print("Computer:" + player.capitalize())
        print("Tie!")
    elif player == "rock":
        if computer == "Paper":
            print("Computer: Paper")
            print("You lose")
        else:
            print("Computer: Scissors")
            print("You Win!")
    elif player == "paper":
        if computer == "Scissors":
            print("Computer: Scissors")
            print("You Lose!")
        else:
            print("Computer: Rock")
            print("You win")
    elif player == "scissors":
        if computer == "Rock":
            print("Computer: Rock")
            print("You lose!")
        else:
            print("Computer: Paper")
            print("You Win!")
    else:
        print("Invalid input. Try again!")

player = False
computer = t[randint(0, 2)]

A: The game doesn't repeat because your condition player == False is never true after the player has made a choice. It always contains the player's last choice, which isn't False.
Instead of using that while condition, allow the user to enter something like quit. Then check for that before running the rest of the code, and break out of the loop.
You can use random.choice() to select an item from a list, instead of randint().
The computer's choice needs to be in the loop. Otherwise, the player can always win because the computer's choice never changes.
from random import choice

t = ["Rock", "Paper", "Scissors"]

while True:
    player = input("Rock, Paper, Scissors, or quit: ").lower()
    if player == 'quit':
        break
    computer = choice(t)
    if player == computer:
        print("Computer:" + player.capitalize())
        print("Tie!")
    elif player == "rock":
        if computer == "Paper":
            print("Computer: Paper")
            print("You lose")
        else:
            print("Computer: Scissors")
            print("You Win!")
    elif player == "paper":
        if computer == "Scissors":
            print("Computer: Scissors")
            print("You Lose!")
        else:
            print("Computer: Rock")
            print("You win")
    elif player == "scissors":
        if computer == "Rock":
            print("Computer: Rock")
            print("You lose!")
        else:
            print("Computer: Paper")
            print("You Win!")
    else:
        print("Invalid input. Try again!")


text:
Q: Height and view of imageview screws up after setimagebitmap Here's my XML:
<LinearLayout
android:id="@+id/afterphotolayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgPreview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:maxHeight="400dp"
        android:contentDescription="@string/image_description"
        android:scaleType="centerCrop" />

    <ImageView
        android:id="@+id/blankView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

But In the code, when I do this:
_imgPreview.setImageBitmap(_compressedBitmap);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0, 1.0f );
_imgPreview.setLayoutParams(param);

My image is still not resized to take up half the screen height and scale by center crop. It seems that the setImageBitmap function screws up the height/width of the imageview and doesn't allow it to be changed even after I try to set a new layout param. Can anyone shed some light on why this is so?

A: I had the same issue! Was going crazy, setImageBitmap completely ignores the layout weight. I also added the setting of the weight programmatically:
barcode.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 2));

but did not help.
But then I did this:
barcode.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1, 2));

and that helped, not giving a '0' value for the height. I just tried this out on lollipop, so haven't tested in on older version, but will probably work.
Frustating, took me too long again to figure out some workaround for an Android quirk


text:
Q: Best way to handle exceptions when the invoked method throws a lot of exception I try to handle rpc exception like this
try {
    rpcService.invokeRemoteMethod(foo)

} catch (Exception e) {
    logger.error("invokeRemoteMethod failed, foo = {} ", foo);
    throw CustomException(e);
}

when the rpcService isn't available, for example timeout, this snippet of code will write a lot of stacktrace log to the file, which may consumes a lot of cup and memory.So I guess whether I can set some threshold, such as when the same exception accurs once a minute, I print the whole exception stack, 10 times a minute, I just print the exception message, 100 and more times, I log nothing.

A: In my opinion, circuit breaker is appropriate pattern to control logging (and also to prevent DOS on service if latency is high). Circuit can be open if more that say 5 exception (can be configuration per service) continuously, so that application doesn't call and log error if remote service is down.
Depending on your project, you can either use open source circuit breakers or can write simple circuit breaker using AOP or wrapping RPC class with circuit breaker.
Very minimal example for understanding is
public abstract class CircuitBreaker
{
    private Circuit circuit;

    public CircuitBreaker(){
        circuit = new Circuit();
    }

    public void execute()
    {
        if(circuit.isOpen()) {
            throw CircuitOpenException();
        }

        invokeService();
    }

    protected void recordFailure(){
        circuit.recordFailure();
    }

    protected abstract <T extends Object> T invokeService();
}

public class RPCServiceExecutor extends CircuitBreaker
{
    protected Result invokeService() {
        try {
            Result result = rpcService.invokeRemoteMethod(foo);
            return new Result();
        } catch (Exception e) {
            this.recordFailure();
            logger.error("invokeRemoteMethod failed, foo = {} ", foo);
            throw CustomException(e);
        }
    }
}

when circuit isOpen don't log exception, when circuit is closed always log exception.
For more details and examples you can refer
https://martinfowler.com/bliki/CircuitBreaker.html
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/concurrent/CircuitBreaker.html
https://spring.io/guides/gs/circuit-breaker/
Hope this help. In case you need more detailed real example let me know.


text:
Q: Confused about the terminology when using the orientation sensor in Android I've written a small app that outputs the roll, pitch, and azimuth returned from the device's sensor.  However, I'm having difficulty understanding the numbers it returns.
Imagine that the user is holding his smartphone in portrait mode with the screen directly in front of him (the pose someone would be using to snap a photograph).  He then jams a pencil through the middle of the screen and rotates the device around that pencil.  If I wanted to detect when the user rotated to exactly 90 degrees around that pencil (relative to it's starting position), which should I be interested in: roll, pitch, or azimuth?
The answer would seem to be obvious after a little experimentation or reading the Google docs.  However, all three numbers change at approximately the same rate during my tests, so I'm thoroughly confused.

A: Why not use the accelerometer instead?
I think that's a better solution for you, when you want to detect the rotation of the phone.
Using the accelerometer will give you this result:
When holding the phone as in your example, one of the x, y or z values will be either -9.82 or 9.82 depending which way you hold the phone.  Let's say x is -9.82, and when it rotates the value will increase until it hits 0 and then y will start increase/decrease depending om the rotation.  When y is either -9.82 or 9.82 you've rotated the phone 90 degrees, and if x goes from -9.82 to 9.82 you've rotated 180 degrees.


text:
Q: NoClassDefFoundError: org.apache.xmlrpc.client.XmlRpcClient I've started developing with XML-RPC in Android but since I've added the JAR files I keep getting this error when I click on my button:
java.lang.NoClassDefFoundError: org.apache.xmlrpc.client.XmlRpcClient

I always get it when I click on the button with this code:
public void addListenerOnButton() {

    button = (Button) findViewById(R.id.button1);

    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            final String url = "http://www.myUrl.com:8069/";
            final String db = "dbname";
            final String username = "username";
            final String password = "password";

            final XmlRpcClient client = new XmlRpcClient();

            final XmlRpcClientConfigImpl start_config = new XmlRpcClientConfigImpl();
            /*Toast.makeText(MainActivity.this,
                    "Your Message", Toast.LENGTH_LONG).show();*/
        }
    });
}

I've added the external JAR files org-apache-xmlrpc, xmlrpc-3.0a1 and xmlrpc-client as you can see here:

And this is the problem that keeps popping up:

Can anybody explain me what I'm doing wrong and how I can fix this please?
I'm really stuck on this one.
Thanks
Yenthe

A: Go to Project/Properties/Java Build Path/Order and Export -- Make sure there's a check in front of Android Dependencies and the support library, if you use it.
Mark all checkboxes and Click on Apply and clean the project.
Hope this helps.

A: It turned out that I had to include another JAR file for the XML-RPC.
You can download all these JAR files here: http://archive.eu.apache.org/dist/ws/xmlrpc/apache-xmlrpc-current-bin.zip
After downloading all these JAR files you should all place them under libs and then clean your project. Then it is solved.

A: I faced the same problem when i was working with WSO2 micro-integrator when initializing the class mediator that implements "XmlRpcClientConfig" interface.I figured out that i should place the jar files for apache-xmlrpc client to the libs folder in WSO2 Micro integrator and it works fine.


text:
Q: How to get an XML file for an sql query result I have to build a report using BI publisher for which i need xml file for a query result am using SQL developer for executing my queries.

A: Oracle provides a lot of syntax for writing out XML formatted content from database columns.
You might want to explore some of that.
It will generate one xml document per row of your query.
If that is what you want.

A: Google "oracle bi publisher xml output" =>
http://cali97.blogspot.com/2008/01/bi-publisher-xml-publisher-can-produce.html
'Hope that helps...


text:
Q: iOS: Maintain status bar after custom modal presentation I have a somewhat complex modal view controller hierarchy that is breaking the status bar in my iOS app.
My main view controller hierarchy is a UINavigationController subclass inside of a container UIViewController. When I enter into a Settings panel, I use a "card-like" animation to "shrink" the contained UINavigationController and then display the Settings panel UIViewController modally on top of the main UINavigationController. So far, so good. If I reverse that animation (exiting the Settings panel), my UI is restored as expected.
There is a function in the Settings panel, however, where another modal UIViewController (a custom UIAlertView-like modal) is displayed on top of the first modal UIViewController. When this happens, all is displayed as expected, but with one exception (detailed below, after some additional details):

*

*Prior to any of these animations, the contained UINavigationController has a UINavigationBar with a height of 64 points (44 points for the UINavigationBar and 20 points for the portion that extends under the status bar). This is correct.

*When the first animation occurs (presenting the "card-like" Settings panel), the 20 points of extra height are maintained, as they should be (this allows the unwinding of the UI to restore the original layout correctly).

*When the second animation occurs, presenting a modal UIViewController on top of the modal UINavigationController, the "extra" 20 points are animated away, and they do not return. This means that, when my animations are unwound, the UINavigationBar of my contained UINavigationController isn't tall enough, and its icons are displayed under the status bar icons.

I do not know why this change only happens when the second modal is presented. How can I keep that "extra" 20 points of padding all the time? If I can't do that, how can I restore it when needed?


text:
Q: Is a generic closed orientable hyperbolic 3-manifold Haken? My question is as follows:
"Is a generic closed orientable hyperbolic 3-manifold Haken?"
Of course the word 'generic' can be interpreted in many ways, and the answer might depend on the way how one interprets 'generic'.
As an example, let's consider the related question
"Is a generic closed (aspherical) 3-manifold hyperbolic?"
In this case there are various notions of 'generic', in each case the answer is a resounding yes.
For example, almost all Dehn fillings on a hyperbolic knot result again in a hyperbolic 3-manifold. Furthermore Maher (Random Heegaard splittings) showed in a precise sense that a 'random gluing of two handlebodies of genus >1' gives rise to a hyperbolic 3-manifold. Similarly, in a precise sense, a 'random' fibered 3-manifold is hyperbolic.
My hunch would have been that a generic hyperbolic 3-manifold is non-Haken (why should it have an incompressible surface?), but I just had lunch with another 3-manifold topologist and his guess was that a generic hyperbolic 3-manifold should be Haken.

A: Firstly, the random Heegard splitting model and the random fibering model are discussed at length in my preprint. (I believe the OP is familiar with it). I believe the question is asked there, though not answered - it is pointed out that the smaller genus of an incompressible surface will grow, but that seems to be neither here nor there. A related question is whether a random fibered manifold has an incompressible surface which is not the fiber of the fibration you started with. Here, the answer is YES, for genus 1 (Floyd-Hatcher), and probably YES for higher genus, which would tend to suggest that a random Dunfield-Thurston manifold might be Haken, but nobody knows for sure.
As for Dylan's comment, it is certainly plausible. Any given configuration of tetrahedra (in particular one with a normal sphere which is not the link of a vertex), in fact, you might as well assume that it is topologically a thickened sphere, will appear with probability one, and it is highly unlikely that it will bound balls on both sides.


text:
Q: THREE.js text not showing with out any errors This is my shape geometry, material and mesh it is pulling no errors yet when I run the code the text doesn't seem to appear does anyone know why?
var shapeText = new THREE.TextGeometry("TheOriginal", {font: 'helvetiker'});
var wrapper = new THREE.MeshBasicMaterial({color: 0xFF0000});
var words = new THREE.Mesh(shapeText, wrapper);
scene.add(words);
console.log(words.position);

A: Move your camera away from object
camera.position.set(300,300,300);
camera.lookAt(words.position);

You are too close to the text. Actually your camera positioned between letters or inside the text mesh and looks outside from the text.


text:
Q: SQL Sum() - 0 in field excluding row from aggregation? Consider the following query:
$query = "
SELECT a_orders.id, a_orders.billing,
   SUM(a_order_rows.quant_refunded*a_order_rows.price*((100-a_orders.discount)*.01)) as refund_total,
   SUM(a_order_rows.quant*a_order_rows.price*((100-a_orders.discount)*.01)) as order_total
FROM a_order_rows JOIN a_orders
ON a_order_rows.order_id = a_orders.id
WHERE a_order_rows.quant_refunded > 0
GROUP BY a_orders.id, a_orders.billing
ORDER BY a_orders.id DESC
LIMIT 50";

The two uses of SUM() are attempting to aggregate the order total and the total amount that has been refunded. They are coming out correctly when when the quant_refunded field is not 0... for example take this data (excluding primary key, item_id for simplicity's sake, assuming each row is a unique item):
Table: a_order_rows
Fields: order_id, quant, quant_refunded
1, 1, 1
1, 2, 1
2, 1, 1
2, 1, 0

In the case of "order 1" the two aggregations are different and behave as expected. But for "order 2" the two numbers are coming out the same - both numbers are what I am expecting refund_total to be. It appears that the row with "0" in quant_refunded is being excluded from the order_total aggregation.
Hopefully this is explained thoroughly enough. Please let me know if you need more info and I will revise. THANKS!

A: $query = "
SELECT a_orders.id, a_orders.billing,
   SUM(a_order_rows.quant_refunded*a_order_rows.price*((100-a_orders.discount)*.01)) as refund_total,
   SUM(a_order_rows.quant*a_order_rows.price*((100-a_orders.discount)*.01)) as order_total
FROM a_order_rows JOIN a_orders
  ON a_order_rows.order_id = a_orders.id
GROUP BY a_orders.id, a_orders.billing
HAVING MAX(a_order_rows.quant_refunded) > 0
ORDER BY a_orders.id DESC
LIMIT 50";

Change that to a HAVING clause. If any quant_refunded rows are > 0, the HAVING MAX will retain it.


text:
Q: Need help writing a Makefile that creates all the objective files into a new subdir I am trying to make a Makefile for a big project.
The project structure is (I've ommitted the header files):
root/feature1/feat1.c
root/feature2/feat2.c
root/srcfile1.c
root/srcfile2.c

I wanted to start easy so I created a simpler project with the source files in the root dir.
I need to create all the object files in one directory, let's say, objdir.
The project structure of the simple project is:
root/main.c
root/word.c

By looking in other questions I have come up with this:
CC = gcc
FLAGS = -c
MKDIR_P = mkdir -p
OUT = words
OBJDIR = objdir
SRCDIR = .
_OBJS = main.o word.o
OBJS = $(patsubst %,$(OBJDIR)/%,$(_OBJS))

$(OBJDIR)/%.o: $(SRCDIR)/%.c
    $(CC) -c -o $@ $<

all: directories program

directories: ${OBJDIR}

${OBJDIR}:
    ${MKDIR_P} ${OBJDIR}

program: $(OBJS)
    $(CC) -o $@ $^ $(LIBS)

clean:
    rm -f $(OBJS)

When running it with make -f ./myMakefile all (changed the filename as in the same dir, there is Netbeans' Makefile), I am getting this output:
gcc -o objdir/main.o main.c
/tmp/ccatfAHu.o: In function `main':
main.c:(.text+0x15): undefined reference to `CreateWord'
main.c:(.text+0x26): undefined reference to `CreateWord'
collect2: error: ld returned 1 exit status
make: *** [objdir/main.o] Error 1

Giving the make all command, it tries to produce the targes directories and program.
The dir objdir is created and in it, there are the main.o and word.o files.
What am I doing wrong with the makefile of the simpleproject?
EDIT:
Added the -c flag at the $(OBJDIR)/%.o rule.
Removed the $(FLAGS) from $(CC) -o $@ $^ $(FLAGS) $(LIBS).
Now, if we move to my project problem, I need to access all the source files from all the directories:

*

*/repo-root

*/repo-root/feature1/feat1.c

*/repo-root/feature2/feat2.c

A: In this rule:
$(OBJDIR)/%.o: $(SRCDIR)/%.c
    $(CC) -o $@ $<

you're missing the -c flag. Instead of building an object file, Make is trying to build an executable named objdir/main.o, and main.c doesn't have all of the needed code. Just do this:
$(OBJDIR)/%.o: $(SRCDIR)/%.c
    $(CC) -c -o $@ $<

A: Try this
#source files to compile relative to the src dir
CSOURCE =  main.c
CSOURCE +=  func1.c
SRCDIR = .
vpath %.c $(SRCDIR)/
CC = gcc
MKDIR_P = mkdir -p
OBJDIR = objdir
BINDIR = bindir
#list of objects
OBJS    = $(addprefix $(OBJDIR)/, $(CSOURCE:.c=.o))
#output name for executable
APP = example

all: ${OBJDIR} $(OBJS) bin

#rule to create bin and objects dir
${BINDIR}:
    ${MKDIR_P} ${BINDIR}

${OBJDIR}:
    ${MKDIR_P} ${OBJDIR}

#rule to compile c files
$(OBJDIR)/%.o: %.c
    $(CC) -c $< -o $@

#to create executable
bin: $(BINDIR) $(OBJS)
    $(CC) $(CFLAGS) $(OBJS) -o  $(BINDIR)/$(APP)

#to clean executable and objects
clean:
    rm -rf $(OBJS) $(BINDIR) $(OBJDIR)

A: Updated root make file, Use this in the root/ directory
WORKDIR = $(shell pwd)
MODULES = feature1 feature2
CSOURCE =  main.c
CSOURCE +=  func1.c
SRCDIR = .
vpath %.c $(SRCDIR)/
CC = gcc
MKDIR_P = mkdir -p
OBJDIR = $(WORKDIR)/objdir
BINDIR = $(WORKDIR)/bindir
OBJS    = $(addprefix $(OBJDIR)/, $(CSOURCE:.c=.o))
APP = example

all: ${OBJDIR} modules $(OBJS) bin

modules:
    for mod in $(MODULES); do \
      echo "Building $$mod ....."; \
      $(MAKE) -C $(WORKDIR)/$$mod all; \
    done

${BINDIR}:
    ${MKDIR_P} ${BINDIR}

${OBJDIR}:
    ${MKDIR_P} ${OBJDIR}

$(OBJDIR)/%.o: %.c
    $(CC) -c $< -o $@

bin: $(BINDIR) $(OBJS)
    $(CC) $(CFLAGS) $(OBJDIR)/*.o -o  $(BINDIR)/$(APP)

clean:
    rm -rf $(OBJS) $(BINDIR) $(OBJDIR)

feature make file, use this in the root/feature1 directory and root/feature2 directory
WORKDIR = $(shell cd ..; pwd)
CSOURCE =  func2.c
SRCDIR = .
vpath %.c $(SRCDIR)/
CC = gcc
MKDIR_P = mkdir -p
OBJDIR = $(WORKDIR)/objdir
OBJS    = $(addprefix $(OBJDIR)/, $(CSOURCE:.c=.o))

all: ${OBJDIR} $(OBJS)

${OBJDIR}:
    ${MKDIR_P} ${OBJDIR}

$(OBJDIR)/%.o: %.c
    $(CC) -c $< -o $@

clean:
    rm -rf $(OBJS) $(OBJDIR)

When you want to add new directory say feature3, you can just add it in main makefile module list and copy the feature1 makefile to feature3 and update source file list
Hope this helps


text:
Q: How to parse JSON in Swift 4 when root element is an array? Some context: reddit post
I have two structs. One is called bio that has fields such as name, bio, spotifyURL, etc. The other struct is called Artists which has one field, bios, an array of bio.
My JSON file has an array as the root element, with two elements (artists) inside it. The identifiers of the elements match up with the identifiers of the fields in the structs.
When I call:
let bioArray = try
   JSONDecoder().decode(Artists.self, from: data)

bioArray.bios is an empty array. Shouldn't this populate the array? The data was retrieved successfully, decode() just isn't doing what I think it should be doing. Thanks
EDIT: Wow, I fixed it. In Artists I had:
let bios:[bio] = []

I changed it to:
let bios:[bio]

and now it works...

A: Wow, I fixed it. In Artists I had:
let bios:[bio] = []

I changed it to:
let bios:[bio]

and now it works...
The answer is in the duplicate link but I'll put it here too:
To fix this either remove the initialization (like I did) or change the let to var.


text:
Q: how to set trendline dynamically in php fusioncharts I have already using the fusioncharts and i am getting the values from database.  I am searching for how to set the trendvalues for a line graph in fusion charts php. Actually i have to get the value from database and set the trendline. Is there any way to do it. I google a lot but i didnt find the answer.
Here is my code:

while ($row = mysql_fetch_array($result)) {
    $categories .= "<category name='" . $row["ondate"] . "' />";
    $systolic .= "<set  value='" . $row["systole_reading"] . "'  hoverText='Systolic' />";
    $diaolic .= "<set value='" . $row["diastole_reading"] . "'  hoverText='Diastolic'/>";
    $map.="<set value='" . $row["map"] . "' hoverText='Mean Arterial Pressure'/>";
    }
$strXML .=" <trendlines>
    <line startValue='".$row["target"]."'  color='ff0000' displayValue='Systolic Target'  showOnTop='1' valueOnRight = '1'/>
  </trendlines>";

TAI

ramsai

A: To set the TrendValues for a Line graph in PHP, you need to concatenate the XML string in the similar way, as you are doing for Data Points.
Ref. Code:
$strXML =" ";
while ($row = mysql_fetch_array($result)) {
 $categories .= "<category name='" . $row["ondate"] . "' />";
 $systolic .= "<set  value='" . $row["systole_reading"] . "'  hoverText='Systolic' />";
 $diaolic .= "<set value='" . $row["diastole_reading"] . "'  hoverText='Diastolic'/>";
 $map .="<set value='" . $row["map"] . "' hoverText='Mean Arterial Pressure'/>";
 $target .= "<line startValue='" . $row["target"] . "' color='ff0000' displayValue='Systolic Target' showOnTop='1' valueOnRight = '1'/>";
}

$strXML .= "<chart><categories>" . $categories . "</categories><dataset>" . $systolic . "</dataset><dataset>" . $diaolic . "</dataset><trendLines>" . $target . "</trendLines></chart>";


text:
Q: Error: ORA-00905: missing keyword I have this code:
select inventory.store_id as store_id,
       film.title as Titel_Film,
        count(film.film_id) as Anz_ausleihbar
from film
join inventory on film.film_id = inventory.film_id
join (select rental.inventory_id, rental.return_date
      from rental
      group by rental.inventory_id) as rental2
on rental2.inventory_id = inventory.inventory_id
where film.title like '%B'
and inventory.store_id = 1
group by film.film_id
order by inventory.store_id asc, film.title desc

I get the error Error: ORA-00905: missing keyword.
Thanks for you help!

A: change your GROUP BY to
GROUP BY store_id, Titel_Film

When using group by, you need to specify "group fields" for all fields not being summarised or aggregated.

A: *

*used a correlated subquery instead of an inline view to limit inventory based on the existence of a rental record.  Exists generally operates faster than in and if you need no data returned, faster than a join.  This also removed the as statement on the table alias.

*Eliminated Group by on inline view.

*Modified group by on outer query to include all non-aggregated fields from the select.

*shortened aliases

.
SELECT I.store_id as store_id
     , f.title as Titel_Film
     , count(f.film_id) as Anz_ausleihbar
FROM film
INNER JOIN inventory I
  ON f.film_id = I.film_id
WHERE f.title like '%B'
  AND i.store_id = 1
  AND exists (SELECT *
              FROM rental r2
              WHERE r2.inventory_ID = i.inventory_ID)
GROUP BY I.store_id
       , film.title
ORDER BY i.store_id asc, f.title desc


text:
Q: Creating an ansible-vault from ansible Can I create a ansible-vault file from within ansible? I am creating a deployment package for another server (to be run locally) from ansible and I want to encrypt sensitive data (the key itself is transferred over a different channel).
Does ansible-vault have a non-interactive mode to create a vault file? Or is there some ansible intrinsic way?

A: You can use the --vault-password-file option of ansible-vault for non-interactive vault file creation. The file passed in can be a text file containing the vault password, or it can be an executable script that retrieves and outputs the vault password.
You would call it like this:
ansible-vault --vault-password-file=vaultpass.txt encrypt sensitive_data.txt

If you would like to create the file on the fly, rather than copying over or encrypting an existing file, you can omit the filename from this command and pipe the data to STDIN:
echo "sensitive data" | ansible-vault --vault-password-file=vaultpass.txt encrypt --output outfile.txt


text:
Q: REST API response includes "This XML file does not appear..." I've created a REST API but when I call it with a GET, it returns this:
This XML file does not appear to have any style information associated with it. The document tree is shown below.

<ArrayOfgetSiteList xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Thor">
<getSiteList>
<responseCode>1</responseCode>
<responseMessage>No message</responseMessage>
<sites>
<Sites>
<siteAddress>11 Main Street054656</siteAddress>
<siteId>1</siteId>
<siteName>Sky Towers</siteName>
</Sites>
<Sites>
<siteAddress>1 Grande Street</siteAddress>
<siteId>2</siteId>
<siteName>Hotel Grande</siteName>
</Sites>
</sites>
</getSiteList>
</ArrayOfgetSiteList>

How do I get it to return just the JSON text within the square brackets, and not the "This XML file..." part? Are there some headers I am supposed to add to the response, and if so how/where do I add it?
Also, how do I get it to be formatted/indented nicely like http://echo.jsontest.com/key/value/mykey/myvalue/anotherkey/anothervalue?
Thanks for the help.

A: Instead of returning PartialView() you should return Json() as your ActionResult.
return Json(someItem,JsonRequestBehavior.AllowGet);


text:
Q: dual boot with windows 8 I have installed ubuntu 12.10 64-bit alonside windows8 64 bit. After installation I am unable to boot windows 8. I have tried the dvd repair for windows and it says couldn't fix the issue. I have used UEFI installation for both ubuntu and windows 8. I am using a dell vostro 2520  model laptop. Help please
sudo add-apt : it says the command not found. :(

A: A very simple answer would be to boot into the live CD/USB and run Boot Repair
Boot Repair PPA

*

*Boot into Live CD/USB.

*Type the following in terminal(one line at a time)
sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt-get update
sudo apt-get install -y boot-repair

*Run Boot Repair

Type in terminal
sudo boot-repair
or
type in Unity dash
Boot Repair

*Click the Recommended repair button

After the process is finished close everything.
This should solve your problem.

I have already answered a similar question here