Hibernate 3.x vs 4.x performance perspective

Question: Is there is any differences in the performance between  hibernate 3.x and 4.x ?
and what is recommended to use (i mean is hibernate 4.x is stable)
Answer: Since Hibernate 4.x has been release a while ago (2011) it can be already seen as stable.
This question highlights what is new/improvements about Hibernate 4 and this website makes a comparison between versions 3 and 4 presenting the improvements made in each release.


Get Data Detail By ID - CODEIGNITER

Question: when i get the data by id, just only display first row from table
This is my controller
public function getDetail($id=true)
{

    $data['detail'] = $this->vendor_model->getDetail($id);
    $this->load->view('vendor/detailvendor',$data);

}

this is my model
 public function getDetail($id)
{

    $this->db->where('no_spk',$id);
    $query = $this->db->query("select a.no_spk, a.nama_pekerjaan, a.alamat, a.latitude, a.longitude, b.nama_vendor, c.progress, c.keterangan, c.gambar, c.gambar2, c.gambar3, d.namapekerja from vendor as b inner join pekerjaan as a on b.id_vendor = a.id_vendor inner join progress as c on c.no_spk = a.no_spk inner join pekerja as d on d.id_pekerja=c.id_pekerja");
    return $query->result();
}

And, this is my view
<?php echo form_open_multipart('homevendor/getDetail'.$this->uri->segment(4)); ?>
<?php echo $detail[0]->no_spk?>

<?php echo $detail[0]->nama_pekerjaan?>

<?php echo $detail[0]->progress?>

<?php echo form_close();?>

the result isview on website
content of table, there are 2 data but only show first data
please help me
Comment: You want to fetch a single row. Right ?
Comment: Edit your question add codeigniter tag so you get better help.
Comment: yes, thats right
Comment: Check the answer if you still need help i am available.
Answer: 1.For getting and showing all records, only change view file code like below:-
 <?php echo form_open_multipart('homevendor/getDetail'.$this->uri->segment(4)); ?>
  <?php foreach($detail as $deta){?>
    <?php echo $deta->no_spk?>

    <?php echo $deta->nama_pekerjaan?>

    <?php echo $deta->progress?>

  <?php }?>
<?php echo form_close();?>

2.For getting and showing single records, use LIMI 1 in query and change view code also like below:-
Modal code:-
public function getDetail($id){
   $this->db->where('no_spk',$id);
   $query = $this->db->query("select a.no_spk, a.nama_pekerjaan, a.alamat, a.latitude, a.longitude, b.nama_vendor, c.progress, c.keterangan, c.gambar, c.gambar2, c.gambar3, d.namapekerja from vendor as b inner join pekerjaan as a on b.id_vendor = a.id_vendor inner join progress as c on c.no_spk = a.no_spk inner join pekerja as d on d.id_pekerja=c.id_pekerja LIMIT 1");
   return $query->result();
}

And view:-
<?php echo form_open_multipart('homevendor/getDetail'.$this->uri->segment(4)); ?>
  <?php foreach($detail as $deta){?>
    <?php echo $deta->no_spk?>

    <?php echo $deta->nama_pekerjaan?>

    <?php echo $deta->progress?>

  <?php }?>
<?php echo form_close();?>

Comment: give me a minute to try that
Comment: by the way thankyou because u help me, i got error because my mistake on button "DETAIL"  typo :))) but thankyou your very is very help me to code next time
Answer:     public function getDetail($id)
{

    //$this->db->where('no_spk',$id);
    $query = $this->db->query("select a.no_spk, a.nama_pekerjaan, a.alamat, a.latitude, a.longitude, b.nama_vendor, c.progress, c.keterangan, c.gambar, c.gambar2, c.gambar3, d.namapekerja from vendor as b inner join pekerjaan as a on b.id_vendor = a.id_vendor inner join progress as c on c.no_spk = a.no_spk inner join pekerja as d on d.id_pekerja=c.id_pekerja WHERE c.no_spk=".$id);
    return $query->row();
}

View
<?php echo form_open_multipart('homevendor/getDetail'.$this->uri->segment(4)); ?>
<?php echo $detail->no_spk?>

<?php echo $detail->nama_pekerjaan?>

<?php echo $detail->progress?>

<?php echo form_close();?>

Explanation
You are looking for to fetch a single row.Use row function instead of result.
Codeigniter database class row function returns an object. SO you will be able to use the -> to accessing the object data.
Comment: i will try that, give me a minute
Comment: I updated my answer just copy the model function and paste it again.
Comment: by the way thankyou because u help me, i got error because my mistake on button "DETAIL"  typo :))) but thankyou your very is very help me to code next time
Comment: by the way help me to upload multiple images, i was post my question but i'm still confused @Adnanhaider
Comment: I don't know your exact question. But check this link before posting any question. https://stackoverflow.com/questions/24895170/multiple-image-upload-php-form-with-one-input

Get Data Detail By ID - CODEIGNITER


Method invocation 'notify' may produce 'java.lang.NullPointException'

Question: NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity(),"M_CH_ID");
    builder.setAutoCancel( true )
            .setSmallIcon( R.drawable.icon_notificacao )
            .setContentTitle( "RPfm 105.3" )
            .setContentText( "Ao Vivo" );
    int id = 1;
    NotificationManager notifyManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
    notifyManager.notify(id, builder.build());

Comment: Isso é um erro ou apenas um aviso?
Comment: um aviso quando passa o mouse por cime do 'notify'.
Comment: Mais agora na aplicação não tá mais aparecendo a notificação, e antes estava.
Comment: Não, sumiu mesmo a notificação quando inicio, como antes.
Qual sugestão?
Comment: Tente: `if(notifyManager != null) { notifyManager.notify(id, builder.build()); }` para remover o aviso.
Comment: Obrigado. Vou tentar aqui
Comment: deu algum resultado?
Comment: Bom, o aviso sumiu, mais não tá notificando ainda. rsrsrsrs
Comment: Você está usando *Fragment*? Tente substituir `getActivity` por `getApplicationContext()` ou `getContext()`
Answer: Isso acontece porque o método getSystemService pode retornar null.
Ele é declarado da seguinte forma (repare na anotação @Nullable):
public abstract @Nullable Object getSystemService(@ServiceName @NonNull String name);

O que acontece é que a IDE detecta a anotação e mostra um aviso.
NotificationManager notifyManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
// Neste momento, a IDE "entende" que notifyManager pode ser nulo,
// e a seguinte chamada de método poderia lançar um NullPointerException:
notifyManager.notify(id, builder.build());

Pra garantir que você nunca cause um NPE, você pode fazer um null check:
if(notifyManager != null) {
    notifyManager.notify(id, builder.build());
}

Mas na prática, isso só será um problema se você passar um name que não existe, ou tentar pegar um service de uma versão do Android posterior à que o dispositivo atual suporta.

Você pode simular o comportamento da IDE, criando um método com a anotação Nullable:
public @Nullable String getFoo() {
    return "1,1";
}

E tentar invocar um método do objeto retornado:
String foo = getFoo();
foo.split(",");

Repare que agora você verá um aviso idêntico ao que você descreveu.


How can I correct "zsh parse error near do"

Question: I'm relatively new to zsh and scripts in general. I need to write an automated command script in zsh with the following code.
#!/usr/bin/env zsh

for ((i = 0; i < 41; i++));

export K='SOME NUMBER'

do ./A-PROGRAM *SOME FLAGS* $i *MORE FLAGS* $K 1 ;

done;

