how many 5-digit numbers satisfy the following conditions

Question: How many five-digit numbers divisible by 11 have the sum of their digits equal to 30?
I am able to get the 5-digit numbers divisible by 11
and
I am also able to get the five-digit numbers whose sum of their digits equal to 30.
But i am not able to get how i can get the count of 5 digit numbers satisying both the condition.
Thanks in advance.
Thanks in advance.
combinatorics permutations
Comment: Perhaps the following rule helps:  A number is divisible by 11 if the sum the digits with alternating $\pm$ signs is zero or divisible by 11
Comment: Rereading your questions it seems that perhaps it is not complete:You talk about 5 digit numbers, and 7 digit numbers.
Answer: A number is divisible by $11$ if the sum of the digits in the tens and thousands place minus the sum of the digits in the ones, hundreds, and ten thousands place is divisible by 11.
So take a number:
$a b c d e$
$(b+d)-(a+c+e)$ is divisible by $11$ (it may be $0$).
$a+b+c+d+e=30$.
$a,b,c,d,e$ are all integers that may be $0$ through $9$.  $a\not=0$.
Combining the two equations above, $2(b+d)-30$ is divisible by $11$, but is also even (since $b$ and $d$ are integers), so it may be $0$, $22$, or $-22$.
If it is $22$, then $(b+d)=26$, which is a contradiction.
If it is $0$, then $(b+d)=(a+c+e)=15$ (condition 1)
If it is $-22$, then $(b+d)=4$ and $(a+c+e)=26$ (condition 2)
Take all such $a,b,c,d,e$ that satisfy the above statements.
If condition 1 holds, then there are $4$ different ways to choose $b$ and $d$ and $4+5+6+7+8+9+9+8+7+6=69$ ways to choose $a,c,e$ that satisfy $a+c+e=15$.  Thus, for condition 1, there are $276$ distinct numbers that satisfy condition 1.
If condition 2 holds, then there are $4$ different ways to choose $b$ and $d$ and $3$ ways to choose $a,c,e$.  So there are $12$ distinct numbers that satisfy condition 2.
Thus, there are $288$ distinct 5-digit numbers that satisfy the desired condition.
Answer: An integer written in ordinary base ten notation is divisible by $11$ if and only if the alternating sum of its digits is divisible by $11$. That is, if the digits of a five-digit number are $d_1,d_2,d_3,d_4,d_5$ from left to right, the number is a multiple of $11$ if and only if $d_1-d_2+d_3-d_4+d_5$ is a multiple of $11$. Let $x=d_1+d_3+d_5$ and $y=d_2+d_4$; you need to choose the digits so that $x+y=30$ and $x-y$ is a multiple of $11$. Since digits must be between $0$ and $9$ inclusive, the smallest possible value of $x-y$ is $-18$ (or $-17$ if you don't allow leading zeroes), and the largest possible value is $27$. Thus, the only possible multiples of $11$ are $-11,0,11$, and $22$. We'll consider each of them separately.
If $x-y=-11$, we must solve the system $$\begin{cases}x+y=30\\x-y=-11\;;\end{cases}$$ adding the equations yields $2x=19$, which is clearly impossible, since $x$ and $y$ must be integers. A similar problem arises if $x-y=11$, so we abandon that possibility as well.
If $x-y=22$, adding the equations yields $2x=52$, so $x=26$, and $y=4$. The only way to have three digits that sum to $26$ is to have two $9$'s and an $8$; two digits that sum to $4$ must be a $0$ and $4$, $1$ and $3$, or a pair of $2$'s. There are $3$ ways to arrange the first, third and fifth digits: $8\_9\_9$, $9\_8\_9$, and $9\_9\_8$. The other two digits can be chosen and arranged in $5$ ways: $\_0\_4\_$, $\_4\_0\_$, $\_1\_3\_$, $\_3\_1\_$, and $\_2\_2\_$. Thus, there are $3\cdot5=15$ numbers of the desired type in this case.
If $x-y=0$, we have $x=y=15$. To finish the problem, you need only count the number of ways to pick three digits adding up to $15$ for the first, third, and fifth slots, and two more adding up to $15$ for the remaining two slots. Clearly there are just $4$ ways to do the latter: $\_6\_9\_$, $\_9\_6\_$, $\_7\_8\_$, and $\_8\_7\_$. Can you finish it off from here?


How to replace deprecated WebSecurityConfigurerAdapter with multiple filters by SecurityFilterChain?

Question: I'm using spring boot 2.7.0 and want to remove the deprecated WebSecurityConfigurerAdapter. I have multiple configs which use one or more (different) filters. I want to update the configs so they don't use the deprecated WebSecurityConfigurerAdapter anymore like it is done in the official spring docs: https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter.
After changing the config (like done in the docs) the filters don't get called anymore.
This is my config now:
<code>@EnableWebSecurity
@Configuration
public class TestConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.antMatcher("/api/path/**")
            .regexMatchers(API_BASE_REGEX + "/ping").permitAll()
            .regexMatchers(API_BASE_REGEX + "/registrations").hasAnyAuthority(TestFilter.ROLE_USER, TestFilter.ROLE_USER_INACTIVE)
            .addFilterAfter(new TestFilter(), AbstractPreAuthenticatedProcessingFilter.class)
            .authorizeRequests().anyRequest().hasAuthority(TestFilter.ROLE_USER)
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
</code>
Filter example:
<code>public class TestFilter extends OncePerRequestFilter {
    public static final String ROLE_USER = "TESTUSER";
    public static final String ROLE_USER_INACTIVE = "TESTUSER_INACTIVE";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        ... (Internal Logic)

        filterChain.doFilter(request, response);
    }

}
</code>
How the config turns out after following the docs:
<code>@EnableWebSecurity
@Configuration
public class TestConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http.antMatcher("/api/path/**")
            .regexMatchers(API_BASE_REGEX + "/ping").permitAll()
            .regexMatchers(API_BASE_REGEX + "/registrations").hasAnyAuthority(TestFilter.ROLE_USER, TestFilter.ROLE_USER_INACTIVE)
            .addFilterAfter(new TestFilter(), AbstractPreAuthenticatedProcessingFilter.class)
            .authorizeRequests().anyRequest().hasAuthority(TestFilter.ROLE_USER)
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        return http.build();
    }
}
</code>
Comment: The bean method needs to be `public` and you are missing the `@EnableWebSecurity` annotation.
Comment: Adding the `@EnableWebSecurity` should be enough. If that doesn't fix it I doubt the configuration is even getting picked up.
Comment: @M.Deinum Thanks for your suggestion but it sadly doesnt fix the problem
Comment: The bean method doesn't need to be `public` at all. Can you share what the request looks like? Please add `logging.level.org.springframework.security=TRACE` to your `application.properties` file and share the content of the console after the request with us
Answer: According to documentation at: https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter
You need to use the filterChain bean like this:
<code>@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests((authz) -> authz
            .antMatcher("/api/path/**")
        .regexMatchers(API_BASE_REGEX + "/ping").permitAll()
        .regexMatchers(API_BASE_REGEX + "/registrations").hasAnyAuthority(TestFilter.ROLE_USER, TestFilter.ROLE_USER_INACTIVE)
        .addFilterAfter(new TestFilter(), AbstractPreAuthenticatedProcessingFilter.class)
        .authorizeRequests().anyRequest().hasAuthority(TestFilter.ROLE_USER)
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        )
        .httpBasic(withDefaults());
    return http.build();
}
</code>
You can add the ".antMatcher", ".regexMatcher", etc. with the 'authz' call.
Afterwards you can configure login and logout etc. as usual.
Or am I misunderstanding something? After all you posted the same documentation--
Ps: Im new to this formatting, so the code sample might have some problems.
Comment: Thanks for the suggestion :D It sadly didn't fix my problems


Can I treat a counting response variable as a continuous variable and run OLS?

Question: What I learned from book is predicting counting is different from predicting a continuous variable. For example, if we want to predict how many mails a person get per day, we may use Poisson regression.
However, if the counting number is big (for example, if we want to predict how many days are sunny in a year.), can we just treat it as a continuous variable? When $\lambda$ is large, the we can use normal distribution to approximate Poisson distribution. Am I right?
Comment: See a similar question and answers
https://stats.stackexchange.com/questions/93680/treating-ordinal-variables-as-continuous-for-regression-problems/407828?noredirect=1#comment762022_407828
Answer: A random variable is a counting variable does not only mean that it has natural number values. So, the number of sunny days in a year is not a counting random variable, because it is not the result of a counting process.  Probably, a day is declared sunny if some burocratic criteria are fulfilled, like at least 5 hours clear sun, or whatever. It is not a count of independent events.  Examples of count data is:  number of auto accidents in new york, per day. Number of stillbirths in Guatemala, per day. These are counting independent events, which could as a first approximation be modelled via Poisson distribution or a poisson point process.  I can see no such Poisson model lurking behind number of sunny days! For instance, have a look at my answer here: Goodness of fit and which model to choose linear regression or Poisson  The arguments used there are irrelevant in your case.
Back to your question, if "the count is big". It is not the bigness in itself that matters, big counts could still be Poisson (but big counts would in practice often be clustered and some more complicated model than poisson would be needed).  For number of sunny days in a year, you could sure try ordinary linear regression, as a starting point.
To elaborate on why "number of sunny days" is not a count variable.  First, number of hours of (sufficiently strong) sunshine is measured at meteorological stations with a Campbell–Stokes recorder, see https://en.wikipedia.org/wiki/Campbell%E2%80%93Stokes_recorder   They look like this:

