Cannot start ` Secure Socket Tuning Protocol Service`

Question: I tried to start Routing and Remote Access Service but I've got an error says the dependency service or group failed to start then I tried to start Remote Access Connection Manager (one of RRAS's dependencies) and the error way same. then I tried to start The Secure Socket Tuning Protocol Service but there was an error says that the the service started then stopped!
the errors form event log is here:
The Remote Access Connection Manager service depends on the Secure Socket Tunneling Protocol Service service which failed to start because of the following error:
The operation completed successfully.
The Secure Socket Tunneling Protocol Service service entered the stopped state.
The Routing and Remote Access service depends on the Remote Access Connection Manager service which failed to start because of the following error:
The dependency service or group failed to start.
sort by date
Does anyone know how can I resolve the problem?
Comment: Have you considered adding SOME Information? Like - is there anything in the event log? Normally starting services leave separate event log explanations.
Comment: @TomTom ok I'll add them
Comment: @TomTom I'm nob in  windows server. can you tell me where I can find the exents of the services? I opened Event Viewer but I don't know where to go!
Comment: @TomTom I've added the data from Event Log
Answer: A couple of things to try without seeing your full event log:

Try backing up your registry and then deleting the following key: HKEY_LOCAL_MACHINE\System\currentcontrolset\services\remoteaccess\routermanagers\IPV6 and then rebooting.
Try removing the RRAS role completely from the server in Server Manager Roles and rebooting then re-adding the RRAS role.  (NOTE: if you have extensive rules/policies/settings within RRAS you will need to document them and recreate them. See here: http://winmasterplan.blogspot.com/2008/01/export-rras-configuration.html
Comment: The problem didn't resolve :(
Answer: It's strange but if you disabled Remote Registry, you have to change it strtup type to manual.
service Remote Registry= disable -> manual
Comment: it's startup is manual and the problem doesn't resolved
Answer: I solved the problem for myself (on Server 2008 R2) when I did the following:

Control Panel > Device Manager > View > Show Hidden Devices. Under Network Adapters, make sure all are enabled (I don't know which ones are the necessary ones).
Control Panel > Network and Sharing Center > Change Adapter Settings. Right-click each adapter, choose Properties, then IPv4 Properties, then Advanced, then WINS tab, then Enable NetBIOS over TCP/IP. Don't know if this was part of the solution, but it was a change I made before RRAS started working.

You may have to then reboot the server.
Answer: The problem was from my VPS provider. They disabled VPN option. We asked them and they Enabled it for us. Now this is our problem!
Answer: I was having the same problem.  I had disabled a host of network devices that were needlessly sucking up all the IPs in my DHCP pool.  When I went and deleted those connections which we will never use, they stayed in the list, however, when I went bgack and enabled each one they disappeared, and once they were all gone, SSTP service started backup as advertised.
Answer: Open services.msc and double click Routing and Remote Access, go to Dependencies tab and note which services are required for this service to be started.
Once this is done try starting up each of the dependencies that are not already started, if for some reason they are unable to start you'll be given a communicate and there should be an event in the Event Log corresponding to that problem.
Depending on which service is unable to start there are different methods of further diagnostics.
Comment: Are there any events in the `System` or `Application` logs about that service? They can have `Source` set to `Service Control Manager` or a specific name for that service. Basically try to start it again and then refresh the Event Log and look for any events that match the exact time of you starting that service.
Comment: I told that `The Secure Socket Tuning Protocol Service` doesn't start!
Comment: I checked the system events and the log about this was `The Secure Socket Tunneling Protocol Service service entered the stopped state.`
Answer: The windows event log will be disabled. That causes SSTP to stop, hence start windows event log in control panel/services. That should help.
Answer: For me, rebooting my VPS fixed the problem. It manifested itself firstly as the IIS web server not being able to talk to the sql server. I could connect to the SQL Server then I found this SSTP problem.
It may be to do with a proxy server and a mail server I also have running on this box - like too many connections or something.
Answer: I had the same problem and I did the followings and the problem solved:
In Services:
-"Windows Event Collector"->Properties->Startup Type->Automatic(Delayed Start).
-"Windows Log"->Properties->Startup Type->Manual.
-"Remote Access Auto Connection Manager"->Properties->Startup Type->Manual.
-"Remote Access Connection Manager"->Properties->Startup Type->Manual.
-"Remote Desktop Configuration"->Properties->Startup Type->Manual.
-"Remote Desktop Services"->Properties->Startup Type->Manual.
-Remote Desktop Services UserMode Port Redirector"->Properties->Startup Type->Manual.
-"Remote Procedure Call (RPC) Locator"->Properties->Startup Type->Manual.


Is it possible to run the Steinberg UR 12 with passive studio monitors on cinch outputs?

Question: I want to buy monitor speakers, but I don't know if I need passive or active ones. Since the passive studio monitor speakers are cheaper, I would like to buy them, but I don't know if they would run well with the UR 12 from Steinberg.
Does anyone has experience with this subject or can at least help me with my decision?
Answer: In order to run monitors or any other kind of sound amplification, you need a power amplifier and a loudspeaker.
A "passive" monitor is just the loudspeaker. "Active" monitors have a power amplifier built-in.
That's why the passive monitors are cheaper — you can't connect them directly to the cinch (RCA) outputs of your audio interface and expect them to make any noise. You'd need to connect your interface to an amplifier (like the one inside an active monitor), and then connect the loudspeaker to your amplifier.
Comment: Cinch = RCA = phono.
Answer: The UR 12 "line output" is meant to drive an amplifier. It doesn't have enough power to drive speakers directly.
Note, the UR12 also has an output that is meant for driving headphones.
Whether you buy passive speakers and a separate amplifier, or active speakers with built-in amplifiers, is up to you.


Testing for paired subjects AND two timepoints

Question: How should I best analyze data that have "2x pairing"? E.g., N set of twins, each twin randomly assigned to active drug or placebo, then measure indicator X at timepoints A (before administration) and B (after administration).
My understanding here is that there are 2 pairings: between time A and B, and between drug and placebo.
Does it make sense to manually calculate the difference in X between the timepoints and just perform a simple paired t-test / Wilcoxon on the differences?
If that's OK, then is there a difference if I do it the other way around, i.e. manually calculate the difference in X between drug and placebo, and perform a simple paired test across the timepoints? (It feels less logical, but I can't place why exactly)
Answer: If your question of interest is "What effect on risk does drug have over placebo?", then it sounds like you are taking advantage of such matches simply to reduce unobserved sources of between group variability, rather than to make inferences about differences between twins.
So your suggestion to measure change in $X$ across the trial period (i.e. $X_{\text{B}}-X_{\text{A}}$) and base your inference on a paired t test or sign-rank test, would seem to be about right.
If you based your inference on $X_{\text{sib drug}}-X_{\text{sib control}}$, and then performed your test (paired t or signed rank), you would then be inferring that there was a change (or not) in drug-placebo differences in prevalence/levels before and after treatment. Possibly also useful. But aren't clinical trials more often used to characterize effects on risk/change?
Comment: Sorry, I didn't know [enter] submitted the comment.

Yup, the main purpose is to compare difference between drug and placebo.

I guess what I meant was, is there a difference if I calculate `X_B - X_A` then perform a paired test across `X_drug` and `X_ctrl`, vs. calculating `X_drug - X_ctrl` then performing a paired test across `X_B` and `X_A`?

Both methods seem to account for the differences between *time period* and *drug/control*... does it matter which particular pair is operated on by the statistical test?
Comment: Does my edit help clarify? The first tests for differences in risk/change, the second tests for differences in prevalence/levels among matched pairs.


Showing a sequence is short exact

Question: Given a domain $R$ which is a UFD and $x,y \in R$ so that $\gcd(x,y)=1$, define $I = \left<x,y\right>$. I need to show that the sequence :
$$ 0 \rightarrow R \xrightarrow f R \oplus R \xrightarrow g I \rightarrow 0 $$
where $$f(a) = (-ya, xa)$$ and $$g(a,b) = ax+by$$
is exact.
I realise that basically means I need to show the surjectivity of $g$ and injectivity of $f$. But I am not sure why the UFD and relatively prime condition of $x$ and $y$ are thrown in. I am missing something elementary quite clearly, but I am unable to figure it out nevertheless. Any hints would be welcome.
Comment: You will need the "relatively prime" assumption in order to prove the other condition for the sequence to be exact: that the kernel of $g$ is equal to the image of $f$.  Injectivity of $f$ and surjectivity of $g$ do not require the "relatively prime" assumption, as you noticed.
Comment: Good, no problem.  May I encourage you to write an answer to your own question? It will get it out of the "unanswered" queue, and I'll vote it up.
Comment: What happens, say, if you write $a$ and $b$ as products of irreducible elements? Can you compare them?
Comment: In general, that is true, but here you know that $ax=-by$...
Comment: The right way to think about that is that $y$ is a non-zero divisor in $R/(x)$. If you use this, you can forget about everything else like co-prime and UFD.
Comment: Yeah..I see it now. Thanks.
Comment: @Pierre-GuyPlamondon , well I seem to be stuck again. Looks like my basics are rusty. I took an element in $(a,b) \in Ker(g)$, giving me $ax = -by$, which as $gcd(x,y)=1$ yields $x|b$ and $y|a$, but I am not able to move from here. Sorry, I guess was a bit too hasty in declaring it done.
Comment: I am not able to grasp your hint....sorry....I don't see how a and b can be compared, they might have some common prime(irreducible) factors or none, that's all
Comment: well would it be right to say that x is one of the prime factors of b and y is one of a? so that would mean xy would be present on both sides
Answer: From $\gcd(x,y)=1$, we see that at least one of $x,y$ is non-zero. Hence the kernel of $f$ is trivial, as desired.
That $g$ is surjective is more or less the definition of $\langle x,y\rangle$.
We have $g\circ f=0$ because $g(f(a))=g(-ya,xa)=-yax+xay=0$ for all $a$.
Remains to show that $g(y,b)=0$ implies $(a,b)=f(c)$ for some $c$.
So assume $ax+by=0$, i.e., $ax=-by$. As $x$ is coprime to $y$, we must have $y\mid a$ and similarly $x\mid b$. So $a=dy$, $b=cx$ with $c,d\in R$. But then $dyx+cxy=0$ and so $d=-c$ and indeed $(a,b)=(-cy,cx)=f(c)$.

Showing a sequence is short exact


Valores checkbox em sessão de array como string

Question: Pretendo juntar num array os valores de um checkbox mas como string e de forma a que fiquem separados por array('string1','string2'), para poder usar numa consulta mysql IN('string1','string2').
Estes valores vêm de um checkbox para uma sessão:
$variavel= $_SESSION['checkbox'] = implode(',',$_POST['checkbox']);

Desta forma, ele separa apenas os valores com ,, array(int1,int2), mas quando junto um valor string ele dá erro.
Como poderei juntar ' a cada valor na array para ficar assim array('string1','string2')?
Answer: Bom, achei uma solução, que até pode nem ser a mais correta, mas que funcionou direitinho através do valor do checkbox, onde apenas concatenei o hiffen antes e depois ao resultado.
Se houver uma solução mais pro para esta situação, agradeço a ajuda e/ou esclarecimento.
o meu checkbox:
<input name="chekcbox[]" type="checkbox" id="chekcbox" value="<?php echo "'".$linhaQueryMySql['campo']."'"; ?>" <?php if(strpos($variavel1,$linhaQueryMySql['campo'])!== false) echo 'checked="checked"'?> />


Como exibir um elemento a partir de um true ou false dentro do Objeto? Javascript ReactJs

Question: eu tenho um array de objetos, e eu quero exibir o value a partir de seu status que é um atributo dentro do objeto.

this.state = {
  objetcs: [{
    value: 1,
    status: false
  }, {
    value: 2,
    status: true
  }]
}
}