I get the following error: program.zsh:8: parse error near `do'
How can i correct this? Thanks for the help in advance!
Comment: Unlike a `while` loop, a `for` loop doesn't not allow an arbitrary list of commands between `for` and `do`. (Indeed, `do` is a reserved word so that you *can* signal the end of an arbitrary command list.) `do` is part of the `for` syntax mainly for symmetry. `zsh` does provide a number of alternate loop forms that don't require `do`; see `man zshmisc`, under the section "Alternate Forms for Complex Commands" for details.
Comment: From the viewpoint of language design, the requirement that - syntactically - `for` must be the prefix of a statement, and that the next statement **must** be a `do`, is not particularily elegant. I don't think that one would do such a construct nowadays, if someone wanted to create a completely new shell language.
Answer: What is the EXPORT doing there between the for () and the do? And do you really need to EXPORT the variable $K. You seem to pass it as parameter to A-PROGRAM anyways?
#!/usr/bin/env zsh

K='SOME NUMBER'
for ((i = 0; i < 41; i++)); do
  ./A-PROGRAM *SOME FLAGS* $i *MORE FLAGS* $K 1
done

Comment: Thanks a lot! This saved the issue. Yes, $K is a parameter for the program, I won't use export if not necessary from now on. Thanks again!


How do I generate-content of a particular type with drush 9.x+

Question: root@0a581055a6ad:/opt/drupal# drush genc 10 --types=article

  The "--types" option does not exist.

devel-generate:content [--kill] [--bundles [BUNDLES]] [--authors [AUTHORS]] [--feedback [FEEDBACK]] [--languages [LANGUAGES]] [--translations [TRANSLATIONS]] [--add-type-label] [--skip-fields [SKIP-FIELDS]] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-d|--debug] [-y|--yes] [--no] [--remote-host REMOTE-HOST] [--remote-user REMOTE-USER] [-r|--root ROOT] [-l|--uri URI] [--simulate] [--pipe] [-D|--define DEFINE] [--notify [NOTIFY]] [--xh-link XH-LINK] [--druplicon] [--] <command> [<num> [<max_comments>]]

root@0a581055a6ad:/opt/drupal# drush --version
Drush Commandline Tool 10.3.4

According to the documentation this was an option with drush 8.x, but I don't see any equivalent in drush 9.x and up. What is the intended way to invoke genc for a particular node type with this new version of drush?
Comment: Going off the the error output, it would probably be `—bundles=article`
Comment: Can't get the above to format properly, but `bundles` instead of `types`, essentially
Comment: doh! Thanks @clive :)
Answer: Yeah, it's --bundles now. That's also what the error output is telling you already when echoing all possible options.
drush genc 10 --bundles article,page


C# WCF Web Service on localhost consumed by Java Client

Question: currently my WCF Service is using net.pipes to talk on local machine.
Now I want to consume the web service in java on the same machine.
Here I have some questions:

Which binding I have to use to talk on local machine with Java client?

I don't want to go over network and the client must be able to consume the web service.
Do you may have any articles or tipps how to start here? May some hints what I have to take care about?
Answer: BasicHttpBinding exposes a SOAP 1.1 wsdl which is probably the most interoperable between JAVA and .NET. If your calls are local then you won't go out to the network.
EDIT
WsHttpBinding supports SOAP 1.2 which is a larger, more complex specification and therefore more open to interpretation by different vendors. So while it may work fine, it will generally be less interoperable.
Specifically there may be differences in the way security is handled on either side (see here for a good explanation).
Comment: will give it a test and accept it if it works. Thanks so far.


Point of Inflection Inequality in a Quartic

Question: The following is a multiple choice question from a workbooklet (year 12):
The family of graphs of the form $y=x^4+ax^3+bx^2+cx$ has two points of inflection if and only if:
A. $b<\frac{3a^2}{8}$
B. $b^2>3c$
C. $a<b$
D. $b^2<4c$
E. none of these
Answer: A
My question is how do I solve this? It would be great if you could show your working. Thanks in advance.
My working
I've done the double derivative but that's it. I'm kinda stuck.
$y=x^4+ax^3+bx^2+cx$
$y'=4x^3+3ax^2+2bx+c$
$y''=12x^2+6ax+2b$
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: Jose. Thanks for feedback. Is this ok now?
Comment: It's better now.
Answer: Hint: Inflection points are points where the function changes concavity, i.e. from being "concave up" to being "concave down" or vice versa. They can be found by considering where the second derivative changes signs. In similar to critical points in the first derivative, inflection points will occur when the second derivative is either zero or undefined.
$y'=4x^3 + 3ax^2 + 2bx + c$
$y'' = 12x^2+6ax+2b$
We have to solve now: $y''=0 \iff 12x^2+6ax+2b=0$.
Next, we require that the family of graphs having two inflection points, so it is necessary that the discriminant $D=(6a)^2-4\cdot12\cdot2b>0$,
i.e.
$$36a^2-96b>0 \iff b< \frac{3a^2}{8}.$$
Comment: Great. Thank-you. I knew I had to use the discriminant! Marked as answer.
Comment: You are welcome @Hugs, and thanks for mark/upvote!
Comment: your welcome Anton


Delphi Converter de Decimal para Horas

Question: Tenho o seguinte decimal 0,0159722222222222 quero transformar em horas no seguinte formato 00:23:00.
Answer: Conheço essas opções:
procedure TForm1.Button1Click(Sender: TObject);
var
  MyDate: TDateTime;
begin

  MyDate := 0.0159722222222222;

  //Com Cast
  ShowMessage(TimeToStr(MyDate));

  //Com Format
  ShowMessage(FormatDateTime('hh:nn:ss', MyDate));

end;

A opção do Format é interessante, por você manipular oque será exibido:
Aqui estão as opções para o format:
y   = Year last 2 digits
yy  = Year last 2 digits
yyyy    = Year as 4 digits
m   = Month number no-leading 0
mm  = Month number as 2 digits
mmm     = Month using ShortDayNames (Jan)
mmmm    = Month using LongDayNames (January)
d   = Day number no-leading 0
dd  = Day number as 2 digits
ddd     = Day using ShortDayNames (Sun)
dddd    = Day using LongDayNames  (Sunday)
ddddd   = Day in ShortDateFormat
dddddd  = Day in LongDateFormat

c   = Use ShortDateFormat + LongTimeFormat
h   = Hour number no-leading 0
hh  = Hour number as 2 digits
n   = Minute number no-leading 0
nn  = Minute number as 2 digits
s   = Second number no-leading 0
ss  = Second number as 2 digits
z   = Milli-sec number no-leading 0s
zzz     = Milli-sec number as 3 digits

fonte: http://www.delphibasics.co.uk/RTL.asp?Name=formatdatetime

Delphi Converter de Decimal para Horas


Distribution specificity of the Anderson-Darling test

Question: When fitting a (gamma) distribution to a data sample and in-turn estimating its parameters (shape/scale), a Kolmogorov–Smirnov goodness-of-fit test is no longer applicable as the distribution being tested against has been derived from the data itself - however this problem can be largely alleviated using parametric bootstrapping where new critical values and a new p-value are calculated through simulation.
I've read how an Anderson-Darling test (a modified form of the Kolmogorov–Smirnov test) typically performs better and is more sensitive to outliers.
It is my understanding that the Anderson-Darling test does not suffer from the same issue outlined above as it calculates critical values for each distribution being tested against as an inherent part of the test - is this correct? Is this done an individual distribution basis? For example, will $Γ(α,β)$ with $α=3,β=10$ produce a different set of critical values than $α=2,β=15$?
Secondly, are there any cases when the Kolmogorov–Smirnov test is preferred over the Anderson-Darling test?
Answer:
It is my understanding that the AD-test does not suffer from the same issue outlined above as it calculates critical values for each distribution being tested against as an inherent part of the test - is this correct?

No, it's a test for a fully specified distribution just like the Kolmogorov-Smirnov. When you estimate parameters but use the Kolmogorov-Smirnov statistic with different tables to account for that, it's properly called the Lilliefors' test; this test is discussed in numerous posts on site.
However, in many cases you can adjust the Anderson-Darling test statistic under the estimation of parameters. (Failing that, your approach of simulation to either get new critical values or p-values for the specific case at hand can work quite well.)
For example, in the case of estimating mean and variance and testing for normality, if the usual statistic $A^2$ is replaced with $A^{*2}=(1+4/n-25/n^2)A^2$ then the usual tables may be used to reasonable accuracy even at quite small sample sizes.
Alternatively in the case of normality, there's a different adjusted statistic $A^{*2}=(1+0.75/n+2.25/n^2)A^2$  (with its own table). To my recollection, details are given in D'Agostino and Stephens (1986) [1], but this result (and more) can be seen in this technical report Stephens (1979); it also has an adjusted statistic for the exponential case (and several other distributions, but not the gamma).
Note that the above-linked report gives an adjustment for the exponential (again with its own table). This page gives one for the Weibull and Gumbel cases.

Is this done an individual distribution basis? For example, will $Γ(α=3,β=10)$ produce a different set of critical values than $Γ(α=2,β=15)$?

Certainly in the case of the beta parameter, you only need to adjust for the fact of estimation itself -- the value of the parameter will make no difference (this is because -- depending on the parameterization you intended -- $\beta$ is either a scale parameter or the inverse of a scale parameter). It's not clear that the alpha parameter always has the same property, but I can be reasonably confident that except at small values of $\alpha$ (i.e. except down near 1 and below 1) it won't matter much. If your gamma has a peak that's well to the right of 0 (i.e. $\alpha>>1$), the cube root is an approximately normalizing transform, so different $\alpha$ shouldn't impact the distribution much -- most of the effect will be caused by estimation of alpha rather than the value (this will be the case more generally -- if there's a monotonic transformation which doesn't depend on the parameters that produces a location-scale family, the parameter values themselves won't matter).
So the fact that there's a transformation to almost-normality for any reasonably large $\alpha$ suggests that the adjustment used for the normal ($A^{*2}=(1+4/n-25/n^2)A^2$) may also work fairly well for gammas -- at least those with non-small shape parameter.
For cases where the shape parameter is -- or might be -- small (somewhere in the region of 1, or smaller), you may need to consider dealing with it individually, but I don't know for sure that it's necessary (the same adjustment may also work okay even there, but you'd need to check).

are there any cases when the KS-test is preferred over the AD-test?

If by "is preferred" you mean "has greater power", then certainly. Where the Anderson-Darling tends to perform better at picking up differences in the tail (especially where the tail may be heavier than supposed), the Kolmogorov-Smirnov tends to have better power at differences "in the middle", and where tails are lighter than supposed. [In some of these situations -- such as testing a uniform against a beta with parameters somewhat larger than 1 -- both of them perform badly and you probably would prefer something else over either, but the Kolmogorov-Smirnov can be considerably less terrible than the Anderson-Darling.]

Note that I wouldn't really call the Anderson-Darling a "modified form of the Kolmogorov-Smirnov". I'd say it's a modified (specifically, weighted) form of the Cramer-von Mises test. They're all tests based on the ECDF, but the Kolmogorov-Smirnov looks at the maximum distance while the Cramer-von Mises looks at something related to a sum-of-squared distances, which looks at things quite differently (and has generally better power against the more interesting alternatives). The Anderson-Darling then adjusts for the fact that the variance of the value of the ECDF is smaller near $0$ or $1$ than it is near $\frac12$, to re-weight those squared deviations for the relative precision (which is why it does better at finding deviations in the tail, especially ones that would tend to be associated with being "further" into the tail of the specified distribution).
[1] D'Agostino, R.B.; Stephens, M.A. (1986),
Goodness-of-Fit Techniques,
New York: Marcel Dekker.
Comment: Actually I have more to add; I now think that the D'Agostino & Stephens reference has information on the gamma as well but I won't be able to look at it for about 18 hours or a day after that. It think it was split into 3 subtables.... $\alpha\leq 1$, $1<\alpha\leq 8$ and $\alpha>8$  -- or at least that's what http://www.ibm.com/support/knowledgecenter/SSLVMB_22.0.0/com.ibm.spss.statistics.algorithms/alg_simplan_goodness_continuous_ad_gamma.htm seems to suggest. There's also some information in a couple of references I found which may or may not be useful.
Comment: The original Lilliefors itself was done only for a location-scale and a scale family (the normal and exponential) so only one table was needed for each and used direct simulation rather than parametric bootstrap. I'd have to think about the best strategy to do this with a parametric bootstrap.
Comment: I've managed to locate a relevant page from the text via google books. It has a table for the gamma distribution on p155 (it's three parameter, but with the location specified). It isn't the table on that earlier linked webpage though. It looks like someone put that condensed table together from the information on p155, but that table doesn't go below $alpha=1$.
Comment: I did find one reference that tried to compute a table based on the ML estimate of $\alpha$. That seems to suggest very little change above $\hat{\alpha}=10$
Comment: +1 extremely informative and helpful, thank you! If simulating with the AD-test, would it be sensible to follow the same regime as lilliefors? Namely: 1. Obtain distribution parameter estimates for the raw data 2. Randomly sample the fitted distributed N times 3. Fit a new distribution to each random sample and store each new KS-stat (or the AD-stat) 4. Calculate new critical values and p-values.
Comment: Using the parametric bootstrap regime described in my comment above (coded in MATLAB), i'm able to replicate the critical values for all three subsections - α ≤ 1, 1 < α ≤ 8 and α > 8 - tested with estimated α values of 0.5, 1, 3.5 and 10.
Comment: Indeed I see very little change for α > 10.
Comment: Yes, but that's when you know alpha is > 10. This is the case where alpha itself might be 5 or 20 but has produced an estimated value of (say) 10. It's harder to do it that way around.
Comment: Is that not something the simulation itself addresses given that i'm ordinarily randomly sampling off the estimated distribution?
Comment: Any followup ideas on this one?
Comment: It wasn't until today that I was able to get to a library that had D'Agostino & Stephens. Unfortunately the catalog's assertion that it was on the shelf proved to be false, so I couldn't check for additional details on the AD test on the gamma there -- at least not today. It may  have been temporarily off the shelf or it may be stolen. I'll try again as soon as I can.
Comment: Thank for your continued help. There is a thesis here (http://www.dtic.mil/dtic/tr/fulltext/u2/a262486.pdf) of potential interest although it is difficult for me to understand a lot of it. In relation to your comment "Yes, but that's when you know alpha is > 10. This is the case where alpha itself might be 5 or 20 but has produced an estimated value of (say) 10. It's harder to do it that way around." - could you explain this a little more? Are there ever actually any solutions to this scenario?
Comment: Yes, I found that thesis (and another one) when looking for resources while answering your question a couple of weeks ago.


How to Create Powershell Script Remove-appxpackage Windows Built-in App Executed by Batch Command?

Question: Can someone confirm that this script are correct.
Batch cmd Execute.bat :
<code>@echo off
color d
echo Execute Powershell Script With Administrative Privileges
echo.
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}"
echo.
timeout /t 5
</code>
And for Powerhsell.ps1 :
<code>Remove-appxpackage Microsoft.XboxApp_5.6.17000.0_x64__8wekyb3d8bbwe

Remove-appxpackage Microsoft.XboxGameCallableUI_1000.10240.16384.0_neutral_neutral_cw5n1h2txyewy

Remove-appxpackage Microsoft.XboxIdentityProvider_1000.10240.16384.0_neutral_neutral_cw5n1h2txyewy

Remove-appxpackage Windows.ContactSupport_10.0.10240.16384_neutral_neutral_cw5n1h2txyewy

Remove-appxpackage Microsoft.BingNews_22.214.171.124_x86__8wekyb3d8bbwe

Remove-appxpackage Microsoft.BingFinance_18.104.22.168_x86__8wekyb3d8bbwe

Remove-appxpackage Microsoft.BingWeather_22.214.171.124_x86__8wekyb3d8bbwe

Remove-appxpackage Microsoft.Getstarted_220.127.116.11_x64__8wekyb3d8bbwe

Remove-appxpackage Microsoft.SkypeApp_22.214.171.124_x86__kzf8qxf38zg5c

Remove-appxpackage Microsoft.WindowsPhone_10.1506.20010.0_x64__8wekyb3d8bbwe

Remove-appxpackage Microsoft.WindowsMaps_4.1505.50619.0_x64__8wekyb3d8bbwe

Remove-appxpackage Microsoft.People_1.10159.0.0_x64__8wekyb3d8bbwe

Remove-appxpackage Microsoft.Office.OneNote_17.4201.10091.0_x64__8wekyb3d8bbwe

Remove-appxpackage Microsoft.MicrosoftSolitaireCollection_3.1.6103.0_x64__8wekyb3d8bbwe

Remove-appxpackage Microsoft.MicrosoftOfficeHub_17.4218.23751.0_x64__8wekyb3d8bbwe

Remove-appxpackage Microsoft.BingSports_18.104.22.168_x86__8wekyb3d8bbwe

Remove-appxpackage Microsoft.Appconnector_184.108.40.206_neutral__8wekyb3d8bbwe

Remove-appxpackage Microsoft.3DBuilder_10.0.0.0_x64__8wekyb3d8bbwe

Remove-appxpackage microsoft.windowscommunicationsapps_17.6002.42251.0_x64__8wekyb3d8bbwe
</code>
And how to add wait time in powershell?
Answer: Yes that should work given that the script and is in the exact location and has the same name as the batch file. I'm not sure why you are wanting to add a wait time in PowerShell, but the cmdlet that you are looking for is start-sleep
Answer: You could put the packages in a text file and do this:
<code>$packages = Get-Content c:\scripts\packages.txt
Foreach ($package in $packages){
 Remove-appxpackage $package
  Start-Sleep -Seconds 15 #change this as needed
}
</code>


Evaluating $-\ln(1-x)$ and an infinite sum

Question: I did a little evaluation of the function $-\ln(1-x)$ with a sum of an infinite series, but I have come to a contradiction, and I would like to ask your help to find my mistake.
Let us start with the sum: $$\sum_{i=0}^\infty x^k = \frac{1}{1-x}$$
which converges at $|x|<1$.
Then, divide it by $x$ and we will get: $$\sum_{i=0}^\infty x^{k-1} = \frac{1}{x(1-x)}$$
Now, we will integrate the infinite sum (which we can for all $|x|<1$), and we will receive:  $$\sum_{i=0}^\infty \frac{x^k}{k} = \int_0^x\frac{1}{t(1-t)}$$
Now, the contradiction comes by the fact that the infinite sum at the left part equals $-\ln(1-x)$, while by using integration by parts for the integral in the right we get:
$$\ln(t)+\ln(1-t)|_0^x$$ which diverges because of $\ln(0)$, and isn't equal to $-\ln(1-x)$.
As I stated above, I obviously have a mistake somewhere, and would be happy to get your help, thanks!
Comment: You have a sum over $i$ of $x^k$. Whatever, the sum starts at zero, so the $x^k/k$ term is wrong.
Comment: Gerry - you're right, I've missed that. thanks!
Answer: Since, for $|x| < 1$ we have
$$\frac{1}{1-x} = \sum_{k = 0}^\infty x^k.$$
Now since
$$\int \frac{1}{1-x} dx = -\ln(1-x).$$
So that $$-\ln(1-x) = \int \left(\sum_{k = 0}^\infty x^k\right) dx = \sum_{k = 0}^\infty \frac{x^{k+1}}{k+1} ~\mbox{for} ~|x| < 1$$


How can I add code that will call the javascript within a block every minute?

Question: I have a block that contains javascript which calls a website that sends an ad to this block (see below: Note: I changed the domain name to adserveringwebsite).
How can I add code that will call the below javascript every minute so that a different ad will show up every minute instead of just one ad at page load?

Comment: This doesn't seem to be Drupal related in any way? If you are wondering about Javascript in general, I think the question belongs on stackoverflow, and if you are wondering about the proper way to add the relevant Javascript to your site, then the question should be significantly rephrased. I fixed your
Comment: Drupal 7 has an AJAX API that is not available from plain PHP/JavaScript. The OP is then asking about a block, which is a concept very specific to Drupal.
Answer: You will need to use JavaScript's setTimeout() function:
To elaborate, place the code that calls your ad server inside a JS function.
Then, use setTimeout(), as demonstrated in the website I linked to, to call it at every x interval.
Answer: To throw in some old-skool, and realize it's up to you to drupalize all of this if your ad site url is dynamic, but, you could also throw all of this in a separate static file and call it from an iframe inside your block and use refresh, eg, in the file, let's say it's /minute_by_minute_ad.htm:

    <meta http-equiv="refresh" content="60">

Then your block would contain something along the lines of:

which would have a potentially added benefit of some speed improvements with ad loads in the iframe (debated heavily online but I've seen some).
Answer: I think the Block Refresh module will do what you want out of the box.
Answer: Using an iframe isn't "the drupal way".
The drupal way is using AJAX to reload only the block. This is the same thing that Block Refresh does.
BUT... if you don't want the overhead of another module and you want to do it in your own module (I'm assuming your module is called 'mymodule' and the delta of the block is 'mymodule-delta'):
Make sure you include a javascript code, use this in your block content generation function:
drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js', array('every_page'=>FALSE));

The javascript file should have something like this in it:
(function ($) {
    setInterval(function() {
        $('#block-mymodule-myblock-delta .content').load('/myblock', function (response,status,xhr){
            if (status == 'error'){// some error checking
                $('#block-mymodule-myblock-delta .content').html("connection lost");
            }
        });
    }, 60 * 1000); // running every 60 seconds
})(jQuery);

That's going to fire an AJAX call to '/myblock' and fill the '#block-mymodule-myblock-delta' element with the content.
Now back in your module, you'll need to make the '/myblock' page like this:
function mymodule_menu() {
  $items = array();
  $items['myblock'] = array(
    'page callback' => 'myblock_via_ajax',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function myblock_via_ajax(){
    $block = module_invoke('mymodule','block_view','myblock-delta');
    print $block['content'];
}


customizing shortcuts firefox webextention

Question: Does anybody know whether it's possible to add a keyboard shortcut to a Firefox webextention add-on where the modifier key is stored by the Storage api, and hence cannot be hard coded?
Answer: You would have to use a content script to add the hotkey to every website that is visited, and you can add a content script to many pages, like the options page for google chrome, so if that page were open then the hotkey would not work.
storing it in storage api is not an issue.


How can i recover bash history while i accidentally typed reboot -f

Question: Scenario :
After working on my Linux server [CentOS 7] ,I typed reboot -f in my terminal,
is it possible to retrieve my bash history  after rebooting it?
I understand that reboot -f will forcefully reboot the machine. This is similar to pressing the power button of the CPU. No shutdown takes place. The system will reset instantly.
As per man page :

When  called  with  --force  or  when  in  runlevel 0 or 6, this tool
  invokes the reboot(2) system call itself (with REBOOTCOMMAND argument
  passed) and directly reboots the system.  Otherwise this simply
  invokes the shutdown(8) tool with the appropriate arguments without
  passing REBOOTCOMMAND argument.

Now my question is: Is it possible retrieve bash history after reboot -f?
Answer: No, as far as I know not as bash maintains history in memory and only writes or appends new history items when the shell exits.
When you "press the power button" (or run shutdown -f) obviously the shell does not exit gracefully and you lose any new history from that session as that exists only in memory. Previous history items from other sessions of course still persist as a reboot does not remove the existing history file.
Many terminal emulators keep a scrollback buffer from which you may recover some commands and others can even be configured to log everything.
Answer: In your .bashrc or the like, add PROMPT_COMMAND='history -a'. This flushes the history to disk every time the prompt shows. This is also useful for synchronizing the history between multiple shells.
It won't help you with the data already lost, but it will help preserve your command history moving forward.


Joint distribution function from marginals

Question: Is it possible to obtain joint distribution function when only the marginal distribution functions of random variables are given and, the random variables are not independent?
If possible, it would be helpful if you could provide how to do it, with an example for a two random variables case. I know how to do it, when the random variables are independent.
Comment: No, you can't obtain the joint distribution with only the marginals given.
Answer: There is much more information in a joint distribution than can
be captured by its marginal distributions.
It is one thing to be told that a joint distribution can't be
constructed from marginals in a unique way. It
is another to have some examples. Here are a few.
Discrete distributions. Consider four different joint distributions
with the same marginals. In all cases, let the marginals have the
distribution Bin(3. 1/2).
<code> Positively Correlated
 x/y      o     1     2     3      Tot
 -------------------------------------
  0      1/8    0     0     0      1/8
  1       0    2/8   1/8    0      3/8
  2       0    1/8   2/8    0      3/8
  3       0     0     0    1/8     1/8
 -------------------------------------
 Tot     1/8   3/8   3/8   1/8      1

 Negatively Correlated
 x/y      o     1     2     3      Tot
 -------------------------------------
  0       0     0     0    1/8     1/8
  1       0    1/8   2/8    0      3/8
  2       0    2/8   1/8    0      3/8
  3      1/8    0     0     0      1/8
 -------------------------------------
 Tot     1/8   3/8   3/8   1/8      1
</code>
A perfectly correlated example arises from putting the
numbers 1/8, 3/8, 3/8, 1/8 down the main diagonal.
And, of course, there is the independent case in which
the cells are filled by multiplying the marginals.
There are many more examples of different joint distributions that have these same
marginal distributions. And maybe you should try to construct one.
Fill in the body of the table any way you like, using
numbers between 0 and 1 such that the marginal totals
remain unchanged.
Continuous distributions. A slightly more advanced situation comes from the family of
bivariate normal distributions with both means 0 and
both standard deviations 1. And the correlation $\rho$
can take any value between -1 and +1.  In this example
both marginal distributions are standard normal, no matter
what the value of $\rho.$


Erro com deploy de Vue.js

Question: api.min.js:2 GET https://api.opmnstr.com/v1/optin/13439/673828 410
(anonymous) @ api.min.js:2
Ye.send @ api.min.js:2
getCampaigns @ api.min.js:2
t.init @ api.min.js:2
o.onload.o.onreadystatechange @ pag:180
load (async)
(anonymous) @ pag:180
(anonymous) @ pag:180
api.min.js:2 [OptinMonster] The campaign could not be retrieved. The following error was returned: A campaign with the ID 673828 does not exist.

Essa é a mensagem de erro que aparece no console quando atualizo a página, pois bem, usei o "npm run build" pra criar uma versão pra fazer o deploy no 000webhost, fiz o upload dos arquivos e abri o link, até ai tudo certo, navega entre páginas e tudo, o problema é ao abrir diretamente a url da página, da erro, se for usando os botões o site navega, mas ao atualizar da erro e diz que a página não existe.
example.com assim funciona, e se clicar pra ir pra página 1 ele vai
example.com/pagina1 porém assim, o site não acha a página
Edit 1:
Vue router:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import pagina from '@/components/pagina'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    }, {
      path: '/pag',
      name: 'pagina',
      component: pagina
    }
  ]
})

Comment: Está usando o router? Se possível poste ele, que só com essa informação so da para saber que o OptinMonster tem algum problema
Comment: Acabei de editar
Answer: Creio que era um problema com o servidor, ele não estava reconhecendo a configuração.
Então procurei no vuejs docs e achei algo que resolveu.
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations
Comment: Era isso que eu queria ver, se você tem o HTML5 History Mode habilitado você tem que redirecionar todas as requisições para o index.html

Erro com deploy de Vue.js


If basis $\beta$ is orthonormal, then $\beta^{*}=\beta$

Question: Let $V$ be a finite inner product space. Suppose that  $\beta$ is orthonormal basis of $V$. How do I show that $\beta^{*}=\beta$?
Where $\beta^{*}$ is dual basis of $\beta$
Dual basis definition:
For all $v_i\in\beta$ and $v_j^{*}\in\beta^{*}$, the inner product $\langle v_i,v^{*}_j\rangle=\delta_{i,j}$
Comment: Doesn't that follow directly from the definition? I can't even see that there is something to prove here. (And on a side note, please use `\langle` and `\rangle` for $\langle$ and $\rangle$. The relation symbols `<` and `>` not only look different, they result in wrong spacing too.)
Comment: This implicitly means that you isometrically identified the dual $V^*$ with $V$, in the first place. That's actually the more delicate part of the whole thing. Once this is understood, $(v_i,v_j)=\delta_{i,j}$ says that $\beta^*=\beta$ immediately.
Comment: maybe is the hour... IDK! :(
Comment: I rather suspect part of the problem lies in bad notation. Which isn't your fault, presumably. To be more precise, a basis ought to be thought of as an ordered sequence of vectors, not a set. This business of $v_i\in\beta$ and $v_j^*\in\beta^*$ giving $\langle v_i,v_j^*\rangle=\delta_{i,j}$ is, frankly, nonsense. One *can* make sense of it, but it takes effort.
Comment: @HaraldHanche-Olsen: After 19 hours of mathematics, I could only take the blame on me! Thank you anyway :)
Comment: 19 hours! You must be kidding! Exam coming up? Go get some sleep! All night cramming is a bad strategy, at least according to my experience. Better to be rested.
Comment: Just give me a minute to copy that answer... :)
Answer: For any $v_i,v_j\in\beta$, we know that $\langle v_i,v_j\rangle=\delta_{ij}$.  It follows that $v_j\in\beta^*$, so that $\beta\subset\beta^*$.  Now since $V$ is finite...
Comment: Damn!!!!7moretogo


cakephp / don't store all user data in session while using authComponent

Question: I'm new to cakephp, and building my first project with the brand new 2.1.
I use auth and session components to build a simple login system. Everything works alright. I'm using a form auth, with custom requested field to use email as login.
When I try
var_dump($this->Session->read('Auth.User'));

I can see all my User data stored in the session, but I don't need all of them here. Of course I can rewrite the session with only the subset of data I need, my session are stored on memecache, and I can't waste memory.
I want to be able to update cakephp easily, so I prefer to not rewrite parts of cakephp components.
I'm looking for a solution letting me specify which fields I need in the session.
Answer: You may write your own auth component like this:
class MyAuthComponent extends AuthComponent {

var $storeFields = array();

protected function cleanupUserData($user) {
    if (empty($this->storeFields)) return $user;

    retrun array_intersect_key($user, array_flip($this->storeFields));
}

    public function login($user = null) {
        $this->_setDefaults();

        if (empty($user)) {
            $user = $this->identify($this->request, $this->response);
        }
        if ($user) {
            $this->Session->renew();
        $user = $this->cleanupUserData($user);
        $this->Session->write(self::$sessionKey, $user);
        }
        return $this->loggedIn();
    }
}

and then write something like this in controller:
$this->MyAuth->storeFields = array('email', 'name', 'dob');


periodicity within Signal

Question:
I am actually measuring the current of a dc motor, it takes values between, and I want to be able to find periodic peaks within my signal. My motor is connected to a spindel, the goal is to detect any problems linked to it, since if the spindel isnt corretly mounted the current will take a silight peak then go back to normal, for each period.
I have used the FFT, but due some problems with the sampling rate, i have been looking for other methods. any suggestions ?
Answer: An FFT should "work" on data sampled at any sampling rate as long you're not bumping into the Nyquist limit.
Although most FFT implementations assume that their input data is regularly spaced (i.e., sampled at a fixed sampling rate), there are algorithms that exist for fourier transforming irregularly-spaced data. These are sometimes called NUFFT (for non-uniform FFT) or NFFT.
This thread on SciComp has some useful pointers, and this paper by Greengard and Lee describes an implementation and has pointers to related work. In brief, they convolve the data with a Gaussian to smear it out onto a very fine grid, run an FFT on the now-regularly-spaced data, and then deconvolve it.
Comment: My pleasure. If you can edit your question to make the data analysis issues a bit clearer, I'd be happy to expand it. All I really had to go on here was that you had issues with the sampling rate and, per my answer, I don't think that should stop you from using an FFT, assuming you're not trying to detect a 10 Hz oscillation in a signal sampled at 1 Hz or something like that.

periodicity within Signal


Is there a systematic method to do transformations on independent variables in logistic regression?

Question: Is there a systematic method for Logistic Regression to do transformations on the independent variables, in order to conclude that the most optimal logistic regression model is fitted?
Illustration of my question:
I have 2 independent variables (strength and minute both on a scale of 0 to 100) and the dependent variable is a binary outcome: win or lose.
I have done a logistic regression (in R with glm) to estimate the probabilities.
Since I already have the probabilities (based on an interpolated pivottable from a very large dataset, see picture below);

I can compare these with the probabilities from the logistic regression, see picture below:

I conclude that the logistic regression does not capture the non-linearity. For that reason I have added several transformations to the independent variables such as an interaction term, 2nd, 3rd and 4th power.
These additions result in a slight improvement measured by AUC after splitting the dataset and performing cross validations. Although visual the 4th power (red) is a deterioration compared to the 3rd power transformation (green); see picture below with the outcomes of 1 vector of the matrix with strength 50, deducted from the similar vector from the pivot table).

Do I have to conclude that Logistic Regression is not flexible enough for my data or that further improvement is possible by doing other transformations? In that case, is there a systematic structured method to do those transformations, in order to conclude that the most optimal model is fitted as possible by Logistic Regression?
PS: if there are any incorrect steps or conclusions above, pls let me know.
Choosing between transformations in logistic regression
Comment: I cover this in detail in my RMS [book and course notes](http://fharrell.com/links).
Answer: There are lots of ways of transforming variables. There are also some caveats: The complex transformation may lack  substantive meaning and it is easy to overfit data. The second of these mandates (or, at least, strongly suggests) using training and test data sets.
You can use a spline of the independent variable. There's many choices of type of spline, in my experience, they tend to give similar results, but some experts feel strongly about one or another type of spline.
There is also a method called optimal scaling. I've only used this in SAS, but I am sure it exists in some R package.
Then you could consider a classification tree, which allows some very complex transformations of the IVs.
I'm not sure there's any way  to guarantee a "best" model since it's not clear what the universe of models should include.
Comment: The step method of variable selection is terrible. (If you mean what I think you mean "stepwise" composed of "forward" and "backward") that's been discussed a lot here. However, you can definitely have one variable as a spline and have other variables too.
Comment: Thank you Peter. I suppose I can conclude that the risk of overfitting is limited in this case since the first heatmap is very smooth and gradual? The reason I try to fit a model (I already have by the pivottable) by LR is that afterwards I intend to add other variables with the step method (which is not possible with the pivottable). Are all 3 methods you suggest viable as a basis in that case? WIth "best", I mean best LR model. Currently I have tried several transformations although how do I know that there is no transformation left which will improve the results.


1st Species Counterpoint Tritone Reached Melodically by Step

Question: I'm reading Alfred Mann's translation of Fux's Gradus (original available here). On page 35, footnote 9 (presumably Alfred Mann, certainly not the original author) says "The tritone is to be avoided even when reached stepwise [examples] if the line is not continued stepwise and in the same direction." (He goes on to talk about tritones arrived at "by the progression of two voices".) The examples he shows are on the treble clef: F4, G4, A4, B4, and another: F4, G4, B4.
However, on page 36, Figure 14, the bass part is: F3, E3, F3, A3, Bb3, G3. This violates the rule given in the footnote by moving from E3 to Bb3 without continuing stepwise in the same direction. I say to myself, "No problem. Nobody's perfect" and continue only to find the same situation in the next example. Page 37, Figure 15, soprano line, notes nine to the end are:  G4, C5, A4, G4, F#4, G4. Again, from notes 10 to 13, we have a descending tritone without continuing stepwise in the same direction! Okay, two "flukes" is a bit much, but warily, I continue. The next example, on Page 39 -- Figure 21 -- tenor (bottom) part, notes 8 - 12 are  B3, C4, A3, F#3, G3. Again, a descending tritone not followed  by step in the opposite direction. Three examples in a row?
It seems that Fux and Mann simply disagree here, but which is correct? Did Fux not care about this "rule"? Did others care about this "rule"? Why would Mann write something like that just before 3 (!) counterexamples?
Comment: Just to clarify it though, the tritones you mention are diminished 5ths. On page 35, Aloysius only mentions the augmented 4th. Don't forget that it is a historic book and you have to adhere to the practices of the time. It was written before the equal temperament tuning become standard and these ecclesiastical modes where not meant to be transposed to distant keys. So there might have been a difference in the sound between a diminished 5th and an augmented 4th.
Comment: @LimitedAtonement Yes, that's the resolution. The original meaning of "tritone"--as used by Fux/Mann here--is three tones, or three whole steps. Nowadays, we call that an augmented fourth. A diminished fifth is not technically a "tritone," since it is 2 tones and 2 semitones away, and it has different tendencies and functions in the context of basic counterpoint.
Comment: Very astute! The counter examples I found all have to do with the diminished 5th. I wonder if this could resolve the issue?
Answer: "Tritone" did not originally refer to both augmented fourths and diminished fifths. In fact, thinking of augmented fourths and diminished fifths as enharmonic respellings of the "same" interval didn't exist either. "Tritone" meant, literally, three tones or whole steps: e.g. F-G-A-B is a tritone, and is what we would now call an augmented fourth. A diminished fifth, such as B-C-D-E-F, is reached via two tones and two semitones and thus can't technically be called a tritone.
More importantly, these two intervals came up in different situations in medieval and renaissance music and had different rules. It's important to remember that—although augmented fourths and diminished fifths are the same size, 600 cents, in equal-tempered music—they are different intervals in just intonation and in the various meantone and well temperaments that predate the far more recent practice of equal temperament. In fact, there are many different possible sizes for these intervals. One fairly common instantiation of the augmented fourth would be about 570 cents, and its partner diminished fifth would have been about 630 cents (thus adding up to a perfect octave, 1200 cents).
Bottom line, the "tritone" had a far more specific meaning in Fux's day, and had rules distinct from the diminished fifth.
Comment: Excellent. This makes sense, and coordinates with my reading. It would be nice to find a reference for this, too!
Answer: When Mann wrote:
<code> The tritone is to be avoided even when reached stepwise [examples] if the line is not continued stepwise and in the same direction.
</code>
...what he was saying is that the tritone must not be outlined in stepwise motion.  With both melodic snippets [F, G, A, B] and [F, G, B], the F and B, which are the outside notes that outline these steps, create the undesired tritone.  This can be fixed, though, if we follow Mann's direction to
<code>(continue) stepwise and in the same direction
</code>
So if we took the first [F, G, A, B] and added C at the end, it would outline a perfect fifth, and this would be okay.  This is what makes [G, C, A, G, F#, G] and [F, E, F, A, Bb, G] acceptable.  Granted, if there was [F, E, Bb, G], that would not work, because there is a direct tritone between the E and Bb (of course that is not stepwise like the other examples).  But [F, E, F, A, Bb, G] solves the outlined tritone by adding F and G to the outside.
Comment: Please let me know if you have more questions about this, or if you don't understand what I wrote. :)
Comment: In [G, C, A, G, F#, G], what is being outlined if not a tritone?
Comment: Great question.  When I say outlined, I mean the first and last notes.  So G - G is the outlined, or "outside" interval.  Can you please edit your question by adding the octave numbers for these notes?  Such as G3 C2, etc.
Comment: I have modified my question to use Scientific Pitch Notation.
Comment: In what context does the note sequence [F,G,A,B] violate the rule (except by itself)? Is [F,G,A,B,G] okay? What about [G,F,G,A,B,G]?
Comment: @LimitedAtonement I will answer this evening - this is a very good question.
Comment: Even in equal temperament the augmented fourth and diminished fifth are (generally) treated differently. In (C for example) the dominant seventh on G will contain either F-B or B-F. The augmented fourth resolves outward, F-B  becomes E-C whereas the diminished fifth resolves inward, B-F becomes C-E. The general rule of augmented intervals resolving outward and  diminished intervals resolving inward holds in this case. In any temperament, the mi-fa and ti-do (or si-ut) intervals are semitones. Fa has a lower semitone neighbor and ti and upper one.
Answer: I should point out that I've read both this book and (more recently) a book on counterpoint in the style of Palestrina.  I noticed, very consistently, that the Palestrina book contradicted itself on many many occasions throughout the entire book.
I've learned to realize that a) mistakes are made b) exceptions are allowed and c) don't focus so much on the little specifics here and there (although it is very frustrating to not have resolution of a contradiction before moving on) and instead focus on the bigger picture.  With that said, I was doing self-study, not in a class, so that might be different (but then again, you can simply bring your questions to the professor...).
Hope this helps.
Comment: "don't focus so much on the little specifics here and there" For a beginner just beginning to learn about music and the theory of music, this makes sense. I'm currently writing a program to compose music (currently, I want it to compose in the style of species counterpoint), so I *really* care about the little specifics ;-)
Comment: That sounds very interesting.  Do you have a resource online where I can learn more about it?  Or is it a personal private project?
Comment: The project is hosted at http://sourceforge.net/projects/partwriter/. Feel free to post a "Discussion" on that page if you want to know more, etc.


Find the shortest route to visit at least once all edges of a undirected weighted non-Eulerian graph

Question: I'm trying to adress the following algorithmic problem using graph theory and Python:
I (personaly) want to find the shortest route I would follow to run through all streets of my district. I don't have the requirement to start from nor end on a particular node, I'm flexible here.
I have represented my district with a weighted undirected graph in Python using Networkx library. Edges weight being the street distance. I have 107 nodes and 130 edges. My graph is not Eulerian and I want to point out that my district has many dead-ends.
I know what I'm looking for is a variant (or equal?) to the Chinese Postman Problem but I could not find any relevant and clear process to progress...
I believe my problem is a variant of the undirected postman/chinease problem but I'm not sure how to start. In particular, I'm not sure which algorithm I could leverage.
I would be very thanksful if I could receive guidance on the approach please.
Comment: Since you're French, for once, the French version of Wikipedia is simpler and more understandable than the English one : https://fr.wikipedia.org/wiki/Probl%C3%A8me_du_postier_chinois

The idea is to add the minimum cost of edges to get a Eulerian graph, where you have your cycle. Compute that with a flow algorithm.
If you only need a path and not a cycle, you can remove the longest edge you had added.
Answer: Thanks @Hugo! It was useful.
I was able to develop an approach and started a Python program to calculate it with inspiration from this article: https://towardsdatascience.com/chinese-postman-in-python-8b1187a3e5a
Here is the approach I followed, my graph being G:

Build a list containing all odd degree vertices of G
Generate all unique pairs of odd degree vertices of G
Recurcively, I generate all odd pairing combinations
Calculate the shortest distance of all pairs
Finally, the shortest route = sum of all G edges + minimum of edges that are necessary to repease (obtained from the previous step)


How to do meta-analysis and create forest plots using Beta correlation coefficients

Question: Does anyone knows how to do meta-analysis and create forest plots using beta-correlation coefficients?
Comment: Please be more specific. Show what you have done and what you really want to do, preferably with some example data.
Comment: based on observational reported data: all you get are the Beta-correlation coefficients and 95% CIs, has anyone meta-analysed and created forest plots using these data?
Comment: If you only have betas, you are lacking critical information about the actual variation of the independent (and dependent) variables. Thus the studies cannot validly be compared; a meta-analysis does not seem possible.
Answer: I am trying to answer despite this being a very old question.
As long as you have standard errors, you can simply pool beta coefficients with inverse variance weighting, for istance using meta or metafor in R.


Como saber se o usuário já está logado em outro dispostivo?

Question: Tenho um aplicativo Android o qual se conecta a API do Parse.com, mas também poderia ser outra API RestFul a qual eu mesmo criei. A dúvida é como fazer controle de sessões em diferentes dispositivos?
Exemplo, um usuário só pode está logado em um único dispositivo em determinado tempo.
Answer: Mateus, pelo que entendo do Parse não faz este tipo de controle de sessão para você. Posso estar enganado, mas as sessões do Parse são bastante limitadas e só recentemente eles incluíram o recurso de validade de sessões, para você ter uma idéia! Até alguns meses a sessão do usuário era eterna, permanecendo a mesma depois dele alterar a senha.
Uma solução seria criar o seu controle. Se o seu objetivo é manter os dados sincronizados em vários dispositivos um caminho seria registrar todos os devices do usuário e criar flags em seus registros informando o dispositivo que inseriu ou alterou o registro. Então através de um script no CloudCode você envia msg para os dispositivos que precisam ser sincronizados novamente.
Acho que este seria um caminho.
Comment: Realmente, busquei em outros forúms, e uma solução foi na tabela de instalações criar um campo para controlar se está ativo ou não a sessão.
Comment: Confesso que estou tendo tantos problemas com o REST e CloudCode do Parse que estou considerando abondar a solução e desenvolver a minha própria. Funciona muito bem para o básico, mas uma vez que você necessite de maior controle a coisa vai se complicando bastante. Boa sorte por aí.


Small Business Server 2011 and Remote access to documents

Question: Assume I'm working away from the office; its a hotel computer Windows 7, Office 2010 and fast - so the best possible conditions.
Using Companyweb - Every time I open a document, I have to go through the logon process - seems odd to have to do that. Is this a 'by design' feature or is something wrong with my configuration?
When I do open the documents, are they being stored somewhere locally and should I be looking to delete on this computer - or are they in a temporary file?
Comment: Are you login into Citrix?  Or is it more of a SonicWall NetExtender type deal?
Comment: Neither. Small Business Server Remote Web Access (its a feature of SBS).
Answer: Something simple to check would be to make sure your Forms Based Authentication service is enabled.  You wouldn't happen to have a 2003 or 2007 SBS box up and running?  Reason I ask is I've seen this issue when migrating exchange from 2003 to 2010 and it isn't passing authentication properly.


Help understanding the result of a Cylindrical Algebraic Decomposition of $V\left( {x,y,z} \right) = {x^2} + {y^2} + {z^2} < 1$?

Question: From https://mathworld.wolfram.com/CylindricalAlgebraicDecomposition.html it is said that:
Define a cell in ${\mathbb{R}^1}$ as an open interval or a point. A cell in ${\mathbb{R}^{k + 1}}$ then has one of two forms:
Form 1: $\left\{ {\left( {x,y} \right):x \in C,f\left( x \right) < y < g\left( x \right)} \right\}$
Form 2: $\left\{ {\left( {x,y} \right):x \in C,y = f\left( x \right)} \right\}$
Where $x = \left\{ {{x_1},{x_2},...{x_k}} \right\}$ and $C$ is a cell in ${\mathbb{R}^{k}}$.
$f$ and $g$ are either:
1/ Continuous function on $C$ such that for some polynomials $F$ and $G$,  $F\left( {x,f\left( x \right)} \right) = 0$ and $G\left( {x,g\left( x \right)} \right) = 0$
2/ $\pm \infty$ and $f\left( x \right) < g\left( x \right)$ for all $x \in C$
A cylindrical algebraic decomposition of $S \subset {\mathbb{R}^n}$ is a representation of $S$ as a finite union of disjoint cells. Let $F$ be finite set of polynomials in $n$ variables.
A cylindrical algebraic decomposition of $S \subset {\mathbb{R}^n}$ is said to be $F$-invariant if each of the polynomials from $F$ has a constant sign on each cell of the decomposition.
An example of the decomposition of the decomposition of ${x^2} + {y^2} + {z^2} < 1$ is:
$\left\{ {\begin{array}{*{20}{c}}
  {\begin{array}{*{20}{c}}
  { - 1 < x < 1} \\
  { - \sqrt {1 - {x^2}}  < y < \sqrt {1 - {x^2}} } \\
  { - \sqrt {1 - {x^2} - {y^2}}  < z < \sqrt {1 - {x^2} - {y^2}} }
\end{array}}&{\begin{array}{*{20}{c}}
  {\left( 1 \right)} \\
  {\left( 2 \right)} \\
  {\left( 3 \right)}
\end{array}}
\end{array}} \right.$
1/ From the result of the example does it mean that (1),(2) and (3) are the three cell of this decomposition ?
2/ In this example does it mean that $S$ is ${x^2} + {y^2} + {z^2} < 1$ , what is $F$ and what does it mean by $F$-invariant ?
3/ From what I know the Cylindrical Algebraic Decomposition could be thought as some form of quantifier elimination. Then does that mean the result in (1)(2)(3) is a quantifier free of this statement:
$\exists x,y,z \in {\mathbb{R}^3},{x^2} + {y^2} + {z^2} < 1$
4/ Is there anyway to rigorous proof that integrating over (3)(2)(1) yield the spherical volume of  ${x^2} + {y^2} + {z^2} < 1$ ? By inspection it seem that way.
Please help me !
Thank you for your enthusiasm !
Answer: 1/ Three cells are specified here.  The first cell, which we will call $C_1$, is in $\Bbb{R}^1$ and is given by (1), in Form 1, and is $(-1,1) \subseteq \Bbb{R}$.
The second cell, which we will call $C_2$, is in $\Bbb{R}^2$ (so take $k = 1$ for this cell), has $C = C_1$, and is given by (2) in Form 1,
$$  \{(x,y) : x \in C_1, -\sqrt{1-x^2} < y < \sqrt{1-x^2}\}  \text{.}  $$
The third cell is in $\Bbb{R}^3$ (so take $k = 2$) for this cell), has $C = C_2$, and is given by (3) in Form 1,
$$  \{((x,y),z) : (x,y) \in C_2, -\sqrt{1 - x^2 - y^2} < z < \sqrt{1-x^2-y^2}  \text{.}  $$
2/ Yes, $S$ is the set in $\Bbb{R}^3$ given by $x^2 + y^2 + z^2 < 1$.
Regarding $F$-invariance...  The use of $F$ in the specification of the cell forms is unrelated to the use of $F$ in $F$-invariance.
In the first cell, we need a polynomial $\hat{F}_1(x)$ that has constant sign on $C_1$.  An example if $\hat{F}_1(x) = x^2 - 1$.  Notice that this polynomial comes directly from $x^2 + y^2 + z^2 < 1$ by ignoring the $y$ and $z$ terms, $x^2 < 1$, then moving everything to the left: $x^2 - 1 < 0$.  This means $\hat{F}_1$ is negative exactly on $C_1$.  However, to match the usage in the example, we should negate this: $F_1(x) = 1 - x^2$.  Notice that this is exactly the form of $x$ that appears in the bounds of the inequality in the second cell.  In particular,
$$  -F_1(x) < y^2 < F_1(x)  $$  (The existence of these polynomial relations for the boundary of $C_2$ in terms of $F_1(x)$ and $y$ is the content of the text "$F(x,f(x)) = 0$ and $G(x,g(x)) = 0$".)
Continuing this pattern, $F_2(x,y) = 1 - x^2 - y^2$ is positive exactly on $C_2$ and $F_3(x,y,z) = 1 - x^2 - y^2 - z^2$ is positive exactly on $S$.  Then the given example CAD is $\{F_1, F_2, F_3\}$-invariant.
3/ Not necessarily.  If the quantifier order and the decomposition order do not match, a CAD may not be very helpful in eliminating quantifiers.
This particular example is easy, though since the variables are quantified in the same order as the variable order of the CAD.  It is trivial to determine that there is an $x$ satisfying (1).  Then, this choice of $x$ gives an interval of choices for $y$ in (2).  Then a choice of $y$ in that interval gives an interval of choices for $z$.  Notice that this is easy when the variable order $x$, $y$, $z$ is the same as the quantifier order.  If we quantify on $z$ first, this CAD is not particularly helpful.  If you construct a new CAD with variable order matching quantifier order, this is easy.
More discussion of quantification and elimination is present in http://www3.risc.jku.at/publications/download/risc_4231/s65kauers.pdf  (Also presented: a nontrivial example and an example of how much changes when you replace the present example of the open unit ball with the closed unit ball.)
4/  Yes.  This is immediate.  The volume $S$ is exactly given by the CAD, so the question you ask is equivalent to "is integration over $S$ given by this one inequality the same as integration over $S$ given by this CAD?"  Yes; they're both $S$.
Comment: @TuongNguyenMinh : The only thing in sight that can be proven is that a CAD for $S$ represents $S$.  Such proofs are widely available in the literature, so I won't be repeating one here.  For the instant example, use the usual method: show that a point satisfying the one inequality necessarily satisfies the three inequalities, then show that a point satisfying the three inequalities satisfies the one inequality -- this is easy enough here that you should have no trouble doing so.
Comment: 4/ Thank you so so much , now I know that they are equivalent but is there anyway to proof that rigorously instead of saying "the equivalent is immediate".
Comment: thank you so much. I was overthinking it


php conditional if (is_page('category/*'))

Question: I'm trying to make a conditional statement where if it is a certain page, but what if I want it to be a certain page with anything after it? I tried using a wild card, but that doesn't seem to work... It doesn't give me an error though...
<?php if (is_page('category/*')) : ?>

Comment: Do you know what column do here?
Answer: try this
<?php if (is_page('category/')) : ?>

or this
<?php if (is_page('category')) : ?>

You may just be able to check a directory.


Localization of a PID is a PID

Question: I would like a verification of a proof for the following statement. Let $S$ be a multiplicatively closed subset of a ring $R$. If $R$ is a PID, then $S^{-1}R$ is a PID.
Let $I = \left<r_1/s_1, r_2/s_2\ldots\right>$ be an ideal of $S^{-1}R$. Since $1/s_i$ is a unit in $S^{-1}R$, we have $\left<r_i/s_i\right> = \left<r_i\right>$. But then $I = \left<r_1/1,r_2/1,\ldots\right>$ and so we may think of $I$ as an ideal in $R$. Since $R$ is a PID, we have $I = \left<x\right>$ for some $x \in R$. So $I = \left<x/1\right>$, thus $S^{-1}R$ is a PID.
Thanks!
Comment: The proof is not valid as written.  $I$ is a subset of $S^{-1}R$, so you need to justify "thinking of it" as a subset of $R$.  The ideal with the same generators is principal in $R$, but you need to _prove_ that this implies that $I$ is principal, not just state it.
Comment: Ah, ok. But what I have written does establish that an ideal of $S^{-1}R$ is a of the form $JS^{-1}R$, where $J$ is an ideal of $R$, correct?
Comment: I would say that it comes close.  Too much is implicit here for my tastes.
Answer: Let me give a proof to

If $A$ is a PID, and $\mathfrak{p}$ a prime ideal in $A$, then the localization $A_{\mathfrak{p}}$ is also a PID.

Proof. Suppose $\mathfrak{a} \subset A_{\mathfrak{p}}$ be an ideal. We need to show that $\mathfrak{a}$ is principal, i.e. $\mathfrak{a}= (f)$ for some $f\in A_{\mathfrak{p}} $. Recall (see Prop. 3.11 in Atiyah-Macdonald) that every ideal in the localization is an extended ideal. Hence there exists an ideal $\mathfrak{b} =(g)\subset A$ such that $(g)^e = \mathfrak{a}$. Now given the cannonical map $\varphi:A\to A_{\mathfrak{p}}, \ x \mapsto x/1$,
$$
\mathfrak{a} = \mathfrak{b}^e :=\langle \varphi(g) \rangle = (g/1).
$$
Thus $A_{\mathfrak{p}}$ is a PID.
This is just a remark that above result gives a nice way of describing the Zariski-open sets in the scheme $\mathrm{Spec}A_{\mathfrak{p}}$ if $A$ is a PID and $\mathfrak{p} \subset A$ is a prime ideal. For a PID $A$, one shows that open sets are same as basic open sets $D(f)$. Indeed, if $U\subset \mathrm{Spec}A$ is open, then $U=V(\mathfrak{a})^c=V(f)^c=:D(f)$ for some $f\in A$ that generates the ideal $\mathfrak{a}.$ Because of the above result in the grey box, we know $A_{\mathfrak{p}}$ is a PID, and hence every open set in $\mathrm{Spec}A_{\mathfrak{p}}$ is of the form $D(g)$ for some $g\in A_{\mathfrak{p}}.$
Answer: the idea behind your method is sound, but it is a little confusing, perhaps, to argue merely that we may think of I as an ideal in R.
the difficulty that this phraseology avoids is that we cannot a priori rule out the presence of a non-finitely generated ideal in $S^{-1}R$. to rule this out we may seek to use the result that the localization of a Dedekind domain at a multiplicative set is again a Dedekind domain. thus any ideal of the localized domain $S^{-1}R$ is a product of prime ideals. this finiteness condition allows us to slide the ideal back up into $R$ through multiplication by a suitably chosen element of $S$.
Answer: Since every ideal of a localization is an extended ideal, so the result is true.

Localization of a PID is a PID


Slick proof that the inverse homotopy continuous?

Question: While trying to learn algebraic topology from Hatcher, I frequently come across maps which are "obviously continuous" but for which it would seem tedious to actually show continuity by appealing to the open set definition.
For example, the text states "if $f_0 \cong f_1$ via $f_t$, then $f_1\cong f_0$ via the inverse homotopy $f_{1-t}$. At a conceptual level, my intuition is that reparametrizing a homotopy by $t\mapsto 1-t$ preserves continuity. I would like a proof that formalizes that if possible...but I don't know how to actually prove that the resulting inverse homotopy is continuous without looking at open sets in the image space and considering their preimages. (Specifically, define a homotopy $G$ such that $G(s,t)=H(s,1-t)$ where $H(s,t)$ is the homotopy from $f_0$ to $f_1$ and show preimages under $G$ of open sets are open).
Comment: Presumably you mean "If $f_0\cong f_1,\dots$" but you write $f_0\cong f_0.$
Comment: @ThomasAndrews thanks, edited
Answer: I like your name, Mithrandir.
This is actually straightforward. The open-set definition makes it easy to show the composition of continuous functions is continuous. The definition of product topology makes it easy to show the product of continuous functions is continuous. Using e.g. the metric space criterion for continuity, $t\mapsto1-t$ is evidently continuous (if $|x-y|<\epsilon$ then $|(1-x)-(1-y)|=|x-y|<\epsilon$ too).
So the composition: $$G:X\times I\overset{1\times(t\mapsto1-t)}{\longrightarrow}X\times I\overset{H}{\longrightarrow}Y$$Is continuous, as a composition of continuous functions.
However, you make a good point that Hatcher and just about any algebraic topology text doesn't often bother to show, in a super precise manner, the continuity of certain functions. This is because it's assumed the reader is sufficiently "good at" general topology to "see" that, if they wanted to, they could make it precise, but it would be a waste of the author's time to go into minute detail and it would distract from the exposition. I don't completely agree with this philosophy, but I don't completely disagree with it either.
Comment: Thanks for the name complement and this answer! (The fact that the product of continuous functions is continuous w.r.t. the product topology is the key fact that I was missing, for some reason I incorrectly thought that only held for nice spaces)
Comment: @Mithrandir No worries. In fact, this property of the product topology is arguably one of the main reasons we like it; if $f:A\to B$ and $g:A\to C$ are continuous, then $(f,g):A\to B\times C$ is continuous. This crucially holds for infinite products. See 'universal property of the product', if you can accept the abstraction


CDF*[1-CDF]/PDF --- name? integrable?

Question: Suppose I have a random variable $X\in\mathbb R$ distributed according to a smooth nonzero probability density function (PDF) $f(x)$, with cumulative distribution function (CDF) $F(x):=\int_{\infty}^x f(\bar x)\,d\bar x$.  The following quantity is showing up in a calculation I'm working on:
$$q(x):=\frac{F(x)\cdot[1-F(x)]}{f(x).}$$
Does this quantity have a name?  And, what are the conditions under which $q(x)$ is integrable?
For what it's worth, it appears to be the product of the Mills ratio and the CDF.
Comment: $E[q(X)]$ is related to the expectations of $X$ and the largest and smallest of an *iid* pair of such variables, and therefore exists if and only if $E[|X|]\lt \infty].$  (This holds whether or not $X$ has a continuous distribution.)
Comment: For what it's worth, this eventually showed up in one of our research papers:  https://arxiv.org/pdf/2012.06958.pdf
Answer: Logistic curve
One relationship might be with logistic growth which is based on the following differential equation:
$$f'(x) = f(x)(1-f(x))$$
But then for $F(x)$ and inhomogeneous (using some variable rate $g(x)$)
$$F'(x) = g(x) F(x)(1-F(x))$$
So if we express the CDF as a logistic curve
$$F(u) = \frac{1}{1+e^{-u}}$$
where the parameter $u$ is an integral of $q(x)^{-1}$ (where $m$ is the median for which $F(m) =0.5$)
$$F(x) = \frac{1}{1+e^{-\int_{m}^x q(t)^{-1} dt}}$$
Then
$$f(x) = F'(x) = F(x)(1-F(x)) q(x)^{-1}$$
or like your expression
$$q(x) = \frac{F(x)(1-F(x))}{f(x)}$$
A related relationship is that the log odds (odds based on the CDF) are
$$\log\left(\frac{F(x)}{1-F(x)}\right) = \int_{m}^x q(t)^{-1} dt$$
And $q(x)$ is the inverse of the rate at which the log odds increase.
Order distribution
The terms like $F(x)\cdot(1-F(x))$ also occur in the distribution of order statistics.
But I am a bit puzzled how you can get this $f(x)$ in the denominator. There are not so many expression where you use $1/f(x)$.

CDF*[1-CDF]/PDF --- name? integrable?


Find the Remainder when $792379237923$...upto 400 digits is divided by $101$?

Question:
Find the Remainder when $792379237923\ldots$upto 400 digits is divided by $101$?

MyApproaach
when ($792379237923\ldots$400 digts)/$101$=
I learned this approach that I have to  calculate(let say U)=Is the sum all of all the alternate groups starting with the rightmost
and (let say)Th=Is the the sum all of all the alternate groups starting with the second rightmost
Rem(U-Th)/$101$=?
But I am not following how to calculate U and Th

Can anyone guide me how to approach this problem?
Answer: Let $N$ be the number. Then we really want to find $N \pmod {101}$.
Note that $N=7923\cdot10^{396}+7923\cdot10^{392}+\cdots+7923$.
Next note that $7923\equiv 45 \pmod {101}$
Also, for example, $10^{100}=100^{50}\equiv(-1)^{50}\equiv 1 \pmod {101}$
We get the same result for each term, and there are $100$ of these terms so $N\equiv 45\cdot 100\equiv 56$.
Answer: Since $100\equiv-1$ mod $101$, your number, mod $101$ is:$$-79+23-79+23-\cdots$$ which is $100$ copies of $-56$. And mod $101$, that makes $56$.
Comment: @alex.jorden $7923$%$10$=-$79$?How
Comment: @Charc248 Thanks! Others rejected your suggested edit but I implemented it.
Comment: @alex.jorden can you look at this question too http://math.stackexchange.com/questions/1510638/find-the-remainder-when-24242424-upto-300-digits-is-divided-by-999
Comment: All mod $101$: $100^0\equiv1$. $100^1\equiv-1$. $100^2\equiv1$ and so on. So $23\cdot100^0+79\cdot100^1+23\cdot100^2+\cdots\equiv23-79+23-\cdots$.
Comment: Actually I don't understand your question. I didn't say $7923\%10$ is $-79$. It's more like I said $7900\%101$ is $-79$.
Comment: It's a typo, in your first line


Is there a linear function that is *not* continuous between two normed vector space?

Question: The textbook says that this function has to be continuous at least in the origin for it to be continuous everywhere. But how is it possible that a function is already linear but somehow not continuous?
For example, $E$ and $F$ are two normed vector spaces. $f:E\rightarrow F$ is a linear function. Obviously we know that $f(0) = 0$. Now, for a non-zero vector $a$ in $E$, as long as $f(a)$ has a definition, say $b=f(a)$ for some $b\in F$. Then for however small $\epsilon$, as long as $\lVert x\rVert<\lVert a\rVert\frac{\epsilon}{\lVert b\rVert}$, we have $\lVert f(x)\rVert<\epsilon$. So it seems that this function is continuous at the origin without stipulating it.
Comment: I don't understand your argument. You make no use of $b$.
Comment: Sorry, typos! I published it before I proofread it. Now I'm doing it.
Comment: Is it worth pointing out that for any linear $f: E \to F$, and any $v$ in $E$, the limit $\lim_{t \to 0} f(tv)$ will exist and be $0$?  This is certainly true.  A second and far more nontrivial true statement is that if $E$ is *finite dimensional* then every any linear map from $E$ to any normed space $F$ will be continuous.  Probably, some blend of these two facts is where your intuition is coming from.  But this intuition does not (and cannot) lead to a proof of a general statement, as examples like Qiaochu's show.
Answer: It's a standard lemma that a linear operator $f : B \to C$ between two normed spaces is continuous if and only if it is bounded in the sense that the image of the unit ball in $B$ is bounded. It is easy to write down unbounded linear operators. For example, let $B = C$ be the subspace of compactly supported sequences in $\ell^1(\mathbb{Z})$ with basis $e_i, i \in \mathbb{Z}$ and consider the linear operator defined by $T(e_i) = i e_i$.
It is simply false that $||x|| < ||a|| \frac{\epsilon}{||b||}$ implies $||f(x)|| < \epsilon$. (Take $f = T, a = e_1, x = \frac{\epsilon}{2} e_3$.)
Comment: @Voldemort: $\ell^1(\mathbb{Z})$ is the space of all functions $f_n : \mathbb{Z} \to \mathbb{C}$ such that $\sum |f_n|$ converges equipped with the norm $\sum |f_n|$. The compactly supported sequences in $\ell^1(\mathbb{Z})$ are the sequences with only finitely many nonzero terms; this is spanned as a vector space by the sequences $(e_i)_n = \delta_{in}$ (which are equal to $1$ if $i = n$ and equal to $0$ otherwise).


How to control content access based on value of a List (text) field in user profile?

Question: When my users sign up, they must choose whether they are a Man or a Woman, via a List (text) field. If a user chooses "Man", they should only be able to see Woman users on the site. Likewise, if a user chooses "Woman", they should only be able to see Man users on the site. The users cannot edit the value of this field once it is set. The user is assigned a custom user role (man or woman) when they sign up, based on what they choose from that field.
I am also open to using Profile2 with two Profile types (man and woman), but I would still need a method to restrict one profile type from viewing other users of that same profile type.
How can I set up a permission that will allow this type of access restriction? I have not been able to find a solution to solve this scenario.
Comment: Any feedback about my answer?
Answer: Check taxonomy_permissions (I think will do in combination with role assignment and has a stable release too), term_access module, Access by Term
Comment: I finally found a module that does the job:  https://www.drupal.org/project/view_profiles_perms
Comment: cool hockey2112
Comment: @hockey2112 post the answer
Answer: I finally found a module that does the job: drupal.org/project/view_profiles_perms.

This module provides permissions to view user profiles depending on what
  roles the profile requested to be viewed has.
Answer: As an "alternative" to the View profiles permissions module you've found yourself, you could also use the Rules module for this, as explained below.
Part 1: Create a 1st rule to assign role "Woman"

Rules Event: after a new user account is created
Rules Conditions:
Check the value specified for your selection list (=Man or Woman), using these conditions:
(a) Entity has field (related to that selection list field), to make that field available to test its value.
(b) Perform a data comparison, to check if the value selected was Woman.
Refer to my answer to "How to specify a Rules condition related to select list values?" which includes a similar set of Rules conditions (though for entity "node" instead of "user" as you would need here).
Rules Action: grant the role "Woman".

Part 2: Create a 2nd rule to assign role "Man"
This is similar to what's detailed in Part 1 (use "Man" instead of "Woman").
Part 3: Optionally combine both rules in a single rule
The reason why you'd need 2 rules as detailed above, is that Rules does not allow to add "Rules Conditions" within the "Rules Actions". To get around that, you may want to use the Conditional Rules module using either Conditional (if/else) or Switch logic. For more details on that, refer to my answer to "How to access rules condition values in the rule event?".
Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).
Video tutorials
If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.
PS: One of the advantages of using the Rules module, is that you can probably (actually: pretty sure) use it for lots of other features to implement in your site (which helps to avoid your site suffering "modulitis", aka "way too much contributed modules that slows down a site").


Criar uma list com valores selecionados da table com checkbox

Question: Eu tenho este código, que ele pega o id selecionado da table:
 $("#tablepesquisaclientes tr").each(function (index, el) {
var $linha = $(el);
var checked = $linha.find('.checked:checked').length;
if (checked === 1) {
    console.log($linha.find('td').eq(1).text());
}
});

Porém eu preciso criar uma lista, para receber no controller, já criei a classe, e já declarei no ViewModel
public class ListaContrato {
    public int Id { get; set; }
}

 public IList<ListaContrato> ListaContrato { get; set; }

Este é o html da minha table

            Nº Contrato
            Cliente
            Valor

        @foreach (var item in Model.Contratos)
        {

                <input type="checkbox" class="checked"/>
                @item.Id
                @item.Cliente.Nome
                @item.Valor.ToString("N2")
                @item.PedidoVenda.EmpresaID

        }

Como posso passar os valores selecionados para o controller ? Tem alguma forma de passar direto para o controller criando uma list, ou passando apenas por ajax ?
Essa é a parte do controller, eu queria receber tudo pela ViewModel se tivesse jeito.
[HttpPost]
    public async Task<IActionResult> EnvioLote(EnviarLoteViewModel model)

Tentei criando também conforme a resposta do Leonardo:
  public int[] Ids { get; set; }

E então no click do button fazendo assim:
 var enviarLote = { Ids: [] };
            $("#tablepesquisaclientes tr").each(function (index, el) {
                var $linha = $(el);
                var checked = $linha.find('.checked:checked').length;
                if (checked === 1) {

                    var id = $linha.find('td').eq(1).text();
                    enviarLote.Ids.push(id);
                    console.log($linha.find('td').eq(1).text());
                }
            });
            console.table(enviarLote);
            $.post("/NFSe/EnvioLote", enviarLote)
                .done(function () {
                    console.log('postado');
                })
                .fail(function (data) {
                    console.log(data);
                    console.log('erro');
                })
                .always(function (data) {
                    console.log(data);
                    console.log('fim');
                });

Porém no controller os Ids continuam null.
Comment: Para enviar para o controller, ou vc submete um form ou faz um Ajax.
Comment: Atualmente eu estou fazendo por `submit`, porém como posso fazer para passar esta lista que vou criar quando selecionar o `checkbox` ?
Comment: Coloque um `name` nos checkboxes em forma de array, tipo: `name="ids[]"`... e coloque também um `value` com os ids: `value="@item.Id"`... assim, quando vc submeter, irá receber os valores dos checkboxes marcados em forma de array chamada `ids`.
Comment: @Sam desta forma eu não consegui, ou eu não entendi o conceito, tentei passar com o `ids` e também com a lista que eu criei `ListaContratos[]` porém não passa nenhum tipo de valor.
Answer: Considerando que sua model seja assim:
public class EnviarLoteViewModel
{
    public int[] Ids { get; set; }
}

Esse javascript fará o post.
$(document).ready(function () {
    $("#enviarBtn").click(function () {

        var enviarLote = { Ids: []};

        $("#tablepesquisaclientes tr").each(function (index, el) {
            var $linha = $(el);
            var checked = $linha.find('.checked:checked').length;
            if (checked === 1) {

                var id = $linha.find('td').eq(1).text();
                enviarLote.Ids.push(id);
                console.log($linha.find('td').eq(1).text());
            }
        });

        $.post("/Home/Enviar", enviarLote)
            .done(function () {
                console.log('postado');
            })
            .fail(function (data) {
                console.log(data);
                console.log('erro');
            })
            .always(function (data) {
                console.log(data);
                console.log('fim');
            });
    });
});

Comment: Eu preciso mostrar esse que eu já mostro, e através dele, criar uma nova lista, com os que foram selecionados pelo `checkbox`
Comment: Fiz a alteração para manter o código javascript que você já tem. ;-)
Comment: Tentei fazer igual você  fez, porém o `Ids` vem `null`, fiz exatamente igual vc deu o exemplo.
Comment: Subi o código aqui - https://github.com/ltreze/questaostackoverflow - Roda aí e me fala, pls.


How to call a function within a function

Question: function btn1(){
alert('hello')
}
function btn2(){
alert('anchor')
}

I want to call the function btn1 and function btn2 separate on clicking the div. As it is shown below.

<input type="button" value="hello" onclick="btn1()"/>

Comment: it's exactly how you have it there.  are you experiencing difficulty with it?
Comment: Also make sure the JavaScript code is in a script tag. :)
Comment: Hi guys i want to call the function separately, suppose I click on entire div it should call the function btn2 and if I click on the input button it should call the function btn1.
Comment: separate or one of the functions together with the other as in function btn2(){
alert('anchor') btn1()
}
Comment: Just a friendly advice, is not necessary but it's good practice, use ";" at the end of the line of the alerts
Comment: It is in script tag. If i clicking on the input button then btn2 function is also happening. I want to call only btn1 function on clicking the input button.
Comment: take a look here: http://stackoverflow.com/questions/387736/how-to-stop-event-propagation-with-inline-onclick-attribute
Answer: If I am getting this right you are probably experiencing bubbling. You might want to read about bubbling and event propagation as it will probably be clearer than what I can try to explain. But to solve your issue you want to take a look at jquery's
event.stopPropagation()

http://www.w3schools.com/jquery/event_stoppropagation.asp
Answer: The Click Event of the button bubbles his way up to the div. Take a look here how to prevent this:
How to stop event propagation with inline onclick attribute?
I recommend you use addEventListener in favor of inline event handler.


Por que suprimir o zero antes do ponto em decimais, como em 0.5 == .5?

Question: Algumas vezes encaro um código em que o programador escreveu um decimal sem o zero, como 0.5 sendo .5, por exemplo:

var decimal1 = 0.5;
var decimal2 = .5;

console.log(decimal1 == decimal2);
console.log(decimal1, decimal2);

No meu ponto de vista, escrever um decimal como .5 deixa a leitura prejudicada, então sempre prefiro utilizá-lo com o zero: 0.5.
O que realmente ocorre quando determinamos um decimal sem o zero antes do ponto? Porque conseguimos definir uma variável decimal desse jeito? Há diferenças entre as duas maneiras? Existe algum aumento na performance?
Comment: Pode testar até em uma calculadora caseira, se digitar .5, ela vai entender que é 0.5.
Acho que é só por convenção mesmo, na faculdade, tinha uma matéria de cálculo numérico, onde tinha um tópico que ensinava as melhores práticas de arredondamento, onde usávamos números bem capciosos, tipo 0.0089240544....
Ai na hora de escrevermos na calculadora, o professor mesmo recomendava essa forma .0089240544 porque querendo ou não, acaba ficando mais fácil pra gente escrever, e na hora de ler no display da calculadora, parece piada, mas 1 caractere a menos acabava facilitando, e muito!
Comment: Não ter o "0" antes não afeta negativamente a legibilidade (no caso geral). É uma convenção amplamente aceita. Por ou não acaba por se tornar apenas uma questão estilística e cultural.
Comment: Há uma técnica de, quanto menos letras numa página, menos peso. Mas não sei se escrever assim chega vale a pena. Observe o que os otimizadores/redutores de javascript fazem com a página, alguns chegam "comer" parte de código que eu teria vergonha de escrever.
Comment: Alguém pode dizer o porquê do `-1`?
Comment: @JeffersonQuesado, sim. Explicitei que é no *meu ponto de vista*, será por isso os votos negativos? Mas por que existe essa questão estilística e por que a linguagem permite? O `.x` existe por algum motivo?
Comment: @MarceloBoni, legal. Já notei que em outras linguagens isso ocorre também. A resposta pra isso fica além da programação, então? Fiquei ainda mais curioso... Eu tinha um professor que dizia o contrário, embora não fossemos fazer uma conta em uma calculadora, dizia para manter o zero para não nos perdermos nas contas.
Comment: Acho que entra no mesmo caso de números definidos como `0x, 0b e 0o` [vide](https://jsfiddle.net/rjzk6n4f/). O interpretador do javascript utiliza alguma regex pra detectar o que vem após o `0x`, `0b`, `0o` e `.` para fazer o calculo de conversão... note que se você escrever apenas `.` sem nenhum número após, o console emite um erro de sintaxe.
Comment: @bio é padrão que o reconhecimento de números de ponto flutuante seja fornecido através de algo próximo da expressão `([1-9][0-9]*|0?)(\.[0-9]*)?`
Comment: O que me preocupa é isso funcionar: `console.log(parseFloat(".2fhh.95fgh/4")); // 0.2` por exemplo
Answer:
O que realmente ocorre quando determinamos um decimal sem o zero antes do ponto?