and works by focusing the sun on a paper clip, and burning a path there when the sun is strong enough.  Then one have to measure the length of the burnt path. That gives a measured variable, not a count variable!  The underlying process is measurement, not counting.  Then this is converted into a binary sunny/not sunny indicator by some arbitrary ("burocratic") cutoff.  Hope this is a better explanation of my answer!
Comment: I believe your characterization of "count" data is much more restrictive than most people intend.  Count data are special not because they are assumed to have Poisson distributions! They can indeed be dependent, too.  Whether or not the criteria for determining what is counted are "bureaucratic" or not doesn't matter, either.  The number of sunny days is an *excellent* example of count data.
Comment: Measurement is a red herring here.  When you're counting green jelly beans, you are making a measurement (of color).  When you're counting isopods, you are classifying them into a genus or size class according to measurements. When you're counting sunny days, you are classifying them into sunny and not-sunny by making measurements.  The fact that the measurement might be continuous, or subject to uncertainty, or correlated, or even arbitrary, is irrelevant to the fact that you're dealing with counted data.
Comment: @whuber: I admit I have never seen a formal definition of "count data", but if it is'nt based on some kind of point process (yes, independence is to strong) then the concept becomes to opaque to have much meaning.  What do counting number of sunny days have in common with counting accidents? (except of the word "counting")
Comment: @kjetilbhalvorsen thanks for the knowledge about sunshine measure!, I did not expect I will get this level of detail. Sunny days is just the first example in my head. So, according to your answer, it really matters on how the variables are measured? and one would different than another? How about something like, number of meetings a person attend in a month or number of active days in the online form? It would be different than sunny days analogy?
Comment: This is being argumentative, the underlying problem being that there is no (or I can't find any) "official" definition of "count data" or "count data models". I have been googling a little, did not find a single paper or website that bothers to define "count data".  But taking the sunshine example, if you are "counting", then you are counting successes (or failures), not events. That lead to a binomial distribution, maybe logistic regression, which is noy usually included in treatments of "count data models".  But without definitions, no surprise that we start arguing ...
Answer: At the fundamental level of chemistry and atomic theory, one could argue that the world is discrete rather than continuous. One might argue that continuous variables themselves are just very useful approximations to an underlying discrete reality. So clearly it is OK to treat counts as continuous variables. We do it all the time in practice.
This is different from the issue of whether Poisson approximations are appropriate for any particular application. The answer from @kjetil covers that well.
Comment: Notwithstanding debates over particle-wave duality, the existence of particles (currently believed fundamental by empirical induction) allows the interpretation that ordinary matter is discrete. I am not aware of how that implies that time/space/space-time are discrete.


AWS ELB stops showing instance as healthy and access logs show no entries

Question: I have a load balancer configured in a public vpc subnet to route traffic from HTTPS (443) to an instance in a private vpc subnet over HTTP (8080).
The setup worked fine for about 24 hours, until the java process on the instance crashed. At this point, the health check started failing and the instance began showing as unhealthy.
I've since restarted the process and can make local 'curl' requests locally on the EC2 instance, as well as from the NAT instance I have in the public subnet (same subnet as the load balancer). Despite the instance being in a healthy state, the load balancer still shows it as unhealthy.
What seems particularly odd to me is that the access log on the EC2 instance no longer shows any attempts from the Load Balancer to access the healthcheck URL. I enabled logging on the load balancer to an S3 bucket but this has only shown a single GET request with a 503 error code.
I've tried unregistering the instance from the load balancer and re-registering it but that made no difference.  Stopping and starting the instance and re-registering it with the load balancer also made no difference
Any ideas why the load balancer isn't even attempting to access the instance?
Thanks for any suggestions!
Comment: Still no answer from AWS support forums, however de-registering the instance, restarting the instance, re-registering the instance...and waiting 18 hours did seem to have an effect.  Finally the load balancer started sending healthchecks which show in the application access logs.
Comment: What does AWS support say?
Comment: I'm waiting for their response (and will post the answer if I get one) but thought the community would be a good place to start.
Answer: It could also be an issue with the .htaccess rules in your public html folder.
Is your .htaccess folder rewriting to a folder?
It was an issue for me also, where the default health check is set to http:80/index.php
But my rewrite was to a folder on the server. So it gave status as unhealthy.
Although i would like to keep my rewrites with .htacess on, but removing .htacess rules allowed elb to ping my public html folder and declare instances as healthy.
Please do let me know if it helps.
Thanks
Comment: Good suggestion, but I think it's unlikely in this case.  The application runs under JBoss, but even the JBoss proxy settings did not change between it working and being broken.
Comment: Here's what can be done.
If you have installed apache on your server, you can keep a healthcheck file on your public html folder and point that in the elb as well.
In that way, you should be able to check the status of the instances
unless if you want to check JBoss server status, which i think in this case is not the purpose.


Operation not allowed after ResultSet closed when deleting from a database

Question: I am currently trying to delete items from my database using JDBC but am getting an error that I can not figure out how to get away. The error is:
Caused by: java.sql.SQLException: Operation not allowed after ResultSet closed

Here is the java:
    System.out.println("Connecting database for Delete...");
    Integer deletedCount = 0;

    Statement deleteStatement = null;
    try (Connection conn = DriverManager.getConnection(url, username, password)) {
        System.out.println("Database connected!");
        deleteStatement = conn.createStatement();
        String selectDelete = "SELECT id FROM table WHERE end <= (NOW() - INTERVAL 1 HOUR)";

        ResultSet rs = deleteStatement.executeQuery(selectDelete);

            while (rs.next()) {

                String eventid = rs.getString("id");
                String deleteSQL = "DELETE FROM table WHERE id = " + eventid;
                deleteStatement.executeUpdate(deleteSQL);
                deletedCount++;
                System.out.println(deletedCount);
            }
       System.out.println("Completed Delete! "+ deletedCount +" deleted!");
    } catch (SQLException e) {
        throw new IllegalStateException("Cannot connect the database!", e);
    }

What I am doing here is first selecting all the items that date has already passed and setting it to a result set. I then go through a while loop in an attempt to delete them from the database. It runs through one time and get the error which I will fully put below. Would I need to create a new delete statement every time I go through the loop? I can not figure a way to properly do this.
Here is the full error:
Connecting database for Delete...
Database connected!
1
Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database!
at JDBC.deleteOverDueEvents(JDBC.java:56)
at EventJSON.main(EventJSON.java:31)
Caused by: java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:743)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6313)
at JDBC.deleteOverDueEvents(JDBC.java:45)
... 1 more

Answer: Why SELECT, LOOP and DELETE when
String deleteSQL= "DELETE FROM table WHERE end <= (NOW() - INTERVAL 1 HOUR)";
Statement deleteStatement = conn.createStatement();
deleteStatement.executeUpdate(deleteSQL);

would work more efficiently
Comment: That would make more sense. I was doing the loop to get the number of deleted items. Can you return it just from that statement?
Comment: Yep, see the return value from https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)
Comment: Perfect, didn't know that returned.
Answer: When the line
deleteStatement.executeUpdate(deleteSQL);

is executed, then ResultSet rs is automatically closed:

A ResultSet object is automatically closed when the Statement object
  that generated it is closed, re-executed, or used to retrieve the next
  result from a sequence of multiple results.

But you can solve this simply by running
String deleteCmd = "DELETE FROM table WHERE end <= (NOW() - INTERVAL 1 HOUR)";
int deletedCount = deleteStatement.executeUpdate(deleteCmd);

instead of selecting the records and deleting each of them.
Answer: I think this is happening because your deleting the row while looping to the result set and your logic is totally wrong. Your selecting all ids with  "end <= (NOW() - INTERVAL 1 HOUR)" then delete it afterward. Why not delete it all in the first place? like this "DELETE FROM table WHERE end <= (NOW() - INTERVAL 1 HOUR)". If you need to get the count to a select statement first then to the delete query.


How can I pass a String as a model to a View in MVC 5?

Question: I have an action defined like this:
    public ActionResult TempOutput(string model)
    {
        return View(model);
    }

And also, I have its view defined like this:
@model String

@{
    ViewBag.Title = "TempOutput";
}

TempOutput

@Model

Then, at one place, I have a return statement like this:
return RedirectToAction("TempOutput", "SEO", new { model = "Tester text" });

And the point is that when I get to my TempOutput view I get an error message saying "The view 'Tester text' or its master was not found or no view engine supports the searched locations.". But I jsut want to print the value of the string inside my view. How can I achieve it?
Comment: Is there a reason you are using RedirectToAction and not a normal return View(model)?
Answer: You are calling different override of View than you want:
View(string viewName);

You want to call View(string viewName, string masterName, object model) like following:
return View(null, null, model);

You can also specify explicit value (i.e. "TempOutput") for view name.
Alternatively you can force selecting View(object model) override by casting "model" to object:
return View((object)model);

Or, you can overload it using Named Arguments
return View(model: model)

Comment: Alexei, I think it would need to be `return View(null, null, model);` because there is an overload that accepts parameters `string viewName, string masterPageName, object model`
Answer: If I remember correctly if you have to use the RedirectToAction you can pass model data like this:
TempData["model"] = "Tester text";
return RedirectToAction("TempOutput", "SEO");

More information about TempData found here.


Paginate Firebase rest api

Question: I am using Firebase REST API to get my data. I am getting data like
[ {
  "date_time" : "2018-01-03 03:30:00",
  "domestic" : "0",
  "f_key" : "",
  "id" : 2,
  "international" : "1",
  "league" : "0",
  "match_number" : "One-day practice match",
  "men" : "1",
  "odi" : "1",
  "result" : "Pakistan won by 120 runs",
  "series_name" : "Pakistan tour of New Zealand, 2018",
  "status" : "2",
  "t1_short_name" : "NZ",
  "t20" : "0",
  "t2_short_name" : "PAK",
  "team1" : "New Zealand",
  "team1_flag" : "https://storage.googleapis.com/ce_flags/nz.png",
  "team2" : "Pakistan",
  "team2_flag" : "https://storage.googleapis.com/ce_flags/pak.png",
  "test" : "0",
  "venue" : "Saxton Oval, Nelson",
  "women" : "0"
}, {
  "date_time" : "2018-01-03 03:30:00",
  "domestic" : "0",
  "f_key" : "",
  "id" : 159,
  "international" : "1",
  "league" : "0",
  "match_number" : "One-day practice match",
  "men" : "1",
  "odi" : "1",
  "result" : "Pakistan won by 120 runs",
  "series_name" : "Pakistan tour of New Zealand, 2018",
  "status" : "2",
  "t1_short_name" : "NZ",
  "t20" : "0",
  "t2_short_name" : "PAK",
  "team1" : "New Zealand",
  "team1_flag" : "https://storage.googleapis.com/ce_flags/nz.png",
  "team2" : "Pakistan",
  "team2_flag" : "https://storage.googleapis.com/ce_flags/pak.png",
  "test" : "0",
  "venue" : "Saxton Oval, Nelson",
  "women" : "0"
} ]

but when i am trying to paginate them its not working i am using like this
https://fir-resttest-4e895.firebaseio.com/Fixtures/All.json?orderBy=%22date_time%22&limitToFirst=2&startAfter=10&print=pretty

how can i use pagination here please  help me to sort out this.
Thanks
Answer: Firebase Database queries do not support an offset parameter like you might be used to.
The value that you pass for startAt must be a value of the type/format of the property you have in orderBy. Since you order on date_time the value of startAt must be a valid date_time:
This will give you all items starting at 2018-01-03 03:30:00.
orderBy="date_time"&limitToFirst=2&startAt="2018-01-03 03:30:00"

Also note that the parameter is called startAt, not startAfter.
Some examples for your data set:

startAt="2018-06-01 20:30:00"
startAt="2018-06-01" (so you can also start at a substring)
Comment: That seems to have nothing to do with this question. If you have a problem of your own, please post a new question with the [minimal complete code that reproduces the problem](http://stackoverflow.com/help/mcve).

Paginate Firebase rest api


Centralizar horizontalmente a logo da página html css

Question: Como centralizar horizontalmente meu logo, essa minha seta não está muito centralizada horizontalmente, queria que estivesse... Alguém pode me ajudar? Tentei o top: 50% e não funcionou...

@charset "UTF-8";
html {
  overflow-y: scroll;
}
.postagem {
 background-color: rgba(255,140,40,.05);
 margin: 0px;
}
#interface {
 width: 1200px;
 background-color: white;
 margin: 90px auto 10px auto;
 box-shadow: 0px 4px 6px 3px rgba(0,0,0,.1);
}