// const object = [{ value: 1, status: false }, {value: 2, status: true} ]

Se o status for true eu renderizo ele, se náo, não renderizo.
Como posso fazer isso ?
Answer: Podes usar .filter para filtrar o state e depois mapear para o JSX que precisares.
Repara que no teu states tens objects escrito objetcs, eu corrigi no exemplo em baixo

class Componente extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      objects: [{
        value: 0,
        status: true
      }, {
        value: 1,
        status: false
      }, {
        value: 2,
        status: true
      }]
    }
  }

  render() {
    const activeElements = this.state.objects
      .filter(obj => obj.status)
      .map(obj => (
{obj.value}
));
    return (
{activeElements}
);
  }
}

ReactDOM.render( <Componente/> , document.getElementById('root'));


Why are ties so difficult in nonparametric statistics?

Question: My nonparametric text, Practical Nonparametric Statistics, often gives clean formulas for expectations, variances, test statistics, and the like, but includes the caveat that this only works if we ignore ties. When calculating the Mann-Whitney U Statistic, it is encouraged that you throw out tied pairs when comparing which is bigger.
I get that ties don't really tell us much about which population is bigger (if that's what we're interested in) since neither group is bigger than the other, but it doesn't seem like that would matter when developing asymptotic distributions.
Why then is it such a quandary dealing with ties in some nonparametric procedures? Is there a way of extracting any useful information from ties, rather than simply throwing them away?
EDIT: In regards to @whuber's comment, I checked my sources again, and some procedures use an average of ranks instead of dropping the tied values completely. While this seems more sensible in reference to retaining information, it also seems to me that it lacks rigor. The spirit of the question still stands, however.
Comment: Thank you.  There are rigorous ways to account for tied groups.  They are important when working with censored (but continuous) data, because frequently the censored values constitute a large tied group.  For the Kruskal-Wallis and Wilcoxon Rank Sum tests, see chapter 18 of R. O. Gilbert, *Statistical Methods for Environmental Pollution Monitoring."  Formulas involving tied data can get complicated, but in some cases (like the K-W test) all you need to do is compute an ANOVA table for the ranks.
Comment: Are you saying that *Practical Nonparametric Statistics* tells you to "*throw out*" data when they are tied?  Could you perhaps be mis-interpreting its advice?  Could you quote it exactly?
Comment: Yes, it is possible that I am misinterpreting the advice. From the same author: http://www.jstor.org/stable/2284536 "Wilcoxon suggested dropping the zeros from the data  initially, and performing the test on the reduced set of data. If there are no nonzero ties this procedure results in a  conditionally (given the number of zeros) distribution free test, and enables the existing exact tables of critical values to be used. For this reason, most books on nonparametric statistics incorporate Wilcoxon's method into their description of the test"
Comment: Granted, this is in reference to the Wilcoxon Signed Rank test, but I have heard similar advice used in other NP procedures. In regards to the Mann-Whitney example, I went back and checked in the book, and you are correct that I am mistaken. With Mann-Whitney, the book recommends averaging the ranks of the tied values, ie: if ranks 6 and 7 are tied, giving each one a value of 6.5.
Answer: Most of the work on non-parametrics was originally done assuming that there was an underlying continuous distribution in which ties would be impossible (if measured accurately enough).  The theory can then be based on the distributions of order statistics (which are a lot simpler without ties) or other formulas.  In some cases the statistic works out to be approximately normal which makes things really easy.  When ties are introduced either because the data was rounded or is naturally discrete, then the standard assumptions do not hold.  The approximation may still be good enough in some cases, but not in others, so often the easiest thing to do is just give a warning that these formulas don't work with ties.
There are tools for some of the standard non-parametric tests that have worked out the exact distribution when ties are present.  The exactRankTests package for R is one example.
One simple way to deal with ties is to use randomization tests like permutation tests or bootstrapping.  These don't worry about asymptotic distributions, but use the data as it is, ties and all (note that with a lot of ties, even these techniques may have low power).
There was an article a few years back (I thought in the American Statistician, but I am not finding it) that discussed the ideas of ties and some of the things that you can do with them.  One point is that it depends on what question you are asking, what to do with ties can be very different in a superiority test vs. a non-inferiority test.


Left merge two dataframes and fill only NaN values in Pandas

Question: For dataframes df1 and df2, I want to left merge them based on date to get df, if v1 or v2 has values, then take them, otherwise take the values from df2.
df1
      date    v1    v2
0  2017-01  12.0   1.0
1  2017-02   2.0  13.0
2  2017-03  15.0   3.0
3  2017-04   NaN   NaN
4  2017-05   NaN   NaN

df2
      date  v1  v2  v3  v4
0  2017-01  13   9   7   7
1  2017-02   5   7   5  56
2  2017-03  15   8   6   9
3  2017-04  12  14   8   0
4  2017-05   8   8   4   6

Just tried with but I get:
df = pd.merge(df1, df2, how = 'left', on = 'date')

Output:
      date  v1_x  v2_x  v1_y  v2_y  v3  v4
0  2017-01  12.0   1.0    13     9   7   7
1  2017-02   2.0  13.0     5     7   5  56
2  2017-03  15.0   3.0    15     8   6   9
3  2017-04   NaN   NaN    12    14   8   0
4  2017-05   NaN   NaN     8     8   4   6

How can I get the desired output as follows? Thanks.
      date  v1  v2  v3  v4
0  2017-01  12   1   7   7
1  2017-02   2  13   5  56
2  2017-03  15   3   6   9
3  2017-04  12  14   8   0
4  2017-05   8   8   4   6

Please note there are duplicated values in date from df1 and df2.
Answer: Try using fillna:
print(df1.fillna(df2).join(df2[df2.columns.drop(df1.columns)]))

Or just:
print(df1.fillna(df2).join(df2[['v3', 'v4']]))

Both Output:
      date    v1    v2  v3  v4
0  2017-01  12.0   1.0   7   7
1  2017-02   2.0  13.0   5  56
2  2017-03  15.0   3.0   6   9
3  2017-04  12.0  14.0   8   0
4  2017-05   8.0   8.0   4   6

Answer: combine_first looks just fine to me, here is an alternative using concat and groupby.first():
pd.concat((df1,df2),sort=False).groupby('date').first().reset_index()

      date    v1    v2   v3    v4
0  2017-01  12.0   1.0  7.0   7.0
1  2017-02   2.0  13.0  5.0  56.0
2  2017-03  15.0   3.0  6.0   9.0
3  2017-04  12.0  14.0  8.0   0.0
4  2017-05   8.0   8.0  4.0   6.0

Answer: This seems works, if you have other solutions. Welcome to share.
df1.set_index('date').combine_first(df2.set_index('date'))\
     .reindex(df1.date)\
     .reset_index()

Output:
      date    v1    v2   v3    v4
0  2017-01  12.0   1.0  7.0   7.0
1  2017-02   2.0  13.0  5.0  56.0
2  2017-03  15.0   3.0  6.0   9.0
3  2017-04  12.0  14.0  8.0   0.0
4  2017-05   8.0   8.0  4.0   6.0