Nada, essa é uma questão de sintaxe, não muda a execução, o significado, nada, só tem um caractere a menos.
O número é o mesmo, isso é só uma representação dele na tela neste contexto. Note que o escrito na tela também é só uma representação textual. Convencionou-se sempre colocar o 0 antes do ponto, o que parece um pouco incoerente.
JS não é conhecida por ter uma forte exigência de sintaxe estrita.

Por que conseguimos definir uma variável decimal desse jeito?

A resposta simples e óbvia é que a linguagem definiu assim. Como não há ambiguidade acharam que não era necessário obrigar algo só pela legibilidade.
Uma hipótese é manter a linguagem menos verbosa, ainda que isso seria questionável. Até falaram sobre ficar um arquivo menor, mas isso ocorre tão poucas vezes que duvido que seria uma boa motivação. Se fosse o caso a linguagem teria outras coisas que permitem o texto menor de forma mais intensa e com menos problemas de legibilidade.
A matemática meio que define assim, zeros no inteiro à esquerda do número não possuem significado, e por isso pode ser omitido. Assim como os zeros à direita na parte decimal.

Há diferenças entre as duas maneiras?

Zero.

Existe algum aumento na performance?

Zero.
Faça como achar melhor, até porque tem pouca relevância.
Comment: Quando criei essa questão imaginei algo diferente. Depois dos comentários percebi que não fazia muito sentido. Pensei que o `.5` existia por algum motivo, mas graças a vocês sei que é uma questão de sintaxe e é comum no meio matemático. Obrigado pela resposta.