.cabecalho {
 transition: 0.2s;
 top: 0px;
 position: fixed;
 width: 100%;
 height: 38px;
 background-color: rgba(255,140,40,1);
 margin-bottom: 0px;
 padding-bottom: 20px;
 padding-top: 20px;
 text-align: center;
}
.logo {
 margin: 0px 0px 0px 0px;
 color: rgba(255,255,255,1);
 font-family: agency fb;
 font-size: 20pt;
 /*display: inline-block;*/
}
#fcor {
 color: rgba(255,220,180,1);
}
.artigo {
 padding: 15px 25px 15px 25px;
}

.titulo {
 font-family: arial;
 font-size: 12pt;
 color: rgba(0,0,0,.8);
 margin: 0px 0px 5px 0px;
 padding: 0px;
}

.paragrafo {
 margin: 0px;
 padding: 0px;
 color: rgba(0,0,0,.6);
 font-family: arial;
 text-align: justify;
}
.li {
 font-size: 20pt;
 font-weight: 900;
}
.link {
 color: black;
 text-decoration: none;
}
.link:hover {
 font-style: none;
 text-decoration: underline;
}
.icone {
 transition: 2s;
 border: solid white 6px;
 box-shadow: 4px 4px 6px 2px rgba(0,0,0,0.1);
 height: 300px;
 width: 300px;
}
#flecha {
 left: 10px;
 position: absolute;
 margin: 0px 0px 0px 0px;
}
/*Folhas de estilo de tabela*/
.tabela {
 border-collapse: collapse;
}
.tdn {
 border: solid black 2px;
 padding: 2px;
}
.vazio {
 border: solid black 2px;
 padding: 12px;
}
.vazio#vm {
 padding: 36px;
}
.tabt {
 background-color: white;
 padding: 2px;
 border: solid black 2px;
}
.subt {
 background-color: lightgray;
 padding: 2px;
 border: solid black 2px;
}
.ft {
 border: solid black 2px;
}
.asst {
 padding: 12px;
 font-weight: 900;
 text-align: center;
}
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title></title>
 <link rel="stylesheet" type="text/css" href="../_css/estilo.css"/>

MANUAIS E PROCESSOS INFORMÁTICA

INSTALANDO SISTEMA OPERACIONAL

   1. Clique com o lado direito na bandeira do Windows ou use o atalho(Windows+X) para abrir o menu abaixo, nele escolha a opção "Sistema".

   2. Vá em "Renomear este computador" e coloque o nome da etiqueta do computador, após isso será necessário reiniciar o computador.

Comment: A dúvida que eu tinha não era referente a um código em si, e sim sobre css e html, se fosse colocar o código teria que colocar o de todas as páginas para ter uma comparação... Mas já resolvi e coloquei outra dúvida no lugar.
Comment: O problema é na logo ou na seta? Qual seria a logo? "Horizontalmente" ou "verticalmente"? Ficou bem confusa a pergunta.
Answer: Sugiro dar uma lida nesse guia de Flex Container, onde terá diversos exemplos de centralização.
Abaixo está o código, utilizei o justify-content: center e o align-items: center para centralizar horizontalmente e verticalmente as
 de cada elemento. Utilizei também o flex-grow para determinar o tamanho que cada um irá ocupar, deixando um pequeno espaço para a seta e todo o restante da área para o logo:

$(document).scroll(function(){
  var y = $(this).scrollTop();
  if (y < 25) {
    $('.cabecalho').css({'padding-top': '20px','padding-bottom': '20px'});
  }
  else {
    $('.cabecalho').css({'padding-top': '6px', 'padding-bottom': '6px'});
  }
});
@charset "UTF-8";
html {
  overflow-y: scroll;
}
.postagem {
 background-color: rgba(255,140,40,.05);
 margin: 0px;
}
.cabecalho {
 transition: 0.2s;
 position: fixed;
 width: 100%;
 height: 38px;
 padding-bottom: 20px;
 padding-top: 20px;
 background-color: rgba(255,140,40,1);
 margin-bottom: 0px;
 display: flex;
 align-items: center;
}
.logo {
 color: rgba(255,255,255,1);
 font-family: agency fb;
 font-size: 20pt;
}
#fcor {
 color: rgba(255,220,180,1);
}
.seta{
 flex-grow: 0;
 display: flex;
 justify-content: flex-start;
 align-items: center;
}
.letras{
 display: flex;
 justify-content: center;
 align-items: center;
 flex-grow: 1;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>teste</title>

MANUAIS E PROCESSOS INFORMÁTICA


Ubuntu Iptables FTP passive mode

Question: I have a problem when trying to define iptables rules in my ubuntu server.
I reject all connections and allow some like FTP.
The problem is that in passive mode I can connect but I cannot list folders.
I tried a lot a things I found on the net but no success.
In my iptables rules I have
<code>-P INPUT DROP
-P FORWARD DROP
-P OUTPUT DROP
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A OUTPUT -p tcp --dport 20:21 -j ACCEPT
-A INPUT -p tcp --dport 20:21 -j ACCEPT
-A INPUT -p tcp --dport 21 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -p tcp --dport 21 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
</code>
Any idea?
Answer: Your iptables rules are very duplicated and think you are missing one iptables module.
<code>modprobe ip_nat_ftp

-P INPUT DROP
-P FORWARD DROP
-P OUTPUT DROP
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp --dport 20:21 -m state --state NEW -j ACCEPT
-A INPUT -p tcp --dport 21 -m state --state NEW -j ACCEPT
</code>
Comment: Hi, what do you say the rules are duplicated ?
Comment: The modules are normally added. The command lsmod | grep ftp shows : nf_nat_ftp,  nf_conntrack_ftp, nf_nat, nf_nat_ftp, nf_conntrack, nf_nat_ftp, nf_nat, xt_conntrack, nf_conntrack_ftp, nf_conntrack_ipv4
Comment: I added the module by editing /etc/rc.local and adding the 2 lines :
/sbin/modprobe nf_conntrack_ftp
/sbin/modprobe ip_nat_ftp
Comment: because if one rule with new state is accepted doesn't new one rules in the output chain to work.
Comment: Hi sorry but I don't get it. If you want to say that RELATED,ESTABLISHED rules should come after then I also tried that

Ubuntu Iptables FTP passive mode


Como fazer query com count

Question: Eu tenho a tabela Resultado com milhares de dados,
Tabela Resultado
    NOME_CASA,   NOME_OPONENTE, RESULTADO_FINAL, NOTA_FINAL.
    timeAzul     timePreto         1             2
    timeAzul     timeBranco        2             2.10
    timeBranco   timeAzul          3             2.20
    timeCinza    timeAzul          3             1.7
    timeverde    timePreto         1             1.92
    timePreto    timeRosa          2             2.05
    timeAzul     timeBranco        1             2.08

Acima mostrei apenas um resumo das colunas e dados na tabela, observem que os dados podem se repetir, para entendimento melhor da pergunta dividi em 2 query que vai nos auxiliar na minha dúvida:
QUERY 1- Retorna todas as equipe da casa, que a nota final esteja entre 2 e 2.20.
SELECT NOME_CASA FROM Resultado where  NOTA_FINAL between 2 and 2.20

QUERY 2 - Retorna todas as equipe da casa, com nota final entre 2 e 2.20, e filtra os que o resultado_final foi igual a 1.
   SELECT NOME_CASA FROM Resultado where  NOTA_FINAL between 2 and 2.20 and RESULTADO_FINAL = 1 ;

Vejam que a consulta fiz na tabela inteira. Agora, eu preciso pegar todas as NOME_CASA que a aplique os dois filtros que citei para cada time especifico, ou seja retornar os nomes dos times onde jogando com nota_final 2 e 2.20, 60% das vezes ou mais termine com o resultado_final =1; Ou seja testaria essa condição para cada time, e retornaria o nome deles.
Resumindo preciso dos nomes das equipes(NOME_CASA) sem duplicar, que 60% das vezes terminam com o resultado_final = 1, quando as NOTA_FINALdele estejam entre 2 e 2.20.
Usando os dados que postei como exemplo, somente o timeAzul retornaria na consulta que preciso, pois em um total de 3 jogos do timeAzul, 3 atendia a query1 e 2 deles terminaram com o resultado_final = 1. Então(2 * 100) / 3 = 66.6%¨
Como montar essa query?
Comment: Olá Clara, pelo que entendi você quer trazer as equipes que possuem um total de registros(usando os filtros da Query2) acima de 60% da quantidade de resultados da *QUERY1*, certo?
Comment: @AndréFilipe na verdade quero buscar todos as equipes(nomeCasa) que emn 60% ou mais das vezes, tiveram o resultado_final = 1, quando a nota_final deles esteja entre 2 e 2.20. Note que a query1 que usei é para toda tabela posso ter errado nisso, preciso saber de cada time. Exemplo todas as evzes que o time azul jogou e estava a nota_final entre 2 e 2.20, digamos que retorne 10 jogos, agora preciso saber quantos desses jogos o resultado_final = 1, digamos q foi 7, então temos 70%. Sendo que isso foi pra apenas um time,quero uma query que traga o nome de todos os times que estejam nessa condição.
Comment: @AndréFilipe acabei de editar o post, eu posso ter me expressada errado
Comment: Clara, fiz uma resposta de seu caso e me dê um retorno se é como esperado.
Answer: Lí umas dezenas de vezes sua pergunta para conseguir entender o seu problema, espero que esteja no raciocínio correto.
Utilizando a cláusula count(*) consegui a quantidade de registros para cada query, e na cláusula HAVING criei a lógica da porcentagem % da qual comentou em sua pergunta.
SELECT NOME_CASA AS NOME_CASA_COLUNA,
       count(*) as qtd_query2
FROM Resultado
       WHERE NOTA_FINAL between 2 and 2.20 and RESULTADO_FINAL = 1
GROUP BY NOME_CASA
HAVING ((qtd_query2 * 100) /
    ( SELECT count(*) AS qtd_query1
        FROM Resultado
        WHERE NOTA_FINAL between 2 and 2.20 AND NOME_CASA = NOME_CASA_COLUNA
     GROUP BY NOME_CASA HAVING qtd_query1 > 1)) > 60;

Nessa query apliquei a Query2 como consulta externa e em seguida faço uma validação com a quantidade total de registros da Query2 e verifico se ela é equivalente à
60% ou mais que a quantidade de registros retornados na Query1.
Comment: Exatamente, muito obrigada!!!
Comment: Fico feliz em poder ajudá-la!
Answer: Veja também no fiddle.
SELECT nome_casa,
       COUNT(CASE WHEN resultado_final = 1 THEN 1
                  ELSE NULL
             END) / COUNT(*) AS percentual
FROM Resultado
WHERE nota_final BETWEEN 2.00 AND 2.20
GROUP BY nome_casa
HAVING percentual >= 0.60;

Answer: Pelo o que eu entendi, você quer usar o COUNT para montar essa query query ((Query2 * 100) / QUERY2) e obter um resultado numérico. Tente fazer dessa forma:
((SELECT COUNT(nome_casa) FROM resultado WHERE nota_final BETWEEN 2 AND 2.20) * 100) / (SELECT COUNT(nome_casa) FROM resultado WHERE nota_final BETWEEN 2 AND 2.20 AND resultado_final = 1)

Comment: Juliana, eu editei o post, acho que  tinha ficado confuso. Eu preciso pegar todas as NOME_CASA que a aplique os dois filtros que citei para cada time especifico, ou seja retornar os nomes dos times onde jogando com nota_final 2 e 2.20, 60% das vezes ou mais termine com o resultado_final =1; Ou seja testaria essa condição para cada time, e retornaria o nome deles.

Como fazer query com count


Equation for Inverse Poisson CDF

Question: I am attempting to calculate quantile probabilities. I.e., the value above which there is only a 1% chance occurrence for an arrival process.
The R code is pretty straight forward with say a lambda = 2.
qpois(.99, 2, lower.tail = TRUE, log.p = FALSE)
But what is the inverse Poisson CDF equation?
Comment: The help page for `qpois` explains the algorithm.  It necessarily involves a numerical search.
Comment: @whuber That's interesting; I'd have assumed the quickest way would would be to use the relationship with the chi-square (and hence call an inverse incomplete gamma routine). Not having worked it through I'm probably missing something obvious though.
Comment: @glen_b Your suggestion works pretty well.  Here's a quick-and-dirty implementation.  Half the code is just to find an upper bound on the solution.  `qpois0 <- Vectorize(function(q, lambda, ...) {
  f <- function(n) pgamma(lambda, n, lower.tail = FALSE, log.p = TRUE) - log(q);
  n.max <- pmax(1, qnorm(q, lambda, sqrt(lambda)));
  while(ppois(n.max, lambda) <= q) n.max <- 2 * n.max;
  floor(uniroot(f, c(0, n.max+1), ...)$root)
})`
Comment: @glen The Gamma shape parameter is varied in the search.
Answer: Quantile function: If you already have the CDF $F$ available, you can write the quantile function for the Poisson distributon as:
$$\begin{align}
Q(p)
&\equiv \inf \Big\{ x = 0,1,2,... \Big| \ p \leqslant F(x) \Big\} \\[12pt]
&= \sum_{x=0}^\infty \mathbb{I}(F(x) < p) \\[6pt]
&= \sum_{x=0}^{x_U-1} \mathbb{I}(F(x) < p) \\[6pt]
&= \sum_{x=0}^{x_U-1} \mathbb{I}(\log F(x) < \log p), \\[6pt]
\end{align}$$
where $x_U$ is any non-negative integer that satisfies $F(x_U) \geqslant p$.$^\dagger$  I will call this formula the long-sum form.  You can also write it as:
$$\begin{align}
Q(p)
&= x_L + \sum_{x=x_L}^{x_U-1} \mathbb{I}(\log F(x) < \log p), \ \ \ \\[6pt]
\end{align}$$
where $0 \leqslant x_L < x_U$ is any non-negative integer that satisfies $F(x_U) < p$.  I will call this latter formula the short-sum form.  I have expressed both formulae in their final form using log-probabilities (instead of probabilities) because it is more accurate to use log-probabilities for computation.

Methods of computation: One simple way to construct an algorithm to compute the Poisson quantile function is to use the long-sum formula, with a first step that identifies an appropriate upper bound $x_U$ from some preliminary step.  Alternatively, you can use the short-sum formula and search only over values between the lower and upper bound.  Alternatively, you can use a "search method over the values between these bounds, where you directly look for the infimum value in the initial definition.
According to the documentation for the qpois function it uses the Cornish–Fisher Expansion followed by a search for the appropriate quantile value.  The function calls the underlying C function C_qpois.  The description suggests a search near the approximating value using the infimum definition.

Computation from the long-sum form: It is possible to compute the quantiles using the long-sum form by having a preliminary step that computes an upper bound $M$.  There are a number of statistical papers that explore probability inequalities for the Poisson distribution (see e.g.,
Hoeffding 1963,
Anderson and Sanders 1967, Short 2013).  However, for simplicity, I will show how you can form a consevative bound using the Chebychev inequality.  This inquality gives:
$$\begin{align}
F(\lfloor \lambda + k\sqrt{\lambda} \rfloor)
&\geqslant \mathbb{P}(\lambda - k\sqrt{\lambda} < X < \lambda + k\sqrt{\lambda})
> 1-\frac{1}{k^2}. \\[6pt]
\end{align}$$
Setting $p=1-1/k^2$ gives $k = 1/\sqrt{1-p}$ so that:
$$x_U = \Bigg\lfloor \lambda + \sqrt{\frac{\lambda}{1-p}} \Bigg\rfloor.$$
We can implement this method in the function below.  We treat the input probability $p=1$ as a special case giving the quantile $q=\infty$ as an output.  We also allow inputs that are NA values and we replicate the output of the base function in this case.  Remaining quantiles are computed from the long-sum formula above.
qpois.alt <- function(p, lambda, lower.tail = TRUE, log.p = FALSE) {

  #Set log-probabilities (lower tail)
  n <- length(p)
  if (log.p) { LOGP <- p } else { LOGP <- log(p) }
  if (!lower.tail) { LOGP <- VGAM::log1mexp(-LOGP) }

  #Set output and deal with special cases (outputs NA and Inf)
  QUANTILES <- as.numeric(rep(NA, n))
  NNA   <- !is.na(LOGP)
  NLOGP <- LOGP[NNA]
  if (length(NLOGP) == 0) { return(QUANTILES) }
  QUANTILES[NNA] <- rep(Inf, length(NNA))
  if (min(NLOGP) >= 0)    { return(QUANTILES) }

  #Set log-CDF vector
  LP.MAX <- max(NLOGP[NLOGP < 0])
  UPPER  <- floor(lambda + sqrt(lambda*exp(-VGAM::log1mexp(-LP.MAX))))
  LOGCDF <- ppois(0:UPPER, lambda, lower.tail = TRUE, log.p = TRUE)

  #Compute output
  for (i in 1:n) {
  if (NNA[i]) {
  if (LOGP[i] < 0) {
    QUANTILES[i] <- sum(LOGCDF < LOGP[i]) } } }

  #Return output
  QUANTILES }

Using the benchmark function it is possible to compare the run-speed of the alternative methods of programming the function.  From the output below you will see that my version is a bit slower (but not much) than the version in the base package.  (Note that the exact output from the benchmarking test depends on the speed of your computer and any background processes, etc., but the relative comparison should be reasonably stable over a large number of replications.)
#Benchmark the function against base version
library(rbenchmark)
PROBS <- 0:1000/1000
REPS  <- 10^5
BENCH <- benchmark('qpois'      = { qpois(PROBS, lambda = 2) },
                   'qpois.alt'  = { qpois.alt(PROBS, lambda = 2) },
                   replications = REPS)

#Show the benchmarking output
BENCH

       test replications elapsed relative user.self sys.self user.child sys.child
1     qpois       100000   45.88    1.000     34.90    10.90         NA        NA
2 qpois.alt       100000   58.18    1.268     58.11     0.05         NA        NA

$^\dagger$ The bounds $x_U$ and $x_L$ implicitly depend on $p$, but we have written the notation without this dependence for brevity.

Equation for Inverse Poisson CDF


How do I retrieve the tokenised path for the Files Directory setting configured via the fields settings?

Question: I'm using this code to retrieve a remote file, during the process of creating a new a media entity.
$url = 'https://example.com/example.jpg';
$image = system_retrieve_file($url, NULL, TRUE);
$entity_array['field_example'] = [
  'target_id' => $image->id(),
];

The second parameter in system_retrieve_file() determines that the file is stored in the public:// directory.
How can I retrieve the tokenised defined in the file fields settings?
Answer: So I had to make a function that I pass a bundle and field name too. Both are in the form of strings. The function then returns a uri with the tokens replaced.
function getFileDirectory($media_type, $field_name) {

        // Fetch all field definitions for the media bundle.
        $fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('media', $media_type);
        foreach ($fields as $field => $field_definition) {
            $bundle = $field_definition->getTargetBundle();

            // Look for the field we need
            if ($bundle == $media_type && $field == $field_name) {

                // Get the settings for the field, in order to start building the directory path
                $settings = $field_definition->getSettings();
                $file_directory_path_tokens = $settings['file_directory'];
                $uri_scheme = $settings['uri_scheme'];

                // Convert tokens in files directory string
                $token = \Drupal::token();
                $directory_path = $token->replace($file_directory_path_tokens);

                // If there is a value for the file directory setting on the file field, ensure the directory exists,
                // if not create it.
                if ($directory_path) {
                    $directory = $uri_scheme . '://' . $directory_path;
                    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
                    $file_system = \Drupal::service('file_system');
                    $file_system->prepareDirectory($directory, FileSystemInterface:: CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
                    return $directory;
                }
                // Otherwise just return the uri_scheme ie public:// or private://
                else {
                    return $uri_scheme . '://';
                }
            }
        }
    }

This is specific for media entities. It wouldn't be too much bother to extend it to be more generic to cover all entities.
I hope this saves someone some pain.


Copy Paste In JavaScript

Question: This is an age-old question, but I'm still having trouble with it. You see, I'm trying to paste some Excel data in a Text Area, but the silly browsers freeze for long periods of time when doing this, because of God-knows-what "smart" parsing they do. I can't get rid of that (file upload is out of the question, my boss wants me to paste rows from Excel in a Text Area).
The good news is that pasting in a standard textbox WORKS. But I can't force them to paste there. So I am trying to catch the paste event in the Text Area and then throw the text over to the textbox. Unfortunately, I stopped short at the pasting part. I can't paste the text via JS into the simple textbox.
So my question is: how do you paste a text, how do you invoke it via JS? There are some solutions which only work in IE, that's not good, of course ::- ).
Comment: The regular textbox is faster because it only holds one line (duh).
Comment: Duh of course. But it still pastes Excel data ok, separated by tab.
Answer: Simple.

var isIe = (navigator.userAgent.toLowerCase().indexOf("msie") != -1
            || navigator.userAgent.toLowerCase().indexOf("trident") != -1);

document.getElementById('textinput').addEventListener('paste', function(e) {
    var text;

    if (isIe) {
        text = window.clipboardData.getData('Text')
    } else {
        text = e.clipboardData.getData('text/plain');
    }

    // Do whatever you want with the text
    console.log(text);

    //If you don't want the text pasted in the textarea
    e.preventDefault();
});
<textarea id="textinput"></textarea>

If you want, you can even get rid of the textarea and do this more directly. I wrote a technical blog post explaining how we do copying and pasting at Lucidchart (where I work).
Answer: Sorry, didn't quite catch the idea. Can't you attach to thextarea's onpaste event (at least I know IE has such event) and then simply set textarea's value to the pasted value?
    pastedContent = window.clipboardData.getData("Text");
    document.getElementById("yourtextarea").value = pastedContent;

EDIT: ok, it seems like this only works in IE and newer versions of FF, but it's not a cross-browser solution.
Comment: This is an IE-only solution ::- (
Answer:
I can't paste the text via JS into the simple textbox

When you say "simple textbox", do you mean <input type="text">? If so, then I think setting its value attribute to the text you've captured from the <textarea> should work.
Comment: as far as I understand, the problem is catching the "paste" event in a cross-browser manner
Comment: I can catch the paste event, but not the pasted data. There are some commands like ExecCommand but they only work in IE.
Comment: Ah. How about: 1. Let the paste event complete in the ``. 2. Read the `value` attribute of the textarea to get the pasted text. 3. Set the `value` of the `` to an empty string. 4. Set the `value` of the normal text field to the text you got in step 2.
Answer: Enable  javascript Copy to Clipboard in Firefox or Mozilla: http://www.febooti.com/support/website-help/website-javascript-copy-clipboard.html
Comment: this is not a solution as you can't control users' FF settings remotely.
Answer: Try CodeMirror as alternate solution. Doesn't check it with copy&paste with huge/excel amount of data but maybe this help...

Copy Paste In JavaScript


my image loads properly on running on eclipse , but when exporting as jar and opening it there is no image at all

Question: The image appears when i run the main class in eclipse but doesn't appear when i export as executable jar file. Even when everything works fine.
icon =new ImageIcon(new ImageIcon("robot.png").getImage().getScaledInstance(150, 150, Image.SCALE_DEFAULT));
label=new JLabel(icon);

Answer: Your image is no longer a "file" when it's packed into a jar, so loading it this way can not work. You can ask your class for a usable URL for the image's contents using #getResource() and use the resulting URL to construct your ImageIcon.
Comment: dude i tried doing this it gave me class not found error , the class name here"GUI"  is the class i wrote the code https://pastebin.com/LxFf7MiM
Comment: If your code is in the GUI class, use getClass(). If not, use GUI.class. You don't have to look up one of your own classes using its name, and that might not work if it's not declared in a package.


Rules: Display Message every first login per day; reset day 12:00am

Question: I am trying to create a rule that will display a message to the user when (s)he logs in for the first time that day.  Reset has to be per day at 12:00am.
Notice: not the first time in 24 hours but the first time that day.
So if user logs in 8/30/2016 11:59 and then 8/31/2016 12:01am then both times (s)he will see message.
I tried to achieve this using event 'User has logged in' and condition: data comparison and comparing last login date with current date and time and offset 1 day.  But it's not workings.  It might be possible to do this with the custom php?
Thanks God Bless.
------------------------------------------Update------------------------------------------
9/1/2016
I need help creating the following rule:
Trigger: User logs in
Condition: User hasn't logged in this today(since 12:00AM)
Action: Display message to user
Am I doing something wrong, or can this be achieved with custom Php?
My attempt is described in first update.  Can't seem to make this work.  The message should only appear every day.
Day = 12:00:00AM - 11:59:59PM
Answer: There's a few things to mention here.

Using the [account:last-login] token won't work here; Drupal's login process updates the user account login timestamp before User logs in event.
Using the [account:last-access] token will work however because the User logs in event triggers before Drupal updates the access timestamp.
PHP's strtotime() has a special keyword for the significant time you're looking for; strtotime('midnight') produces the timestamp of when the current day started.

Putting that together, you can create your own custom rules condition via hook_rules_condition_info() and using it compare against the [account:last-access] token in the User logs in event to produce the effect you're looking for:
/**
 * implementation of hook_rules_condition_info()
 */
function MYMODULE_rules_condition_info() {
  return array(
    'MYMODULE_condition_before_midnight' => array(
      'label' => t('Before Midnight'),
      'arguments' => array(
        'last_login' => array('type' => 'date', 'label' => t('The date to compare.')),
      ),
      'module' => 'MYMODULE',
      'group' => t('MYMODULE'),
    ),
  );
}

/**
 * Condition MYMODULE_condition_before_midnight
 */
function MYMODULE_condition_before_midnight($last_login) {
  return ($last_login < strtotime('midnight'));
}

Comment: Yes, a conditional callback return either `TRUE`/`FALSE` so that rules knows to execute the actions.
Comment: Could you give me a rule I could import?  Because it won't work me just placing this into condition..  Please paste an Export of this rule. Thanks
Comment: Rules doesn't export custom conditions. You can use the existing rule that you have. This is custom code that needs to placed into a module so a that any rule can make use the condition.
Comment: This answer assumes custom rules integration, a custom module (e.g. mymodule.info/mymodule.module) with the MYMODULE prefix changed to whatever you've named your module. Using rules with _Execute custom PHP code_ is a different thing.
Comment: I've been using this for about two weeks now and ran into a little problem.  Some user don't even log out. So if they get on yesterday and again today,  code won't get activated if their browser kept them logged in. Would I be able to just change your code from using `last_login` to `last_access` and would it work still? Only once per day no matter how much times they actually access. But at least they won't have to log out the day before. Thanks.
Comment: do you think it could work? Thanks
Comment: Yes, the same logic would hold, `last_access` is updated every time an authenticated user requests a page.  You need probably want to add some additional condition to your rule to trigger in either case. BTW, comments are not for added conversation/additional questions. Please ask new questions or open a chat room in the future.
Comment: how can I open a chat room?
Comment: Follow the "chat" link in the site footer.
Comment: please join this [chat room](http://chat.stackexchange.com/rooms/46310/before-midnight-condition)
Answer: No problems, here's a basic tutorial. The code goes in your .module file and the functions must have MYMODULE renamed to whatever you name your module.
Comment: [Continue this in chat](http://chat.stackexchange.com/rooms/45076/discussion-between-sammy7-and-shawn-conn)
Comment: Thank you I'm starting to understand you more now.  But I still don't get how I can get rules to connect with the new module I just created.  Isn't it supposed to be triggered through condition? How do I like my rule condition to this module? Thanks again
Comment: please help me out


Bottom Strap Holder Broke, Can I Fix it?

Question: So I was playing my Epiphone Les Paul Standard 100 and the bottom strap holder broke off.  Not the strap, but the thing built into the guitar that holds the strap.  I tried screwing it back in, but the past owner or I must have done something wrong because the screw won't screw back in.  I was wondering if you have any solutions or if I should just go to a guitar store and have them fix it.
Also, this is my first question on this site so tell please me if I did something wrong.
Comment: Broke off, or fell out? Pictures might help.
Comment: Sorry, fell out.
Answer: If someone has previously drilled the hole larger, or swapped the screw, or even just continued to screw in a screw that was coming loose & eventually wearing the hole out… the task really just becomes "simple woodwork".
At its most basic, the hole needs to be smaller so the screw will bite.
You could use match sticks, cocktail sticks, chop sticks... wood filler, glue, a bigger screw…
literally anything that just makes the hole smaller than the thread.
Comment: Thanks, I used a toothpick.  Split it, stuck it in there, and then screwed it back in.
Comment: Ok, and you don't think this could damage the guitar?
Comment: If you select wood that is too large and hammer it in, it could act as a wedge and split the wood. But if you are careful to size the replacement wood properly so it is snug, and use plenty of wood glue, you should be fine. Matchsticks and glue is good. a twig whittled down to the right size would work also.
Comment: Great answer. Be careful with the bigger screw solution - it probably won't go through the hole in the little 'knob'. ( I had problems with Dunlop 'knobs'). A longer screw probably isn't a solution either.


Significado desta sintaxe

Question: Preciso continuar um trabalho que está parcialmente pronto. No entanto não encontrei na internet arquivos que descrevessem ou ensinassem isso de uma forma compreensível. Qual o significado desta sintaxe ?
 Ide: NetBeans e linguagem C++
void Grafo::buscarElosEmProfundidade(No *origem, std::function<bool(No*, No*, Elo*)> func)

A parte No origem eu entendo que seja um ponteiro, mas e essa parte de std::functio bool(No *, No *, Elo *) func)? o que isso significa ?
A função completa é esta :
void Grafo::buscarElosEmProfundidade(No *origem, std::function<bool(No*, No*, Elo*)> func){
ListaParEloPercorrido *percorridos = this->getPercorridos(false);
ListaParNoVisitado *visitados = this->getVisitados(false);
if(!origem->getElos()->empty())
this->buscarElosEmProfundidadeAux(*(origem->getElos()->begin()), origem, visitados, percorridos, func);
delete percorridos;
delete visitados;

}
 Eu tentei chamar esta função assim : buscarElosEmProfundidade(No*ponteiro) e deu erro .
Qual a forma certa de chamá-la então ?
E ela não deveria ser void, certo ? Pois a intenção desta função é retornar uma lista com os nós que são "atingíveis" a partir da origem.
Comment: Se você que está fazendo o código não sabe, pra gente fica mais complicado ainda. S sintaxe é sobre isto: http://en.cppreference.com/w/cpp/utility/functional/function Agora como usar depende do seu código. Você não postou informações que indiquem como deve ser usado.
Answer: Esta notação std::function<bool(No*, No*, Elo*)>func indica um ponteiro para uma função de protótipo bool func(No*, No*, Elo*) que deve ser passada como parâmetro na chamada da função buscarElosEmProfundidade.
Você deve fazer mais ou menos assim:
// ...
// ...
// ...

// coloquei nomes genéricos na função e nos parâmetros porque não
// sei como serão usados, mas você deve colocar nomes explicativos
bool nomeFunc(No* no1, No* no2, Elo* elo)
{
   // ...
   // sua implementação
   // ...
}

// ...
// ...
// ...

No origem;

// ...
// ...
// ...

buscarElosEmProfundidade(&origem, nomeFunc);

// ...
// ...
// ...

PS. código não testado.

Significado desta sintaxe


Axiomatization in first order logic

Question: I am trying to understand what the term axiomatization exactly means . We didn't really discuss this in the lectures at my school but I have to write a homework related to that and I don't understand the question of the task. Can someone explain what the concept of axiomatization really means? My task is: Given a signature σ1 and a set of formulas Φ1 ⊆ FO[σ1] I have to show that  Φ1  "axiomatizate" the class of fields . Of course I don't expect someone to solve the problem for me but I would really appreciate some easy examples of which steps should I follow to solve it (example of how to show the same thing not for fields but for something else) and what exactly this axiomatization concept means.
Thanks in advance!
Comment: A family $\Phi$ of sentences *axiomatizes* a class $\mathbb{K}$ of structures (say, the class of fields) if the models of $\Phi$ are exactly the structures in $\mathbb{K}$. That is, to show $\Phi$ axiomatizes $\mathbb{K}$, you need to show two things:

 - Every model of $\Phi$ is a structure in $\mathbb{K}$.

 - Every structure in $\mathbb{K}$ is a model of $\Phi$.
Comment: Do you believe that you are breathing air? In this Room?
Comment: @Socrates What do you mean?
Comment: @NoahSchweber I don't even know! Maybe it would be possible to know something if we assume some things, and see how it plays out. I can't seem to find the keyword for this process.
Answer: An example is provided by the theory of groups, whose signature may be chosen to contain the binary function symbol $\circ$ (the group operation), the constant $e$ (the identity), and the binary equality relation.  The theory of groups is then defined by the following axioms:

$\forall x, y, z \,. x \circ (y \circ z) = (x \circ y) \circ
  z$ (associativity of $\circ$);
$\forall x \,. x \circ e = e \circ x = x$ (existence of
identity);
$\forall x \,. \exists y \,. x \circ y = y \circ x = e$
(existence of inverses).

The choice of signature (and consequently axioms) is not unique.  In
the case of groups, one may include a unary function for the inverse,
or omit the constant for the identity.

Axiomatization in first order logic


KinectJS drag image demo not working in latest chrome version

Question: I am having a similar issue on my project but was able to reproduce it on the kinectjs demo site. The following page works on IE but the latest version of Chrome (ver. 26.0.1410.43) the drag and drop features no longer work.
http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-an-image-tutorial/
Hopefully, the issue can be identified so we can fix my environment as well.
Thanks
Comment: So the demo site uses 4.3.1-beta2 version of Kinetic.js. The latest 4.4.0 did not work but 4.3.3 worked for our solution.
Answer: I had the same problem with an application i built and updating to the latest version of kineticJs solved my problem. (4.4.0)
Answer: I got problems with this demo too, on Android's 4.1.x native browser. On Chrome mobile and other browsers, it works like a charm. On native browser, right after the dragstart, the image goes to top left corner and stays there until i redraw the layer.


Qual a diferença de uso de return false, event.stopPropagation() e event.preventDefault()?

Question: Num handler de evento do jQuery, pode-se usar return false, event.stopPropagation() e event.preventDefault() (ou combinações desses) para "cancelar a ação" do evento.
Sei que tem diferença no comportamento deles, mas sinceramente sempre que preciso fazer algo do tipo, começo com return false e vou na tentativa e erro, porque ainda não compreendo muito bem a diferença.
Já li em algum lugar que return false é a mesma coisa que acionar event.stopPropagation() e event.preventDefault() ambos e já li gente dizendo que não é bem assim.
Alguém pode explicar melhor como devo fazer pra decidir qual desses caras eu preciso, com exemplos?
Answer: Retornar false em um handler de evento do jQuery é a mesma coisa que chamar event.preventDefault() e event.stopPropagation() (onde event é o objeto recebido como parâmetro).
Então:

event.preventDefault() impede que o evento padrão ocorra (ex.: seguir um link);
event.stopPropagation() impede que o evento seja propagado para os handlers dos elementos DOM pais;
return false faz as duas coisas (e ainda interrompe a execução do handler imediatamente, sem executar as instruções que vêm depois).

(Fonte: https://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false)
Por exemplo, suponha que você tem o seguinte trecho de HTML:

cliqueaqui

E agora você instala dois handlers:
$('#main a').click(function(event) {
    alert('main a');
});

$('#main').click(function(event) {
    alert('main')
});

Ao clicar no link, os dois handlers serão executados e logo depois você será redirecionado para a página "teste" (esse é o comportamento default de um link).
Usando apenas event.preventDefault()
$('#main a').click(function(event) {
    // impede o comportamento default (ir para página "teste")
    event.preventDefault();
    alert('main a');
});

Nesse caso, o event.preventDefault() impede de você ser redirecionado, mas o outro handler ainda será executado.
Usando apenas event.stopPropagation()
$('#main a').click(function(event) {
    // impede de propagar o evento para os elementos pais (ex.: #main)
    event.stopPropagation();
    alert('main a');
});

O segundo handler não será mais executado, mas você ainda será redirecionado.
Usando os dois ou com return false
$('#main a').click(function(event) {
    alert('main a');
    return false;
});

Se, no entanto, você chamar event.preventDefault() e event.stopPropagation() (ou, equivalentemente, apenas retornar false), o primeiro handler de evento será chamado mas, no entanto, o evento não será propagado para o segundo handler.
Pensando nos casos mais comuns, o stopPropagation() é útil para links, que têm um comportamento padrão associado, mas nem tanto para texto puro (afinal, o navegador não faz nada especial quando você clica no texto).
O preventDefault() é útil quando você tem diversos handlers e quer que um elemento tenha um comportamento único, sem herdar o comportamento dos elementos onde ele está contido.
Comment: @elias, adicionei um exemplo. Ficou mais claro?
Comment: Olá, Rodrigo. Então, já li essa resposta também, entendo que o comportamento deles é diferente, o que não está claro é o resultado de cada um, por isso pedi exemplos. Você poderia dar exemplos de quando é útil usar só stopPropagation ou só preventDefault?
Comment: Boa, ficou bem mais claro! Valeu! =)
Comment: Explicação perfeita!


Do AWS Registered Domains support more than 6 Name Servers?

Question: Does AWS support more than 6 name servers for a single domain? The UI (see attached image) appears to reject more than 6 name servers for a domain when trying to add a 7th. Google Cloud seems to allow up to 12. Is this intentional? Are there other methodologies or workarounds?
Comment: The RFCs define no maximum, just a minimum of two. But we can see from your image that something else is wrong: You need to replace the old nameservers, not add to them.
Comment: See https://blog.serverfault.com/2017/01/09/surviving-the-next-dns-attack/ where the conclusion is any number above 4 will provide little value. You should interleave aws and google name servers to reduce the performance penalty when aws or google's name servers are unavailable (assuming you want both and are not making the mistake @michael-hampton suggests).
Comment: @MarkWagner If ALL of Amazon's nameservers are unavailable it's because an EMP went off and we're all living in the Stone Age again. I'm not worried about configuring my domain for this event...
Comment: @MichaelHampton I could see a bad configuration change somewhere in AWS causing all of Amazon's nameservers to be unavailable. I can't speak to their DDOS resistance but my company was affected when dyn's name servers were in 2016.
Comment: @MichaelHampton There are far other possible and more probable causes, as it happened in the past globally for other providers. A single human mistake can sometimes ripples to configuration of all routers or triggers BGP announces that will render all IPs unreachable.
Answer: Why do you need so many and how do you intend to keep them in sync? Do Google domains support AXFR from Amazon? If not you're up for inconsistencies between the two sets of nameservers.
Better rethink what you're doing and how. Perhaps share more details what are you trying to achieve as there is rarely a need for so many nameservers.
Comment: We're investigating the ability to use our current domain (hosted in AWS) for a new service that we want to deploy in GCP. We don't want to migrate at this point, but we want to host a sub-domain for this new service on GCP.

We created a managed zone in GCP but during the Registrar Setup the GCP console suggests that we must use all 4 of its name servers (ns-cloud-d{1…4}googledomains.com) to be covered by the [Cloud DNS SLA.](https://cloud.google.com/dns/sla?hl=en_US&_ga=2.128525775.-2105471364.1553643612). The idea was to add each of these name servers to our existing domain in AWS.
Comment: @BrandenP I see, so it's a completely different issue then. I have added a new answer detailing what you should do.
Answer:
Based on the OP's comments the problem is that they want to have a new service in GCP with DNS for that service in GCP.

Say your domain is example.com. What you need to do is this:

In GCP create a subdomain, for example gcp.example.com.
Create any records you need for your new service in the GCP DNS management, e.g. create coolservice.gcp.example.com.
In AWS Route53 create a NS record in example.com for name gcp.example.com with the list of 4 nameservers provided by Google.
If you need to refer to the GCP service from your main domain, e.g. as coolservice.example.com you can create a CNAME in AWS Route53 pointing to the GCP name coolservice.gcp.example.com.

Alternatively don't worry about DNS in GCP at all and simply create the required records for the GCP services in AWS Route53. Not always possible if you want to rely on tight integration between your service and GCP DNS but if you can use statically allocated IPs for A records or can use CNAME records this is probably the easiest thing to do for start.
Hope that helps :)
Comment: Awesome. I marked your original answer as the accepted one because it more directly pertains to the original question. I'll update here once I get a chance to validate you're prescribed steps above. Thanks a ton!
Comment: We tested the above solution and it works well! We were curious if it is possible to make HTTPS calls to this Route 53 CNAME (i.e. coolservice.example.com) if it points to a GCP load balancer with an associated SSL certificate. We attempted to make API calls through the Route 53 endpoint but we had issues related to verifying our SSL certificate: "SSL: no alternative certificate subject name matches target host name". We figure this is because we're used to having Route 53 point to an ELB with an SSL Certificate in the same domain, but this subdomain strategy changes this architecture.
Comment: @BrandenP When you create the SSL certificate you can specify any number of hostnames it will be valid for. Typically you create a single cert for `example.com` and `www.example.com`. Simply add include the names you want to use, e.g. `coolservice.example.com` and `coolservice.gcp.example.com` and `www.coolservice.example.com` etc. These additional names are the "alternative subject names" that your browser complained about. Bottom line: recreate the SSL cert with all the names you want to use.


Are ASP and ASP.NET entirely separate in IIS 7.5?

Question: This is probably a silly question, but the names are confusing and I can't find a direct answer. There are a lot of limits in the ASP section of the IIS configuration that I might want to tweak (such as bufferingLimit, maxRequestEntityAllowed, and queueTimeout) -- but only if they affect ASP.NET.
But I suspect that they don't. Is this correct? Are ASP and ASP.NET entirely different entities as far as IIS 7.5 is concerned?
Answer: ASP and ASP.NET settings are treated as separate entities.  ASP is considered "Classic ASP" and is more of a server-side scripting method -JScript/VBScript-. ASP.NET relies on the .NET Framework -it is compiled-, and ASP.NET applications run in their own AppPool's.
The answer would be "yes."
Answer: Yup, entirely different. Something applying to system.webServer/asp will not affect system.web or system/webServer (any other section) settings in the slightest.


function composition with itself, infinite iteration

Question: Is it possible to find out what the "limit" is as the number of iterations of compositions a certain function with itself, like a trig function for example, tends to infinity?

$\sin(\sin(\sin(\dots(\sin(x))\dots)))$
$\cos(\cos(\cos(\dots(\cos(x))\dots)))$

In the first one, I'm composing sine with itself infinitely many times and in the second, I'm composing cosine with itself.
Answer: Observe that $\sin(x) \in [-1,1]$ and for $x \in [-1,1]$ we have $\lvert \sin(x) \lvert \leq \lvert x \rvert$. This shows that it converges.
In fact, you could also just use Banachs Fixed Point theorem. And you'll see that the sequence will converge to the fixedpoints of $\sin$ and $\cos$ (in the interval $[-1,1]$).
Answer: Yes it is possible.
Just consider the sequence defined by induction:
$$\begin{cases} u_0=x \\ u_{n+1}=f(u_n). \end{cases}$$
where $f$ is the function you consider (here $\sin$ and $\cos$).
Then look at the limit
$$\lim_{n\to\infty} u_n$$
with the usuals theorems.


What's the name for this skateboard trick? (180 kickturn)

Question: So I'm wondering if there's a special name for this trick. It's very basic. You're moving forward, and you do a 180 degree kickturn (i.e. pivot off the tail, turn the nose 180 degrees). At the end you're still going forward. You just have the tail in front and the nose in the back. Is there a special name for this trick?
I'd think it would be called a 180 spin, but looking online a 180 spin usually refers to an ollie with 180 degree spin. This is simpler than that. I looked at reverts also, but in a revert the wheels slide instead of pivot.
This isn't an endover because for an endover you pivot on the nose.
Is this just called a 180 kickturn? I tried googling '180 kickturn', but I only see it used in the context of ramps. I'm just referring to a 180 spin on flatground.
Note that the body turns 180 along with the board.
Comment: If I understood correctly... I think you're describing a [Shove it](https://www.youtube.com/watch?v=fBAW51ilpLw)...?
Comment: Well, it's like a shove-it, but your body turns along with the board. In a shove-it, only the board turns.
Answer: So you are saying there is NO POP involved right? And its on flatground? Thats really confusing.
If theres pop involved its either FS or BS 180. No Pop? I guess you could call it a revert but you dont really lift either side of your board on reverts so that wouldnt really be what you are describing
Comment: This guy calls it a manual revert: https://www.youtube.com/watch?v=7A7H5O9yJmY&t=10s But he's doing legit long manuals before and after the turn. I'm thinking of only lifting the wheels during the turn.
Answer: it is called "revert", no pivot on the wheel so it is not manual. U can search revert skateboard on youtube.
Comment: Welcome to Sports Stack Exchange. The question appears to reject the suggestion of a revert, based on the movement of the wheels. Can you expand on your answer to explain why that idea was incorrect or inaccurate, and hence how *revert* is the correct term?
Answer: If your back wheels are sliding, I'd consider this a 180° powerslide, regardless of whether your front wheels are touching the ground or not.
Don't get hung up on what it's called though; just keep drawing outside the lines.


How to migrate using explode with occasional empty array

Question: We've made a migration from the City of Helsinki's Linked Events API, and during this work we've been seeing these migration messages:

Array index missing, extraction failed

Here is an example of an event that works nicely:
https://api.hel.fi/linkedevents/v1/event/hko:14004/
And one that causes the error:
https://api.hel.fi/linkedevents/v1/event/matko:16134/
In the latter you see that offers is returned as an empty array. We're using the skip_on_empty plugin to handle those:
field_offers_is_free:
  -
    plugin: skip_on_empty
    method: process
    source: offers
  -
    plugin: extract
    index:
      - 0
      - is_free
field_offers_info_url:
  -
    plugin: skip_on_empty
    method: process
    source: offers
  -
    plugin: extract
    default: false
    index:
      - 0
      - info_url
      - fi

The problem is that never reaches the skip_on_empty plugin. I've been stepping through this in the debugger based on my findings I created an issue in Drupal Core https://www.drupal.org/node/2905929
When Get sets $multiple to true, processRow() in MigrateExecutable runs a foreach () on an empty array - resulting in the skip_on_empty plugin to be skipped.
Is there something wrong in our setup or did I uncover a bug? Any ideas on how to work smoothly around this?
Answer: I solved this by creating my own migrate plugin that sets the multiple flag to false if we get an empty array, like this:
/**
 * The Get plugin causes issues for us when it fetches and array that is empty.
 *
 * It sets multiple to true which prevents the skip_on_empty plugin from being
 * triggered.
 * @see https://www.drupal.org/node/2905929
 *
 * @MigrateProcessPlugin(
 *   id = "get_array_fix_multiple",
 *   handle_multiples = TRUE
 * )
 */

class GetArrayFixMultiple extends ProcessPluginBase {

  /**
   * Flag indicating whether there are multiple values.
   *
   * @var bool
   */
  protected $multiple;

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
      $array = is_array($value);
      $empty = empty($value);
      $this->multiple = $array && !$empty;
      return $value;
  }

  /**
   * {@inheritdoc}
   */
  public function multiple() {
    return $this->multiple;
  }

}

Either the bug is in the get plugin or then skip_on_empty should support multiple.


NgClick on  NgClick inside of it

Question: I have following code:

X

Y

I am switching classes if the value is selected. I would like to add an event on icon (which is only visible when its is selected), however, whenever I click on the icon, two ng-click's are triggered. My question is: how can I disable the ng-click on the parent element, when the row is selected?
Answer: You need to add $event.stopPropagation() to your inner ng-click:

This will prevent the ng-click on the parent element from being called.
Comment: Sweet! That works great! Are there any drawback of using this approach?
Answer: When you write and event in a DOM element, it's invocation bubbles up to call event attached to all it's parent till HTML tags.
You can prevent this occurrence by preventing the event to propagate further. stopPropagation does exactly that. You can find, details here https://developer.mozilla.org/en/docs/Web/API/Event/stopPropagation
In your, unselect function, you can call like this
function unselect(event) {
    event.stopPropagation();
    // Your original code
}

NgClick on  NgClick inside of it


What is it called when 2 players make a full run around a table in table tennis?

Question: In modern table tennis it is a common practice to acting the fool when the match is almost over. I.e. players used to flip the side and play a little bit awkward analogue of table tennis when you need to hit your own side and not the another one.
Here is a couple examples what I'm talking about.

World Tour Grand Finals Highlights: Ma Long vs Xu Xin (7:34)
Another example

Is there a special name for it?
Is it a valid table tennis draw according the rules?
And why actually this trick become so popular?
Maybe there is some story behind it?
Answer: This is like playing a mini game but doesn't have a specific name for it. If you observe both videos you will find that this was done in the end of the match. People do this when they have no hope of winning. Though it not very sportive it is still done. Hope your query is cleared!
Answer: In Italy it is friendly called "around the world".
Is it possible to be played by 2 or more player.
I believe there are no official rules for this kind of matches/points.
A Particular version if surviving around the world where many players (more than 2) starts to play in order one shot each moving to the part of the table of that shot (if there are odd numbers of player thay have to move from one side to the other, otherwise thay can hit from the same part of the table) and who fails is eliminated. The game continues until there are no two players who play a traditional point in the final
Comment: I'm afraid it's not that. "Around the world" have nothing about "need to hit your own side of a table and not the another one"
Comment: In Italy is is common to call "around the world" also this kind of game. There are several possibilities to play **around the world** and this is one of them. Maybe someone knows another name for this spaciality...


Error while updb, how to debug it?

Question: I've updated opigno_lms to 2.29 version without any problems by composer and then "drush updb", then installed 3.0.2 version through composer, but "drush updb" gives me:

[notice] Update started: opigno_statistics_update_9001
[error]  Argument 2 passed to Drupal\Core\Config\CachedStorage::write() must be of the type array, bool given, called in /home/mine/praca/gitowanie/opigno_project/web/modules/contrib/opigno_statistics/opigno_statistics.install on line 83
[error]  Update failed: opigno_statistics_update_9001

Anybody has solution for that? Or idea how to debug it? Every other update goes nice, but this one breaks everything... I tried already plenty of times, but it fails all the time, on 2 different servers.
Answer: If you look for a way to effectively debug updb, then try to use Xdebug. If you have problems configuring it for command line scripts, you can always run updates via update.php in your browser.
When you set a breakpoint on opigno_statistics_update_9001, you will see exactly where the faulty argument comes from.

Error while updb, how to debug it?


Evaluation time of C# properties

Question: class Bar
{
  private byte[] dg;

  Bar(byte[] datagram)
  {
    dg = datagram;
  }

  int Foo
  {
    get { return BitConverter.ToInt16(dg, 8); }
  }
}

When are properties evaluated? At the time Foo is accessed? The debugger evaluating all properties is scaring me.
Comment: It is generally a bad idea to have a property getter do any extensive work, because someone using your code will assume evaluating the property will be a cheap operation. If that's not the case, use a `GetFoo()` method.
Comment: In that example I would do the conversion first and then save it to be returned in Foo.
Comment: @Ed Swangren Why save a bunch of conversions if most of them are never used or only used once.

@Thorarin I agree a method would be much nicer. But with good documentation the property will be just fine. If people want to put something as dumb as properties in a language then I'm going to use them.
Answer: Yes, a property is just syntactic sugar for the call to get accessor method. Every time property is read, the method executes. And yes, this does include the debugger (which is why if your property gettors have side effects, debugging can actually affect the way your program works).
Answer: Yes, C# properties are simply syntactic sugar for specialized methods so they are evaluated when called, like any other type of instance method.

Evaluation time of C# properties


iText Detect Text Overflow or Copy Fit

Question: I need to put some dynamic text onto a pdf.  I need to verify that the text does not overflow the boundary box I am allowed to use to place the text in.

Is there a way to detect if this is happening?
Are there any copy-fit rules that I can use to handle it when it does happen?

Thanks
Comment: Are you using iText5 or iText7? The tag itext usually refers to the former. Also, java or .Net? Both versions have some way of simulating the placement of content, but the answer depends on the version :)
Comment: *"I need to put some dynamic text onto a pdf"* - How shall that be done? Do you want to fill **AcroForm** text fields? Or do you want to add **FreeText** (**FreeTextTypeWriter**) annotations? Or do you want to add to the page **Contents** streams?
Comment: Define "dynamic text". Is it text that you don't know the length of before running your program? Or is it as mkl posts?
Comment: @SamuelHuylebroeck I haven't choosen a version yet, I would think since this is a new project I could use iText7.  It will be C#.
Comment: @mkl I'm not sure actually.  I am creating the PDF myself so I am available to do whatever works best.  The end result will be text on the page, not annotation.
Comment: @MichaëlDemey The text will come from a database so the length will vary with each run.
Answer: iText5 is in maintenance mode and I recommend that you start your project using iText7. iText7 currently does not provide out of the box mechanisms for copy-fitting, but it can be done manually with little effort because layout engine is very flexible in iText7. Technically it can be done in iText5 as well, but I will provide an answer for iText7 for Java, and converting to C# shouldn't be a problem for you.
The basic idea is to make use of the Renderers concept and try yo layout your paragraph in the given area with different font sizes until you find the size which is OK for you. A binary search approach fits perfectly here.
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName));
Document doc = new Document(pdfDoc);

String text = "...";
Rectangle area = new Rectangle(100, 100, 200, 200);
// Just draw a black box around to verify the result visually
new PdfCanvas(pdfDoc.addNewPage()).rectangle(area).setStrokeColor(Color.BLACK).stroke();

Paragraph p = new Paragraph(text);
IRenderer renderer = p.createRendererSubTree().setParent(doc.getRenderer());
LayoutArea layoutArea = new LayoutArea(1, area);

// lFontSize means the font size which will be definitely small enough to fit all the text into the box.
// rFontSize is the maximum bound for the font size you want to use. The only constraint is that it should be greater than lFontSize
// Set rFontSize to smaller value if you don't want the font size to scale upwards
float lFontSize = 0.0001f, rFontSize = 10000;

// Binary search. Can be replaced with while (Math.abs(lFontSize - rFontSize) < eps). It is a matter of implementation/taste
for (int i = 0; i < 100; i++) {
    float mFontSize = (lFontSize + rFontSize) / 2;
    p.setFontSize(mFontSize);
    LayoutResult result = renderer.layout(new LayoutContext(layoutArea));
    if (result.getStatus() == LayoutResult.FULL) {
        lFontSize = mFontSize;
    } else {
        rFontSize = mFontSize;
    }
}

// lFontSize is guaranteed to be small enough to fit all the text. Using it.
float finalFontSize = lFontSize;
System.out.println("Final font size: " + finalFontSize);
p.setFontSize(finalFontSize);
// We need to layout the final time with the final font size set.
renderer.layout(new LayoutContext(layoutArea));
renderer.draw(new DrawContext(pdfDoc, new PdfCanvas(pdfDoc.getPage(1))));

doc.close();

The output:
Final font size: 5.7393746

Visual result:

iText Detect Text Overflow or Copy Fit


False statements in intuitionistic logic

Question: In the explanations of intuitionistic logic I've been reading (1, 2, 3), especially in the explanation of the semantics, I don't understand how a proposition being false influences the situation.
These explanations say something like "$W \Vdash p$ iff $p$ is true in $W$". That sounds clear enough, and then they continue and define the other operators. What I don't get is, when $W \not\Vdash p$? In source 3 they later show some diagrams where actually in every world each proposition has a truth value, either 0 or 1, so in that case I guess when $W(p) = 0$ then $W \not\Vdash p$. I feel like, for this to be the case, the explanation should have contained a short line saying, $\Vdash$ is the minimal relation following these definitions, otherwise it would be allowed to have $W \Vdash p$ even though $W(p) = 0$.
However 1 makes me doubt my interpretation for 3, as it contains the following:

you can think of intuitionistic logic as a logic where at a given point of time, a statement can have three truth values: T (top), which means provably true; ⏊ (bottom) which means provably false, and unproved

Following this line of reasoning, whenever $p$ is unproved, you can have neither $\Vdash$ nor $\not\Vdash$. But I feel this would make the definition of negation in 3 useless...? As a computer scientist with only a passing knowledge of formal logic, this is were my brain sputters to a halt.
My questions:

Is the explanation in 3 correct in that in a given world, a $p$ is either assigned $0$ or $1$? (This is the case, as stated on slide 27.)
Is it a safe way to model intuitionistic logic, or does it exclude true statements/proofs that the description in 1 would allow?
What is the canonical source I can read for a a semantics for inuitionistic propositional logic that is broadly accepted as standard (or, at least has some degree of consensus around it)?

(As a side note: 1 seems to skip defining negation for formulas, is that just an oversight or could 3 have skipped defining it, as it is implied by the other definitions?)
Thanks for any explanatations or tips for other reading material!
Comment: Canonical sources? many... Some ML textbook have chapter on IL; see e.g. [van Dalen](https://archive.org/details/springer_10.1007-978-3-540-85108-0), **Ch.5 Intuitionistic Logic**.
Comment: 1st question not clear... $p$ is an *atom*: thus either it is True in a state W or it is False; see source linked in 3 slide 25 and 27: for each state W function $\pi_W$ (truth assignment) is a fucntion from atomic propositions to booleans $\{ 0, 1 \}$.
Comment: Maybe useful [Intuitionistic Logic](https://plato.stanford.edu/entries/logic-intuitionistic/)
Comment: I missed the part on slide 27, that answers my first question, thanks a lot! The stanford link is very good but a bit dense for me as a non-logician. I guess I'll have to try harder next time I read it.
Comment: But this does not hold for **every** formula: there are "conjectures" like the [Twin prome conjecture](https://en.wikipedia.org/wiki/Twin_prime#Twin_prime_conjecture) i.e. formuals not (yet) proved neither refuted.
Answer: You say

" whenever $p$ is unproved, you can have neither ⊩ nor ⊮."

This isn't correct. Consider the Law of the Excluded Middle $A \lor \neg A$. Intuitionistic Logic doesn't have to have this formula satisfied at an arbitrary world, but that doesn't mean it has to be false in every world in a given model. That of course would be inconsistent, since Intuitionism proves the double-negated version.
In particular, there is a difference between
$w \not \Vdash p$
and
$w \Vdash \neg p$
as the latter means $v \not \Vdash p$ whenever $w \le v$, while the former simply means the value of $p$ is $0$ at $w$.
Comment: Note that standard Intuitionistic tautologies still hold at an arbitrary world, even if that proposition isn't explicitly mentioned in a given model. Basically, assigning a proposition $0$ at a world is just another way of saying it isn't $1$ at that world, and that holds for propositions not mentioned in the model.
Comment: Okay, that makes sense (to the classical part of my brain). Is it too strict to say that for w and any v >= w, any p that occurs in the formula is defined in w? So every world in the model must assign either 0 or 1 to any propositional variable in the formula?  Or do some intuitionistic logic distinguish that as well, meaning, some u < w might not define p, w(p) = 0, and for some v >= w, v(p) = 1? It seems that my sources seem to have different opinions about this, but they are not explicit about it.
Comment: I'm not sure what you mean by "defined at $w$", but all it takes for $v(p)$ to be $0$ is for $p$ to not be satisfied at $w$.
Comment: Maybe I can clarify: in source (1) of my question, worlds are basically mappings from propositional variables to truth values. E.g. slide 28 has root world w0 with: p -> 0, q -> 0, r -> 0. This world/mapping is defined for p, q, and r, but not for some external propositional variable b. Is each world required to provide a value for each propositional variable in the formula? E.g. if w0 did not have the entry p -> 0, w0 would not be defined for p. Is that allowed?


The slotted plane for countable lines through $z$ removed.

Question: At each point $z$ in the plane, the basic neighborhoods at $z$ are to be the sets {$z$} $\cup A$, where $A$ is a disk about $z$ with a finite number of straight lines through $z$ removed.
That this gives a topology on the plane. But, what happen if we re-replace "finite" in the definition of this space with "countable"?
Could you help to answer that quiestion?
Comment: One answer to "what happens" is "that makes some other topology", just like any choice of basic neighborhoods would make. What do you want to know more specifically?
Comment: Is still a topology with countable lines through z removed?
Answer: The family $\mathcal S$ with a countable number of straight lines through $z$ removed, which you described is not a base of a topology. Indeed, let $z=0$ and $A$ be a unit open disc centered at $0$ with countably many  radii removed, such that the endpoints of the removed radii is a dense set (in the usual topology) on the circle which bound the disk. Then any point $t$ of $A$ does not have a "neighborhood" of the form $\{t\}\cup B\subset A$, where $B$ is a disc (with a non-zero radius) centered at $t$ with countably many  radii removed.
Thus if we want to define a topology $\tau$ on the plane in  which all elements of $\mathcal S$ are open, we should to consider the family $\mathcal S$ not as a base of $\tau$, but, for instance, as its subbase.
Comment: $B$ is a disc centered at $z$, is it not at $t$?
Comment: @lepstein Yes, thanks. Corrected.


How can I sign a JSON transaction?

Question: I have a JSON representation of an XRPL transaction, like the one below, and I want to sign it in C++ using rippled. How can I?
{
  "TransactionType" : "Payment",
  "Account" : "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
  "Destination" : "ra5nK24KXen9AHvsdFTKHSANinZseWnPcX",
  "Amount" : "1000000"
}

Answer:
Parse a transaction, represented by the class STTx (which stands for "serialized type: transaction"), from JSON. ripple-libpp has good example code.
Construct a signing key, represented by the type SecretKey. If you have a Base58-encoded signing key, you can use parseBase58 (pass TokenType::AccountSecret for the first parameter).
Derive the verifying key (represented by the class PublicKey) from the signing key with derivePublicKey (pass KeyType::secp256k1 or KeyType::ed25519 for the first parameter, depending on the signing algorithm you choose to use).
Sign the transaction with STTx::sign.
Read the signature via Blob const signature = sttx.getFieldVL(sfTxnSignature) (a Blob is a vector of bytes).

How can I sign a JSON transaction?


$E(x^k)$ under a Gaussian

Question: What would be the expectation of $|x|^k$, where $x\sim\mathcal{N}(0,1)$, $k>0$ and $k$ is not an integer?
Comment: This reads like standard bookwork for a basic subject on distributions. Is this for some subject?
Comment: I think youneed to use absolute value, as non-integer power don't make sense for negative numbers.  Or are you intending to get an answer in the complex domain?
Comment: @Glen_b it's for my PhD. I've oversimplified the actual problem that I have
Answer: $E(x^k)$ can be worked out directly from the law of the unconscious statistician
$E(x^k) = \int_{-\infty}^\infty x^k \phi(x) dx$ where $\phi$ is the standard normal pdf
You may be able to make progress with a simple substitution.
See also:
http://mathworld.wolfram.com/NormalDistribution.html (this gives the numeric answers)
and
http://mathworld.wolfram.com/GaussianIntegral.html

Responding to the updated question: we just follow my suggestion above (simple substitution).
\begin{eqnarray}
E(|x|^k) &=& \int_{-\infty}^\infty |x|^k \frac{1}{\sqrt{2\pi}} e^{-x^2/2}dx\\
         &=& 2\frac{1}{\sqrt{2\pi}} \int_{0}^\infty x^k e^{-x^2/2}dx
\end{eqnarray}
Let $u = x^2/2;\,$ so $ du  = x\,dx;\,x=(2u)^{1/2}$
\begin{eqnarray}
   &=& 2\frac{1}{\sqrt{2\pi}} \int_{0}^\infty (2u)^{\frac{k-1}{2}} e^{-u}du\\
   &=& \frac{2^{k/2}}{\sqrt{\pi}} \int_{0}^\infty u^{\frac{k-1}{2}} e^{-u}du\\
   &=& \frac{2^{k/2}}{\sqrt{\pi}} \Gamma\left(\frac{k+1}{2}\right)
\end{eqnarray}
In fact the second link above shows you how to it for the non-integer case - see eqns (9)-(12); there's nothing there requiring the power to be an integer.
Comment: (+1) The Gamma function is defined for all *complex* numbers except the non-positive integers, so this solution certainly works for positive non-integral reals.  However--a little nit-pick--the calculations done here are meaningless until one changes $|x^k|$ to $|x|^k$ or else makes some assumptions about branches of the complex logarithm. :-)
Comment: All the answers given are in the case when k is an integer. I'm afraid I need it for the non-integer case
Comment: @whuber Thanks, that's a typo - it's meant to be as in the current question; fixed.

$E(x^k)$ under a Gaussian


In azure, is there any way to know who and when an app was published?

Question: We have an azure web app that we deploy with a publish profile and webdeploy. What I'd like to know is if there is any log about this deployment activity ? I read the logs but I can't find any trace of my deployments.
Note : we're not using git automated deployment
Comment: using web apps or cloud services?
Comment: we are using web apps
Answer: In the Azure Management Portal (manage.windowsazure.com), select Management Services and then the Operation Logs tab.

Or, in the Azure Preview Portal (portal.azure.com), select Browse All and then Audit Logs.
Comment: I see many things there, what kind of message is supposed to be displayed on a  publish ?
Comment: You will see UpdateWebSite operations.  There's not a lot of data.  But, it will show you the site that was updated, when it was updated, and who updated it.
Comment: You can also click "Operation Logs" inside your website dashboard (quick glance). This will navigate directly to operations logs filtered by the specified website.
Comment: Is this supposed to be updated fast ? I just deployed my app twice (once without modification, once with a change) and I can't see anything yet
Comment: yes. Check date/time filter. Once you publish the project using VStudio it will instantly show in operation logs.
Comment: I don't believe deployments viw FTP / Web Publish direct from Visual Studio will ever be logged in these (Operation Logs / Audit Logs). There go only the Service Management API / ARM operations.
Comment: Yes, they are.  There is not much data logged, but they are there.  It may take a few minutes (I've seen up to 5) before you will see the log there.
Comment: I still don't have it (the last deploy was 1h ago), in portal or manage. Could it be a timezone problem ?
Comment: Hmmm, that's odd.  It works for me.  Try refreshing the page.
Comment: Worked for me as well. Just deployed using visual studio directly. Shows instantly.
Comment: are you guys (who see audit logs) deploying using the Publishe Profile or using Deployment Credentials?
Comment: Could it be because I'm using a free web app ?
Comment: @astaykov using web deploy.  Also, is not specific to pricing plan.