Comment: Since I have duplicates `date`, so I get `ValueError: cannot reindex from a duplicate axis`. :(


Isomorphism between homotopy groups of Lie group, Grassmann manifold

Question: It is asserted without proof in a book edited by Novikov and Rokhlin that
$$\pi_{k - 1}(\text{GL}_n^+(\mathbb{R})) \cong \pi_k(\tilde{G}_n).$$
I know how to show that these two spaces are bijective. But I can't see for the life of me why they're isomorphic, i.e. why
$$f \mapsto \text{clutching function of } f^* \gamma_n(\tilde{G}_n)$$
is a homomorphism. Here, $\gamma_n$ is the tautological bundle. Could anybody help?
Answer: The oriented grassmanian $\tilde{G}_n$ is the classifying space of $\operatorname{GL}^+_n(\mathbb{R})$, i.e. $\tilde{G}_n = \operatorname{BGL}^+_n(\mathbb{R})$. So there is a principal $\operatorname{GL}^+_n(\mathbb{R})$-bundle $\operatorname{EGL}^+_n(\mathbb{R}) \to \operatorname{BGL}^+_n(\mathbb{R})$; the associated vector bundle is $\gamma_n$. Applying the long exact sequence in homotopy to the $\operatorname{GL}^+_n(\mathbb{R})$-bundle, we get the exact sequence
$$\dots \to \pi_k(\operatorname{EGL}^+_n(\mathbb{R})) \to \pi_k(\operatorname{BGL}^+_n(\mathbb{R})) \to \pi_{k-1}(\operatorname{GL}^+_n(\mathbb{R})) \to \pi_{k-1}(\operatorname{EGL}^+_n(\mathbb{R})) \to \dots$$
As $\operatorname{EGL}^+_n(\mathbb{R})$ is contractible, $\pi_k(\operatorname{BGL}^+_n(\mathbb{R})) \cong \pi_{k-1}(\operatorname{GL}^+_n(\mathbb{R}))$. Replacing $\operatorname{BGL}^+_n(\mathbb{R})$ by $\tilde{G}_n$, you obtain the desired result.
Note that one could instead pass to the compact subgroup $\operatorname{SO}_n(\mathbb{R}) \subset \operatorname{GL}^+_n(\mathbb{R})$ as the two spaces are homotopy equivalent. In particular, $\tilde{G}_n = \operatorname{BSO}_n(\mathbb{R})$.

The argument given above can be used to show that $\pi_k(BG) \cong \pi_{k-1}(G)$ for any topological group $G$.
Comment: Small nitpick: $\gamma_n$ is not the principal  $\operatorname{BGL}^+(n, \mathbb{R})$-bundle $\operatorname{EGL}^+(n, \mathbb{R}) \to \operatorname{BGL}^+(n, \mathbb{R})$, but the associated vector bundle.
Comment: @archipelago Of course you are correct. I have edited accordingly. Thanks.


How to import 5 GB MySQL Dump file in phpmyadmin

Question: I want to import a sql file of approx 5 GB. But its causing problem while loading. Is there any way to upload it without splitting the sql file ?
i have tried to import by terminal also but that also so many errors.
please help me on this.
Comment: the command line is always the safest option as it is quick than the phpmyadmin and is more reliable
Comment: try using https://dev.mysql.com/downloads/workbench/ or http://sqlyog.en.softonic.com/
Comment: people are not interested in marking and up-voting the answers. really frustrating. waste of effort. deleting my answer.
Comment: @Anant i can not see your answer and also not understand what you want to say
Comment: @ShivSingh check now and at-least after trying all answers, mark and up-vote one answer which is correct for you.
Answer: Most probably you won't be able to import a 5GB database on PHPMyAdmin. Try BigDump. You can download it here. Step are mentioned below.
Download and unzip bigdump.zip on your PC.

Open bigdump.php in a text editor, adjust the database configuration and dump file encoding.

Drop the old tables on the target database if your dump doesn't contain "DROP TABLE" (use phpMyAdmin).

Create the working directory (e.g. dump) on your web server

Upload bigdump.php and the dump files (*.sql or *.gz) via FTP to the working directory (take care of TEXT mode upload for bigdump.php and dump.sql but BINARY mode for dump.gz if uploading from MS Windows).

Run the bigdump.php from your web browser via URL like http://www.yourdomain.com/dump/bigdump.php.

Now you can select the file to be imported from the listing of your working directory. Click "Start import" to start.

BigDump will start every next import session automatically if JavaScript is enabled in your browser.

Relax and wait for the script to finish. Do NOT close the browser window!
IMPORTANT: Remove bigdump.php and your dump files from your web server.

Else try the command line
mysql -u user_name -p database_name < path/to/the/file.sql

Answer: Method 1:-
If you aren't familiar with the command line and you really want to stick with a GUI style import then you can use BigDump (http://www.ozerov.de/bigdump/).

I used it once but it's been a while. From what I remember you will download a file named bigdump.php (with some instructions) and put it on your webserver in the directory with the MySQL DB dump file that is too large to import via PHPMYADMIN.
Then navigate to it using your browser - something like http://your-website.com/bigdump.php.

If you are familiar with the command line and using a Linux based system then you can use code like like this:
mysql -u USERNAME -p DATABASENAME < FILENAME.sql

The database and user (with privileges to the database) will need to exist prior to running this command though.
Note I copied the above command from another source. I always do my dumps and restores like this: DUMP: mysqldump -u DB_USER -h DB_HOST -pDB_PASSWORD DB_NAME | gzip -9 > DB_NAME.sql.gz RESTORE: gunzip < PATH_TO_DUMP/DB_NAME.sql.gz | mysql -u DB_USER -pDB_PASSWORD DB_NAME

Finally, and most painfully, you could choose to dump individual tables or groups of tables into small enough dumps. Then restore these individual dumps one at a time via PHPMYADMIN.
You can approach second method also:
Method 2:-
You can:

increase memory_limit
increase post_max_size
increase max_execution_time
must restart Apache after doing all this.
or use Big Dump
Comment: even though you increase the parameter's in method-2 I don't think it will be able to achieve something like 5 GB !
Comment: Yes @PreetiMaurya you are correct 5 GB file uploading configuration in Apache is not correct way
Comment: Method 1 - told me "MySQL server has gone away"
Answer: if your apache is not enabled to max file size 5GB than you can not import such big file.
Use php big dump tool its best ever i have seen. its free and opensource
http://www.ozerov.de/bigdump/


RegEx multiple optional characters in group

Question: How would I define optional characters in a group?
I am trying to match the following...
kg
kilo
kilos
kilogram
kilograms
g
gram
grams

I know I can put them individually in a group, but was wondering if I could do something fancy like this...
(kg|kilo?g?ram?s?)

Problem is it could match only the s? or none of the second alternation so it would match zero length.
Comment: Your current regex actually matches such oddities as `kilorams` and `kilgras`.
Comment: https://regex101.com/r/oD8fA8/1
Answer: You can use (?:) to group items without capturing (this works in most RegEx flavours; look up "non-capturing groups" in your engine's documetation if you are unsure).
With that, you can try something like this:
(k?g|(?:kilo)?grams?|kilos?)

This matches exactly
g kg gram grams kilogram kilograms kilo kilos

and nothing else.
Comment: It makes it possible to match `kilo` or `kilos`.
Answer: I would start by enumerating all of the possible match conditions and then paring down from there to see if there is a more efficient solution:
kg|kilo|kilos|kilogram|kilograms|g|gram|grams

the plural 's' is an obvious redundancy:
kg|kilos?|kilograms?|g|grams?

g and kg can be collapsed:
k?g|kilos?|kilograms?|grams?

We can collapse the units for kilograms:
k?g|kilo(?:s|grams?)?|grams?

Are you OK with the six character duplication of "grams?" :)


Import/Export of Panelized Nodes

Question: I'm using Panelizer to panelize nodes of a specific content. This content type is used so that content editors on the website can easily edit (with the help of Panels IPE) the content of pages which all have unique custom layouts (ie. different sets of panels panes at different positions).
To ease deployments, I"m looking for a way export panelized nodes from the development (local) site to the validation and production sites in a non-interactive fashion. Import/Export of nodes themselves is not the issue here, there is several solutions. But, AFAIK, none of them handle the panelizer part. The solutions to use will likely depend on the exact how to export/import the panelizer part of the panelized nodes and how it can be integrated in an automated workflow.
So far, for a panelized <code>$node</code>, I've found the following
<code>// Export the panelized entity information
ctools_export_crud_export('panelizer_entity', $node->panelizer['page_manager']);
// Export the panel display of the entity
ctools_export_crud_export('panels_diplay', $node->panelizer['page_manager']->display);
</code>
Answer: You can do that by using uuid_features the dev version (dev+36)
 and you may need Panelizer (dev) there are some patches there that will solve problems for you.
Also you can try deploy module, though I didn't use it, but it looks like it will become a more promising solution.
Answer: Depending on your Panel contents, you may be able to use Node Export and Features modules. With this, I'm able to export the fully configured and populated Panelizer node.
However, I'm running into a problem where, if I've added an existing node, the NID isn't being translated to the new NID.
If you are just exporting a Panelizer node with panes to fields, or views, etc., i.e. something where the machine ID is the same on all servers, this should work very well.
Make sure to configure your Node Export Features settings the same way on all servers.
Additionally, you should use the XML export option or PHP serialize (if that works for you). See this thread for issues with Panelizer exports: https://www.drupal.org/node/1304942 and https://www.drupal.org/node/1916524

Import/Export of Panelized Nodes


Salesforce digital experience page is sometimes requiring authentication for access even though the guest user has access

Question: I'm not posting any code, but can if anyone believes it's relevant.  But the symptoms don't seem to point to the page or the code.
We have configured a Digital Experience.  For the experience, we have created a single Visualforce page.  The guest profile has been given access to the page and the page's controller.  We have assigned that page as the "Active Site Homepage".  The site will work as planned, meaning that when going to the base site URL or directly to the page, it will load without authentication.  After a given amount of time (which we are not sure how long at this point) of the site not being accessed, when attempting to access the site, it will require authentication.
When that happens we try to troubleshoot.  For example, I commented out some of the code on the page that was loading a Visualforce component.  Tried loading the page, but it still took me to the login page.  So I removed my comments, setting the page back to normal.  Suddenly the page starts working and is accessible to everyone, from any location.  Even for people who have never logged into the backend org.  The page will continue to work for the rest of the day.  The next morning we are back to square 1 and the site is requiring authentication.
I thought maybe it was the proxy caching by Salesforce, so I told everyone to stay out of the experience and waited 30 minutes.  Since Salesforce says the caching is 10 minutes.  But when I went to the page it worked without requiring authentication and I'm pretty sure that tomorrow morning it will start asking for authentication again.
The biggest issue is that we can't seem to troubleshoot. I will make a change to try and see what is happening and sometimes that change will cause the page to work, but then immediately reversing that change doesn't cause the page to break.
Has anyone else experienced this behavior before?
Answer: Interesting.
You might have more luck posting in dedicated https://salesforce.stackexchange.com/
Have you tried attaching debug logs? You can find the special <code>{site name} guest user</code> in the lookup and put debugging on for 24h, maybe it'll catch something. Is there any fancy JavaScript on the page that might be causing redirects, lazy loading of some images that might need authentication? Is there a LiveAgent embedded in the community?
Put up as simple version of the page as you can and inspect the generated html. Maybe you're using spyware... sorry, analytics / tracking scripts like Google Tag Manager or Adobe's?
Have you tried browsing with browser's console open (typically F12), maybe you'll catch something weird in Network tab that fails and redirects you to login page. Can you reliably reproduce it in incognito / inprivate / etc mode? Maybe something with cookies?


According to these audio, am I a baritone or a tenor?

Question: I am having trouble to find my voice type, I don't know if I am a baritone or a tenor. I have 30 years of age. My lowest note that I can support is G2, but my comfortable note starts at A2-Bb2. I feel like I strain at F#4, my second passaggio,so literally i am in my head  register at F#4, and I can mix up to A4-B4 in my good days.
Comment: I'm voting to close this question because 1) it's a transcribing question, which is off topic, and 2) the links are dead.
Comment: Question as an answer - why do you feel the need to have a label put on the estimated range of your voice? What difference will it make to anything you sing in the future?  It's a good voice - just use it!
Comment: Just wanted to know if i can sing Tenor repertoire, because i would like to get some classical lessons for opera. I do not like Baritone repertoire in opera. Thanks for the answer.
Comment: A2-A4 is more of a baritone range in "classical" opera. Tenors need to be able to nail a string of C5s in an aria (without using falsetto) if they want to get the girl! But playing evil/comic roles as a baritone is also fun...
Answer: You "would like to get some classical lessons for opera"?  Well, do so.  Your vocal coach will hopefully be much more qualified to answer your question than strangers on the Internet.
Answer: Comparing your voice to a lot of the Baritones and Tenors I've heard I'd have to say you're definitely closer to a Tenor.


Running a function after another function with loops & promises in jQuery/JavaScript

Question: I'm working on a college/personal project which takes RSS urls and sends them through a series of APIs. Code follows:
var tempStory = [];
function getFeed () {
        $.getJSON('spoonfed/app/scripts/categories.json', function(categories){
            for (var category in categories){
                if (categories[category][2] === true){
                    getFeedURLs(categories[category][0]).then(function(rssData) {
                        for (var item in rssData){
                            tempStory.push(rssData[item]);
                        }
                    });
                }
            }
    });
}

There are an unknown number of categories I need to iterate over in addition to 10 news stories in each category, which are then pushed to the array tempStory. I need to run another function on this array of data. I think promises are the key here but I can't get my head around how I'd use them in this case.
Any help would be really appreciated and I'm happy to provide more of the code if needed, including the structure of the categories.json file and the getFeedURLs function.
Comment: Can include `getFeedURLs` text at Question ?
Comment: @Quill - maybe or maybe not.  It could be that `categories[category][2]` could contain several different types of values and the OP wants to make sure it's `===` true, not any other truthy value.
Comment: @jfriend00, yes, I see your point now. Thanks for clarifying.
Answer: If the issue is that you're just trying to figure out how to get all the data out, then you can do this:
function getFeed() {
    return $.getJSON('spoonfed/app/scripts/categories.json').then(function (categories) {
        var tempStory = [], promises = [];
        for (var category in categories) {
            if (categories[category][2] === true) {
                promises.push(getFeedURLs(categories[category][0]).then(function (rssData) {
                    for (var item in rssData) {
                        tempStory.push(rssData[item]);
                    }
                }));
            }
        }
        return $.when.apply($, promises).then(function() {
            // return results array as the fulfilled value of the promise
            return tempStory;
        });
    });
}