How can I prove this properly?

Question: If $f(0)=g(0)$ and $f'(0)>g'(0)$ then there exists $n>0$ so that $f(x)≥g(x)$ $∀x ∈ [0, n]$.
Comment: But it is common practice that it does and hence misleading, when it does not.
Comment: I'm guessing it should be true $\forall x\in [0,\frac {1}{n}]$ and not $[0,n]$.
Comment: Can you please show what you have tried?
Comment: @Jamal $n$ is never stated to be an integer
Comment: @Omnomnomnom oh yeah sorry. My mistake.
Answer: Hint: Use the definition of a limit, noting that $\lim_{x \to 0^+}\frac{f(x) - f(0)}{x} = f'(0)$.
Answer: Let $h(x)=f(x)-g(x)$, then $h(0)=0$ and $h'(0)\gt0$. Then using the definition of a limit, we know that there is a $\epsilon \gt 0$ such that for every $x \in (0,\epsilon)$ then,
 $$\frac{h(x)-h(0)}{x}>0.$$

How can I prove this properly?


QueryBuilder and the MVC

Question: I'm programming on Symfony2 and I have a doubt: If I want to respect the MVC pattern, I should do the queries with the QueryBuilder on the Controller's actions or in methods inside the entities?
Thanks.
Answer: I think you should do query in Repository classes: http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes

In the previous sections, you began constructing and using more complex queries from inside a controller. In order to isolate, test and reuse these queries, it's a good idea to create a custom repository class for your entity and add methods with your query logic there.
Answer: First of all, please note that Symfony2 doesn't fully respect the MVC pattern. It provides controllers and templates (views), but not models.
A controller is a layer between 'http land' and 'application land' [1]. It's not just a layer, it should be the thinnest layer possible. On the other hand, the 2 'lands' should be big.
That means that there should be now querybuilder in the controller, but this should be done in the repository of the user. In the controller, you should just need to call one method of that repository.
More about custom repositories in the documentation

QueryBuilder and the MVC


Does this system of equations have any solutions?

Question: I would just like to know if this system has a solution:
$$\begin{cases}
x = \dfrac{1}{\sqrt{2}} \cos(x+y) \\
y = \dfrac{1}{\sqrt{2}} \sin(x+y)
\end{cases}$$
I don't know how to do it at all. Could someone help me?
Answer: Hint. By summing the two equations we obtain
$$x+y=\dfrac{1}{\sqrt{2}} \cos(x+y)+\dfrac{1}{\sqrt{2}} \sin(x+y)=\sin(x+y+\pi/4)$$
Show that there is a unique value of $x+y$ which solves the above equation.
P.S. Note that the function $t\to f(t)=t-\sin(t+\pi/4)$ is continuous, strictly increasing in $\mathbb{R}$ and  $\lim_{t\to\pm\infty}f(t)=\pm\infty$.
Answer: If it did $x^2+y^2=1/2$. On this circle, $t=x+y$ varies between
$-1$ and $1$. So can we find $t$ with $\cos t+\sin t=\sqrt2 t$?
Drawing a graph seems to indicate there's just one such $t$.