Arrays and loops in Clojure

Question: I am trying to learn the programming language Clojure. I have a hard time understanding it though. I would like to try to implement something as simple as this (for example):
int[] array = new int[10];
array[0] =1;
int n = 10;

for(int i = 0; i <= n; i++){
    array[i] = 0;
}
return array[n];

Since I am new to Clojure, I don't even understand how to implement this. It would be super helpful if someone could explain or give a similar example of how arrays/for-loops works in Clojure. I've tried to do some research, but as for my understanding Clojure doesn't really have for-loops.
Comment: The code you want to translate is very strange. It contains a number of off-by-one errors that would result in a runtime error, attempting to read and write `array[10]`, which is out of bounds. Further, it initializes a whole array but then throw it away and return a single element. If you want to translate code, it will be easier if the code you are translating has clear features.
Answer: The Clojure way to write the Java for loop you wrote is to do consider why you're looping in the first place. There are many options for porting a Java loop to Clojure. Choosing among them depends on what your goal is.
Ways to Make Ten Zeroes
As Carcigenicate posted, if you need ten zeros in a collection, consider:
(repeat 10 0)

That returns a sequence – a lazy one. Sequences are one of Clojure's central abstractions. If instead the ten zeros need to be accessible by index, put them in a vector with:
(vec (repeat 10 0))

or
(into [] (repeat 10 0))

Or, you could just write the vector literal directly in your code:
[0 0 0 0 0 0 0 0 0 0]

And if you specifically need a Java array for some reason, then you can do that with to-array:
(to-array (repeat 10 0))

But remember the advice from the Clojure reference docs on Java interop:

Clojure supports the creation, reading and modification of Java arrays [but] it is recommended that you limit use of arrays to interop with Java libraries that require them as arguments or use them as return values.

Those docs list some functions for working with Java arrays primarily when they're required for Java interop or "to support mutation or higher performance operations". In nearly all cases Clojurists just use a vector.
Looping in Clojure
What if you're doing something other than producing ten zeros? The Clojure way to "loop" depends on what you need.
You may need recursion, for which Clojure has loop/recur:
(loop [x 10]
  (when-not (= x 0)
    (recur (- x 2))))

You may need to calculate a value for every value in some collection(s):
(for [x coll])
  (calculate-y x))

You might need to iterate over multiple collections, similar to nested loops in Java:
(for [x ['a 'b 'c]
      y [1 2 3]]
  (foo x y))

If you just need to produce a side effect some number of times, repeatedly is your jam:
(repeatedly 10 some-fn)

If you need to produce a side effect for each value in a collection, try doseq:
(doseq [x coll]
  (do-some-side-effect! x))

If you need to produce a side effect for a range of integers, you could use doseq like this:
(doseq [x (range 10)]
  (do-something! x))

...but dotimes is like doseq with a built-in range:
(dotimes [x 9]
  (do-something! x))

Even more common than those loopy constructs are Clojure functions which produce a value for every element in a collection, such as map and its relatives, or which iterate over collections either for special purposes (like filter and remove) or to create some new value or collection (like reduce).
Answer: I think that last point in @Lee's answer should be heavily emphasized.
Unless you absolutely need arrays for performance reasons, you should really be using vectors here. That entire chunk of code suddenly becomes trivial once you start using native Clojure structures:
; Create 10 0s, then put them in a vector
(vec (repeat 10 0))

You can even skip the call to vec  if you're ok using a lazy sequence instead of a strict vector.
It should also be noted though that pre-initializing the elements to 0 is unnecessary. Unlike arrays, vectors are variable length; they can be added to and expanded after creation. It's much cleaner to just have an empty vector and add elements to it as needed.
Answer: You can create and modify arrays in clojure, your example would look like:
(defn example []
  (let [arr (int-array 10)
        n 10]
    (aset arr 0 1)
    (doseq [i (range (inc n))]
      (aset arr i 0))
    (aget arr n)))

Be aware that this example will throw an exception since array[i] is out of bounds when i = 10.
You will usually use vectors in preference to arrays since they are immutable.
Comment: Bear in mind that this approach, although better for performance, is not exactly idiomatic Clojure for day to day use. @Carcigenicate's example is far more like normal Clojure. We deal with transformations of immutable values, that's why there aren't really many looping constructs. In Clojure you compose functions such as map and filter to reach your result. It's a real shift in thinking, but it's interesting! :D
Comment: Oh nice!! Thank you so much!! I will definitely try this. Is it possible to create an array without defining it's size as well?
Comment: @Anna - arrays are fixed-length containers so you have to specify the size on creation. If you want a variable-sized container you can use clojure's `vector` or `list` types, or Java's `ArrayList`.
Answer: You can get a good start here:

Brave Clojure
The Clojure CheatSheet
Comment: Thanks for the tip! I've already looked at the CheatSheet but will take a look at Brave Clojure also :)

Arrays and loops in Clojure


break away from a controller action

Question: My question is if there is a rails equivalent to 'breaking' away from a controller action such as
def new
    if some_confirmation
        do_stuff
        break #I know this only breaks out of a loop but I want it to break out of the action. is this possible?
    end
    do_some_other_stuff_which_it_should_not_reach_after_breaking
end

Also this raises the question if I'm doing something wrong and shouldn't be rather doing it with a before_filter
Also last question, is it better to enclose everything in a 'if-else'-statement in such definitions (not necessarily controller actions but also normal definitions) or do it like the way I intend to do up there ^?
Answer: The answer is to use return. Controller actions are just methods and return is how you return early from a method. There's nothing wrong with doing this and you should feel free to do so as needed.
You can use before_filters (which has been renamed to before_action in Rails 4), as you mention, but I recommend only doing this if every method in the controller requires the condition. Otherwise, you end up with a huge list of before_actions at the top that you have to keep in mind (or be surprised by) while reading the actions later; and it gets especially confusing if you have to keep in mind which ones apply and which ones don't for which actions!
Whether or not if-else statements are preferred is a bit of an opinion... but, inspired by Avdi Grimm's excellent book Confident Ruby, I recommend to do as you've done here... what you've set up is essentially a guard clause whereby you take care of exiting the method early up front, and then you get into the actual meat of the method. In Confident Ruby, Avdi Grimm talks about breaking methods up into logical parts to tell a coherent story that doesn't force readers to keep track of various states throughout the life of the method. Using an if-else statement tends to force readers to keep track of state, whereas using guard clauses allows you to quickly identify conditions to leave the method via and then forget about them so you can focus on the actual purpose of the method.
Comment: Thank you, that was exactly what I needed and also very informative!

break away from a controller action


Uniform convergence of the series $\sum_{n=1}^{\infty} \frac{z^n}{n}.$

Question: How to check uniform convergence of the series  $\sum_{n=1}^{\infty} \frac{z^n}{n} $ on $|z|<1.$ Clearly it is power series with radius of convergence as $1$  and power series converges in any compact subset of its domain of convergence on $|z|<1$. How to check its uniform convergence? $M_{n}$ test is not working here. Thanks.
Comment: See proposition 3.1 in this book: https://books.google.com/books?id=xUHDAgAAQBAJ&printsec=frontcover&dq=cartan+elementary+theory+of+analytic+functions&hl=en&sa=X&ved=0ahUKEwjQjLSVlsTPAhXMbz4KHULjCgcQ6AEIHjAA#v=onepage&q=normally&f=false
Comment: ok i will look it...thanks..
Answer: If there was uniform convergence on the open unit disk, then we would have
$$\lim_{N\to +\infty}a_N\mbox{ where }a_N :=\sup_{|z|\lt 1}\left|\sum_{n=N +1}^{2N}z^n/n\right|. $$
We have the bounds
$$a_N\geqslant \sup_{0\lt t\lt 1}\sum_{n=N+1}^{2N}t^n/n\geqslant  \sup_{0\lt t\lt 1}t^{2N}/2  =1/2        $$
since the sequence $\left(t^n/n\right)_{n\geqslant 1}$ is decreasing.
Comment: What is here $t $?


Cluster-robust standard errors in panel data analysis

Question: In a simple panel data analysis with data on 64 firms over 8 years, I use cluster-robust standard errors (at the firm level) to evaluate significance of coefficients. I observe important differences between clustered and non-clustered standard errors.
1) Does these differences necessarily mean that there is indeed serial correlations at the firm level in my data?
2) How could I test for serial correlation at the firm level to evaluate whether clustered standard errors are needed?
3) Say we observe that there is no serial correlation at the firm level, what is the impact of using clustered standard errors instead of non-clustered standard errors?
Answer: If, for each firm, time periods are independent then cluster-robust standard errors and standard errors without clustering will estimate the same thing (the same population standard deviation), but will use different strategies to do so.
The standard errors without clustering will use more information (they don't have to infer that auto-correlations are zero from the data) and are expected to be a slightly better estimator. For large panels this will not make much of a difference but $N = 64$ is fairly small.

No, as explained some differences are expected. There may be a statistical test to explore this more formally. In practice, if differences between the two standard errors are observed, then one just uses the robust version. It is applicable under a larger set of models (this is what "robust" means in this context), and the "statistical cost" of choosing it over the alternative is very small.
Testing this is hard for two reasons

Your time series is very short. Too short.
Tests for auto-correlation look for specific forms of auto-correlation. Even if you could rule one form of auto-correlation (say AR-1), other forms may still be present.

Not much, as explained above you are still estimating the correct standard deviation. You are doing so in a slightly less efficient way but that shouldn't matter much (it will not matter at all if your panel is  very large).

If you are wondering whether you should cluster: you probably should.
Comment: Great answer, thank you very much. I have read that with few clusters, using cluster-robust SE can actually not be the proper solution. Is 64 considered a sufficient number of clusters to use cluster-robust SE?


Switching nodes no refresh AJAX

Question: What I have is a view that shows couple of nodes of type "product", they are related by an SKU ID.
What I'm trying to achieve is a way to switch between those related product produced by the view without refreshing the page.
Checking "Use Ajax" in my view did not achieve what I want.
Thanks,
Answer: i have developed module ajax_links_api which help you to load any drupal page to a specified div with help of JQuery Ajax.
in your tpl =>
<code>    <?php  l_ajax($title, $path, $target)  ?>
</code>
$title: Title.
$path : Drupal path.
$target (optional): ID or CLASS of DIV to be replaced. Default value is .region-content, you can change default value in admin page 'admin/settings/ajax_links_api'
Example :
<code><?php l_ajax("Load node 1", "node/1", ".region-content") ?>
</code>
Hope you can use this for this case

Switching nodes no refresh AJAX


How to display the size of a mailbox in imapsync (without migrating it)?

Question: I only want to calculate how much space the mailbox has, I don't want to migrate. Is there a way to know the space with imapsync?
Thank you.
Comment: Why do you specifically want to use imapsync to do this?
Answer: Use --justfoldersizes and the same account as source and destination.
https://imapsync.lamiral.info/FAQ.d/FAQ.Folders_Sizes.txt
<code>=======================================================================
Q. How can I know the size of all folders before launching a sync?

R. Use --justfoldersizes option.

With the --justfoldersizes option, imapsync evaluates and displays the
folders sizes on both sides and then exits without doing any transfer.
Example:

  imapsync ... --justfoldersizes

=======================================================================
</code>


Given an unsorted array of integers, all two elements of the array that sum to the value x. You must use a stack or a queue

Question: I have thought about it over and over but I can't figure out how a Stack or a Queue would be of any use in this case. Note that the use of a stack or queue is required... Please help!
Edit: I forgot to mention what the output should look like. Here is sample output:
All 2-Elements adding to 100 in the array are:
Indices 0 & 3 with values 20 & 80
Indices 3 & 6 with values 80 & 20
Indices 3 & 12 with values 80 & 20
Indices 4 & 5 with values 30 & 70
etc.

Comment: Then don't use a stack or queue. Your requirements are unrealistic.
Comment: It's a homework question. I've been stuck on it for days and it's due tonight :(
Comment: Does your instructor approve of plagiarizing solutions/ideas from the internet?
Comment: I'm not stealing someone else's work without permission, I'm asking for help. There's a difference.
Answer: Something like this? (not the most effective way to solve the problem in question, obviously; e.g. putting all elements into a hash, then iterating over that hash and checking for every a[i] if the hash contains x-a[i] is supposed to be faster)
(assumptions: stack supports 2 operations:

push - adding elements on top of the stack
top - getting the value of the element on top of the stack without removing it from the stack)

a = input_array

l = list // list of pairs

s = stack

for i from 0 to length(a)-2:

  s.push(a[i])

  for j from i+1 to length(a)-1:

      if s.top + a[j]==x:

          l.add(pair(s.top,a[j]))

return l

Comment: Wouldn't I have to pop the elements in the stack in the if/else for this to work?
Comment: they are pushed into the stack in the outer cycle. in the if-else you only check what's on top of the stack.


Should I remove co-varying factors before clustering?

Question: I have a data set of around 850 factors representing 150 geographical areas. I am looking to cluster these geographical areas, and I am intending to use a K-means clustering algorithm to do this. My exploratory analysis (plotting heatmaps, example below) has suggested there are quite a few of these factors that co-vary. Should I remove these co-varying factors before clustering? If so, what threshold is standard, and is there any standard method for deciding which factor to remove? I am trying to do this in python with scikit, so any pointers in this direction would be helpful.
Answer: I would rather try to weight them appropriately.
I don't think you can compute the "correct" weights. Just like the scaling they are all equally valid, it is a choice of the user how to weight factors. But of course you should take redundancy into account when weighting factors.
But consider, for example, population and GDP. They are probably highly correlated. You don't want to remove either. However, for data analysis, it is more meaningful to use GDP per capita instead, i.e., normalize and preprocess the data differently.
Furthermore, you will have to carefully do the weighting anyway, because clustering - in particular k-means - is very sensitive to scaling of variables.


Standard deviation of symmetric data

Question: Within my field a recent study suggested to use the symmetric properties of certain image datasets to improve signal to noise ratio (SNR). I will spare you the details, but in the end one can get a symmetric dataset (as described below) with improved SNR. However the way that one typically computes SNR is to compare the "amount of signal" (sum of the pixels in the central region, more or less), to the overall standard deviation (std).
The properties of the symmetrized data are such that if one computes the std over the entire image (in a standard way), std is indeed lower than in the original image, leading to the improved SNR.
However I am bit skeptical regarding the fact that one should compute the std in the same way as in a "normal image". Indeed, here we have an image with identical pixels according to certain symmetries (around central vertical axis, horizontal vertical axis, both diagonals, and [$\pi/2$] rotations). Many pixels are hence correlated, and I am not sure that simply computing the std across the whole map is a fair assessment of the SNR.
The question is: how do I compute the standard deviation from such a dataset? Should I take into account the fact that many pixels are not independent (correlated)? How?
example symmetric data set (don't mind the central black circle):
https://i.stack.imgur.com/TzlAS.png
Comment: Welcome to [math.se] SE. Take a [tour]. You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit]): What you understand about the problem, what you've tried so far, *etc.*; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Comment: do you know what are the symmetries of images? are they the same across different images?
Answer: The short answer is that it should be Ok to use SNR as you described in certain case as explained below.
Consider this: the simplest way to improve the example image knowing its symmetry would be to calculate the average on 8 repeating slices. One slice goes from the center to the right horizontally and from the center to upper right corner at 45 degrees. So you stack up all 8 slices, and create a new slice whose pixels are average across 8 slices, then create a new image by repeating this new slice 8 times. The resulting image should have lower noise.
The way you defined the noise includes two components: complexity of an image and bona fide noise. If your image was a simple white noise, then the contribution from the complexity would be zero. In your case there's some structure in the background, which contributes to the noise. By using the symmetry, we reduce noise coming from the bona fide noise, and not the complexity of the background.
So, the simple standard deviation of the whole image will reflect the reduction of bona fide noise after image processing. Hence, it seems to me it's an acceptable metric to compare images with the same symmetric background. If the backgrounds are different, then this metric would not account for the complexity of the background. Whether you need to account for this or not depends on your goals.
In your image the symmetry group is probably $D_2$.  This is a very interesting question indeed.
background of the signal
If I had to account for the background of the image, then something like Kernel density could be used to extract the background on the slice. Then I'd calculate the noise over the background and use it to get stdev. This way we could compare noise between images of different background complexity.
Consider the variance equation: $$\frac 1 n \sum_i(x_i-\bar x)^2$$
Instead of using a global average $\bar x$, we'll calculate the local average $\mu_i$, perhaps, using Kernel density estimators such as $$\mu_i=\sum_j K(x_i-x_j)x_j$$
Then the local variance would be $$\frac 1 n \sum_i(x_i-\mu_i)^2$$
This equation excludes the complexity of the background that is represented with smoothed pixels $\mu_i$, and makes it possible to fairly compare images of different backgrounds.