getFeed().then(function(data) {
    // all the data available here
}, function(err) {
    // error here
});

The key aspects of this are:

Return the original ajax promise from getFeed().
When iterating the categories, push all those promises into an array to collect them all
Use $.when() with your array of promises to know when all of those are done
From within the $.getJSON.then() handler, return the $.when() promise which will chain to the $.getJSON() promise and let you return an array of results.
From within the $.when().then() handler, return our results so that becomes the fulfilled value of the final promise

Note: because of the way you chose to accumulate the tempStory array, it's results are not in a guaranteed order.  Additional code could be written to maintain the order.
Comment: This is awesome, thank you- I didn't realise promises could be used in that way but to be honest promises were pure AJAX magic up to this point!
Comment: @JamesCyan - The real power of promises comes when you're trying to do something exactly like this - manage a whole bunch of async operations and end up with all the results and handle errors appropriately.
Comment: @JamesCyan - Since it looks like you may be fairly new to Stack Overflow, do you realize that if you get your question answered, you can check the green checkmark to the left of the best answer.  That will both indicate to the community that your question has been answered and will earn your some reputation points.


the "min" part of the min/max isnt working - javascript

Question: So Ive got this script to find a random number between two user-typed in values. The "max" part works, the randomly generated number is never higher than the higher number. But the numbers generated are still from 1 to the highest number, not whatever "min" to set to. What am I doing wrong?
Looking at other codes Ive tried the "(max - min + 1) + min" formula but it gave the exact same result as Im having now. And sometimes it didnt register at all. It may be a simple syntax problem Im missing? Other variations end up with the random generated number concencrated with the value of "min" instead of adding the two number values together. For example, between 10 and 20, Ill roll an 8 and it will display "810" in the answer box, instead of 18 like it should be.

Comment: Try: `var rangeA = Math.min(minA,maxA);`. Also, use `parseInt` when getting `value` from DOM. Also note that you're missing `}` of the function
Comment: I havent learned about ParseInt yet, how would I go about implementing that?
Comment: See [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt)
Comment: Doesnt really help me figure out where in the code its supposed to go lol is it something like `var minA = parseInt(document.getElementById('hp_one').value;` ?
Comment: Read my first comment again, I've mentioned where it need to be used.
Comment: !!! that WAS it! I cant believe I got it right! XD Im really bad with syntax lol Thanks you so much!! It works now!!
Answer: Try this:
function roll_the_dice() {
    //parseInt to convert string values to Integer
    var minA = parseInt(document.getElementById('hp_one').value);
    var maxA = parseInt(document.getElementById('hp_two').value);
    //Math.min-> returns smallest vale from provided numbers
    var rangeA = Math.min(minA, maxA);
    document.getElementById('hp_result').value = Math.floor(Math.random() * rangeA + 1);
}

Comment: Don't forget the _radix_ when using `parseInt`
Comment: @Tushar, That is an optional argument I suppose. I dont think we need to mention `base` for this example..
Answer: var resultA = Math.floor(Math.random() * (maxA - minA) + minA);

should do it. You are multiplying the output of Math.random() with what I believe to be a tuple, and I don't think that's doing what you want it to be doing. Also, as Tushar said, you should be using parseInt() on the user inputs, or else you'll be multiplying by strings.


How do elections prediction works

Question: Here in my country it's time to choose a president. So some institutions make surveys about how many votes (in %) the candidates are gone get in the poll day. The population is about 200 million peoples, but to make these surveys about 2000 people are asked their opinions. How it's possible to predict the result of the election with only such small number of the population?
Comment: I was expecting a less technical answer to be honest...
Comment: You can predict the results using far fewer than 2000 people: even one well-chosen person will do.  The issue, therefore, is *how accurately and precisely* can the result be predicted? Accuracy requires selecting the sample with great care, using procedures that ensure the sample results are likely to reflect the voting.  Precision increases with *sample* size and scarcely depends on the population size.  In a well-designed survey of 2000 people, the precision is usually small enough (a few percent) to be useful.
Answer: so for one thing the variability only decreases with the square root of the number of people by the law of large numbers - so there is a diminishing returns effect on adding more people to the sample
furthermore people use stratified sampling - collecting samples from each age group (etc) and weighting by their known electoral proportions

How do elections prediction works


DataStage execute shell script to sleep in a loop sequence job

Question: Currently, I have a sequence job in DataStage.

Here is the flow:
StartLoop Activity --> UserVariables Activity --> Job Activity --> Execute Command --> Endloop Activity

The job will run every 30 minutes (8 AM - 8 PM) to get real data. The first loop iteration will load data from 8 PM the previous day to 8 AM the current day, and the others will load data that happens in the last 30 minutes.

The UserVariables Activity is to pass variables (SQL statement) to filter data getting in the Job Activity. The first iteration the UserVariables pass variable A (SQL statement 1) to the Job Activity, from the second iteration, it will pass variable B (SQL statement 2) to the Job Activity.

The Execute Command I currently set the 'Sleep 1800' command for the job to sleep 30 minutes to end the iteration of the loop. But I realized now that it is affected by the running time of each iteration. So with my knowing-nothing about shell script, I have searched for solutions and have this file to sleep until a specific time when minute like 30 or 00 (delay 0-1 minute but it's fine).

The shell script is below, I ran it fine on my system but no success on making it as part of the job.
#!/bin/bash
minute=$(date +%M)
num_1=30
num_2=60
if [ $minute -le 30 ];
then
  wait=$((($num_1 - $minute)*$num_2))
  sleep $wait
fi
if [ $minute -gt 30 ];
then
  wait=$((($num_2 - $minute)*$num_2))
  sleep $wait
fi

I am now facing 2 problems right now that I need your help with.

The job runs the first iteration fine with the variable A below:

select * from my_table where created_date between trunc(sysdate-1) + 20/24 and trunc(sysdate) + 8/24;

But from the second iteration it failed with the Job Activity with the variable B below:
select * from my_table where created_date between trunc(sysdate-1/48, 'hh') + 30*trunc(to_number(to_char(sysdate-1/48,'MI'))/30)/1440 and trunc(sysdate, 'hh') + 30*trunc(to_number(to_char(sysdate,'MI'))/30)/1440;

In the parallel job, the log said:
INPUT,0: The following SQL statement failed: select * from my_table where created_date between trunc(sysdate-1/48, hh) + 30*trunc(to_number(to_char(sysdate-1/48,MI))/30)/1440 and trunc(sysdate, hh) + 30*trunc(to_number(to_char(sysdate,MI))/30)/1440.

I realized that maybe it failed to run the parallel job because it removed the single quote in hh and MI.

Is it because when passing variables from UserVariables Activity to Job Activity the variable will remove all the quotes? And how can I fix this?

2. How can I make the shell script above as part of the job like Execute Command or some other stage. I have searched for solutions and I think it's about the ExecSH Before/ After Routine Activity. But after reading from IBM pages, I still don't know where to start with it.

Sorry for adding 2 questions at 1 post that makes it so long but it's very relative to each other so it will take lots of time to answer if I separate it into 2 posts and you guys need more information about it.

Thank you!
Answer:
Try escaping the single quote characters (precede each with a backslash).
Execute the shell script from an Execute Command activity ahead of the Job activity.


Count status code in log file

Question: I'm trying to count the amount of times a status code repeats in a log file. This is an example of the content of the file '10.10.10.10 - - [29/Aug/2017:06:29:44 -0400] "GET /isomaster/download/ HTTP/1.1" 200 - "-" "curl/7.49.1"\n' but it repeats multiple hundred times with different requests containing different status codes. This is my attempt to getting the count of all 200 status code.
def loadFiles():

    #READ From access_log
    access_0 = open('file0','r')
    line_0 = access_0.readlines() #readlines() read the text line per line
    print(line_0)
    access_0.close()

    access_1 = open('file1','r')
    line_1 = access_1.readlines() #readlines() read the text line per line
    return print(line_1)
    access_1.close()

    access_2 = open('file2','r')
    line_2 = access_2.readlines() #readlines() read the text line per line
    return print(line_2)
    access_2.close()

    access_3 = open('file3','r')
    line_3 = access_3.readlines()
    return print(line_3)
    access_3.close()

def total_200():

        values = loadFiles()
        values_200 = re.findall(r'\d{200}\s',values)
        string_count = values_200.count('200')
        print(string_count)

The loadFiels() loads in the content of all the multiple files I want to read, but what this does is only print the all the strings with the status code 200, it doesn't not count it. Any suggestions on how to go about this? Thanks!
Answer: string_count is a list. You can simply use len(string_count) to get the integer count.
Comment: I'm getting an error at  `values_200 = re.findall(r'\d{200}\s',values)` because it's expecting a string or a byte-like object where `values` is since my file is in a list format. Would I need to convert this list into a string or is there a better way of getting around this?
Comment: @Katz maybe you can just loop through the list. So run this for each value in 'values'.

Count status code in log file


Is there a way to show that the addition of the first n terms of the Fibonacci sequence squared gives an answer divisible by a particular number?

Question: Is there a way to show that the addition of the first n terms of the Fibonacci sequence squared gives an answer divisible by a particular number?
Comment: lol I looked at that question, but I don't understand all the whacky notation that they use.
Comment: What "whacky notation"? It's only "$F_n$", which means the $n$-th Fibonacci number.
Comment: What notation?  $F_n$ just means the $n^{th}$ Fibonacci number.  you can prove the desired claim by induction...no need to go through the geometric argument (though it is interesting).
Comment: [this question](http://math.stackexchange.com/questions/442459/for-the-fibonacci-numbers-show-for-all-n-f-12f-22-dotsf-n2-f-nf-n1) is very relevant.
Answer: There is no need to find an explicit formula for $\sum_{n=1}^{600}F_n^2$ (but this is doable and I'll show it in the second part of this answer). The Fibonacci sequence obeys the relation $F_{n+2}=F_{n+1}+F_{n}$ and $8$ is a Fibonacci number, hence the sequence $\{F_n\pmod{8}\}_{n\geq 1}$ has a short period and the same applies to $\{F_n^2\pmod{8}\}_{n\geq 1}$:
$$\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|}\hline  n & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 &9 & 10 & 11 & 12\\ \hline F_n\pmod{8} & 1 & 1 & 2 & 3 & 5 & 0 & 5 & 5 & 2 & 7 & 1 & 0 \\ \hline F_n^2\pmod{8} & 1 & 1 & 4 & 1 & 1 & 0 & 1 & 1 & 4 & 1 & 1 & 0\\ \hline\end{array}$$
By direct inspection, we have that $F_{6n+1}^2+F_{6n+2}^2+F_{6n+3}^2+F_{6n+4}^2+F_{6n+5}^2+F_{6n+6}^2$ is always a multiple of $8$, hence $6\mid 600$ implies $8\mid\sum_{n=1}^{600}F_n^2$.

Now the brute-force approach. Let $\sigma=\frac{1+\sqrt{5}}{2}$ and $\bar{\sigma}=\frac{1-\sqrt{5}}{2}$. We have $\sigma+\bar{\sigma}=1$, $\sigma\bar{\sigma}=-1$ and
$$ F_n = \frac{\sigma^n-\bar{\sigma}^n}{\sqrt{5}},\qquad F_n^2 = \frac{\sigma^{2n}+\bar{\sigma}^{2n}-2(-1)^n}{5} $$
hence it is enough to show that $8$ is a divisor of $L_2+L_4+\ldots+L_{1200}$, where $L_n=\sigma^{n}+\bar{\sigma}^n$ is a Lucas number. Lucas numbers obey the same recurence relation as Fibonacci numbers, hence
$$ L_2+L_4+\ldots+L_{1200} = L_{1201}-L_{1} $$
can be easily proved by induction and it is enough to show that $L_{1201}\equiv L_1\pmod{8}$.
$$\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}\hline n & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 \\ \hline L_n\pmod{8} & 2 & 1 & 3 & 4 & 7 & 3 & 2 & 5 & 7 & 4 & 3 & 7 & 2 & 1 \\ \hline \end{array}$$
By direct inspection, the period of the sequence $\{L_n\pmod{8}\}_{n\geq 1}$ is $12$, hence $L_{1201}\equiv L_1\pmod{8}$ as wanted.
Comment: @differentialequation: $F_n$ is the $n$-th Fibonacci number and $F_n^2$ is its square.
Comment: Thank you so much!! This is actually a very elegantly produced solution and I can't believe I actually understand all of the notation (I'm pretty new to modular arithmetic, etc.)
Comment: Sorry for sounding really naive but what does the numbers in superscript and subscript mean after the 'F'?
Answer: You can prove by induction that the sum of the squares of the first $6n$ terms is divisible by $8$.

First, show that this is true for $n=1$:
$\sum\limits_{m=1}^{6}F_m^2=40$
Second, assume that this is true for $n$:
$\sum\limits_{m=1}^{6n}F_m^2=8k$
Third, prove that this is true for $n+1$:
$\sum\limits_{m=1}^{6(n+1)}F_m^2=$
$\sum\limits_{m=1}^{6n+6}F_m^2=$
$\left(\color\red{\sum\limits_{m=1}^{6n}F_m^2}\right)+F_{6n+1}^2+F_{6n+2}^2+F_{6n+3}^2+F_{6n+4}^2+F_{6n+5}^2+F_{6n+6}^2=$
$\color\red{8k}+F_{6n+1}^2+F_{6n+2}^2+F_{6n+3}^2+F_{6n+4}^2+F_{6n+5}^2+F_{6n+6}^2=$
$\small8k+F_{6n+1}^2+F_{6n+2}^2+(F_{6n+1}+F_{6n+2})^2+(F_{6n+1}+2F_{6n+2})^2+(2F_{6n+1}+3F_{6n+2})^2+(3F_{6n+1}+5F_{6n+2})^2=$
$8k+16F_{6n+1}^2+40F_{6n+2}^2+48F_{6n+1}F_{6n+2}=$
$8(k+2F_{6n+1}^2+5F_{6n+2}^2+6F_{6n+1}F_{6n+2})$

Please note that the assumption is used only in the part marked red.
Answer: Use the Pisano Period for $n=8$. It's $12$, meaning that after the first 12 numbers the residues modulo $8$ start repeating. Hence it's enough to split the $600$ numbers in groups of $12$ and it's fairly easy to notice that the sum of squares of numbers of each such group is divisible by 8, by just checking the first such group.
Comment: Hi, I actually had no idea what the 'Pisano Period' is so would you mind quickly explaining how I could apply this problem to it? I've been reading about it for a few minutes..
Comment: @differentialequation The Pisano Period for some positive integer $n$ is some integers after which the Fibonacci Sequence taken modulo $n$ starts repeating. In other words the Pisano Period is the length of the period modulo $n$. It's been proven that the Fibonacci Sequence is periodic modulo any positive integer.
Answer: Taking squares, the period of $F_n^2$ modulo 8 is just 6. A little calculation gives (overline=repeat):
$$ (F_n^2)_{n\geq 1} \equiv \overline{[1,1,4,1,1,0]}  \ \ {\rm mod} \ 8 $$


Are there any timeframe selector web controls for .NET?

Question: I would like to use a timeframe selector in a web page, that is optimized for touchscreen usage. (e.g. large buttons).
I am actualy looking for a control that mimics iPhone UI for selecting a time frame or a time interval, say from 10:30 AM to 15:00 PM.
Answer: I don't know about the iPhone UI - I dont have one - but this is quite a nice timeframe / recurrence library. It might help :)


Propensity Score Matching implementation after multiple imputation

Question: There is a very good thread about Propensity Score Matching after multiple imputation with the articles referred:

Propensity score matching after multiple imputation

In the refered articles, they talk about

averaging of propensity scores after multiple imputation, followed by causal inference (method 2 in your post above)
causal inference using each set of propensity scores from the multiple imputations followed by averaging of the causal estimates.

Method 2 is propensity score matching, lets say when someone imputes 5 datasets, in all 5 of them. However, we then end up with 5 propensity score matched cohorts and we want to make 1 propensity matched cohort of it; also how to implement this in SPSS/R, this stays unclear.
Some Articles also talk about the Rubin's Rule for pooling; but could not find good implentation in SPSS/R literature on that, if somebody could help on that I would appreciate it.
So in short, the question is: how to properly perform propensity score matching after multiple imputation and how to implement it in SPSS/R?
If anybody has reference material, I would like to read it!
Answer: Update 1/4/20: A new package has been written for this purpose called MatchThem. It's on CRAN, and an article about how to use it is under review. It's compatible with version 4.0.0 of cobalt for balance checking. It has built-in functions for performing matching and estimating treatment effects from multiply imputed data. It has integration with svyglm() and svycoxph(), so you can estimate treatment effects for various forms of outcome. It really smooths out the process of estimating effects from multiply imputed data.

I answered this question which provides R code for your case after using mice to multiply impute, MatchIt to match within each imputed data set, and glm() to estimate treatment effects in each imputed data set.
See the documentation for cobalt for an example of the other method (averaging propensity scores across imputations).
Comment: thank you very much! The link was very useful! Cobalt documentation was also very useful.

However, when matching the data with

  `m.out <- matchit(t ~ v1 + v2 + v3, data = imp.data[imp.data$.imp == i,])`, we get matched data per imputed dataset. However, how do we see each matched dataset; how can we take each matched dataset from the total imputed dataset apart; and perform lets say a cox regression per matched dataset per imputed dataset?


php: preg_match and preg_replace

Question: I'm unsure of how to do the following...
I need to search through a string and match all instances of a forward slash and certain letters. This is for word modifications that users have the ability to input and I want them to be able to modify individual words.
Here is an example string

Hello, isn't the weather just absolutely beautiful today!?

What I'd like the user to be able to do is something like this

Hello, isn't the /bo weather just /it beautiful today!?

take note of the /bo and /it
what I'd like to do is have a preg_match and or preg_replace statement that finds and replaces the instances of /bo and /it and converts them instead into html tags such as bolded html tag and italics html tag (i cant type them here or they get converted into actual html. but wrap themselves around the word immediately following the /bo so in this example it would wind up being
Hello, isn't the weather just beautiful today!?

Any ideas how I could do this with a regex?
Once the conversions are done i'll do the standard sanitizing before inserting the data into the database along with prepared statements.
Comment: You can type them here. Just use the code block. If you are not able to, then type it...someone here will do it for you
Answer: $string = "Hello, isn't the /bo weather just /it beautiful /bo today!?";

var_dump(preg_replace (array('/\/bo\s(\w+)/', '/\/it\s(\w+)/'), array('$1', '$1'), $string));

"Hello, isn't the weather just beautiful today!?"
Comment: @Uchiha You always correct me if something goes wrong :)
Comment: @Uchiha, Just do not tell anyone :) My mom trains the brain solving Sudoku I decided to use this website for this purpose and, before retirement, recall programming, that i did not use  last 25 years)
Answer: The regexp
/\/(bo|it)\s+([\S]+)(?=\b)/g

and replacement string
<$1>$2</$1>

would almost do it:
Hello, isn't the <bo>weather</bo> just <it>beautiful</it> today!?