Standard deviation of symmetric data


Partial Derivative Question Relating to Chemistry

Question: The Ideal Gas Law PV=nrT shows the relationship between pressure P, volume V, and temperature T of a gas, where n is the number of moles of the gas and r is the universal gas constant. Prove \begin{equation}
\frac{\partial V}{\partial T} \times \frac{\partial T}{\partial P} \times \frac{\partial P}{\partial V} = -1
\end{equation}
Answer: The functions you are considering are the following:
$$V(T,P) =  \frac{nrT}{P}, \quad T(V,P) = \frac{PV}{nr}, \quad P(V,T) = \frac{nrT}{V}. $$
This implies
$$\frac{\partial V}{\partial T} =\frac{nr}{P}, \quad \frac{\partial T}{\partial P} =\frac{V}{nr}, \quad \frac{\partial P}{\partial V} = -\frac{nrT}{V^2}. $$
Multiplying these three quantities you get
$$\frac{\partial V}{\partial T} \frac{\partial T}{\partial P} \frac{\partial P}{\partial V} = -\frac{nrT}{PV} = -1.$$


Which texts to study mathematical logic, for subsequently studying Godel's incompleteness theorems?

Question: I want to study Godel's incompleteness theorems and I look for a text which provide mathematical logic with a nice way to make me able to study Godel's incompleteness theorems
I didn't study mathematical logic before. some people recommended Rene Cori and Daniel lascar text. what do you think ?
Comment: I _almost_ feel like preempting Peter Smith and recommending his book, [_An Introduction to Gödel's Theorems_](http://www.logicmatters.net/igt/), whose second edition is forthcoming.  But I won't.
Answer: Well, how can I resist? My Introduction to Gödel's Theorems (CUP, 2007; second edition forthcoming in March 2013) was written precisely for those with little prior background in mathematical logic, and aims to be very accessible while actually giving the main proofs in quite a bit of detail.
Other options that range a bit more widely into logic and the theory of computation include George Boolos and Richard C. Jeffrey, Computability and Logic (CUP, 3rd edn 1989: there are expanded later editions with John Burgess as a third author, but these are arguably less elegantly done). Richard L. Epstein and Walter Carnielli's very nice Computability also discusses
computation in general before covering the incompleteness theorems; this
is attractively written with a lot of interesting historical asides.
Comment: I realise that my comment above may be taken as a slight directed at you: be assured that no slight was intended. I greatly appreciate that you share your insight on many logical matters here on math.SE.
Comment: Oh no worries, @ArthurFischer, it made me smile and I took it in the spirit intended!
Comment: thank you prof Peter Smith , I read the content , and found it Great ! it cover also turing machines and many subjects , it's a great text I think " I know little about turing general machine from prof Roger Penrose book " mind , computer and the laws of physics "  "

I read  that your intro text is for philosophy students and first semester undergrad students in maths ,
Comment: is there other text can I use as a intro text to mathematical logic and enable me to study godel's theorems in more detail later ?

what do you think about Rene Cori and Daniel lascar text ?
is it good ? do you recommend it also to study mathematical logic ?
or other text ?
Comment: @MathsLover There's a lot of reading advice at http://www.logicmatters.net/students/tyl/
Answer: I would like to recommend A First Course in Logic: An Introduction to Model Theory, Proof Theory, Computability, and Complexity. I am in a similar position as yourself, though probably a week ahead, as in without a prior background in symbolic Logic but curious to learn Godel's incompleteness theorem's. I started with this book last week. I am finding it to be a rigrous and pleasurable exposition.
Answer: This is not a complete answer, but: If you are just getting started and you are particularly interested in Gödel's Theorems, then I can recommend Gödel's Proof by Nagel and Newman as a gentle introduction. The nice thing about this book is that it is relatively short and not too technical.
Comment: in the truth , I look for a technical way , that means , i look for a good introduction to mathematical logic which make me able to study godel's theorems :) ,
Comment: @MathsLover: In that case, the book will not be the best, but since you wrote that you have not studied mathematical logic before, it might (might not) be helpful to start with a gentle introduction. The book actually outlines the proof, so when you get another book with the details, you will already know a bit about the ideas behind the arguments. It is very easy to get lost in technicalities.
Answer: I learned logic from "Mathematical Logic," by Kleene. It starts from the basics and then goes into Godel's theorems. It's a very solid book, with plenty of examples.


scala : it is impossible to put a tuple as a function's argument

Question: I can't pass a tuple as a method parameter:
scala> val c:Stream[(Int,Int,Int)]= Stream.iterate((1, 0, 1))((a:Int,b:Int,c:Int) => (b,c,a+b))
<console>:11: error: type mismatch;
 found   : (Int, Int, Int) => (Int, Int, Int)
 required: ((Int, Int, Int)) => (Int, Int, Int)

thanks.
Answer: Just as the function literal:
(x:Int) => x + 1

is a function of one argument, the following
(x:Int, y: Int, z: Int) => x + y + z

is a function of three arguments, not one argument of a 3tuple
You can make this work neatly using a case statement:
scala> val c: Stream[(Int,Int,Int)] =
       Stream.iterate((1, 0, 1)){ case (a, b, c) => (b, c, a+b) }

c: Stream[(Int, Int, Int)] = Stream((1,0,1), ?)

An alternative is to pass the tuple, but that's really ugly due to all the _1 accessors:
scala> val c:Stream[(Int,Int,Int)] =
         Stream.iterate((1, 0, 1))( t => (t._2, t._3, t._1 + t._2) )

c: Stream[(Int, Int, Int)] = Stream((1,0,1), ?)

Comment: it works, thank you. In fact I tried something like this (the use of case) but I did not put the case between curly brackets. Why simple brackets do not work?
Comment: @lolveley Because `case` is not a `simple expression`, which is all that is allowed inside `()` argument lists
Comment: Another issue with `case` is you could get runtime errors if your types or number of arguments get out of sync. :(
Comment: In some contexts, yes - but here the Stream is already constrained to `(Int,Int,Int)` so `case` will always succeed
Answer: The lambda (a:Int,b:Int,c:Int) => (b,c,a+b) is a function taking three arguments. You want it to take one tuple, so you can write ((a:Int,b:Int,c:Int)) => (b,c,a+b). But this gives an error!
error: not a legal formal parameter.
Note: Tuples cannot be directly destructured in method or function parameters.
      Either create a single parameter accepting the Tuple3,
      or consider a pattern matching anonymous function: `{ case (param1, ..., param3) => ... }
       (((a:Int,b:Int,c:Int)) => (b,c,a+b))
         ^

Luckily, the error suggests a solution: { case (a, b, c) => (b, c, a+b) }
Answer: It is also possible to use the tupled option:
def a = (x:Int, y: Int, z: Int) => x + y + z).tupled
val sum = a((1,2,3))

Answer: My guess is that the expression (a:Int,b:Int,c:Int) => (b,c,a+b) defines a lambda with three arguments, and you need one decomposed argument.


Every deployment to Heroku displays different errors

Question: These are my configuration files:
build.properties
sbt.version=0.13.0

Build.sbt
libraryDependencies += "org.scalatest" % "scalatest_2.10" % "2.0" % "test"

libraryDependencies += "org.seleniumhq.selenium" % "selenium-java" % "2.39.0" % "test"

libraryDependencies += "org.mockito" % "mockito-all" % "1.9.5"

resolvers += Classpaths.typesafeResolver

Build.scala
import sbt._
import Keys._
import play.Project._

object ApplicationBuild extends Build {

  val appName         = "library"
  val appVersion      = "1.0-SNAPSHOT"

  val appDependencies = Seq(
    // Add your project dependencies here,
    jdbc,
    anorm,
    cache,
    "postgresql" % "postgresql" % "9.1-901.jdbc4"
  )

  val main = play.Project(appName, appVersion, appDependencies).settings(
    javaOptions in Test += "-Dconfig.file=conf/test.conf"
  )

}

You can see from these samples, the first and second deployment logs, that it always throws different errors everytime I do git push to heroku.
The errors are always somewhere along these lines:

[warn]   ::::::::::::::::::::::::::::::::::::::::::::::
  sbt.ResolveException: download failed: com.typesafe#config;1.0.2!config.jar(bundle)

or

:::: ERRORS
  SERVER ERROR: Service Unavailable url=http://s3pository.heroku.com/ivy-typesafe-releases/org.scala-sbt/main/0.13.0/ivys/ivy.xml

Any idea what's happening and possible workaround?
Comment: looks like their local cache is failing. You might want to ping them if this is a production issue.
Comment: Just to confirm it: exactly the same happens to me, when I try to deploy my app (same sbt-version, different libraries...). Right now I do not have a solution, but I will keep trying...
Comment: Thank you for the reponse, wheaties. They're looking into it now.
Answer: The problem has been resolved after Heroku support looks into it. They had some issues with S3pository which is their service that helps serve build dependencies.


O que significa Assets?

Question: Trabalho há muito tempo com frameworks MVC em PHP, tais como Symfony, Laravel e Codeigniter.
Geralmente, quando se trata da estrutura de views, sempre há funcionalidades para facilitar a inclusão de arquivos como CSS e Javascript. Geralmente, são funções ou classes chamada assets que fazem esse trabalho.
Embora tenha entendido quais são as funcionaldades dessa funções, eu não entendo o significado da palavra assets. Eu traduzi essa palavra no Google Translate e o resultado foi "ativos".
Gostaria de saber se essa palavra assets é um termo específico da estrutura MVC, ou da programação no geral.
Assets se trata de um padrão ou apenas um termo?
Comment: Esta pergunta quase poderia estar no SOpt e no PL ao mesmo tempo :)
Comment: [O que é Assets?](http://tableless.com.br/workflow-para-cuidar-dos-seus-assets/)
Comment: As pessoas que deram downvote poderiam deixar um esclarecimento para auxiliar a melhorar a pergunta? Existe algum problema com a minha pergunta?
Answer: O termo asset é apenas uma palavra utilizada com um "contexto" um pouco diferente do normal no inglês.
Asset significa: ativo.
Mas é uma referência de ativo relacionado à bens.
Veja:

Liquid assets can be sold more quickly
(Ativos líquidos podem ser vendidos mais rapidamente)
Assets held by the company in Asia
(Ativos retidos pela empresa na Ásia)
The business disposed of all its capital assets
(A empresa eliminou todos seus bens de capital)
He transferred all his assets into his wife's name
(Ele transferiu todos os seus bens para o nome de sua mulher)
The courts can order a company's assets to be frozen
(Os tribunais podem ordenar que os bens de uma empresa sejam congelados)

Em tecnologia a resposta se vem ao fato dos seus "assets" serem os recursos do seu projeto. O seu "banco" de bibliotecas.
No caso pode-se dizer que o termo é mais uma adaptação da palavra do contexto do inglês para os projetos em si.
Pode complementar sua leitura com este link.
Answer: Asset é um ativo, é um bem. Mesmo em software ele é assim. Asset é usado para designar itens que alguma entidade possui. Um bem não precisa ser tangível, então a tradução literal sem contexto já cabe quando falamos de software.
Claro que podemos definir melhor o que é um asset quando usamos no contexto de software. E pode ter até contextos mais específicos como o de um projeto, que pode ser de software, mas parece que não é o que deseja saber. Também pode ser uado em TI de forma geral no sentido mais normal de bens de uma corporação.
No software em si um asset é um recurso, é um item necessário para que o software funcione.
Um executável pode ser um asset. Mas geralmente usa-se mais o termo para penduricalhos que vão em volta dele. Podem ser arquivos necessários para o funcionamento da aplicação. E vão junto com ela para fazer o deploy (que pode ser uma instalação).
Em projetos mais soltos, especialmente web, o termo é muito usado e podem ser as imagens, e outros arquivos. É comum ver as pessoas tratando alguns tipos de arquivo como não sendo assets, mas estritamente eles são.
O que verá em projetos web é que alguns tipos são classificados assim e podem estar em uma pasta com esse nome. Nenhum problema usar o termo de forma um pouco variada, desde que todo mundo entenda assim. Então no contexto da pergunta um asset é um arquivo adicional aos arquivos que são consideramos principais do conteúdo, que pode ser HTML puro ou que sejam processados por alguma linguagem, como o PHP por exemplo, e gere o HTML final. Nesses casos não é incomum que até as imagens não entrem como assets. Portanto o termo pode ser sido usado para indicar que é algo que não seja o conteúdo principal de texto e imagens. E de fato ele é usado basicamente no contexto de views.
Ele é só um termo e não está vinculado a nada especificamente. Nunca vi algo que diz que o MVC tenha que ter assets, ele fala da relação dos seus componentes principais indicados pela sigla. E aí temos que fazer uma distinção do MVC web que as pessoas usam que é algo diferente do MVCV original, mas é outro assunto. Você pode fazer MVC sem assets explícitos, embora eles estejam lá de alguma forma.
Alguns frameworks incorporaram o termo para organizar sua estrutura básica, conforme citado na pergunta. Poderiam ter usado outro termo ou organizado de outra forma que funcionaria do mesmo jeito.
É só um nome que alguém deu para alguns arquivos para facilitar a comunicação, não é algo tão relevante assim. E pode ter significados ligeiramente diferentes dependendo de quem fala. Eu entendo que tem alguma vantagem, mas acho ela dispensável na forma que costumam usar. Poderia ser melhor em projetos muito complexos. Espera, MVC só deveria ser usado em projetos muito complexos... :)

O que significa Assets?


Where is the parent/child relationship between nodes stored in the database?

Question: I am migrating a site from one CMS to Drupal and I'm working on migrating link structures over correctly. This is something I am going to have to automate because there are over 3,500 nodes of content that I am migrating over.
I can't seem to find in Drupal 8's database schema where the relationship between parent and children nodes are stored. I have been looking for something like a 'pid' or a 'cid' column (parent id and child id, respectively), but I can't seem to find a column like that in the schema.
I know you can make nodes children of other nodes, so I know it has to store this information somewhere. If someone could tell me what table and column this information gets stored in I would greatly appreciate that.
Drupal 8 Database Schema
Answer: The simple answer is, there is none.
Nodes in Drupal does not have a hierarchy, it's other things on top of it that allow you to do that, depending on the use case:
Menu links: You can have menu trees and each points to a node, but the nodes themself don't really about that. Some parts might look like it does, e.g. breadcrumb but that is simply based on the path.
Book module: This allows to create a book (basically a hierarchic structure of nodes), but this only makes sense for specific cases, e.g. structured documentation that has chapters and so on.
References: In many cases, nodes are just connected between each other with reference fields, which you could make look like a hierarchy.
Taxonomy: You can have Terms with a hierarchy and reference those from nodes, but again by default that doesn't give you anything hierarchy-like unless you start to combine with with path aliases or so.
=> Content in Drupal is very different from how most other sites handle it and you can't just convert it 1:1.
Answer: What you are looking for is the EntityReferenceField.
To understand more its behavior:

Create a content type ('MyTest')
Add a ContentReferenceField (EntityReferenceField on nodes). It machine name could be for example field_my_reference.
Choose whatever bundle you want a reference to.
Create a 'MyTest' element, and add a reference.

Now go to PHPMyAdmin or similar, and start type in the autocomplete field the following:
node__field_my_reference
Then you can see the table scheme, and how referencing in the Drupal works in general. There are two main columns:

"entity_id" - that is the host entity which has the reference field
And the last column of the table "..._target_id", that's the ID to which entity it is referring too

That being said, I don't recommend you to do this by "hand". I mean writing SQL queries with exact table names.
Instead, use Drupal EntityTypeManager when setting up relationships between two entities (one must have of course an EntityReferenceField).
More on that, how to do that programmatically read this.


Translate from English to first-order logic: There is somebody who likes everyone who likes John

Question: Translate from English to first-order logic: There is somebody who likes everyone who likes John
I'm not sure about the answer. What I'm thinking is $(∃x)(L(x,y)∧L(x,J))$
Comment: I'm assuming $L(x,y)$ means $x$ likes $y$.

Reading your thought to myself, I read: "There is somebody ($x$) who likes $y$ and who likes $J$."
Answer: $$(\exists x)(\forall y)(L(y,J)\rightarrow L(x,y))$$
Translation:
There exists $x$ such that if $y$ likes John, then $x$ likes $y$.
Comment: Don't you mean $(\exists x)(\forall y)(L(y,J)\to L(x,y))$? The way you wrote it, $y$ is a free variable.
Comment: I guess I assumed that an unquantified variable not specified as constant was automatically quantfified, by default, with "for all". But I'll edit my answer to make that explicit. Thanks.
Comment: Wouldn't the default be $(\forall y)(\exists x)(L(y,J)\to L(x,y))$?
Comment: I guess so, so the edit was _necessary_, else the default order would yield the wrong meaning. Thanks again.
Answer: The English language is not logically precise, so the sentence has two (possible more) interpretations. The first, as given by @quasi, is "there is somebody who likes (everybody who likes John)", and has the translation $(\exists x)(\forall y)(L(y,J)\rightarrow L(x,y))$. The second is "there is (somebody who likes everybody) who likes John", which has the translation $(\exists x)[(\forall y(L(x,y)))\,\land\,L(x,J)]$. Here $L(a,b)$ means $a$ likes $b$.
(The first is probably the intended meaning, because if somebody liked everyone, they would surely like John. I'm just pointing out an interpretation closer to what you were originally thinking.)
Comment: Thank you. The second answer is what I originally thinking. I was not sure how to translate it correctly. I agree with you that the first translation might be the intended meaning.
Comment: @Haley_Q You're welcome! If you like my answer, please upvote it (the up arrow) and accept it if it answers your question.
Comment: For the first interpretation, do you really want $y$ to be a free variable, or did you miss out a $\forall y$?
Comment: @bof Thanks, fixed it.
Answer: There is some person who likes everyone who likes John. So, there is some person $x$ who likes all people $y$ who satisfy the condition that $y$ likes John.  So, there exists a person $x$ such that for all $y$, if $y$ likes John then $x$ likes $y$. We have the expression: $\exists x, \forall y (L(y,J) \implies L(x,y))$.


Linq to SQL 'Select Where' Problem (WPF C# 4.0)

Question: I used linq to sql many times its work correctly but today something wrong
this is code which must select password from users table.
I call this method tell wright... result is not password please see picture.
public void GetPassword(int id)
    {
        using (HProDataContext db = new HProDataContext())
        {
            _CurrentPassword = (from p in db.users
                                    where p.id == _CurrentID
                                    select p.password).ToString();
        }
    }

this how i use this method
private void btnOK_Click(object sender, RoutedEventArgs e)
    {
        if (listView1.SelectedItems.Count < 1)
        {
            MessageBox.Show("Please Select User");
        }
        else if (listView1.SelectedItems.Count > 1)
        {
            MessageBox.Show("Please Select Only One User");
        }
        else
        {
            _CurrentID = Convert.ToInt32(listView1.SelectedValue);
            GetPassword(_CurrentID);

            if (PasswordBox.Password == _CurrentPassword)
            {
                MessageBox.Show("You r in");
            }
            else
            {
                //MessageBox.Show("Password Is incorrect, please try again");
                MessageBox.Show(_CurrentPassword);
            }

        }

    }

Answer: You are missing a SingleOrDefault call or a call to Single, First or FirstOrDefault:
_CurrentPassword = (from p in db.users
                    where p.id == _CurrentID
                    select p.password).Single().ToString();

Explanation: Your query returns an IEnumerable<string> even if there is only one item returned. You first need to get that item, before you can make a sensible call to ToString(). BTW: I think the call to ToString() is not needed, because p.password already should be a string.
Answer: It looks like you're doing ToString() on the LINQ expression, not the password.  Can you try removing .ToString() in GetPassword?
Also, as someone else pointed out, you need to select a single value from the enumerable -- SingleOrDefault() should do the trick.
Answer: The result of the expression:
from p in db.users
  where p.id == _CurrentID
  select p.password

is IQueryable<string>, not string (assuming p.password is a string). Use .First() or other method to just select a single element from the queryable collection.
Answer: What you are doing is to convert what is inside the linq query to a string, not the result of the query.You can
try
_CurrentPassword = (from p in db.users
                    where p.id == _CurrentID
                    select p.password).FirstOrDefault().ToString();

or
_CurrentPassword = (from p in db.users
                    where p.id == _CurrentID
                    select p.password).SingleOrDefault().ToString();

Please refer to these questions and answers to choose between Single(), SingleOrDefault(), First(), FirstOrDefault().
When to use .First and when to use .FirstOrDefault with LINQ?
and
LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria


Expected value of betting gains (de Finetti)/ Law of Total Probability

Question: Reading de Finetti's "Foresight", there is an issue I would like to clarify:
We have $n$ mutually exclusive events, $E_1, E_2, \dots, E_n$, that we believe to occur with probability $p_1, p_2, \dots, p_n$ respectively. Now we want to bet on those events, so if for example $E_1$ materialized and the others not, we would make a gain of $(1-p_1)S_1 - p_2S_2 - \dots -p_nS : = G_1$, that is we wager $p_1S_1 + p_2S_2+ \dots + p_nS_n$ to win either $S_1, S_2$, or $S_n$.
This gives a system of linear equations, with the determinant of the coefficient matrix necessarily equal to zero. Otherwise, we could construct a Dutch Book.
$$ \begin{vmatrix}
1-p_1 & -p_2 & -p_3 &\dots & -p_n \\
-p_1 & 1-p_2 & -p_3 & \dots & p_n \\
\vdots &  \vdots & \vdots & & \vdots \\
-p_1 & -p_2 & -p_3 & \dots & 1-p_n
\end{vmatrix} = 1 - \sum_{i = 1}^n p_i = 0
$$
De Finetti now claims that, if the determinant is equal to $0$, the expected value of the gains is equal to $0$, or $\sum_{i=1}^n p_iG_i = 0$. I verified the result for the first three dimensions, but have failed to generalize it so far.
Any input would be highly appreciated!
Answer: Although this can be done by simplifying the double summation, it might be more revealing to do the algebra with matrix notation.
Let $p=(p_1,p_2,\ldots, p_n)^\prime$, $S=(S_1,S_,\ldots, S_n)^\prime$, and $G=(G_1,G_2,\ldots,G_n)^\prime$ represent the information as column vectors. Write $\mathbf{1}=(1,1,\ldots, 1)^\prime$ and let $\mathbb{I}_n$ be the $n \times n$ identity matrix.
We know
$$p^\prime \mathbf{1}=1,$$
we are given
$$G = (\mathbb{I}_n - \mathbf{1}p^\prime)S,$$
and wish to compute the number
$$p^\prime G.$$
Substituting the foregoing into this expression gives
$$p^\prime G = p^\prime(\mathbb{I}_n - \mathbf{1}p^\prime)S = p^\prime S - (p^\prime \mathbf{1}) (p^\prime S) = p^\prime S - (1)(p^\prime S) = 0,$$
QED.
Comment: I have long been grateful for having had the opportunity, very early in my career, of taking a challenging and rigorous course in linear algebra.  Such courses are difficult to find, but nevertheless I would warmly recommend the experience for anyone wishing to work in a quantitative field.
Comment: There must be thousands of current linear algebra texts, and the one I used is now very old (but not outmoded!), so I'm in no position to make recommendations. There is an ongoing stream of reviews in *The American Statistician* that over the years has covered such textbooks from a statistical perspective, so that might be a good place to do some research.
Comment: Once again, I am indebted to you, @whuber. Thank you very much indeed! Your skill and expertise is really inspiring, I hope that with the years I shall come somewhat closer to your level of knowledge!
Comment: Yes, I see the necessity as well. Despite receiving the equivalent of As in my LinAlg and Linear Models classes, I picked up "Matrix Algebra from a Statistician's Perspective" and read in it, whenever I have some spare time. Would you have further recommendations?


Erro com getimagesize no upload de foto

Question: Estou tentando montar um sistema que verifica o mime type da imagem ao fazer o upload. Porem está dando um erro.
Segue o código:
<?php

$action = addslashes(filter_input(INPUT_GET, 'action',FILTER_SANITIZE_SPECIAL_CHARS));

if ((!empty($action)) and ($action == "add")) {
   // Recebe a imagem
   $imagem = $_FILES["imagem"];

   $size = getimagesize($imagem);

   switch ($size['mime']) {
       case "image/gif":
           echo "Image is a gif";
           break;
       case "image/jpeg":
           echo "Image is a jpeg";
           break;
       case "image/png":
           echo "Image is a png";
           break;
       case "image/bmp":
           echo "Image is a bmp";
           break;
   }
}

?>

<form name='form' method='post' action='?action=add' enctype='multipart/form-data'>
    <input type="file" name="imagem">
    <input type="submit" value="ok">
</form>

Log do erro:

Warning: getimagesize() expects parameter 1 to be string, array given in /Library/WebServer/Documents/teste.php on line 12

O erro ocorre nessa linha:
$size = getimagesize($imagem);

Modifiquei para
$imagem = $_FILES['imagem']['tmp_name'];
Mas retorna erro no getimagesize(). "Parameter cannot be empty"
Answer: Nesse trecho do código original,
$imagem = $_FILES["imagem"];

Modifique para
$imagem = $_FILES['imagem']['tmp_name'];

O exemplo acima é considerando uma imagem apenas.
Para upload de múltiplas imagens necessita de um tratamento diferente.
Caso tenha dúvidas sobre quais são os índices do array, faça um print_r($_FILES); exit;. Então poderá ver a estrutura.
Para dar mais consistência no switch()
 case "image/jpeg":
       echo "Image is a jpeg";
       break;

Mude para
 case "image/jpeg":
 case "image/pjpeg":
 case "image/jpg":
 case "image/pjpg":
       echo "Image is a jpeg";
       break;

O motivo é que jpg pode vir com um desses 4 formatos.
Outro ponto que necessita ser mais consistente é verificar se a imagem existe antes de tentar usá-la.
if (file_exists($imagem)) {
    $size = getimagesize($imagem);
} else {
    // dispara um exception, seta um código de erro.. enfim, o que vc preferir
}

Há muitos outros detalhes. Apenas mostrei os mais óbvios e simples.
Os exemplos são meramente didáticos.
Comment: deu erro `Warning: getimagesize(102.jpg): failed to open stream: No such file or directory in /Library/WebServer/Documents/teste.php on line 8` a linha 8 é `$imagem = $_FILES['imagem']['tmp_name'];`
Comment: Estranho pois `tmp_name` não retorna o nome original. Retorna o path absoluto do arquivo temporário. O nome é serializado, algo como um formato md5. Tire a dúvida fazendo um breakpoint com `print_r()` conforme comentado na resposta.
Comment: atualizei minha pergunta com o novo código. da uma olhada ai por favor
Comment: Não modifique a questão inteira. Quando for assim apenas adicione mais abaixo da pergunta alguma informação nova. Eu reverti e coloquei a nova informação.  Mas, pela terceira vez, peço que coloque o breakpoint com `print_r()`.   Sem um feedback adequado não posso continuar.
Comment: desculpa minha ignorância,  mas a onde devo colocar o  print_r();?
Comment: olha percebi que eu copiar a imagem para a pasta a onde esta o arquivo php, o erro não ocorre. parece que o sistema so lê a imagem se ela estiver no servidor.
Comment: A imagem está no servidor, senão o copy não seria possível.

Erro com getimagesize no upload de foto


Trying to change Android title to look better: requestWindowFeature

Question: Sample code:
// activity contains different controls so inherits from Activity
public class Main extends Activity implements OnClickListener, TextWatcher  {

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        boolean titleSupported = false;
        if (true) { // for on/off testing
          titleSupported = this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        }
        setContentView(R.layout.activity_main);

        // see: http://stackoverflow.com/questions/3438276/change-title-bar-text-in-android
        if (titleSupported)) {
          getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
          final TextView myTitleText = (TextView) findViewById(R.id.myTitle);
          if ( myTitleText != null ) {
            myTitleText.setText("@string/app_name");
          }
        }

When I include the "requestWindowFeature" the app stops/crashes in emulator. I don't understand why. I am new to Eclipse and Android, but from what I can search, I am doing things in the correct order. Any ideas of the cause?
with "requestWindowFeature" before "setContentView" I get:

02-04 12:35:05.883: E/AndroidRuntime(755): java.lang.RuntimeException:
  Unable to start activity
  ComponentInfo{com.xxx.yyy/com.xxx.yyy.Main}:
  android.util.AndroidRuntimeException: You cannot combine custom titles
  with other title features

With "setContentView" before "requestWindowFeature" I get:

02-04 12:32:32.660: E/AndroidRuntime(784): java.lang.RuntimeException:
  Unable to start activity ComponentInfo{com.xxx.yyy/com.xxx.yyy.Main}:
  android.util.AndroidRuntimeException: requestFeature() must be called
  before adding content
Comment: any stacktrace on logcat?
Comment: Added! Sorry I did not add it in my initial question.
Comment: Can you show what is `titleSupported` ?
Comment: I have now included complete example of what I am trying to achieve. (Just in case it in any way is related to my question and/or if others searching for the same can use it some day into the future.)
Answer: take the requestfeature call after setcontentview
    setContentView(R.layout.activity_main);
    titleSupported = this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

Comment: I do not believe that solves my problem. I have expanded my original post. (I get an error as well using your suggestion.)
Answer: Try to set
<item name="android:windowNoTitle">false</item>
in your theme.


Import iOS 3.2 source code if user has iOS 3.1.3 or lower

Question: I am using the MPMoviePlayerViewController, which is only supported in iOS 3.2+. How would I obtain the source code for this class and import it if the user has iOS 3.1.3 or lower?
Comment: I don't think that the source code for that part of iOS is available. From what I can see there it's just the open source components that iOS uses which are available elsewhere (minus the changes that apple has made to them)
Comment: AFAIK you can't, if you require the functionality might as well make 3.2+ a requirement to install the app.
Comment: That's an API exposed and coded into that iOS version, you can't just import source code like that
Comment: I see, they've pretty much open-sourced useless stuff as required by law.
Comment: I want to support 3.1.3 and lower without having to re-implement `MPMoviePlayerViewController`.
Comment: Apple did open source the iOS API. When I click into, say [iOS 4.3.3](http://www.opensource.apple.com/release/ios-433/), I'm presented with 10 choices. Which one do I download? And what is the class equivalent of `respondsToSelector`? Something like `classExists`?
Comment: What I'm saying is that even if you add the code it many not work as it might rely on some underlying change made in version 3.2 that won't work in other versions.
Comment: I would at least like to look at the source code to see what it's doing so I can create my own version that is backwards compatible.
Answer: As Jesus says, source code for iOS is not available. That's because it's a commercial secret — Apple's view is that they would put themselves at a significant commercial disadvantage if they revealed it.
Your best course of action is to check if MPMoviePlayerViewController is available using normal runtime methods, and find a way to use the older MPMoviePlayerController if it isn't. You'll get into that situation on iPhones and iPod Touches only because the original iPad shipped with iOS 3.2 from day one. The latter differs from the former in that you can't take out the view and composite it by any other means and it doesn't play well with tab bar controllers. So they're always full screen. You can add extra views on top but the MPMoviePlayerController is always the thing in charge.
Comment: NSClassFromString(@"MPMoviePlayerViewController") will return nil if no class of that name exists.
Comment: What is the best way to check if `MPMoviePlayerViewController` is available? I was looking for a class analogy to `respondsToSelector`.


Basic networking: Centos Server Router + Ubuntu Client setup.. unable to access outside world from client

Question: I am trying to set up my Centos Server with two NICs as a router.  eth0 is connected to the outside world and eth1 is connected to an Ubuntu client.
Here's eth0 on the server:
DEVICE=eth0
BOOTPROTO=dhcp
ONBOOT=yes
TYPE=Ethernet

eth1 on the server:
DEVICE=eth1
BOOTPROTO=static
IPADDR=192.168.0.10 # a free address on my network
ONBOOT=yes
TYPE=Ethernet

My server has IPv4 packet forwarding turned on and my iptables only contains:
# iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE
# iptables --append FORWARD --in-interface eth1 -j ACCEPT

My Ubuntu client has this in its /etc/network/interfaces
auto lo
iface lo inet loopback

iface eth0 inet dhcp
   gateway 192.168.0.10

but I can't get an Internet connection from the server for my client.  I can't even ping my server from the client:
$ ping 192.168.0.10
Destination Host Unreachable

Comment: I suggest you get your server sorted out before worrying too much about the client. You have at least two problems on the server: (1) Your internal and external addresses have the same network address (`192.168.0.0/24`). That's no good. Change one of them. (2) The external interface IP is non-routable (per RFC 1918). If your server is to be doing NAT for your internal network, you really want it to get a globally routable address on the external side.
Comment: Does your local network have a DHCP server? What is the output of `ip addr show` on the client and on the server?
Comment: Hi Steven, `ip addr show` on the server shows`eth0` getting an IP of `192.168.0.4/24` and `eth1` getting an IP of `192.168.0.10/24` which is what I would expect.  *BUT* `ip addr show` does not show an IP address of the client
Comment: so the client isn't getting an IP.. it guess it should be getting one via DHCP from the server?
Comment: Once the server is good, then yes, you should probably install DHCP on it and configure it to hand out IPs to the local network. The Ubuntu client config looks mostly okay, except for the `gateway` line. Remove that line, since DHCP should be configuring that for clients.
Comment: With iptables disabled, the problem continues?. And the output of route command on the router?
Answer: Am I the only one that noticed eth1 on the Centos server and eth0 on the client share the same IP, if the configs you posted are right. My habit is if I'm going to use a machine as a linux gateway, I usually use .1 as the last octet. so eth1 on the server would be 192.168.0.1, and eth0 on the client would be 192.168.0.10. Of course, you do have to input the route for the gateway with route add default gw 192.168.0.1 on the client. I'll look over your iptables settings again later, to check if I see anything.
With eth0 on the server using dhcp, if should grab everything it needs from the ISP, so there's nothing wrong there... (Oh, and you shouldn't need to do anything with routes or iptables to just ping the Centos router. Routes and iptables only come into play when trying to get to the outside world, so lets work on one thing at a time, and just get the client talking to the router first. That ip conflict is probably what's preventing that.) Good luck!!!
Answer: For starters, are you running DHCP on the Server?
Looking at the above, eth0 on the Server is the "inside" interface.  The network config above suggests the inside interface on the server (aka router) use DHCP.  Is there a reason for this config?  It's usually better to set the gateway IP address to be static.  Also, the Server eth0 ip address should be different than 192.168.0.x/24 (I'm assuming you're using a 24 bit mask here).
The client eth0 config (I'm assuming this is the only interface on the client and connects the client to the Server eth0 port via switch/hub/l2 device) also uses DHCP.  Perhaps it's easier to use a static IP address for testing.  Again, the client IP address should not be on the 192.168.0.x/24 subnet.
Lastly, the gateway on the client should be set to the eth0 ip address on the server.
The routing table on the Server should show both 192.168.0.x/24 and 192.168.1.x/24 (you could use any other private ip address) as directly connected with its default route pointing to the gateway IP address for that segment (not 192.168.1.10 but the gw given to you by your ISP).
hth


Can't render a block due to recoverable fatal error

Question: I had code to programmatically render a block.
$block = \Drupal\block\Entity\Block::load('bartik_search');
$block_content = \Drupal::entityManager()
  ->getViewBuilder('block')
  ->view($block);
return array('#markup' => drupal_render($block_content));

After updating to Drupal 8.2.x, I get the following error:

Recoverable fatal error: Argument 1 passed to Drupal\block\BlockViewBuilder::view() must implement interface

How do I fix this error?
Comment: Do you check block with delta **bartik_search** exited? You can debug with kint($block) to see it.
Comment: You should not need to call the view builder. Block plugins have a ::build method that returns a render array, which you can just return. What are you trying to do that you need to render and then place into a new render array?
Comment: Hi @Jonh , I check block **bartik_search** exited..
Comment: Hi @mradcliffe ..so what's solution ? Could you show code ?
Comment: I really do not understand what you are trying to do? Are you trying to place a Search Form or a Search Block Form on the page somewhere? Where on the page? Through what mechanism? Knowing that I can provide the best answer. Thanks.
Comment: Possible duplicate of [How can I programmatically display a block?](https://drupal.stackexchange.com/questions/171686/how-can-i-programmatically-display-a-block)
Answer: The error:

Recoverable fatal error: Argument 1 passed to Drupal\block\BlockViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface

usually is caused by viewing the invalid block (NULL). So for some reason Block::load() fails to load your block (bartik_search). So clear your caches and check whether the block exists at Block Layout page, theme is enabled and permissions are configured properly. If this still happening and the block is definitely there, please raise a relevant issue ticket.
You can always add the condition or try/catch block whether the code loads the block correctly.
Please also note that drupal_render() is deprecated and you should return $block_content instead.@googletorp Or use \Drupal::service('renderer')->renderRoot() instead.
See also: How can I programmatically display a block?


Probability of random value being correct within X amount of tries,

Question: Let's say I have 4 numbers:
1234

These numbers have a predetermined combination of 2 that is the correct value, which could be any of the following 16. (1 in 16 chance)
11
12
13
14
21
22
23
24
31
32
33
34
41
42
43
44

What is the probability of guessing the correct pair within 10 tries?
I'm not much of a mathematician and have no clue how to figure out a percentage chance.
Answer: We assume that we make distinct guesses!
I am interpreting within $10$ trials as meaning in $10$ or fewer trials. This is the probability that if we choose $10$ pairs, then ours is one of them. That probability is $\frac{10}{16}$.


How to differentiate a MP3,MP4 file?

Question: I don't want to use pathExtension to do this, as it's not rigorous. I differentiated image files by the file header, but I can't find any information about this for MP3/MP4.
(Either Swift or OC is OK)
Comment: This question is vague.  What do you mean by "divide"?  to split the file into pieces or display it in a table or view or?
Comment: @MichaelDautermann thanks, I meant to differ files.
Answer: To determine it's a mp3, look at the first two or three bytes of the file.  If it's 49 44 33 or ff fb, you have a mp3.
And a signature of ftyp may indicate a .mp4 file.
Here's some Swift code I worked up for this purpose:
import Foundation

var c = 0;
for arg in Process.arguments {
    print("argument \(c) is: \(arg)")
    c++
}

let pathToFile = Process.arguments[1]

do {
    let fileData = try NSData.init(contentsOfFile: pathToFile, options: NSDataReadingOptions.DataReadingMappedIfSafe)

    if fileData.length > 0
    {
        let count = 8

        // create array of appropriate length:
        var array = [UInt8](count: count, repeatedValue: 0)

        // copy bytes into array
        fileData.getBytes(&array, length:count * sizeof(UInt8))

        var st = String(NSString(format:"%02X %02X %02X %02X %02X %02X %02X %02X",
            array[0], array[1], array[2], array[3], array[4], array[5], array[6], array[7]))

        // 49 44 33 is mp3

        //
        print("first \(count) bytes are \(st)")

        // f t y p seems to determine a .mp4 file
        st = String(NSString(format:"%c %c %c %c %c %c %c %c",
            array[0], array[1], array[2], array[3], array[4], array[5], array[6], array[7]))

        print("first \(count) bytes are \(st)")
    }
} catch let error as NSError {
    print("error while trying to read from \(pathToFile) - \(error.localizedDescription)")
}

Comment: Thanks,I'll try this.
Answer: You'd want to do what you did with images and use the header information in both files to determine whether it's an mp3 file, or an mp4 file. There's information about the mp4 header here: Anyone familiar with mp4 data structure?.
Answer: Swift 5
func doStuff(fileData: Data) {
    if fileData.count > 0 {
        let count = 8

        // create array of appropriate length:
        var array = [UInt8](unsafeUninitializedCapacity: count) { buffer, initializedCount in
            for x in 0..<count { buffer[x] = 0 }
            initializedCount = count
        }

        // copy bytes into array
        fileData.copyBytes(to: &array, count: count * UInt8.bitWidth)

        var st = String(NSString(format: "%02X %02X %02X %02X %02X %02X %02X %02X",
            array[0], array[1], array[2], array[3], array[4], array[5], array[6], array[7]))

        // 49 44 33 is mp3
        print("first \(count) bytes are \(st)")

        // f t y p seems to determine a .mp4 file
        st = String(NSString(format: "%c %c %c %c %c %c %c %c",
            array[0], array[1], array[2], array[3], array[4], array[5], array[6], array[7]))

        print("first \(count) bytes are \(st)")
    }
}

How to differentiate a MP3,MP4 file?


Is it possible to display value of App Service Config of Function App(Configuration) on Azure dashboard?

Question: As title says is it possible? Could not even find an option to pin app service config settings into dashboard.
Comment: why -1? Please elaborate.
Answer:
Is it possible to pin app service config settings into dashboard?

No, it is not possible to pin App service configuration settings to the azure dashboard.

You can add only resources or resource groups or any arm endpoint operations to the azure dashboard directly.


Where to get apache poi port for .net

Question: I would like to know if there is a website where I could download the Apache POI ported for .net?
I already found this link in the web
http://www.apache.org/~avik/dist/poi-2.5.1-dev-20040708.dll
I also found a repository of poi.net from novel but it is quite old (2004)
http://developer.novell.com/wiki/index.php/Poi.Net
But the version of apache poi now is 3.6, I was wondering if there is a latest version out there? Does the apache foundation support such porting? I already tried to search the apache website too with no avail.
As for using Microsoft library, the excel interopt is not that good for concurrent processing like a web backend. If I use the DocumentFormat.OpenXML library, I have a limitation of creating office 2007 document only.
If there is no library out there? is there a JAR to .NET assembly(.dll) converter tool out there?
Answer: I found out the answer. You can get the latest apache poi version then convert the jar into dll on your own using IKVM.NET. After that, add the assembly of the POI dll to your .net application plus the IKVM.NET core and JVM dll. And you can finally use the Apache POI in your  .NET project.
Answer: Another solution is a partial port of POI to .NET, named NPOI.
(Found it on that other question)
Comment: As of 2016, it looks like NPOI is about a year or more behind POI.

Where to get apache poi port for .net


Question about the concept of connected set

Question: From the definition, $Y$ is disconnected if $Y=A\cup B,A,B\ne\emptyset A\cap B=\emptyset$ and $A,B$ are both open. So for proving $\mathbb{Q}$ is not connected, normally the textbook would suggest $\mathbb{Q}\cap(-\infty,r)\bigcup\mathbb{Q}\cap(r,+\infty),r\in\mathbb{I}$. Also the textbook would say the open ball of rational number set is not connected. Here's my question.
First, why do we need to consider about $\mathbb{R}$ when proving $\mathbb{Q}$ is not connected?? Aren't we jsut need to consider $\mathbb{Q}$ only? In fact if we just consider $\mathbb{Q}$, it doesn't seem obvious and i first thought that it is connected as i am not sure how to separate it into 2 separated set.  Intiutively, if you consider just $\mathbb{Q}$, the only clopen subset in $\mathbb{Q}$ should be itself and $\emptyset$, isn't it? I couldn't find any subset which are clopen in rational set.
Secondly, what if some set which is not familiar with you, how can you really determine whether it is connected or not? Some time the set may be dense and intuitively it seems connected for me but it is not always connected. Some set may even not easy to picture out let alone determine if it is connected
Last, how do one show the open ball $B\subset\mathbb{Q}$ is not connected?
Comment: Connectedness is a topological property, it depends on the topology of $\mathbb{Q}$. You give it the topology it inherits from $\mathbb{R}$ what else do you expect?
Comment: The questioner ought to insist that $A,B$ are both open (or both closed, which implies both open under these conditions).
Answer: You don't need to consider $\mathbb{R}$ if you don't want to. For instance, you can take
$$A = \{ x \in \mathbb{Q}\, :\, x^2 < 2 \}\ \text{and}\ B = \{ x \in \mathbb{Q}\, :\, x^2 > 2 \}$$
Then $A$ and $B$ are open disjoint sets which cover $\mathbb{Q}$. Both these sets are clopen, since
$$ \{ x \in \mathbb{Q}\, :\, x^2 < 2 \} = \{ x \in \mathbb{Q}\, :\, x^2 \le 2 \}$$
or, more concisely written, $\mathbb{Q} \cap (-\sqrt{2},\sqrt{2}) = \mathbb{Q} \cap [-\sqrt{2}, \sqrt{2}]$. In fact, $\mathbb{Q}$ has lots of clopen sets.
The argument that shows that open balls in $\mathbb{Q}$ are disconnected is almost identical.
Comment: I see, for some rational number, there doesn't exist another rational numbers which square of its value equal to it. So there came a separation and we can defined a coninuous 2 valued functions and it is possible to have 2 values so it is not connected


Double summation in abelian group

Question: How can we prove that in abelian group the following equality holds?
$$ \sum_{\nu=1}^n\sum_{\mu=1}^ma_{\mu\nu}=\sum_{\mu=1}^m\sum_{\nu=1}^na_{\mu\nu}$$
Comment: Could you explain your notation?
Comment: @amWhy
To each pair of indexes $(\nu,\mu)$ such that $1 \leq \nu \leq n, ~~ 1 \leq \mu \leq m $ an element $a_{\mu \nu}$ of a group is assigned.
Comment: @amWhy
The following definition is given in the book:
$\sum_{\nu = 1}^{n} \sum_{\mu = 1}^{m} a_{\mu \nu} = \sum_{\nu = 1}^{n} ( \sum_{\mu = 1}^{m} a_{\mu \nu} ) $
Comment: Got it...thanks.
Answer: To expand on Daniel Robert-Nicoud's answer, one induction actually suffices:
For $m=1$ the result is clear.
Suppose $\sum_{\nu=1}^n\sum_{\mu=1}^k a_{\mu\nu} = \sum_{\mu=1}^k\sum_{\nu=1}^n a_{\mu\nu}$ for all $n\in\mathbb{N}$.
$$\sum_{\mu=1}^{k+1}\sum_{\nu=1}^n a_{\mu\nu} = \sum_{\mu=1}^k\sum_{\nu=1}^n a_{\mu\nu} + \sum_{\nu=1}^n a_{k+1,\nu} = \sum_{\nu=1}^n\sum_{\mu=1}^k a_{\mu\nu} + \sum_{\nu=1}^n a_{k+1,\nu} = \sum_{\nu=1}^n\left(\sum_{\mu=1}^k a_{\mu\nu}+a_{k+1,\nu}\right) = \sum_{\nu=1}^n\sum_{\mu=1}^{k+1} a_{\mu\nu}.$$
The general statement now follows by induction.
Comment: Indeed you do. Although induction on $n$ would work just as well of course.
Comment: Thank you. It's clear now.
Answer: You can easily prove it by induction on $n$ and $m$.
Answer: Note that $\prod $ is (or can be) defined recursively as
$$\tag1\prod_{k=1}^0  a_k = 1$$
$$\tag2\prod_{k=1}^{N+1} a_k = \left(\prod_{k=1}^{N} a_k\right)\cdot a_{N+1}$$
Lemma 1. $$\tag3\prod_{k=1}^N 1=1.$$
Proof: The case $N=0$ follows from $(1)$, the induction step by
$$\prod_{k=1}^{N+1} 1\stackrel{(2)}= \left(\prod_{k=1}^{N} 1\right)\cdot 1=1\cdot 1=1.$$
Lemma 2. $$\tag4\left(\prod_{k=1}^N a_k\right)\cdot \left(\prod_{k=1}^N b_k\right)=\prod_{k=1}^N (a_kb_k).$$
Proof: If $N=0$, this follows from $1\cdot 1=1$.
For the induction step, note that
$$\begin{align}\left(\prod_{k=1}^{N+1} a_k\right)\cdot \left(\prod_{k=1}^{N+1} b_k\right) &\stackrel{(2)}=\left(\prod_{k=1}^{N} a_k\right)\cdot a_{N+1}\cdot \left(\prod_{k=1}^{N} b_k\right)\cdot b_{N+1}\\&\stackrel{\text {ab.}}= \left(\prod_{k=1}^{N} a_k\right)\cdot \left(\prod_{k=1}^{N} b_k\right)\cdot a_{N+1} b_{N+1}\\&\stackrel{(4)}= \left(\prod_{k=1}^N (a_kb_k)\right)\cdot a_{N+1}b_{N+1}\\&\stackrel{(2)}=\prod_{k=1}^{N+1} (a_kb_k).\end{align}$$
Now for the desired claim:
First case: $n=0$
In this case, the left hand side is
$$\prod_{\nu=1}^0\prod_{\mu=1}^m a_{\mu\nu}\stackrel{(1)}=1.$$
The right hand side is
$$\prod_{\mu=1}^m \prod_{\nu=1}^0 a_{\mu\nu}\stackrel{(1)}=\prod_{\mu=1}^m 1 \stackrel{(3)}=1.$$
For the induction step, assume that $$\prod_{\nu=1}^n\prod_{\mu=1}^m a_{\mu,\nu}=\prod_{\mu=1}^m\prod_{\nu=1}^n a_{\mu,\nu}$$
for all $m$ and all choices of $a_{\mu,\nu}$.
Then
$$\begin{align}
\prod_{\nu=1}^{n+1}\prod_{\mu=1}^m a_{\mu,\nu}
&\stackrel{(2)}= \left(\prod_{\nu=1}^{n}\prod_{\mu=1}^m a_{\mu,\nu}\right)\cdot \prod_{\mu=1}^m a_{\mu,{N+1}} \\
&\stackrel{(4)}= \prod_{\mu=1}^m\left(\prod_{\nu=1}^{n} a_{\mu,\nu}\right)\cdot \prod_{\mu=1}^m a_{\mu,{N+1}}\\
&\stackrel{(4)}= \prod_{\mu=1}^m\left(\prod_{\nu=1}^{n} a_{\mu,\nu}\right)\cdot \prod_{\mu=1}^m a_{\mu,{N+1}}\\
&\stackrel{(3)}= \prod_{\mu=1}^m\left(\left(\prod_{\nu=1}^{n} a_{\mu,\nu}\right)\cdot a_{\mu,N+1}\right) \\
&\stackrel{(2)}= \prod_{\mu=1}^m\prod_{\nu=1}^{n+1} a_{\mu,\nu}.
\end{align}$$
Comment: Thank you very much!
It's just what i was looking for!

Double summation in abelian group


Problema com Regex no PHP

Question: Tenho a seguinte função que serve para tirar caracteres especiais de uma string:
function removeSpecialChars($string){
  //List (Array) of special chars
  $pattern = array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/","/(ç)/","/(Ç)/","/(\'|\"|\^|\~|\;|\:|\°|\?|\&|\*|\+|\@|\#|\$|\%|\!|\\|\/|\(|\)|\||\=|\.|\,)/");

  //List (Array) of letters
  $replacement = array('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'n', 'N', 'c', 'C', '');

  return preg_replace($pattern , $replacement, $string);
}

Ele funciona bem, o único problema é que essa função não consegue substituir a barra, seja ela invertida (\) ou normal (/), e o cifrão($), mas se eu colocar essa expressão regular em algum site para testar, como coloquei nesse link funciona normalmente.
Alguém sabe o motivo de não funcionar no PHP?
Answer: Isso acontece porque dentro de uma string (entre as aspas), a barra invertida deve ser escapada e escrita como \\ (conforme descrito na documentação).
Por isso, \/ deve ser escrito como \\/, e \\ deve ser escrito como \\\\ e assim por diante. Outro detalhe é que o próprio caractere de aspas (") também deve ser escapado e escrito como \". Ou seja, dentro da string, o trecho \" da expressão deve ser escrito como \\\".
Então sua expressão ficaria assim:
function removeSpecialChars($string){
  //List (Array) of special chars
  $pattern = array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/","/(ç)/","/(Ç)/","/(\\'|\\\"|\\^|\\~|\\;|\\:|\\°|\\?|\\&|\\*|\\+|\\@|\\#|\\$|\\%|\\!|\\\\|\\/|\\(|\\)|\\||\\=|\\.|\\,)/");

  //List (Array) of letters
  $replacement = array('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'n', 'N', 'c', 'C', '');

  return preg_replace($pattern , $replacement, $string);
}

echo removeSpecialChars("áçõ/\\?&"); // aco

No site que você testou não foi necessário escapar a \ porque ali a regex não está dentro de uma string PHP.

Uma outra opção é usar classes de caracteres (delimitado por []), tomando o cuidado de usar a flag u, pois caracteres acentuados podem não funcionar corretamente quando usados dentro de uma classe de caracteres:
function removeSpecialChars($string){
  $pattern = array("/[áàãâä]/u","/[ÁÀÃÂÄ]/u","/[éèêë]/u","/[ÉÈÊË]/u","/[íìîï]/u","/[ÍÌÎÏ]/u","/[óòõôö]/u","/[ÓÒÕÔÖ]/u","/[úùûü]/u","/[ÚÙÛÜ]/u","/ñ/u","/Ñ/u","/ç/u","/Ç/u", '/[\'"\^~;:°?&*+@#$%!\(|\)=.,\/\\\\]/');

  $replacement = array('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'n', 'N', 'c', 'C', '');

  return preg_replace($pattern , $replacement, $string);
}

echo removeSpecialChars("áçõ/\\?&");

Existe ainda outra opção, que é usar a classe Normalizer para remover os acentos. Para usá-la, você deve habilitar a extensão intl:
function removeSpecialChars($string){
  $semAcentos = preg_replace('/\p{M}/u', '', Normalizer::normalize($string, Normalizer::FORM_D));
  return preg_replace('/[\'"\^~;:°?&*+@#$%!\(|\)=.,\/\\\\]/' , '', $semAcentos);
}

echo removeSpecialChars("áçõ/\\?&");

Com isso, os acentos são removidos de uma vez, bastando usar a regex para remover os caracteres especiais no final.
Comment: Perfeito, agora funcionou, obrigado.
Answer: Mais simples você colocar tudo dentro de colchetes [] (character set, ou conjunto de caracteres), e claro, escapando as barras e as aspas duplas delimitadoras:
"/['\"^~;:°?&*+@#$%!\/()|=.,\\\]/"
    ↑               ↑       ↑↑
 escape          escape   escape

Agora eu senti falta de outros caracteres, como os colchetes [] e as chaves {}, por exemplo. Se for incluí-los, precisa escapar os colchetes também:
"/[{}\[\]'\"^~;:°?&*+@#$%!\/()|=.,\\\]/"
     ↑ ↑  ↑               ↑       ↑↑
    escapes            escape   escape

Comment: Uma boa ideia também, vai simplificar o código, obrigado.
Comment: @GabrielQueirozSchicora Eu ia sugerir isso, mas quando testei com `preg_replace` não funcionou, [veja](https://ideone.com/XMAdo1). Talvez eu esteja muito enferrujado com PHP, não sei se eu que errei alguma coisa :-/
Comment: De qq forma, é uma dica válida para simplificar a regex, então +1 :-)

Problema com Regex no PHP


What does one mean when $\int \frac{\sin x}x$ doesn't exist?

Question: Well I say that by taylor's expansion:
$$\int\frac{\sin x}x=\int\frac{x-x^3/6+x^5/120+...}x=x-x^3/18+x^5/480+...+\mathbb{C}$$
It's another thing that there doesn't exists a closed form for the sum/difference.But it does exists.So I am now confused about:

Does integration to every function exists?

[I partly understand something told about elementary functions etc.]

If it does, does there exists a closed form always?

[I think no, but can't support my contradiction]

Can taylor series be always used like this, atleast for approximation?

[I think it always can be]

and similar ones, can somebody help?
Comment: There **is** an antiderivative of $\frac{\sin x}{x}$. The antiderivative cannot be expressed in closed form using elementary functions. Every continuous function has an antiderivative. So do some non-continuous functions. Taylor series apply only to nicely behaved functions, which luckily include many of the useful ones.
Comment: http://en.wikipedia.org/wiki/Sine_integral#Sine_integral  Not elementary, but useful for enough people that it was given a name.
Comment: There may not be a elementary closed-form expression for the antiderivative, but that is not the same as saying that it does not exist. Indeed, the integral $\int_a^b (\sin(x)/x) dx$ exists for all finite $a,b$ since the integrand is continuous (after setting the value at $x=0$ to $1$). In addition, $\int_{-\infty}^\infty (\sin(x)/x) dx$ exists as an improper integral and equals $\pi$.
Comment: there is nothing such as integral does not exist , How ever if the integral is bounded it might be not integrable at that interval only or it might have branch cut .  who told you anyway it does not exist ?!.
Comment: You may be interested in this. It might be too advanced for you now, but you may want to try it later after you have taken more mathematics. It's interesting anyway. http://www2.maths.ox.ac.uk/cmi/library/academy/LectureNotes05/Conrad.pdf
Answer: I don't know who told you $\int \dfrac{\sin x}{x}\; dx$ doesn't exist.  It does, and it even has a name: ${\rm Si}(x)$.  But it is not an elementary function.

Every continuous function has an antiderivative.
Not every elementary function has an elementary antiderivative.  There is a well-developed theory behind this: see Risch algorithm.  "Closed form", on the other hand, is a nebulous concept: it may depend on whether somebody cared enough about this integral to give it a name.
The Taylor series of any analytic function can be integrated term-by-term to give the Taylor series for an antiderivative.
Answer:
Does integral always exist?

No. There are non-integrable functions. Integrability was a major reason to switch from Riemann integral to Lebesgue. However, continuous functions always have a primitive, so it's rather a theoretical concern, though a very important one.

Does there always exist a closed form?

No. And you just pointed an example. Some such "bad" integrals get a name, when they are generally useful, and this give rise to a whole zoo of special functions. Yours above is called the sine integral.

Can Taylor series always be used?

Only if the integrand can be expressed (easily) as a Taylor series. Often the series has no simple form, so it's just replacing a difficult problem with another as difficult. However, special function may often be defined as series expansion. And some functions are not analytic at all ($\exp (-1/x)$ is a classical example, around 0, and with Borel's lemma it's easy to get other ones, but see also here).
Comment: The Gamma function has a simple pole at $0$, so if you want an antiderivative in a series around $0$ you'll need a logarithmic term to take care of that.  Away from the poles, Taylor series do exist and can be used for integration.
Comment: @RobertIsrael Your're right of course. I don't know where I got this. :-) Maybe I had in mind that Gamma function does not satisfy an easy differential equation. Anyway, sorry for this!
Answer:
The Lebesgue Integrability Condition says that any bounded, almost-everywhere continuous function on a compact interval is Riemann integrable.  In particular, this means that, say, $$\int_1^x \frac{\sin t}{t} \, dt$$
is a well-defined function.  In fact, in this particular case the integral from zero exists also, because the function
$$f(t) := \begin{cases}
\displaystyle\frac{sin(t)}{t} & \text{ if } t \neq 0 \\
1 & \text{otherwise}
\end{cases}$$
is continuous everywhere.  This function is sometimes called $Si(t)$ (for Sine integral), and you can see a graph here:  http://www.wolframalpha.com/input/?i=plot+integral+sin%28t%29%2Ft+dt
There is no closed form for this integral in terms of elementary functions.  In fact that's the case for most integrals.
Yes, you can commute integrals and sums, but there are certain convergence issues to worry about.
Comment: I said "most" because I wanted to be vague.  I mean, obviously if you start with something that's just an arbitrary continuous function that has no closed-form expression then you wouldn't *expect* its integral to have a closed form.  So the relevant statement would be what proportion of *elementary functions* have integrals that are elementary.  Unfortunately the set of elementary functions is countable up to the choice of finitely many real coefficients, so there's no natural measure on it that lets us talk about "almost all."  It's a fundamentally discrete-ish object.
Comment: In regards to #2, alas, "almost all" integrals don't even _have_ nice ways to write the "antiderivative".  One tries not to become depressed about it...
Comment: I wasn't making my comment as a criticism:  I was merely remarking that the careful analytical techniques we learn and teach for "exact" integration only work on a minute (infinitesimal?) proportion of all the integrands we encounter (or can think up), something I warn students about in courses.  It's part of what keeps numerical analysts and supercomputers employed...
Comment: Sure, it's just that what you said is a bit misleading.  You can say that almost all integrals of continuous functions aren't elementary, but that's just because almost all continuous functions aren't elementary -- it's not relevant to the issue at hand, which is the integrals of *elementary* functions.  You *can't* say that almost all integrals of elementary functions aren't elementary, because there's no natural probability measure on the set of elementary functions.
Comment: The original post asked about "every function", and was what I thought you were referring to in the phrase "most integrals".  I guess my attempt at humor about what we face in dealing with integration misfired.


Como apagar dados de uma tabela com dependências em outras tabelas

Question: Preciso excluir dados de uma tabela que tem dependências em outras tabelas.
Por exemplo pra que eu possa excluir um dado da tabela pessoa primeiro eu tenho que excluir uma dependência que existe na tabela credencial que por sua vez tem dependência em outra tabela e assim se repete com outras 3 tabelas . O problema é: Não tenho só um dado pra excluir, se não me engano vai de 1000 a 1500. Acho que já tinha ouvido falar em uma forma de excluir dados com dependências com um só script. Só que a agora não encontro já pesquisei em vários lugares mas não encontro.
Answer: Desabilitando e Habilitando as constraints de chave estrangeira. Os comandos são os seguintes:
Para SQL Server:
-- Desabilita todas as constraints de uma tabela

ALTER TABLE MinhaTabela NOCHECK CONSTRAINT ALL

-- Habilita todas as constraints de uma tabela

ALTER TABLE MinhaTabela CHECK CONSTRAINT ALL

-- Desabilita uma constraint

ALTER TABLE MinhaTabela NOCHECK CONSTRAINT MinhaConstraintDeFk

-- Habilita uma constraint

ALTER TABLE MinhaTabela CHECK CONSTRAINT MinhaConstraintDeFk

Para MySQL:
SET foreign_key_checks = 0;
// Delete o que tiver que deletar

SET foreign_key_checks = 1;
// Ative a checagem novamente

SET foreign_key_checks = 0;
// Delete o que tiver que deletar

SET foreign_key_checks = 1;
// Ative a checagem novamente

citações:

Resposta do Stack Overflow (em inglês)
Foreign Key Checks (referência do MySQL)
Comment: mas tenho que fazer isso pra todas as tabelas?
Comment: @PatiiHenrii Você quer o comando pra todas as tabelas também? Não recomendo. O ideal é usar somente para as tabelas envolvidas com a sua alteração.
Comment: entendi, vou testar aqui, no banco de teste que tenho! obrigado.
Answer: SET foreign_key_checks = 0;
// Delete o que tiver que deletar

SET foreign_key_checks = 1;
// Ative a checagem novamente

Comment: Se este comando existisse seria uma boa. Onde você viu isso? Pode incluir um link para a documentação do comando? Na verdade até a sintaxe do uso do SET está errada. Me parece que você não observou que o banco é MS SQL Server (este comando aí é do MySql).
Answer: Quando for criar um relacionamento entre as tabelas coloque o on delete e delete update em cascade.
Exemplo:
ALTER TABLE `tab_audiencia` ADD CONSTRAINT `tab_audiencia_ibfk_1`
    FOREIGN KEY (`usuario`) REFERENCES `escala`.`usuarios`(`id`)
        ON DELETE CASCADE ON UPDATE CASCADE;

Assim quando for apagado o registro da tabela "usuario" os demais relacionamentos serão apagados automaticamente
Answer: Sei que o post já tem 1 ano, mas como sempre os usamos como referência, gostaria de fazer um alerta.
A ideia do Cigano é bem pontual e deve ser usada com extremo cuidado. Desligar constraints não é uma boa prática, principalmente usando usando o complemento ALL. Você fica sem saber quais constraints foram desligadas e por consequência não fica sabendo quais são as tabelas envolvidas.
Se deixar uma tabela "filha" sem ser limpa ela ficará com "lixo" e pra ajudar, todas as vezes que limpamos uma tabela é normal dar um reset nas sequences. Ai já viu. Vai chegar um momento em que nossa sequência alcançará registros antigos e se misturá às informações novas. Já da para saber onde isso vai dar.
Esse post não é uma critica ao seu autor, é apenas uma recomendação de cuidado ao seu uso.
Comment: Faltou dizer qual opção é melhor do que aquela.
Comment: Concordo com @Caffé. Sinta-se à vontade para elaborar um pouco mais a sua resposta com uma implementação do que você considera a abordagem correta, Sérgio - no momento é mais um comentário do que uma resposta.
Answer: Quando você manipula dados de um banco de dados, presume-se que você conhece o banco, ou você não saberia o que está fazendo.
Desativar as constraints temporariamente resolve? Não creio pois depois você terá que ligar de volta então de qualquer modo não poderá ter corrompido o relacionamento dos registros.

Ou seja: você não escapa de saber o que está fazendo, precisa conhecer previamente os relacionamentos e precisa saber das implicações de se excluir um registro com dependências.

A opção que mais faz sentido para mim é excluir os registros na ordem das suas dependências, primeiro os filhos e depois os pais, em vez de fingir ignorar estas dependências.
Você ainda poderá fazer a exclusão em massa: exclua os 1500 registros filhos, depois os 1500 registros pai e depois os pais destes e assim por diante.
Se a exclusão das dependências ao deletar um pai for um procedimento padrão para estas tabelas, então eu fico com a opção do Math: alterar a tabela de modo a tornar automática e definitiva a exclusão de dependências.
Agora, se você realmente não liga para os dados
Se você estiver por exemplo usando uma base de testes pode ser aplicável de vez em quando sair excluindo registros e destruindo dependências como se não houvesse amanhã.
Neste caso uma opção é um script que recupere os metadados da tabela e percorra as dependências fazendo a exclusão na ordem correta.
Este script pode ser um código quebra-galho no lado do cliente na linguagem da sua preferência, ou uma stored procedure.


Angular2 changes to (click) functions not working

Question: I've been messing around with Angular2 and I have no idea why my changes to these functions do nothing. So say my code first looks like this:
//home.component.html

<sm-button class="positive" (click)="remove()">Button</sm-button>

//home.component.ts
import { Component } from "@angular/core";

@Component({
    selector: "home",
    templateUrl: `client/components/home/home.component.html`
})
export class HomeComponent {
    constructor() {}
    remove() {
        console.log("Hello");
    }
}

But then I change it to this:
//home.component.html

<sm-button class="positive" (click)="load()">Button</sm-button>

//home.component.ts
import { Component } from "@angular/core";

@Component({
    selector: "home",
    templateUrl: `client/components/home/home.component.html`
})
export class HomeComponent {
    constructor() {}
    load() {
        console.log("Hello");
    }
}

Now the load function cannot be found when clicking the button. What is going on here?
EDIT: changed code to include full files
Comment: have you add template in `@Component`
Comment: did you forget to compile?  It would help if you posted both files, before and after.
Comment: Yes. The template loads the button and pressing it works when the click function is remove. It's like the changes I make in home.component.ts aren't actually doing anything. Why would that be happening? I have lite-server running so shouldn't it auto compile on changes or do I still need to compile manually?
Comment: it depends on if you are running the server concurrently with "tsc -w"  If you are just running lite-server, it will only watch for file changes and then refresh, but it won't compile for you.  Try running tsc and see if it works then.
Comment: I am running with "tsc -w"
Comment: Just change now load with your name awillis() and try
Answer: Seems like tsc-w doesnt work properly.
Look into server console, was command run or not.
Also, try to clear console cache.
Look at your javascript generates sources and check, whether it was updated or not