But the tags are not quite right yet ... They need to be single letters. :-(
Try here: https://regex101.com/r/oB9gT0/1
2. Edit - a bit late, but now it works:
$str=preg_replace('/\/([bi])((?<=b)o|(?<=i)t)\s+([\w]+)/','<$1>$3</$1>',$str);

will now deliver the correct result:
Hello, isn't the weather just beautiful today!?

see here: https://regex101.com/r/oB9gT0/3
Answer: You can use preg_replace_callback for this purpose.
This basically calls a callback method for every match that occurs.
Inside the callback, you can perform the replacement according to your conditions(bold for bo, italics for it, heading for he et al.)
Something like this -
$str = "Hello, isn't the /bo weather just /it beautiful today!?";
$regex = "/\/(.*?)\s+(.+?)\b/";

function callback($matches){
    $type = $matches[1];
    $text = $matches[2];
    switch($type){
        case "bo":
            return "".$text."";
            break;
        case "it":
            return "".$text."";
            break;
        default:
            return $text;
    }
}

$resp = preg_replace_callback(
    $regex,
    "callback",
    $str
);

var_dump($resp);

/*
OUTPUT-
Hello, isn't the weather just beautiful today!?
*/

This example could be extended further by checking for various types and invalid types

php: preg_match and preg_replace


How to deployed Mvc Application on shared-hosting Server?

Question: I My Web site on a HELM Control Panel. I developed my web site on MVC.But My Hosting Provider having a Following components installed on That Hosting Account framework 3.5 and IIS6. But I am Unable to Run My site it display me Page not found error.
Answer: The problem will be that you're running under IIS6 and if its on shared hosting you're unlikely to have sufficient control to make MVC run without "cheating" a bit.
Under IIS6 requests are only routed to the ASP.NET handlers (I don't promise to get the terminology right) if they have the right extension (.aspx, .asmx, .ashx, etc) with a nice MVC URL there's no extension at all so it doesn't get see by ASP.NET and hence the request won't hit the routing within your MVC app and so you get page not found.
Under IIS7 everything (ish) goes through the ASP.NET handler and so it just works.
So a couple of links to help, here's a stackoverflow question:
ASP.NET MVC on IIS6
and here's Phil Haack on the subject:
http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx
Hope this helps.
http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx
Comment: +1 Note that on IIS7 the host provider must run the web site in an application pool set to "Integrated" mode for ASP.NET MVC to work.


Given the set $D$ compute its triple integral in two different orders

Question: Given the set $D = \{(x, y, z) \in R^3 : 0<z<y<2 ; 0<x<2y + z\}$ compute the integral in the orders $dx\,dy\,dz$ and $dz\,dy\,dx$.
My problem is that I cant find the upper and lower bounds for $z$ in the first case and for $x$ in the second case.
Any help is much appreciated.
Comment: Are you looking to find the volume $\iiint_D\,\mathrm{d}V$, or is there more to the problem?
Comment: Yes that's what I'm looking to do, but in the given orders. I'm sorry if I wasn't explicit enough, english isn't my first language.
Answer: In either order, the limits of the last variable ($z$ and $x$, respectively) can be determined by figuring out the vertices of the pentahedron bounded by $D$.
You can do this is by solving case-by-case the following system (which is just a list of all the bounding planes given in the definition of $D$):
$$\begin{cases}z=0\\z=y\\y=2\\2y+z=x\\x=0\end{cases}$$
To find the possible locations of each vertex, you can construct a table like this:
$$\begin{array}{c|c|c|c}
x&y&z&\text{vertex}\\
\hline
0&2&0&(0,2,0)\\
0&2&y&(0,2,2)\\
0&z&0&(0,0,0)\\
0&z&y&\text{no unique solution}\\
2y+z&2&0&(4,2,0)\\
2y+z&2&y&(6,2,2)\\
2y+z&z&0&(0,0,0)\\
2y+z&z&y&\text{no unique solution}
\end{array}$$
This means that in the first order of integration, you would have $0<z<2$, and in the second, you would use $0<x<6$ (well, not exactly; see my edit).
Added:
Here's a graphic showing the bounding planes (somewhat transparent) surrounding the pentahedron (blue). (Rendered in Mathematica; I picked out two viewing angles that seemed sufficient to me to be able to make out the region well enough.)

For the first order, $\mathrm{d}x\,\mathrm{d}y\,\mathrm{d}z$, we are essentially already given a convenient set of bounds for each variable.
$$D=D_{x,y,z}=\{(x,y,z):0<x<2y+z,\,z<y<2,\,0<z<2\}$$
and so the volume is given by
$$\iiint_{D_{x,y,z}}\mathrm{d}V=\int_0^2\int_z^2\int_0^{2y+z}\mathrm{d}x\,\mathrm{d}y\,\mathrm{d}z$$
The second order involves a bit more work. Considering the $z$ direction first, it's clear that the lower bound of $D$ is the plane $z=0$ (light orange) in one segment of the solid, while in another the lower bound would be the plane $z=x-2y$ (light purple). Meanwhile, the upper bound is uniform in the shape of the plane $z=y$ (light blue).
One way to work around this is, as you say, split up the integration region. In particular, we can split up the "base" of the pentahedron along the intersection of the two different lower bounds in the $z$ direction:
$$(z=0)\land(x=2y+z)\implies x=2y$$
and again along the intersection of this new plane with the plane $y=2$, since $y$ doesn't vary uniformly in the smaller sub-region obtained by the first splitting plane.
Here's a graphic with the region and these two splitting planes:

So now we write
$$D=D_{z,y,x}=D_1\cup D_2\cup D_3$$
where
$$D_1=\left\{(x,y,z):0<x<4,\,\frac{x}{2}<y<2,\,0<z<y\right\}\\
D_2=\left\{(x,y,z):0<x<4,\,0<y<\frac{x}{2},\,x-2y<z<y\right\}\\
D_3=\left\{(x,y,z):4<x<6,\,\frac{4}{3}<y<2,\,x-2y<z<y\right\}$$
The volume is then given by
$$\begin{align*}
\iiint_{D_{z,y,x}}\mathrm{d}V&=\left\{\iiint_{D_1}+\iiint_{D_2}+\iiint_{D_3}\right\}\mathrm{d}V\\[1ex]
&=\left\{\int_0^4\int_{x/2}^2\int_0^y+\int_0^4\int_0^{x/2}\int_{x-2y}^y+\int_4^6\int_{4/3}^2\int_{x-2y}^y\right\}\mathrm{d}z\,\mathrm{d}y\,\mathrm{d}x
\end{align*}$$
Unless I made a mistake somewhere, both setups should give the same result.
Comment: But how do I know that I won't have to split the volume throughout different integrals? For example, the set given by the inequalities $x/2 < y < x; 0 < z < x; x < 1$. To compute the volume of this set in the order of integration $dx\,dy\,dz$ you'd have to split the volume throughout 6 different triple integrals.
Comment: @Pedro sorry, I assumed your question was about determining the last variable's limits. If I have time later today I'll add more details to the remaining setup of each integral.
Comment: It's okay, I wasn't clear enough, the next time I have a question I'll be sure to explain myself better.
Comment: @Pedro I've added some more details to my answer
Comment: In that last triple integral isn't the lower bound of the y variable x/3?
Comment: I wish I could upvote your answer because you did some explendid work, thank you so much for your answer, you have no idea for how long this problem's been upsetting me!


During switching from TextField to DropDownButton, the last one appears only for a moment and disappears again

Question: During switching from text field (with opened keyboard) to dropDownButton a dropDown menu appears for a moment and disappears because of keyboard closing

<code>@override
  Widget build(BuildContext context) {
    ...
          child: Form(
            child: Column(
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(bottom: 8.0),
                  child: Text(
                    "Product name",
                    style: _textStyle,
                  ),
                ),
                TextFormField(
                  autofocus: true,    controller:_newProductPagePresenter.newBakeryNameController,
                  decoration: InputDecoration(
                    fillColor: Colors.white,
                    filled: true,
                    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8.0)),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(
                      top: 15.0, bottom: 8.0, right: 8.0, left: 8.0),
                  child: Text(
                    "Product category",
                    style: _textStyle,
                  ),
                ),
                DropdownButtonFormField(
                  decoration: InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      contentPadding: EdgeInsets.fromLTRB(10.0, 8.0, 10.0, 8.0),
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8.0))),
                  onChanged: (String value) {
                    setState(() {
                      currentDropDownMenuValue = value;
                    });
                  },
                  value: currentDropDownMenuValue,
//                  items: <String>['Cake', 'Pancake', 'Free', 'Four']
                  items: _productCategories
                      .map<DropdownMenuItem<String>>((ProductCategory category) {
                    return DropdownMenuItem<String>(
                      value: category.id.toString(),
                      child: Text(category.name.en),
                    );
                  }).toList(),
                ),
              ],
            ),
          ),
        ),
...
</code>
I need to switch between them smoothly, maybe wait until the keyboard is closed and only then open dropDownMenu. Thanks!
Answer: I've solved the problem by creating custom alertDialog and adding to it a GlobalKey


How much SWAP space on a 2-4GB system?

Question: How should I decide what size to make my swap on a new Linux machine (Debian) with 2-4 GB of RAM? Do I really need swap space?
Comment: 2-4 GB is not really high memory anymore 5 years later.
Comment: @KasperSouren No, it is not.  Was a fair amount at the time.
Answer: There are lots of ways you can figure out how much swap use in a machine.  Common suggestions use formulas based on RAM such as 2 x RAM, 1.5 x RAM, 1 x RAM, .75 x RAM, and .5 x RAM.  Many times the formulas are varied depending on the amount of RAM (so a box with 1GB of RAM might use 2 x RAM swap (2GB), while a box with 16GB of ram might use .5 x RAM swap (8GB).
Another thing to consider is what the box will be used for.  If you're going to have a huge number of concurrently running processes running on the box, but a significant number of them will be idle for periods of time, then adding extra swap makes sense.  If you're going to be running a small number of critical processes, then adding extra swap makes sense (this might seem counter-intuitive, but I'll explain in a minute).  If you're running a box as a desktop, then adding extra swap makes sense.
As for whether you should include swap, yes, you should.  You should always include swap space unless you really know what you're doing, and you really have a good reason for it.
See, the way the Linux kernel works, swap isn't only used when you have exhausted all physical memory.  The Linux kernel will take applications that are not active (sleeping) and after a period of time, move the application to swap from real memory.  The result is that when you need that application, there will be a momentary delay (usually just a second or two) while the application's memory is read back from swap to RAM.  And this is usually a good thing.
This allows you to put inactive applications to "sleep", giving your active applications access to additional RAM.  Additionally, Linux will use any available (unallocated) RAM on a machine as disk cache, making most (slow) disk activity faster and more responsive.  Swapping out inactive processes gives you more disk cache and makes your machine overall faster.
Lastly, let's face it, disk space is cheap.  Really cheap.  There's really no good reason at all not to swipe a (relatively) small chunk of space for swap.  If I were running with 2GB - 4GB of RAM in a machine, I'd probably setup my swap space to be at least equal to the RAM.  If it were less than 2GB of RAM, then I'd still go with at least 2GB of swap.
UPDATE: As an excellent comment mentioned (and I forgot to include), if you're running a laptop or a desktop that you might want to put in 'hibernate' mode (Suspend to Disk), then you always want at least as much swap as you have memory.  The swap space will be used to store the contents of the RAM in the computer while it 'sleeps'.
Comment: Great answer, but you forgot just one thing. If it's a desktop or laptop, make sure that swap is at least as big as the RAM you have so you can hibernate your computer. This saves the RAM to swap.
Comment: Great post.  Sander beat me to the only thing I was going to add to it.  I though of one additional item, if you have multiple drives, putting your swap on a drive that doesn't have the rest of your active file systems can improve performance as it won't have as many conflicts.
Comment: @earthmeLon - I would suggest still having a little bit of swap.  Disks are big and cheap these days, so the loss of a few GB of disk space to swap is negligible.  Having some swap space gives you an insurance policy in case something eats up more RAM than you expect it to.
Comment: as I [found out](http://antipaucity.com/?p=984) this past summer, you need to have substantial swap space if you are running Java
Comment: @ChristopherCashell After reading about *swappiness*, I can see that it's better practice to use SWAP; even on machines with large amounts of RAM.  Having the OS use SWAP *only* when necessary is a good solution, imo :D
Comment: If the user has an amount of RAM much larger than the amount that they will actually use (16GB/32GB) on a 100% uptime Desktop computer (no hibernation) then do you still suggest requesting processes to be put to SWAP?  It seems to me there would be benefits of leaving everything on RAM unless you were ever nearing it's capacity.
Comment: How can the ram be stored in swap to go to sleep, when it also needs to keep the contents of swap intact(since that's RAM too, kinda).   You can never have enough swap to contain swap+RAM!
Answer: Red Hat recommends the following formula for servers with lots of ram:
if MEM < 2GB then SWAP = MEM*2 else SWAP = MEM+2GB

If your system has 1 GB ram, your swap would be 2 GB, for 16 GB it would be 18 GB.
Comment: Relevant Link from the RHEL6 Storage guide: http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Storage_Administration_Guide/ch-swapspace.html#s1-swap-what-is
Comment: A server would be pretty be stalled if it consistently use 1Gb of swap because it's ram would be full.
Answer: Late answer, and I think this was pretty much covered in the selected answer, but there is some good and easily digestible info in the answer provided by @ssapkota here (copy/pasted below).
Here's a very good recommendation from RedHat:Recommended System Swap Space
An excerpt from the same link:

In years past, the recommended amount of swap space increased linearly with the amount of RAM in the system. But because the amount of memory in modern systems has increased into the hundreds of gigabytes, it is now recognized that the amount of swap space that a system needs is a function of the memory workload running on that system. However, given that swap space is usually designated at install time, and that it can be difficult to determine beforehand the memory workload of a system, we recommend determining system swap using the following table.

Current table (as of December 2012):
Amount of RAM in the system   Recommended swap space         Recommended swap space
                                                             if allowing for hibernation
---------------------------   ----------------------------   ---------------------------
2GB of RAM or less            2 times the amount of RAM      3 times the amount of RAM
2GB to 8GB of RAM             Equal to the amount of RAM     2 times the amount of RAM
8GB to 64GB of RAM            0.5 times the amount of RAM    1.5 times the amount of RAM
64GB of RAM or more           4GB of swap space              No extra space needed

Original table:
Amount of RAM in the System     Recommended Amount of Swap Space
4GB of RAM or less              a minimum of 2GB of swap space
4GB to 16GB of RAM              a minimum of 4GB of swap space
16GB to 64GB of RAM             a minimum of 8GB of swap space
64GB to 256GB of RAM            a minimum of 16GB of swap space
256GB to 512GB of RAM           a minimum of 32GB of swap space

Answer: It depends quite a bit on what you're doing with it. With the
appropriate workload, you don't actually need any swap space, whether
you have 16MB or 16384MB of RAM; indeed most embedded Linux devices run
without any (what would they swap to?)
Considering RAM prices, you're probably not going to use swap for active
computation. So, what's left?

On desktops, swap space is used for suspend-to-disk. This swap space
needs to be around 1 × RAM, depending on how well the memory contents
compress.
Allowing inactive tasks to be removed from RAM to make more room for
disk cache
Same, but to allow active processes to use it instead for heap/stack

(2) and (3) heavily depend on workload. On my desktops, I can easily use
4GB+ on (2), from leaving vims, xterms, etc. running on other
desktops.
On most of the servers I run, there is hardly ever anything swapped out
and 1–2GB of swap (regardless of RAM amount) seems OK.
Comment: swap space is also used if you run *anything* that utilizes the JVM: don't chintz and forget to allocate swap space if you're running Java!
Comment: @warren: I have Tomcat instances, each in excess of 3GiB, yet using no swap (and one is using hugepages, and thus can't be swapped). Not sure what you're talking about.
Comment: there is a semi-obscure bug in the JVM related to minimum and maximum memory settings that I ran into this past summer (http://antipaucity.com/?p=984). TL;DR - every time the JVM asks for more memory from the OS, it writes itself out to swap, gets its new memory chunk, then reads itself back into RAM so that its memory is contiguous
Comment: @warren: OK, I'm running OpenJDK on 64-bit, with Xmx and Xms the same. But I'm not sure how java would force itself to swap, the only syscall close would be `madvise`, but that won't fail... that bug talks about running out of memory during garbage collection. Adding swap prevents that, of course, but so would adding RAM. Maybe its due to 32-bit with PAE?
Comment: it happens with the 64-bit JVM, too: if you have `Xms` and `Xmx` not set to the same values, it can bite you badly: caused major issues for us for two+ weeks til we finally tracked it down
Answer: Well, it depends on what services and applications you plan to run. You can watch your memory usage with free -m and adjust your swap partition accordingly over time.
Here's an interesting discussion on the subject. Personally (and after reading that discussion) I'd still leave about 1 GB for swap.
Answer: I can't speak to Debian directly, but I know that when you get up above 2 GB of RAM, the original 2xRAM equation changes, usually down to 1xRAM.  I think once you hit 16 GB RAM the suggestion lowers again to .75xRAM.
Of course, I found this true for Solaris, and is actually the metric used for Oracle installations, so YMMV depending on the apps you're going to be running on there.
Answer: I always make as much swap (at least) as RAM. Just in case I want to hibernate the machine some day. Can work with less, but could as well not.
HDD space is cheap this days, therefore I don't hesitate giving away swap space.
Answer: Swap space can serve as "padding" when you would otherwise run out of memory immediately.
When a process consumes all of the available RAM and then some the machine will run very slowly, but you will usually be able to recover. It will also be easier to see which process is causing the problem.
Comment: This is a double-edged sword : on my home PC, I removed swap when I was using Firefox 2.x, because it was slowly eating all memory, and when the machine went swapping it became completely unusable; without swap, the firefox process was simply closed by the kernel :)
Answer: Over the years I have followed the rule that for Windows machines you have as much swap as you have RAM...On Novell we would tune swap higher if we had more printers...For linux the rule and practice for me has been 1GB swap for every 2GB RAM you have.  And you place it at the front of the disk so it is accessed quicker.

If it is a mail/spam gateway I use double the swap to RAM
If it is a * server I don't use swap at all
if it is a LAMP server the 1/2 rule is in effect.
Mileage will vary depending on application and GUI usage.
Comment: Actually, I'd think that swap in the *middle* of the disk would be accessed the most rapidly.
Answer: I create 1GB swap and purchase more RAM the second its being used.  You don't really need swap on modern computers, RAM is so cheap.
Answer: What are you using the system for? Personally I don't use any swap. If anything use a token 512MB or something just so things can get put to disk if resident but inactive for long periods.
Answer: I just use a small token swap (usually 256 MB, but I have even done 64 MB) because configuring a system with zero swap needs special configuration.
Disk space is cheap, but slooooooooow. As soon as the system starts swapping, performance is zero. And RAM is no longer so expensive.
Trust me, buy a slightly slower processor and buy more RAM. 2.8 GHz instead of 3.0 GHz will save you enough money to buy another 2 GB RAM, at least.

How much SWAP space on a 2-4GB system?


can I say $\mathfrak{T_1}\subseteq\mathfrak{T}_2$?

Question: $(X,d)$ be a metric space and define $p(x,y)=\min\{{1\over 2},d(x,y)\}$ $\mathfrak{T_1},\mathfrak{T}_2$ be the topology generated by $d,p$, I need to know relations between them.
Well, open sets of $\mathfrak{T}_1$ are smaller than the other  one that I can see easily, so can I say $\mathfrak{T_1}\subseteq\mathfrak{T}_2$ ?
Comment: See http://math.stackexchange.com/questions/156318/proof-that-every-metric-space-is-homeomorphic-to-a-bounded-metric-space and http://math.stackexchange.com/questions/275841/standard-bounded-metric-induces-same-topology
Comment: @ChrisCulter Thank you very much for these links
Answer: You can say more, namely $\mathfrak T_1=\mathfrak T_2$.
Assume $U\in \mathfrak T_1$. Then for every $x\in U$ there is an open ball around $x$ contained in $U$, that is for some $r>0$, all $y$ with $d(y,x)<r$ belong to $U$. May may as well assume that $r<\frac12$ and in that case also all $y$ with $p(y,x)<r$ are in $U$. Hence $U\in\mathfrak T_2$.
The same idea that we may assume wlog. that $r<\frac12$ works just as well to show that $U\in\mathfrak T_2$ implies $U\in\mathfrak T_1$.
Answer: Open sets in a metric spaces are completely determined by all open balls of radius at most $r$, for any $r>0$. The reason is that any open ball in a metric space is the union of open balls of radius at most $r$. So, the two topologies you describe are equal.
Answer: Note that in order to show that two topologies are equal it suffices to prove that there are bases $\cal B_i$ of $\frak T_i$ such that every open set in $\frak T_1$ contains a basic open set from $\cal B_2$ and vice versa.
Hint: Show that $\left\{B_r(x)\mathrel{}\middle|\mathrel{} x\in X, r<\frac12\right\}$ is a basis for both topologies.


Exibir dados da tabela com chave primaria na tabela que tem a chave estrangeira - SQL

Question: Criei em meu banco duas tabelas: PRODUTO e FORNECEDOR.
Na tabela FORNECEDOR há um campo CNPJ que é uma chave primaria.
Na tabela PRODUTO há uma chave estrangeira FK_PRODUTO que é interligada com o campo de CNPJ da tabela FORNECEDOR.
Estou fazendo a consulta da tabela PRODUTO usando SELECT * FROM PRODUTO; mas os dados da coluna CNPJ_FORNECEDOR que deveriam ser trazidos da tabela FORNECEDOR aparecem como NULL.
Código de criação das tabelas:
CREATE TABLE FORNECEDOR
(
    CNPJ BIGINT PRIMARY KEY,
    RAZAO_SOCIAL VARCHAR(50),
    ENDERECO VARCHAR(50),
    CIDADE VARCHAR(50)
);

CREATE TABLE PRODUTO
(
    CODIGO INT PRIMARY KEY,
    DESCRICAO VARCHAR(60) NOT NULL,
    ESTOQUE INT,
    VALOR INT,
    CNPJ_FORNECEDOR BIGINT,
    CONSTRAINT FK_PRODUTO FOREIGN KEY(CNPJ_FORNECEDOR)
    REFERENCES FORNECEDOR (CNPJ)
);

Comment: Não , não deveriam , os valores de CNPJ precisam serem inseridos na table PRODUTO.
Comment: @Motta, não existe nenhuma forma de trazer esses dados sem necessariamente inseri-los nas duas tabelas?
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: *"mas os dados da coluna CNPJ_FORNECEDOR"* se estão null é pq foram inseridos como nul, é um problema dos dados e não da query. Ou seja, quando inseriu o produto, não "ligou" a nenhum cnpj de fornecedor
Answer: Precisamos entender alguns pontos primeiro. Se temos um produto relacionado á um fornecedor, em teoria, não podemos cadastrar um produto sem um fornecedor, ou seja, uma relação bem amarradinha, o sgbd nem deixaria cadastrar um produto com o campo cnpj_fornecedor vazio ou com um cpnj no qual ainda nenhum fornecedor fora cadastrado ainda. Resumindo, Vc só poderia cadastrar um produto com um cnpj que ja existisse na tabela de fornecedores. Em suma, um produto que não possui um fornecedor, é produto que surgiu do além, pois mesmo que fosse criado por sí mesmo, ele deveria ter você mesmo como fornecedor.
Levando essa informação em conta, então cnpj_fornecedor deveria ser "not null". assim obrigando a existência de um fornecedor e evitando produtos sem origem com cnpj_fornecedor null por exemplo.
Então a tabela produto poderia ser criada assim:
CREATE TABLE PRODUTO
(
    CODIGO INT PRIMARY KEY,
    DESCRICAO VARCHAR(60) NOT NULL,
    ESTOQUE INT,
    VALOR INT,
    CNPJ_FORNECEDOR BIGINT NOT NULL,
    CONSTRAINT FK_PRODUTO FOREIGN KEY(CNPJ_FORNECEDOR)
    REFERENCES FORNECEDOR (CNPJ)
);

Dessa forma evita inserir produtos sem fornecedores, ou pelo menos sem cnpj.
Comment: Valeuu, Bruno!!


Limit of integral of negative simple function?

Question: Define $$f_j(x) := -j1_{[j,j+1]}.$$
Is it true that $$\int f_j \ d \mu = -j \mu([j,j+1]) = -j?$$ with the Lebesgue measure? I know it is true for simple, positive functions, but does it hold for negative too?
Also, is $\lim_{j \rightarrow \infty} f_j = 0$or what? I'm not sure what $-\infty 1_{\varnothing}$ means.
Answer: Yes, the integral is defined to be linear, so
$$ 0=\int 0 \, d\mu = \int (f-f) \, d\mu =\int f \, d\mu + \int (-f) \, d\mu, $$
so $\int (-f) \, d\mu = -\int f \, d\mu.$
For your second question, it depends what you mean. $f_j \to 0$ pointwise, since for each $x$, $f_j(x)=0$ for all $j$ bigger than some $J$ (that depends on $x$). However, the integrals do not converge, and there is no function $f$ so that
$$ \int \lvert f-f_j \rvert \, d\mu \to 0, $$
so in this sense (called strong convergence), $f_j$ does not converge.
Answer: Also, note that for measurable function $f \colon \mathbb{R} \to \mathbb{R}$, Lebesgue integral
$$\int f d \mu = \int f^+ d \mu - \int f^- d \mu$$
(usually by definition) when at least one of the two integrals on the RHS is finite, where
$$\begin{aligned}
   f^+(x)= & \max\{f(x),0\} \\
   f^-(x)= & \max\{-f(x),0\}.
\end{aligned}$$


Alternative to to C# minor to G# minor progression on ukulele?

Question: I'm a beginner on the uke, and I'm having some trouble with a chord progression my brother wrote for a song on guitar. Essentially, the trouble I'm having boils down to a quick couple quick moves between C# minor and G# minor.
I've been using the following fingerings because I thought they would be easiest.
C# minor:

G# minor:

But, I'm still struggling. And, while I'm enjoying the challenge, I'm curious if there's another progression that I might be able to substitute or even that might sound nice as an accompaniment.
Comment: Depends on the context. But you can try E instead of C#m and B instead of Abm.
Comment: @KrisVanBael Good idea, although it's worth noting that the E chord on the ukulele often poses a threat in and of itself :)
Answer: Without knowing the context, such as the key of the song, the rest of the chords and their functions it is difficult to suggest an effective alternative chord progression. One thing I can suggest is a different way to play the C#m, which might make it easier for you to make the switch. Try 6-4-4-4. You can barre the top 3 strings with your 1st finger and play the 6th fret of the G string with the 3rd finger. Another option suggested by @user45266 is to use 1-4-4-4. This requires more of a stretch but keeps the 1st finger in the 1st fret for both chords.
Comment: @user45266 That works, I included it as an option in my answer. Since I don't play much uke voicings like that don't usually occur to me,
Comment: Better than 6-4-4-4 is 1-4-4-4, in my opinion. Trade-off with that voicing is that one has to stretch one fret farther, but in return gets to eliminate the position shift by staying down near the headstock. And a lot of finger repositioning gets easier during the switches, especially with the 4th finger barring the 4th fret.


How to force BIND 9.16 to resign my zones after editing zone file

Question: I'm using BIND 9.16 new dnssec-policy feature on my zones, following the guide to enable DNSSEC. Everything worked like a charm.
Now, I need to add another record to one of my zones, but after editing the zone file on /var/lib/bind/db.mydomain.com and using:
rndc reload
systemctl restart bind9

my .key file Kmydomain.com.xxxx.key is not being updated and on the logs, I see messages with the old serial for the zone (signed) and the new serial for the zone (unsigned).
Oct  8 13:07:04 bind named[622]: zone mydomain.com/IN (unsigned): loaded serial 2021100801
...
Oct  8 13:07:04 bind named[622]: zone mydomain.com/IN (signed): loaded serial 2021100607 (DNSSEC signed)
...
Oct  8 13:07:04 bind named[622]: all zones loaded
Oct  8 13:07:04 bind named[622]: running
Oct  8 13:07:04 bind named[622]: zone mydomain.com/IN (signed): receive_secure_serial: unchanged
Oct  8 13:07:04 bind named[622]: zone mydomain.com/IN (signed): sending notifies (serial 2021100607)
Oct  8 13:07:04 bind named[622]: zone mydomain.com/IN (signed): reconfiguring zone keys
...
Oct  8 13:07:04 bind named[622]: zone mydomain.com/IN (signed): next key event: 08-Oct-2021 17:59:00.636

Reading the docs, I can't find references to a manual step to ask BIND to resign my zone, and I would like to know how to proceed.
My zone for the domain on /etc/bind/named.conf.local is
zone "mydomain.com" in {
    type master;
    file "/var/lib/bind/db.mydomain.com";
    allow-transfer { 220.127.116.11; };
    also-notify { 188.8.131.52; };
    dnssec-policy default;
};

Comment: [Did you read teh Manual?](https://bind9.readthedocs.io/en/latest/advanced.html)
Comment: It is not clear why you need to "resign".  You say you add a record (which one?) and then you say your keyfile is not updated, what does that mean? Did you see this in documentation: "By default, the key directory is checked for changes every 60 minutes; this period can be adjusted with dnssec-loadkeys-interval, up to a maximum of 24 hours. The rndc loadkeys command forces named to check for key updates immediately."  `rndc sign` can give you various insights on what is currently happening inside bind when it maintains the DNSSEC status automatically (it decides itself what and when to sign)
Comment: Sorry if I was not clear, english is not my main language.
I waited over 4 hours before sending the original question, so I don't think it was just a matter of waiting for BIND.

I'm using the default paths ( /etc/bind, /var/lib/bind, /var/cache/bind ) and everything works fine, I just could not get BIND to "see" the changes I made to the zone file and generate a new signed zone
Answer: In the end I used the "nuclear" option of removing the K* files for mydomain.com from /var/cache/bind/
rm -f /var/cache/bind/Kmydomain.com.*

Followed by restarting BIND
rndc reload
systemctl restart bind9

I had to generate a new DS record and update it on my parent DNS server, but I could not wait any longer.
If you know how to properly ask BIND to generate new (key/private/state) files when editing zone files I really would like to know.


What does it mean to refer to a player as a "dagger man"?

Question: What does it mean to say that a player is his team's "dagger man," and in what sports does it apply?
I presume it has something to do with being a player who scores. Does it matter how they score (e.g., from close range) or just that they score a lot?
Comment: In Basketball a big shot at the end of the game, that generally puts the team too far in the lead to lose is often referred to as a dagger, or a nail in the coffin.
Comment: @RoB, just to clarify: in football the term "dagger man" is more likely to be used for a _striker_ specifically, so that Eto'o fits the category more comfortably than Zidane, right? EDIT: or maybe I should have asked about Messi rather than Zidane, since Messi is the highest goal-scorer for his club despite playing from the wing.
Comment: Not sure to put this as a proper answer because I have no sources but I have heard it being used in reference to a striker (Samuel Eto at Barcelona) in football, meaning that he provides the cutting edge for the team by scoring a lot. Not too sure about other sports though.
Comment: Usain Bolt is known for daggering...but that falls under a completely different context...
Comment: @kuzzooroo, yea I imagine that it applies to Messi more than Zidane. I only heard it that one time said by Ray Hudson on ESPN(?), it was Barcelona vs Zaragoza from 2009 I think.
Answer: I am familiar with this as the person that makes of habit of making the score that finishes the opponent.  Especially with Basketball, I recall Larry Bird making shot in the final seconds and the announcers saying "Dagger!" implying that was the final blow in finishing off the opponent.


UIBarButtonItem Custom Image is Stretched (Xcode)

Question: I'm creating a side menu in Xcode, and to open it I'm using a navigation view controller like the following:

I need the left bar button item to be on the left.
I added a left bar button item. Without changing it to a custom image, it is aligned to the left, as desired. When I change it to the custom image (the three lines) it stretches and aligns itself in the center. I have not written any code for this view controller yet, so none exists for the bar button item.
How can I get this aligned to the left as it should be? (Above the "Home" text).
Thanks for any help.
Answer: This is because your menu icon size is bigger.I have added two images one is with 64*64 px size which is perfect and in another icon with 512*512 px size

Hope it will help.Thank you.
Comment: I'm using a PDF vector on a universal scale though. Why can't that work?
Answer: You can't use any image size for UIKit tab bar or navigation items.
Please read this guideline from Apple:
https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/custom-icons/


Unity + Atenticação Cadastro + Firebase

Question: Estou com um problema, criei um app android pelo UnityHub e estou com problemas no cadastro e no banco de dados, sempre ao clicar no botão de cadastro ou de login aparece o erro: "NullReferenceException: Object reference not set to an instance of an object"
Script do Login/Cadastro (Código C#)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Script : MonoBehaviour
{
    Firebase.Auth.FirebaseAuth auth;
    public InputField email;
    public InputField password;
    public Text resultText;

    // Start is called before the first frame update
    void Start()
    {
        Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void SignUp()
    {
        auth.CreateUserWithEmailAndPasswordAsync(email.text.ToString(), password.text.ToString()).ContinueWith(task => {
            if (task.IsCanceled)
            {
                Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled.");
                return;
            }
            if (task.IsFaulted)
            {
                Debug.LogError("CreateUserWithEmailAndPasswordAsync encountered an error: " + task.Exception);
                return;
            }

            // Firebase user has been created.
            resultText.text = "Registrado com sucesso!";
            Firebase.Auth.FirebaseUser newUser = task.Result;
            Debug.LogFormat("Firebase user created successfully: {0} ({1})",
                newUser.DisplayName, newUser.UserId);
        });
    }

    public void SignIn()
    {
        auth.SignInWithEmailAndPasswordAsync(email.text.ToString(), password.text.ToString()).ContinueWith(task => {
            if (task.IsCanceled)
            {
                Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
                return;
            }
            if (task.IsFaulted)
            {
                Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: " + task.Exception);
                return;
            }

            resultText.text = "Login efetuado com sucesso!";
            Firebase.Auth.FirebaseUser newUser = task.Result;
            Debug.LogFormat("User signed in successfully: {0} ({1})",
                newUser.DisplayName, newUser.UserId);
        });
    }

}

Obs: tanto para o cadastro quanto para o login só é necessário o email e a senha, sem necessidade de confirmação alguma.
Erro do botão de login:

Erro do botão de cadastro:

Alguém sabe como resolve-los?
Agradeço desde já, é minha primeira vez usando o site
Answer: Firebase.Auth.FirebaseAuth auth; // variavel que você utiliza

void Start()
{
    // inicializa uma variavel local, mas não a da classe
    Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
}

Para corrigir só tirar essa nova variavel
void Start()
{
    auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
}

Unity + Atenticação Cadastro + Firebase