How to get an entity create route, given an entity type and bundle?

Question: I am the maintainer for Views Add Button: https://www.drupal.org/project/views_add_button , which creates a button (link with classes) in a Views header or footer, that allows the user to add content of a particular type. Link building and access checking are meant to be handled automatically by the module, so that the user does not have to write a custom plugin or put a "view in a view" to handle access control.
While working on a Drupal 8 port I'm running into some trouble getting the correct route for entities. At this time, the options form for the plugin will pass an entity type and bundle, but given that there are many entity types, some with bundles and some without, I am not sure how to calculate the route name for a given entity-bundle combination.
So far, I've written this to manually create the URL, based on some assumptions. I left the options building out as it is not relevant to the topic:
<code>// Get the create route
$type = explode('+', $this->options['type'], 2);
$entity_type = $type[0];
$bundle = $type[1];
$u = $entity_type === $bundle ? '/' . $entity_type . '/add': '/' .$entity_type . '/add/' . $bundle;
// Create the link
$url = Url::fromUserInput($u, $opts);
</code>
The goal is to use Url::fromRoute() instead of Url::fromUserInput, using the entity type and bundle. For example, 'node' and 'article' should return 'node.add' , which would then be given to Url::fromRoute().
Comment: An entity type doesn't necessarily have to have an add form, so I guess it's not something you can determine via the API. Take node v. user for example: nodes have a _create_ link listed in their annotation, whereas users don't, they have a _register_ form (not link) declared for that instead. Then have a look at the differences in the way the routes are created for each - nothing common there at all. Unless there's a higher level API somewhere that I'm not aware of, I think you're out of luck
Answer: Given Clive's comment, and some further thought about it, one thing I could do is create an annotation, such that custom entity developers can declare their route. Further, I can add annotations to the module that cover all core cases (node/user/taxonomy), such that the module works with core out of the box.
From there, I could add conditional logic that looks for a given entity's annotation, and if it doesn't find it, it would then make the same assumption (/{entity_type}/add/{bundle}) as above. I suppose from there either developers can declare an annotation in their own module, or if a particular custom entity is popular and keeps hitting the issue queue, I could add that as well.


htaccess rule to protect against malicious post requests to WordPress index.php?pubkey=

Question: I've been looking at a log created by a WordPress plugin called Bad Behavior and in it there are many entries from different IP addresses at various intervals during the day that are requesting the following URL:
POST www.example.com/index.php?pubkey=b13bdb8297326599cf86aj25274e6a0c&bvTime=1549500166&bvVersion=0.1&bvMethod=getdata&sha1=true&sig=53fb643e40685ed89aa6754483b0a0d06bf1e63d0
The part of the URL that remains the same is /index.php?pubkey= then the rest is different for the other entries in the log.
What I am looking to do if it's possible, is to block those post requests via the .htaccess in the root directory.
While researching I found this answer here: Restrict Access To index.php - Apache
But since I don't really understand how to build directives correctly in the .htaccess file, I don't want to add something in there that can potentially block legitimate traffic or cause other problems.
Also while searching I found this piece of information at https://perishablepress.com/protect-post-requests/ but they warn you that using the following rule can be problematic if the website is not static and or uses forms, which this particular website does.
#deny all POST requests
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_METHOD} POST
RewriteRule .* - [F,L]
</IfModule>

So with that said, I hope enough information was added here that can help someone to help me find an answer to this particular problem.
Answer: The solution is indeed very similar to the question you linked to.
However, one question I would ask is, do you need to specifically target POST requests? Why not any request (GET or POST) that starts/index.php?pubkey=? Or does this carry some other meaning in WordPress?
In which case, you can do something like the following at the top of your .htaccess file:
RewriteCond %{QUERY_STRING} ^pubkey=
RewriteRule ^index\.php$ - [F]

No need for the <IfModule> wrapper. No need to repeat the RewriteEngine directive as that is no doubt set later in the file.

To specifically target POST requests then you can add another condition, as you did in your example:
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{QUERY_STRING} ^pubkey=
RewriteRule ^index\.php$ - [F]

UPDATE: it didn't work as I was expecting, since I was able to load the page by visiting www.example.com/index.php?pubkey=

This could happen if the above directive is in the wrong place in the .htaccess file and is conflicting with other directives. It needs to be at the very top of the .htaccess file, before any existing mod_rewrite directives.

After some trial and error this is what blocked me completely, it works but I don't understand why, can you please explain the difference between what you gave me and this?
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{QUERY_STRING} (pubkey=.*) [NC]
RewriteRule (.*) - [F,L]
</IfModule>

This is far more general and blocks much more than just the URL stated in your question (possibly too much). These directives block any URL-path that contains pubkey= (case-insensitive) anywhere in the query string. So, it will block the following URLs (in addition to the URL stated above):

example.com/foo/bar?pubkey=xyz
example.com/foo/bar/baz?abc=1&xyz=2&pubkey=
example.com/foo/bar/baz?def=2&xyz=3&PuBkEy=xyz

These directives can be simplified:
RewriteCond %{QUERY_STRING} pubkey= [NC]
RewriteRule .* - [F]

No need to capture the RewriteRule pattern or CondPattern. The regex pubkey= is the same as pubkey=.*. The L flag is not required when the F flag is used. And as mentioned above, no need to repeat the RewriteEngine directive or use the <IfModule> wrapper.
Comment: Yes, it's a regex (the same as used by many programming languages... PHP, JavaScript, C# etc.). Strictly speaking `^` denotes the start of the _string_ that the regex matches against. (It doesn't necessarily denote the start of the _regex_.) You can't "flip the order of the lines". They are already in the most efficient form. The `RewriteRule` _pattern_ (regex) is processed _before_ the `RewriteCond` directive that precedes it. Only when the `RewriteRule` _pattern_ matches are the preceding conditions processed.
Comment: You are correct about the location. Initially I added the directives all the way on the top per your suggestion, I then moved it down further while troubleshooting and enclosed it with that wrapper. Thank you so much for your suggestions with this issue, also your explanations of the different options in the directives were really helpful, you thought me more than one new trick. With your assistance I call this a resolved issue, and I hope that your answer can help someone else in the future. Thank you again MrWhite!
Comment: To better understand your answer I looked up what this character meant ^, the definition I found is "Denotes the beginning of a regex (regex = regular expression) test string. That is, begin argument with the proceeding character.".

With that said, would it be better to flip the order of the lines you wrote so the htaccess file looks at the pieces of that directive in order, or that order is not important?

Also I don't know if targeting the POST request exclusively is good, bad or indifferent to be honest.

Thanks for your answer btw I am testing it right now, will post results soon.
Comment: I tested further over the weekend and this are the results. I went with your suggestion and eliminated the POST Request_Method to target anything with pubkey=, however it didn't work as I was expecting, since I was able to load the page by visiting  www.example.com/index.php?pubkey=

After some trial and error this is what blocked me completely, it works but I don't understand why, can you please explain the difference between what you gave me and this? Thanks!

RewriteEngine On
RewriteCond %{QUERY_STRING} (pubkey=.*) [NC]
RewriteRule (.*) - [F,L]
Comment: That perhaps suggests you put the directive in the wrong place, or there is a conflict with existing directives? I've updated my answer addressing the points you've raised.


JS ERROR: Error: Expected an object of type GCancellable for argument 'cancellable' but got type string

Question: I'm trying to follow this tutorial.
Basically, I want to create my custom function that creates a folder if it not exists.
var makeDir = (path) => {
    const file = Gio.file_new_for_path(path);

    if (file.query_exists(path)) {
        print(`Dir already exists ${path}`);
        return;
    }

    print(`My Path: ${path}`);

    // file.make_directory(path);
};

When I run this code I'm receiving an error:
Gjs-CRITICAL **: 17:35:17.161: JS ERROR: Error: Expected an object of type GCancellable for argument 'cancellable' but got type string

In the documentation I see that GCancellable is optional. So I have no idea why my code does not work. Haw can I make it work?
Answer: In the C documentation, "optional" means something else than it usually does in JS: it means it's optional to pass a real pointer as that argument, and you may also pass NULL.
The error message is complaining about a string because query_exists() does not take a path string argument. Check the JS documentation for the list of arguments accepted in JS: you should call file.query_exists(null).


In amCharts ensure irregular intervals on x-axis between data points when not using dates

Question: I have a line graph with an X axis, with data that doesn't correspond to a dates but are numerical values.
I'd like my x-axis to have it's content appropriately spaced according to it's value on the axis.
However, as you will see in the example, there's equal spacing between each datapoint even though there are unequal jumps in the value on the x axis.
https://jsfiddle.net/shwaydogg/xfxk5gwu/3/
<code>"dataProvider": [
    {
    x:1,
    visits: 1,
  },        {
    x:1.1,
    visits: 2,
  },        {
    x:1.3,
    visits: 3,
  },        {
    x:5,
    visits: 4,
  },        {
    x:10,
    visits: 5,
  },        {
    x:100,
    visits: 6,
  },        {
    x:10000,
    visits: 7,
  },        {
    x:100000,
    visits: 8,
  },
],
</code>
note: I am aware of equalSpacing, but it's default value is false, it has not changed anything for me yet and seems to be geared towards keeping equal spacing if you are using parseDates which I am not.
Comment: What about using a XY Chart? [example](https://jsfiddle.net/wws3u9nh/)
Answer: Instead of using an XY chart that loses some of the features of the serial chart I opted for a bit of a hack.  In the dataprovider I added all the missing x-axis values without giving them a y-value (a value that corresponded with one of the lines).  e.g.:
<code>"dataProvider": [
  {
    x:1,
    visits: 0,
  },{
    x:1.25,
    visits: 1,
  },{
    x:1.75,
    visits: 2,
  },{
    x:2.25,
    visits: 3,
  }
]
</code>
changed to =>
<code>"dataProvider": [
  {
    x:1,
    visits: 0,
  },{
    x:1.25,
    visits: 1,
  },{
    x:1.5       //Added
  },{
    x:1.75,
    visits: 2,
  },{
    x:2         //Added
  },{
    x:2.25,
    visits: 3,
  }
]
</code>
Answer: An official response from the amCharts support team shows how to use XY Chart as @gerric indicated correctly:

Serial charts are not appropriate if you're using a numeric x-axis as the categoryAxis uses the exact values for each tick like string-based categories. You'll want to use an XY chart instead, which will create a full numeric x-axis with appropriate scaling.
I made some minor modifications to your existing chart here: https://jsfiddle.net/xfxk5gwu/4/

<code>var chart = AmCharts.makeChart("chartdiv", {
    "type": "xy",
     ...
</code>


wxStaticBox equivalent for QT

Question: In wxpython I can use a staticbox in combination with a staticboxsizer to make a box with a title around a widget, like this:

I am fairly new to qt and don't know all the widgets, so maybe I'm missing something trivial, but how can I implement this in pyqt/pyside?
Answer: It's called a QGroupBox:

You can either create it via a GUI editor (my preferred method), or you can create a QGroupBox() object in Python and add it to your window's layout.
Comment: Thank you for the fast answer, this is exacly what I wanted.  Qt designer is my preferred method too. I have it [integrated with eclipse](http://qt.nokia.com/products/eclipse-integration/) and run [this](http://pastebin.com/gRDkXh9w) script via external tools to make the ui files. It works quite well together.

wxStaticBox equivalent for QT


What is the difference succinct and unclear?

Question: This question was put on hold as unclear. What is the reason for this? Is it because the OP did not define what he meant by fiscal multiplier? I only found one definition via Google and that was quite clear.
Comment: A agree that the question seems clear enough.
Answer: There is an English mistake in the title, and there is no redundancy in the question itself which shows poor effort at expressing oneself as well as possible, which is why I put it on hold as unclear. If you edit the title to correct the mistake, I would vote to reopen.
More generally: I don't mind very short questions as long as they're crystal-clear. This one is not.


How to show main menu links based on user roles?

Question: I am showing menu items and I want to show some links to Anonymous user only and some links to Authenticate user.
It it possible to accomplish this in Drupal 7? If so how?
Answer: Meet Menu Per Role Module

This module allows you to restrict access to menu items1 based on user
  roles. It depends on the Drupal core menu.module—just activate both
  modules and edit a menu item as usual.
Answer: You can use the Menu item visibility module.

This module exposes configurable and extendable visibility settings
  for menu links.
Comment: it causes problem  like we cannt move  menu items, it has some bugs
Answer: Also go for Custom Menu Permissions
It allows for the permission used to access any menu item on the system to be overridden.
It allows for custom permissions (see hook_permission()) to be created through the admin interface. These permissions can be used the same as any permissions created in a module using hook_permission() - ie in modules, templates, and in hook_menu() callbacks.
Answer: If you don't want to install any contributed module. Create two menus one for anonymous and one for authenticated. Assign them to two blocks. (Menu Blocks).
Now give access permissions to those Blocks accordingly. One Block to anonymous and one for authenticated.
So the menu links added for them will be visible based on their role


Subtrair após remover uma linha da tabela JavaScript

Question: estou com um certo bug aqui.
Tenho uma função que calcular a quantidade x preço unitário para dar o valor total e com isso fazer o sub total. Como se fosse um carrinho de e-commerce.
$('.total').prop('readonly', true);
$('.vlun').mask("000.000.000.000.000.00", {
    reverse: true
});

function somarPrecos() {
    $('.vltot').prop('readonly', true);
    var $tblrows = $("#pecasList tbody tr");
    $tblrows.each(function(index) {
        var $tblrow = $(this);
        $tblrow.find('.qtd, .vlun').on('change', function() {
            var qtd = $tblrow.find(".qtd").val();
            var unt = $tblrow.find(".vlun").val();
            var subTotal = parseInt(qtd, 10) * parseFloat(unt);
            if (!isNaN(subTotal)) {
                $tblrow.find('.vltot').val(subTotal);
                var grandTotal = 0;
                $(".vltot").each(function() {
                    var stval = parseFloat($(this).val());
                    grandTotal += isNaN(stval) ? 0 : stval;
                });
                $('.total').val(grandTotal);
            }
        });
    });
};

nessa tabela eu posso adicionar e remover produtos. Eu queria que quando removesse a linha deste produto ele subtraisse o valor total do sub total da tabela. Eu fiz uma função para isso e funcionou meia parte pois ele só subtrai apenas 1 vez.
$("#pecasList").on('click', '.remover-peca', function() {
    var removesub = $('.total').val();
    var removetot = $('.vltot').val();
    $(this).each(function() {
        $(this).parents("tr").remove();
        var grandsubTotal = removesub - removetot
        $('.total').val(grandsubTotal);
    });
});

Alguém pode me dar uma luz?
 html abaixo:

            Peça:

            <button type="button" class="btn btn-warning add-novo"> Adicionar peça</button>

            Qtd
            Descrição
            Valor Unitário
            Valor Total
            Remover

                Sub-Total:
                <input type="text" class="form-control required total">

Função para adicionar as linhas da tabela:
$(".add-novo").click(function(){
    var linha = '
<input type="number" class="col-md-12 form-control required qtd" name="pedidoAssistencia.qtd">	<input type="text" class="col-md-12 form-control required nomeproduto" name="pedidoAssistencia.nmpeca">	<input type="text" class="col-md-12  form-control required vlun" name="pedidoAssistencia.vlunit">	<input type="text" class="col-md-12 required form-control vltot" name="pedidoAssistencia.vltotl">	<button type="button" class="btn btn-warning remover-peca btn-block"></button>
'
    $("table tbody").append(linha);
    somarPrecos();
});

Answer: Sugiro apagares a linha e depois calcular de novo o total das linhas que sobram:

$("#pecasList")
  .on('input', 'input', somarPrecos)
  .on('click', '.remover-peca', function() {
    // apaga a linha clicada
    $(this).closest("tr").remove();
    somarPrecos();
  });

function somarPrecos() {
  // calcula de novo o total
  var subTotal = 0;
  $("#pecasList tbody tr").each(function() {
    var qtd = Number($(this).find('.qtd').val());
    var vUnit = Number($(this).find('.vlun').val());
    var total = qtd * vUnit;
    $(this).find('.vltot').val(total);
    subTotal += total;
  });
  $('.total').val(subTotal);
}

$(".add-novo").click(function() {
  var linha = '
<input type="number" class="col-md-12 form-control required qtd" name="pedidoAssistencia.qtd">	<input type="text" readonly class="col-md-12 form-control required nomeproduto" name="pedidoAssistencia.nmpeca">	<input type="text" readonly class="col-md-12  form-control required vlun" name="pedidoAssistencia.vlunit" value="30">	<input type="text" readonly class="col-md-12 required form-control vltot" name="pedidoAssistencia.vltotl">	<button type="button" class="btn btn-warning remover-peca btn-block"></button>
'
  $("table tbody").append(linha);
  somarPrecos();
});

                            Peça:

      <button type="button" class="btn btn-warning add-novo"> Adicionar peça</button>

      Qtd
      Descrição
      Valor Unitário
      Valor Total
      Remover

        Sub-Total:
        <input type="text" class="form-control required total">

Comment: Meu calculo de soma estava complexo demais para uma coisa tão simples. Funcionou perfeitamente muito obrigado.


error LNK2005: _DllMain@12 already defined in MSVCRT.lib

Question: I am getting this linker error.

mfcs80.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined in MSVCRT.lib(dllmain.obj)

Please tell me the correct way of eliminating this bug. I read solution on microsoft support site about this bug but it didnt helped much.
I am using VS 2005 with Platform SDK
Answer: I had the same error message, but none of the answers here solved it for me.
So if you Encounter that Problem when creating a DLL Project that uses MFC, it can be resolved by entering the following line:
extern "C" { int __afxForceUSRDLL; }
to the cpp file where DllMain is defined. Then your own DllMain implementation is used, rather than the one from dllmain.obj.

When we try to use MFC library, we surely will include afx.h directly
or indirectly, then MFC(afx.h) tell the linker to find the symbol of
__afxForceUSRDLL and put that object which contains __afxForceUSRDLL into the program, so linker searches and puts dllmodule.obj into our
program, because __afxForceUSRDLL is defined in dllmodule.cpp.
That's the common scenario. When we want to use our own DllMain in a
mfc dll project, linker complains that there are two DllMain, one in
our code, one in Dllmodule.obj.
So we need to tell the linker to add our dllmain.obj for
__afxForceUSRDLL. So we need to define __afxForceUSRDLL in our own cpp file where our own DllMain is defined, then the linker will ignore
mfc's dllmodule.obj and see only one DllMain and never complains.

Source: http://social.msdn.microsoft.com/Forums/en-US/0d78aa6b-1e87-4c01-a4a7-691335b7351a/how-to-build-mfc-application-dll-in-visual-c-2010
Comment: I removed `//AFX_MANAGE_STATE(AfxGetStaticModuleState());`
http://stackoverflow.com/a/9070135/1641556
Comment: For code that must compile as 32 bit and 64 bit use this
    #ifdef _X86_
    extern "C" { int _afxForceUSRDLL; }
    #else
    extern "C" { int __afxForceUSRDLL; }
    #endif
Comment: Worked for me, I had AfxWin.h included and slightly different library causing the problem:
uafxcwd.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined
Comment: @JonDrnek
This should be:
#ifdef _WIN64
extern "C" { int __afxForceUSRDLL; }
#else
extern "C" { int _afxForceUSRDLL; }
#endif
Comment: Worked for me with VS2008 and a DLL where I'd caused the link error by  using MFC collections, specifically CMapStringToString.
Comment: These options also doesn't work for me...                  i am now getting error: mfcs140.lib(dllmodul.obj) : error LNK2005: DllMain already defined in  xxxMyclassMain.obj
Comment: It's now 2023 and I am using VS 2019. The error I got had very little detail, just these two lines: 'LNK2005 _DllMain@12 already defined in dllmain.obj' and 'LNK1169 one or more multiply defined symbols found'. I used Anurag's solution, but JonDrnek's may work as well. My starting point was a MS article, https://learn.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=msvc-170, which doesn't say anything about this. C++ is a little too finicky sometimes. I'm trying to program, not understand all these switches to support an endless array of environs.
Answer: If you read the linker error thoroughly, and apply some knowledge, you may get there yourself:
The linker links a number of compiled objects and libraries together to get a binary.
Each object/library describes

what symbols it expects to be present in other objects
what symbols it defines

If two objects define the same symbol, you get exactly this linker error.  In your case, both mfcs80.lib and MSVCRT.lib define the _DllMain@12 symbol.
Getting rid of the error:

find out which of both libraries you actually need
find out how to tell the linker not to use the other one (using e.g. the tip from James Hopkin)
Comment: Missing detail - some libraries define weak linkages, defining the correct library inclusion order would have mfc used first and msvcrt second and so silently drop the weak linkage
Comment: That detail has cost me hours of astonishment and misery (silently linked in an imported library's `main`).  Weak linkages may have their use, though.
Answer: If you're defining your own DllMain, in your project settings you need to set 'Use of MFC' in the 'Configuration Properties/General' to 'Use Standard Windows Libraries'.
You should do a clean rebuild after changing it.
Comment: I have a pure C, non-MFC DLL set to "Use Standard Windows Libraries," but the error still pops up.
Comment: I found that removing _WINDOWS from the preprocessor defines in Project Settings -> C/C++ -> Preprocessor got rid of the spurious reference to MSVCRTD.lib . I'm using VS2010.
Answer: In my project I was able to solve this problem by adding mfcs80.lib and msvcrt.lib as additional dependencies in the project settings. The 'additional dependencies' can be found under Linker -> Input.
In the debug configuration that would have to be mfcs80d.lib and msvcrtd.lib respectively.
By the way, I am working with Visual Studio 2010, so in my case the MFC lib is called mfc100.lib.
I am not sure why this worked. It is not necessary to add these lib files as additional dependencies because I already set 'Use of MFC' to 'Use MFC in a shared dll'. I guess that by specifying these libraries as additional dependencies they are linked in a different order.
This solution is more or less the same as the one suggested on the Microsoft site: http://support.microsoft.com/kb/148652, except I did not need to type anything in the 'Ignore specific default libraries' box.
Answer: For me the direct cause was indeed a missing _afxForceUSRDLL symbol reference, but the indirect cause was a missing _USRDLL macro definition. It is defined by default by the VC wizard, but occasionally devs erase it erroneously.
Here it is in more words.
Comment: I had the opposite! I had a rogue _USRDLL in the preprocessor that should have been a _LIB. Doh!
Answer: MSDN knowledge base ID Q148652.
http://support.microsoft.com/kb/148652
Cause:
Visual C++ compiles the source files in alphabetical order, and passes the compiled object files to the linker in alphabetical order.
If the linker processes DLLDATAX.OBJ first, the source code references DllMain, which the linker loads from MSVCRTD.LIB(dllmain.obj).
The linker then processes an object file compiled from a C++ file that contains #include "stdafx.h", which references the symbol
__afxForceUSRDLL, which the linker loads from MFC42D.LIB(dllmodul.obj). This object module also contains an implementation for DllMain,
causing the conflict.
Answer: I have a very similar problem. [mfcs110d.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined in MSVCRTD.lib(dllmain.obj)] and the solution was add mfcs110d.lib to Additional Dependencies
Comment: I am also getting same error:
mfcs140.lib(dllmodul.obj) : error LNK2005: DllMain already defined in msvcrt.lib(dll_dllmain_stub.obj)                                                                                Tried by adding these libraries in 'Additioonal dependencies' but still it couldn't solve.. I am still getting same error.. I am building dll as final output not an exe..
Comment: Have a simple project sample to download?
Answer: For all those who are experiencing this error in ATL projects (mostly when trying to add MFC support), here's the solution I found after days of frustration!
First of all, this link was more helpful to me than all the others. It pointed me into the right direction. The problem occurs, if the "generated files" (containing the proxy and stub code, just as the type guids) for some reason have been removed and readded to the project. This causes Visual Studio to add them in the wrong order!
Usually you first come up with the "ATL requires C++ compilation" error, but you may have fixed this by turning out the Yc/Yu (precompiled headers) setting for that file.
What you should do next is unloading your project and edit it. Search for the item groups that define the build and include order (ClCompile and ClInclude). Check their order and settings.
The compiles should appear in this order:

dllmain.cpp (with CompileAsManaged set to false and PrecompiledHeader left empty).
Library source (MyLib.cpp, containing DllCanUnloadNow and so on)
Proxy/Stub code (MyLib_i.c; with same settings as dllmain.cpp)
stdafx.cpp (with PrecompiledHeader set to Create)
All the other library source files (your actual libraries content)
xdlldata.c (with the same settings as dllmain.cpp)

The includes should then be ordered like this:

dllmain.h
MyLib_i.h
Resource.h
stdafx.h
targetver.h
... (actual library headers)
xdlldata.h

Fixing the build order fixed my project and I was able to create a new clean build.
Comment: Just wanted to comment that this answer was immensely helpful; I did not know the linker was dependent on the build inclusion order in the project, but indeed, this fixed the problem for me.
Answer: I have personally got rid of this error this way: right-clicked project in the Solution Explorer, selected Properties from pop-up menu, clicked Linker tab and added mfcs71ud.lib into Additional Dependencies. If you're using Visual Studio 2005, it should be "80" instead of "71" and so on.
Comment: I have a very similar problem. [mfcs110d.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined in MSVCRTD.lib(dllmain.obj)] and the solution was **add mfcs110d.lib to Additional Dependencies**
Answer: In my case I had a problem with the preprocessor directives.
For some reason _USRDLL was defined, when it should not have been.
To check this, go to the menu  Project , select  Project Properties , then select the snippet  Configuration Properties  -->  Preprocessor .
The preprocessor directives will be found there.
Comment: This advice has to be slightly updated for Visual Studio 2107. Select your project in the Solution Explorer, right click and select Properties. Now go to C/C++>Preprocessor>Preprocessor definitions, and edit out _USRDLL
Comment: user1741137 - Is gennerally right, but instead of having to wait 86 years from know, the advice has been valid for about 4 years already  [snarky: 2017 not 2107] :)
Answer: Declare the mfc80ud.lib and mfcs80ud.lib in the Additional Dependancies field in the Project Properties -> Linker Tab -> Input of Visual Studio to fix the issue.
Comment: Though somebody gave the same answer about a year earlier, this one is on top, so I'll leave my 5 cents here. It seems the msvcrt.dll imports dllmain only when it wasn't declared earlier. Adding the mfc*.dll to "Additional Dependencies" makes it being processed earlier and solves the issue. As somebody else mentioned /FORCE:MULTIPLE sliences the linker as well, yet in my case produced .dll was crashing in runtime.
Answer: Just #undef the _USRDLL before including afx.h, or even better, edit your project configuration and remove the macro.
This is the usual configuration for a MFC extension DLL: Build Settings for an MFC DLL
Answer: Make sure you include "Stdafx.h" at the top of each .cpp file.  I was getting the exact same error and had a single .cpp file that did not include this header at all.  Adding the #include solved the problem.
Answer: I found solution Here
Visual Studio 2010 library linking order
this is: /FORCE:MULTIPLE
in linker options
I had to mix ATL and MFC together , to use
[module(name = "mymodule")]; construction in MFC application together with "__hook" keyword
Answer: I found this which helped me:
http://support.microsoft.com/kb/148652
Basically the linker order was incorrect. the CRT libs were getting linked before the MFC libs. Turns out, the MFC libs had to get linked FIRST, and then the CRT libs could be linked.
Yucko Microsoft!!
Answer: There is a common theme running through some of the answers here.
Avishek Bose:-

Declare the mfc80ud.lib and mfcs80ud.lib in the Additional
  Dependancies field in the Project Properties -> Linker Tab -> Input of
  Visual Studio to fix the issue.

vmb100:-

I am working with Visual Studio 2010, so in my case the MFC lib is
  called mfc100.lib.

joseAndresGomezTovar:-

I have a very similar problem. [mfcs110d.lib(dllmodul.obj) : error
  LNK2005: _DllMain@12 already defined in MSVCRTD.lib(dllmain.obj)] and
  the solution was add mfcs110d.lib to Additional Dependencies

So the general case seems to be to first find the name of the library to add ...

and then to add it ....

Note that there seem to be some prerequisites and/or alternative solutions.
Answer: This can also occur if your solution has multiple projects that export the same symbols. For example if you have sub-project that builds foo.dll with a foo.def file that exports DoFoo and a sub-project for bar.dll with a bar.def file that exports DoFoo, a collision will occur and this is the error you will see when you link.
Answer: In case of migrating from old version of Visual Studio to new one, maybe this help:
got to project Properties => C/C++ => Preprocessor => preprocessor definitions
add __afxForceUSRDLL and done.
Also check if there was _USRDLL there, delete it and just add __afxForceUSRDLL .
this helped me


Copy to clipboard from website when browser is not focused

Question: I wanted to create very small extension for website that will automatically copy some value to the clipboard.
The problem is that I want it to copy the value even if browser is not focused e.g.:

I open the website, my extension listens to the change on the page
I open different application
If something changes on the page then the extension should copy some value
Main application that I'm working with is still focused but I can CTRL+V paste value copied from the website without alt+tab

I tried to use Clipboard API:
navigator.clipboard.writeText(...)

but I don't think it will work because browser have to be focused(I think).
When page is focused then copying works fine. If I try to switch to different application I get an exception when my extension tries to copy the value:
DOMException: Document is not focused.

Is there any way to do this?
Comment: No, and this is by-design, so malicious websites cannot interfere with the user's clipboard unless the user expects them to.
Comment: Is there any way to get around it somehow? Different browser, settings or something like that?
Comment: Does this answer your question? [DOMException on calling navigator.clipboard.readText()](https://stackoverflow.com/questions/56306153/domexception-on-calling-navigator-clipboard-readtext)
Answer: This is not possible for security reasons.. It's hard to imagine anyone wanting this behavior...
This document has a lot of good info..
In Chrome, you can request clipboard-write permissions to write to clipboard outside of a small user generated event, although it does not appear as though Chrome limits you to when you can write to clipboard.. According to the article below, you can write to the clipboard in Chrome from the background, etc.. See the note at the bottom of this section for more info.
If Chrome does allow you to write to clipboard from the background or if the window is not selected, you could possibly use the Page Visiblity API to kick off the copy event when "that" specific window is not visible.
You could possibly even use the window.addEventListener('blur', function(){...}) handler to test, etc...
All in all, this MAY be possible in Chrome, but it is definitely not supported in Firefox.
You can check out the differences between browsers and how they handle clipboard related events/permissions/etc, here..


How can we tell which branch is newer in Git?

Question: I have two branches: origin/A and A (locally).
Assuming one - and only one - has advanced by one commit, but I don't know which branch advanced, how do I tell which one has the extra commit?
Comment: If its always going to be 2 branches, the method specified by Makato would suffice. Else, I suggest you look at http://stackoverflow.com/a/5972362/4433695
Comment: possible duplicate of [git: programmatically know by how much the branch is ahead/behind a remote branch](http://stackoverflow.com/questions/2969214/git-programmatically-know-by-how-much-the-branch-is-ahead-behind-a-remote-branc)
Answer: Use git fetch to get the latest commits from the tip of your remote, then use git status to tell whether or not your remote or local is ahead.
If origin/A is ahead, then when you run git status, you'll be told that your local A branch is behind origin by a commit.
If your local A is ahead, then when you run git status, you'll be told that your local A branch is ahead of origin by a commit.
Answer: git rev-list HEAD --count will give you the number of commits on your current branch. Assuming you using github you can see the number of commits on the stop left of the repo.
Comment: This *kind of* works, but you've got to do the math yourself.
Answer: If your goal is to do this as part of an automated bash script, you can use the git rev-parse command. To see the commit hash of a given branch, use this command:
git rev-parse branchname

Or, to see the hash of the previous commit from a given branch, use this command:
git rev-parse branchname^

So, if you want to see which branch is ahead, you can run the following four commands and compare output:
git rev-parse A
git rev-parse origin/A^

git rev-parse A^
git rev-parse origin/A

If the output of the first and second commands match, then A is the branch with one additional commit. If the output of the third and fourth commands match, then origin/A is the branch with one additional commit.
If neither pair of commands has matching output, then you don't have one branch that is ahead of the other by exactly one commit.
Comment: I'm not sure that guarantees that there is only ever one commit discrepancy between the two branches.  It guarantees that there's a SHA difference, but not *necessarily* that there's a numeric difference between the number of commits on these branches.
Comment: You are right, this method only works if the assumption stated in the question are correct: *Assuming one - and only one - has advanced by one commit*. If that assumption is not correct, then *neither* of the command pairs I listed will compare correctly. However, if that assumption is correct, and the branches do differ by exactly one commit, then this method will work.
Comment: I'm not sure answering a terrible question with an answer very specific to the arbitrary nature of that question is a good thing.


compactness / sequentially compact

Question: I'm looking for two examples:

A space which is compact but not sequentially compact
A space which is sequentially compact but not compact

Explanations why the spaces are compact / not compact and sequentially compact / not sequentially compact would be appreciated. A reference would also be appreciated. So the conclusion would be, that there's no equivalence in general. Of course they are equivalent in a metric space.
math
Comment: ...and the canonical reference for answering such questions quickly and reliably is Steen and Seebach, *[Counterexamples in Topology](http://books.google.com/books/about/Counterexamples_in_Topology.html?id=DkEuGkOtSrUC&redir_esc=y)*.
Comment: http://en.wikipedia.org/wiki/Sequentially_compact_space
Comment: See also: http://math.stackexchange.com/q/44907/5363
Comment: http://planetmath.org/encyclopedia/SequentiallyCompact.html , http://ncatlab.org/nlab/show/sequentially+compact+space here you should find both counterexamples.
Answer: The following examples are from $\pi$-Base, a searchable database of Steen and Seebach's Counterexamples in Topology.
(Click on the following links to learn more about the spaces.)
For compact but not sequentially compact:

Stone-Cech Compactification of the Integers
Uncountable Cartesian Product of Unit Interval ($I^I$)

For sequentially compact but not compact:

An Altered Long Line
$[0, \omega_1)$ ($\omega_1$ is the first uncountable ordinal)
The Long Line
Tychonoff Corkscrew
Comment: There are tables at the back of the book, where you can find such examples with patience.  And isn't there a Venn diagram in the section on compactness at the beginning?  Of course, the automated Spacebook is easier.
Comment: @ Austin Mohr: My first attempt was Counterexamples in Topology. Without knowing that the Cartesian product of unit interval and $[0,\omega_1)$ are examples, it's hard to find something in there. So thanks for your answer.
Comment: $I^I$ is correct, but it is wrong to characterize this as "uncountable cartesian product of unit interval" - we need the product to be of cardinality at least the continuum. As [explained by KP Hart](https://mathoverflow.net/a/29220/61785), it is consistent with ZFC that $[0,1]^{\aleph_1}$ is sequentially compact (necessarily with the continuum hypothesis being false).
Answer:
Example 1 with proof: Stone-Čech Compactification of the Integers $\beta \omega$
Proof: It is compact obviously. We will prove that $\beta\omega$ is not sequentially compact. Note that every infinite set in $\beta\omega$ has $2^\mathfrak c$ cluster points, hence the only convergent sequences in $\beta\omega$ are those which are eventually constant; therefore if $X$ is a subspace of $\beta\omega$  and $X$ is sequentially compact, then $X$ is finite. So $\beta\omega$ cannot be sequentially compact.
Comment: Didn't you post this answer somewhere else today?

compactness / sequentially compact


How can I determine whether $\int _{ 1 }^{ \infty }{ \frac { 1+\sin ^{ 2 }{ (x) } }{ \sqrt { x } } dx } $ is convergent or divergent?

Question: Use the Comparison Theorem to determine whether the integral is convergent or divergent.
$$\int _{ 1 }^{ \infty  }{ \frac { 1+\sin ^{ 2 }{ (x) }  }{ \sqrt { x }  } dx } $$
So, I see $\sin ^{ 2 }{ (x) }$, a function that could possible lead me to a oscillating divergence.
I also see how this integral looks somewhat similar to $\frac { 1 }{ x } $. How can I utilize these things to help me determine whether the integral is convergent or divergent? If I'm not on the right track, I would appreciate some more help/guidance.
Comment: $1+\sin^2 x\ge 1$.
Comment: @DavidMitra Is this correct? $\frac { 1+\sin ^{ 2 }{ (x) }  }{ \sqrt { x }  } \ge \frac { 1 }{ \sqrt { x }  } \ge \frac { 1 }{ x } $
Comment: @Cherry_Developer Yes on $[1, \infty)$ you have that $\sqrt{x} \leq x$ hence $\frac{1}{\sqrt{x}} \geq \frac{1}{x}$.
Comment: ignore the second part of the numerator. what happens if you just integrate the first part (the second part gives another contribution with the same sign)
Comment: The numerator remains in the range $[1,2]$, so the behavior of the integrand is essentially that of $1/\sqrt x$.
Answer: Hint: The integrand is positive.
Note that $1\leq 1+ \sin^2(x) \leq 2$. So your problem is reduced to finding the integral
$$\int_{1}^{\infty}\frac{1}{\sqrt{x}}\mathrm{dx}=\lim_{b\to \infty}\int_1^{b}\frac{1}{\sqrt{x}}\mathrm{dx}.$$
Can you complete it from here?
EDIT:
Using $1/x$ as a lower bound is also possible. But in general it is better to find the most exact estimate. The better your estimate is the better are the chances to get a lower divergent bound or upper and lower convergent bounds. To make this point clear, if you had selected 0 as a lower bound you would have failed in detecting divergence.
Comment: I used the fact that if a smaller series diverges, then the larger one diverges as well. Is that wrong? I didn't integrate..
Comment: How can you inferre divergence of the lower bound if you didn't integrate it? Normally we seek a lower and or upperbound for the integrand which is easy to integrate. From the result we inferre if the integral in question diverges/converges.
Comment: If the lower bound diverges, then doesn't the upper bound diverge as well?

https://www.khanacademy.org/math/ap-calculus-bc/series-bc/convergence-divergence-tests-bc/v/comparison-test
Comment: Yes, I always try to find lower bounds and upper bounds. For divergence the lower bownd is helpful. For convergence the upper and lower bound might be useful. In your case the lower bound is sufficient to inferre divergence.
Comment: So am I fine with my method?
Comment: Yes you are fine, but your estimation is too strong. You should always try to get the most exact estimation. For your example $1/\sqrt{x}$ is a better estimate then $1/x$. For example if you use 0 as an lower bound you will not be able to detect divergence.
Comment: "Yes you are fine", "but your estimation is to strong." Which one is it? Do I need to redo it with integration? Or am I fine with what I utilized?
Comment: Please read my comment and my edit with more patience :).
Answer: since, $0\le\sin^2 x\le 1\iff 1\le1+\sin^2 x\le 2$
so $$\frac{1}{\sqrt x}<\frac{1+\sin^2 x}{\sqrt x}\qquad \forall 1\le x<\infty$$
now, using comparison test,
$$\int_1^{\infty}\frac{1}{\sqrt x}\ dx<\int_1^{\infty}\frac{1+\sin^2 x}{\sqrt x}\ dx$$
since $\int_1^{\infty}\frac{1}{\sqrt x}\ dx$ is diverging hence $\int_1^{\infty}\frac{1+\sin^2 x}{\sqrt x}\ dx$ is also diverging
Comment: Second statement is incorrect you are missing a +1
Comment: oops i am sorry. thank you very much for noticing
Comment: There are many errors in your Answer. If the upper bound is divergent that doesn't mean that the integral is divergent.
Comment: see top answer hans huttel is using same method
Comment: No he doesn't he uses a lower bound but you are using a upper bound. The lower bound clearly implies divergence whereas the upper bound doesn't. Maybe you have typsetted the wrond inequality sign?
Comment: ok i got it & i corrected
Answer: $$\int _{ 1 }^{ \infty  }{ \frac { 1+\sin ^{ 2 }{ (x) }  }{ \sqrt { x }  } dx }>\sum_{n=1}^{\infty }\frac{1}{\sqrt{n}}$$
the series  diverges according to Riemann criteria, so the integral diverges
Answer: Let us look at a lower bound of the improper integral. We know that $0 \leq |\sin x| \leq 1$, so $0 \leq \sin^2 x \leq 1$. Therefore
$\int^{\infty}_{1} \frac{1}{\sqrt{x}} dx \leq \int^{\infty}_{1} \frac{1 + \sin^2 x}{\sqrt{x}} dx$
Now, $\frac{1}{\sqrt{x}} = x^{-\frac{1}{2}}$, which has the antiderivative $2x^{\frac{1}{2}} + C$ ($C$ being an arbitrary constant). So $\int^{\infty}_{1} \frac{1}{\sqrt{x}} dx = \lim_{y \rightarrow \infty} [2 x^{\frac{1}{2}} - 2]^y_1 = \infty$.
Comment: Your limit might be confusing. You should change the variable in the limit.
Comment: @Hans: see your error $\int^{\infty}_{1} \frac{1}{\sqrt{x}} dx < \int^{\infty}_{1} \frac{1 + \sin^2 x}{\sqrt{x}} dx$
Comment: Note that $\leq$ denotes "less than or equal to"; "or" is interpreted in the usual sense. We do not need to be concerned about the strictness of the inequality; we are only interested in proving divergence.
Comment: the sign of equality is not correct for $1\le x\le \infty$ so using equality is mathematically incorrect
Comment: No, it is not incorrect. We have that e.g. $2 \leq 3$.
Answer: We may prove much more than divergence. The integral $\int_{1}^{+\infty}\frac{\cos(2 x)}{\sqrt{x}}\,dx $ is convergent by Dirichlet's test, hence
$$ \int_{1}^{N}\frac{1+\sin^2(x)}{\sqrt{x}}\,dx = O(1)+\int_{1}^{N}\frac{3 dx}{2\sqrt{x}}=\color{red}{3\sqrt{N}+O(1)}.$$


How to execute macros

Question: I'm trying to execute this simple macro but it won't execute. After clicking on the .docm file I click on enable content but no macro gets executed.
Sub Workbook_Open()
    MsgBox "Welcome to Excel! This macro is running automatically."
End Sub

How can I make sure the macro is executed after clicking on enable content?
Comment: Workbook_Open won't do anything when you open a *Word document*. To get something to happen automatically when you do that you would usually need to put some Word VBA code in the Word Document or its associated Template and you would use another event (e.g. Document_Open).
Answer: Just reopen it. Because Workbook_Open() this event will only be triggered when the/a Workbook is opened.
Or you in the VBE, to run it. Just place the cursor in the code, then press key F8 (step by step) or F5 to run it. (There are corresponding buttons and options in the toolbar and menu).

How to execute macros


replace set of integers with respective string values

Question: I have a query which return the output like -- 5,4,6
Where 1 = apple, 2 = mango, 3 = banana, 4 = plum, 5 = cherry, 6 = kiwi etc.
I would like to update my output as cherry,plum,kiwi instead of 5,4,6
How can I achieve that in the same select statment.
I am okay to hard code the values.
Please confirm
May be I did explain clearly
Here is the sample
SELECT fruits FROM t_fruitid where id  =   7
is returning me  '5,6,4'  as a single row
Now I want to update this single row output as 'cherry,plum,kiwi'
How do I do this
Thanku
Answer: You should either query a reference table which has the integer values and the text strings in it (the preferred option) or use a case statement to do the conversion.
The preferred option
SELECT {YourExistingColumns}, NewTable.DescriptionColumn
FROM YourTable
JOIN NewTable ON YourTable.SomeIdColumn = NewTable.SomeIdColumn

Other option.
SELECT {YourExistingColumns}, CASE WHEN SomeColumn = 1 THEN 'apple' WHEN SomeColumn = 2 THEN 'mango' WHEN SomeColumn = 3 then 'banana' WHEN SomeColumn = 4 THEN 'plum' WHEN SomeColumn = 5 THEN 'cherry' WHEN SomeColumn = 6 THEN 'kiwi' END
FROM YourTable

Comment: Hi
I updated by above description, please look at the below lines

May be I did explain clearly

Here is the sample

SELECT fruits FROM t_fruitid where id = 7

is returning me '5,6,4' as a single row

Now I want to update this single row output as 'cherry,plum,kiwi'

How do I do this
Comment: SELECT  REPLACE(fruits, 5, 'cherry')
AS fruits_list
FROM fruitid  WHERE ID = 2
is doing for one value but I need to for all the values in the '5,6,4'
trying for the approach to replace the ids with values in the output
Comment: I got it, I was able to achieve this using

SELECT REPLACE( REPLACE( REPLACE( REPLACE( REPLACE( REPLACE(fruits, 1, 'apple'),  2, 'mango'), 3, 'banana'), 4, 'plum'), 5, 'cherry'), 6, 'kiwi')

Thanku


If going with the opposite prediction of a bad predictor gives good predictions, why not do that?

Question: Let's restrict our consideration to binary outcomes.
I have a friend who is terrible at predicting the future, always predicting the opposite of what winds up happening. For instance, my friend predicted Cincinnati to win the Super Bowl, but they lost. My friend predicted that Croatia would beat France for the 2018 World cup, but France won. Et cetera...
That is, my friend's predictions give me excellent predictive accuracy if I go with the opposite of what he predicted. "My friend always gets it wrong, so bet on Los Angeles to beat Cincinnati," I should have thought a few weeks ago. "Bet on France to beat Croatia," I should have thought four years ago.
What is wrong with applying this logic to a classification or probability machine learning model that consistently predicts the opposite, measured by $AUC\approx 0?$ I realize that the coefficient estimates should not be trusted, but if we care about the prediction above all else, the danger is not so apparent to me.
That is, if I get $AUC = 0.2$ from the probability predictions $p_i$ of a model, why not take $1-p_i$ as my final predicted probability?
EDIT
$AUC<0.5$, McFadden's $R^2<0$…whatever metric convinces you that you're consistently predicting the opposite of what you're seeing (though I have only ever seen this suggested when the $AUC$ is less than $0.5$, which I'm pretty sure is how some popular software packages approach ROC and AUC calculations).
Comment: Can I get an easy upvote-and-accept by simply answering "of course, go ahead, do that and have a nice day"? Seriously, your friend is a wonderful predictor, feed them into a model and buy them a cup of coffee. Alternatively, if you *need* to consider your friend a *model* and not a *predictor*, then what they need is just some post-processing, AKA *classifier calibration*.
Comment: For binary outcomes... maybe... hard to apply for multi-class.
Comment: @user2974951 Yes, it gets complicated for multiple classes. I've edited to clarify that I want to consider the binary case.
Comment: @StephanKolassa Not quite, but if you tie this back to calibration, that would make for an interesting answer! (It seems like that would be something like Platt scaling.)
Answer: This is a valid approach to having a two-step pipeline that makes your final predictions.

Get the model predictions that are reliably terrible (the friend who always predicts the wrong team to win).

Transform the model predictions so they are reliably good (the friend always picks the wrong team to win, so I pick that team to lose and always pick the correct winner).

This is a calibration step, not particularly different from any other calibration step, just with a sign change to the log-odds. However, keep in mind that the final predictions are made by this two-stage pipeline, not just by the original model.
I would have doubts about the first stage of the predictor, but being thorough to verify that, yes, the first stage is reliably wrong should be able to set up a calibration step that, when used on the original model predictions, makes for good final predictions.
(I am reminded of a line from the show Scrubs, something along the lines of, "You're typically wrong, so if I'm in doubt, I just go with the opposite of what you think." If that colleague really tends to get it wrong, then going with the opposite will tend to get it right.)
Answer: Your question: "That is, if I get $AUC=0.2$ from the probability predictions $p_i$ of a model, why not take $1-p_i$ as my final predicted probability?"
If you did that, then, indeed, your AUC would improve. But your prediction probabilities could be bad. Imagine, all your original prediction probabilities are very high, e.g. $p_i > 1-10^{-6}, i=1,\ldots, N$, but still your $AUC$ is only 0.2 (this is of course possible). Then, when using $1-p_i$, you would predict that nothing is ever happening.
The problem here is that $AUC$ doesn't care about the values of your $p_i$, only about their order.
Comment: This seems more like a criticism of AUC in general than of taking the opposite probability value.
Comment: @Dave You asked why not take $1-p_i$ when the AUC is 0.2, and I pointed out why not.


if a is local minimum of f show that $\forall h \in \Bbb{R^n} < H_f(a)\cdot h,h> \ge 0 $

Question: Let $ U \in \Bbb{R^n}$ be a domain, and $f: U \to \Bbb{R^m}$ ,$f \in C^2(U)$
show that if $a \in U $ is a local min of  $f$ then
$\forall h \in \Bbb{R^n}  < H_f(a)\cdot h,h> \ge 0 $
where $H_f(a)$ is the Hessian matrix
I tried to define $g(h) = < H_f(a)\cdot h,Ih>$ (where I is the unit matrix) and find its deritative
using the deritative show that $h=0$ is a local minimum of $g(h)$ and that it equals to 0, so for every other $h \in \Bbb{R^n} g(h) > 0$
I'm not sure I'm calculating the deritative correctly:
$\dot g(h) = < \dot  H_f(a), Ih> + < H_f(a), \dot Ih> = 2< H_f(a), h> $
if It is the deritative then its easy to show that $\dot g(h) = 0 $ iff $h=0$
but is it that correct? and if so, how to show it is a minimum?
Answer: Hint:
Use Taylor's formula at order $2$. It can be written as
$$f(a+h)=f(a)+\nabla f(a)\cdot h + \langle H_f(a)h,h\rangle+o\bigl(\lVert h\rVert\bigr).$$
At a critical point, $\nabla f(a)=0$, and we obtain
$$f(a+h)-f(a)=\langle H_f(a)h,h\rangle+o\bigl(\lVert h\rVert\bigr).$$
If $\lVert h\rVert$ is small enough, the sign of the r. h. s. is the sign of the inner product. Thus if $f(a)$  is a local minimum, this sign is positive or $0$, which means the quadratic form $\;\langle H_f(a)h,h\rangle$ is semi-definite positive.
Comment: Thx, if I got you right, I can show there is a small enough enviorment around 0 , where for every h there the expression is right, from that I can obtain that its true for every h (cause there exists a positive c where $c\cdot h$ will be in that enviorment? and I'm still intrested in knowing if that the way to derive inner products and matrices. btw you are missing 1/2 in your taylor formula


Unable to install exenstions and updates for Visual Studio 2017 RC (15.0.26014.0)

Question: I recently installed  Visual Studio 2017 RC (15.0.26014.0) and was trying to install extensions. However while installing any extension using Tools->Extensions and Updates menu fails. Following is installation log.
<code>27-Dec-16 10:35:19 AM - Beginning to install extension to Microsoft Visual  Studio Enterprise 2017 RC...
27-Dec-16 10:35:19 AM - Install Error : System.IO.FileNotFoundException: Unable to find the specified file.
at Microsoft.VisualStudio.ExtensionManager.ExtensionEngineImpl.GetCurrentSetupInstance()
at  Microsoft.VisualStudio.ExtensionManager.ExtensionEngineImpl.PerformSetupEngineInstall(InstallableExtensionImpl extension, Boolean installPerMachine, Boolean isPackComponent, IDictionary`2 extensionsInstalledSoFar, List`1 extensionsUninstalledSoFar, IInstalledExtensionList modifiedInstalledExtensionsList, IProgress`1 progress, InstallFlags installFlags, AsyncOperation asyncOp, IInstalledExtension& newExtension)
Microsoft.VisualStudio.ExtensionManager.ExtensionEngineImpl.InstallInternal    (InstallableExtensionImpl extension, InstallFlags installFlags, IDictionary`2 extensionsInstalledSoFar, List`1 extensionsUninstalledSoFar,
IInstalledExtensionList modifiedInstalledExtensionsList, AsyncOperation asyncOp, IProgress`1 progress)
at Microsoft.VisualStudio.ExtensionManager.ExtensionEngineImpl.BeginInstall(IInstallableExtension installableExtension, InstallFlags installFlags, AsyncOperation asyncOp)
at Microsoft.VisualStudio.ExtensionManager.ExtensionEngineImpl.InstallWorker(IInstallableExtension extension, InstallFlags installFlags, AsyncOperation asyncOp)
</code>
I checked and found corresponding VSIX file is present in temp folder (C:\Users\xxxxx\AppData\Local\Temp)
Comment: I have the same error, but it raises when extension is to be installed on VS 2012.
Answer: I'm currently having the same problems.  According to this post, repairing the installation might help.


Google API Geocode using JavaScript error when run

Question: I am attempting to print out an address on the console log. However, when I run the code I end up getting an error stating that
{
   "error_message" : "Invalid request. Missing the 'address', 'components', 'latlng' or 'place_id' parameter.",
   "results" : [],
   "status" : "INVALID_REQUEST"
}

I use an npm module called request and am trying to simply print out the address onto the log. I've tried other addresses and keep on running into the same issue. What exactly am I missing here ?
const request = require('request');

    request({
      url: 'https://maps.googleapis.com/maps/api/geocode/json?address%20=%201301%20lombard%20street%20philadelphia',
      //json = true
    }, (error, response, body) => {
      console.log(body);
    });

The formatting seems to be correct, based on the first example given in the link https://www.npmjs.com/package/request
Answer: Remove the %20 (space) after address in the link :)
Comment: When I do that the error I get is different.                                                                                {
   "error_message" : "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account",
   "results" : [],
   "status" : "REQUEST_DENIED"
}
Answer: I use other Google Maps API so going try to help you.
Please use your target address in 'address=1301%20lombard%20street%20philadelphia' format
https://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia&key=PASTE_YOUR_API_KEY
You will need API key. Head over to : https://developers.google.com/maps/documentation/javascript/get-api-key
your response will be :
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "1301",
               "short_name" : "1301",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Lombard Street",
               "short_name" : "Lombard St",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Washington Square West",
               "short_name" : "Washington Square West",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Philadelphia",
               "short_name" : "Philadelphia",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Philadelphia County",
               "short_name" : "Philadelphia County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Pennsylvania",
               "short_name" : "PA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "19147",
               "short_name" : "19147",
               "types" : [ "postal_code" ]
            },
            {
               "long_name" : "1003",
               "short_name" : "1003",
               "types" : [ "postal_code_suffix" ]
            }
         ],
         "formatted_address" : "1301 Lombard St, Philadelphia, PA 19147, USA",
         "geometry" : {
            "location" : {
               "lat" : 39.9444071,
               "lng" : -75.16317189999999
            },
            "location_type" : "RANGE_INTERPOLATED",
            "viewport" : {
               "northeast" : {
                  "lat" : 39.9457560802915,
                  "lng" : -75.16182291970848
               },
               "southwest" : {
                  "lat" : 39.9430581197085,
                  "lng" : -75.16452088029151
               }
            }
         },
         "place_id" : "EiwxMzAxIExvbWJhcmQgU3QsIFBoaWxhZGVscGhpYSwgUEEgMTkxNDcsIFVTQSIbEhkKFAoSCU38VoEkxsaJEedji1ij51aUEJUK",
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}


least value of floor of $z_{1}+z_{2}$

Question:
If $z_{1},z_{2},z_{3},z_{4}$ are the roots of the equation
$z^4+z^3+z^2+z+1=0.$ Then the least value of
$\lfloor |z_{1}+z_{2}|\rfloor +1$ is

Try: From given equation $z^4+z^3+z^2+z+1=0$
$$\frac{z^5-1}{z-1}=0(z-1\neq 0\Rightarrow z\neq 1.)$$
So $$z^5=1\Rightarrow z = (1)^{\frac{1}{5}}=\bigg(\cos 2k\pi+i\sin 2k\pi\bigg)^{\frac{1}{5}}$$
So $$z=e^{i\frac{2k\pi}{5}} = \cos \frac{2k\pi}{5}+i\sin \frac{2k\pi}{5}.$$
For $k=0,1,2,3,4$
So $$z_{i}\in \cos \frac{2k\pi}{5}+i\sin \frac{2k\pi}{5}$$ for $i=1,2,3,4,5.$
Now i did not understand how i find least of $z_{1}+z_{2}.$
could some help me to solve it, thanks
Answer: Note that minimum value of $|z_1+z_2|$ is the minimum magnitude of the vector that can be obtained by the sum of vectors with angle $2\pi /5$ and $4\pi/5$ between them, all having magnitude of $1$ (by geometrical interpretation of $n^{th}$ roots of $1$).
$$|z_1+z_2|=\sqrt{1+1+2\cos\theta}$$
$\cos\theta=0.309$ OR $-0.809$ (corresponding to $72$ and $144$ degrees respectively).
So, $$\text{min}|z_1+z_2|=\sqrt{0.381}\implies \text{ans}=0+1=\boxed{1}.$$
Comment: @AnuragA There are just 2 possible angles. $2\pi/5$ and $4\pi/5$. I hope you know this, because of the angles of a regular pentagon (without visual inspection). I've given both of the possible values. I don't know what you're thinking is wrong with it
Comment: Your claim about the sum of vectors having minimum magnitude while correct only depends on *visual inspection*. A **rigorous argument** would be more appropriate for that.
Comment: @AnuragA I completely disagree. Note that the person asking the question has already written the general form of solutions, it means he has a good understanding of complex numbers. That formula (for z) combined with De Moivre's Rule itself tells you that the roots will be the vertices of $n$ sided regular polygon ($n=5$ in this case), inscribed in a circle with center at origin. Further, the almost every problem related to addition in complex numbers becomes way easier if you treat it as a vector addition. I don't think I need to give any rigurous argument in the favor of my answer
Comment: I am well aware of all the different mathematical stuff you have used but how do you know that those angles are the ones which give you the minimum? Isn't it based on visual inspection.
Answer: Let $\alpha=e^{i\frac{2\pi}{5}}$, then each root of the given equation $z^4+\dotsb+1=0$ is a power of $\alpha$. Let $z_1=\alpha^k$ and $z_2=\alpha^j$, where $k \leq j$ and $k,j \in \{1,2,3,4\}$.
Let us first consider $$|z_1+z_2|=|\alpha^k||1+\alpha^{j-k}|=|1+\alpha^{j-k}|=\sqrt{2}\sqrt{1+\cos\left(\frac{2\pi(j-k)}{5}\right)}=2\left|\cos\left(\frac{2\pi(j-k)}{10}\right)\right|$$
Thus we want to minimize $\color{blue}{\left\lfloor 2\left|\cos\left(\frac{2\pi(j-k)}{10}\right)\right|\right\rfloor +1}$.
Observe that the only possible values of $\left\lfloor 2\left|\cos\left(\frac{2\pi(j-k)}{10}\right)\right|\right\rfloor$ are $0,1,2$ ($\because 0 \leq |\cos \theta| \leq 1$).
We can show that this could be zero. Because $j-k \in \{0,1,2,3,4\}$, therefore $j-k$ can take the value $2$. In which case,
(using the decreasing nature of the cosine function) we have $$\frac{4\pi}{10} > \frac{\pi}{3} \implies \cos\left(\frac{4\pi}{10}\right) < \cos\left(\frac{\pi}{3}\right)=\frac{1}{2}$$
Thus  $\left\lfloor 2\left|\cos\left(\frac{2\pi(j-k)}{10}\right)\right|\right\rfloor$ can take the value $0$. Thus the minimum value of the given expression is $\color{red}{1}$.
Answer:
$$\frac{z^5-1}{z-1}=0(z-1\neq 0\Rightarrow z\neq 1.)$$
So $$z^5=1\Rightarrow z = (1)^{\frac{1}{5}}=\bigg(\cos 2k\pi+i\sin 2k\pi\bigg)^{\frac{1}{5}}$$
So $$z=e^{i\frac{2k\pi}{5}} = \cos \frac{2k\pi}{5}+i\sin \frac{2k\pi}{5}.$$
For $k=0,1,2,3,4$

Not quite. Don't forget that $z \neq 1$, so $k \neq 0$.

$|z_1| = |z_2| = 1$ because they're roots of unity. Therefore $|z_1 + z_2| \le 2$ with equality only when $z_1 = z_2$. Also $0 \le |z_1 + z_2|$ with equality only when $z_1 = -z_2$.
Thus immediately we see that $\lfloor |z_{1}+z_{2}|\rfloor$ is $0$ or $1$.
To see geometrically whether it must be $1$, consider the Argand diagram. If you draw a circle of unit radius centred on the origin, and then a second circle of unit radius centred on $z_1$ (on the circumference of the first circle), by the standard compass-and-ruler construction of a hexagon a third of the circumference of the second circle lies inside the first circle. Therefore the question is whether any of the other roots lie in that third when we translate the second circle back to the first circle, and the answer is obviously yes, since they're spaced every fifth of the circumference.

Alternatively, taking a more algebraic approach: since the coefficients are real, roots occur in conjugate pairs. It suffices to find a root whose real part is in the range $(-\tfrac12, \tfrac12)$.

least value of floor of $z_{1}+z_{2}$


how to extract last and first rows of numpy array having specific values

Question: I hae a list of numpy arrays and want to xport some rows of each array. My list is:
all_data=[np.array([[1., 1., 2.], [2., 1., 4.], [3., 1., 5.], [1., 2., 4.]]),\
          np.array([[3., 1., 3.], [4., 1., 4.], [3., 2., 7.], [4., 2., 1.]]),\
          np.array([[0., 0., 0.], [1., 1., 1.], [3., 1., 0.], [4., 2., 4.]]),\
          np.array([[2., 2., 2.], [3., 2., 1.], [4., 2., 5.], [5., 2., 4.]])]

My all_data has four arrays here (in reality it has much more). In each array I am firstly interested in knowing how many unique or repeated values are existing in the second column. Than, for even array, I wan to extract the last row of the rows having the same value in their second column. If a row has a unique value, I only extract that row. For odd arrays, I want to extrat the first row of the rows having the same value in their second column and again for rows with unique values, I extract that single row. Finally, I want the following list of array and my output:
[np.array([[3., 1., 5.], [1., 2., 4.]]),\
 np.array([[3., 1., 3.], [3., 2., 7.]]),\
 np.array([[0., 0., 0.], [3., 1., 0.], [4., 2., 4.]]),\
 np.array([[2., 2., 2.]])]

I tried the following code but it was not successful at all.
extracted=[]
for i,h in enumerate (all_data):
    nums, counts=np.unique(h[:,1],return_counts=True) # to find the frequency of values in second column
    if i%2 ==0:
        a=np.where(np.isin(h[:,1],nums).any(-1))[-1]
    else:
        a=np.where(np.isin(h[:,1],nums).any(-1))[0]
    extracted.append (a)

I do appreciate any help in advance.
Answer: To get "wanted" rows from arr (array No i from all_data)
define the following function:
def getRows(i, arr):
    vals, inv, cnts = np.unique(arr[:, 1], return_inverse=True, return_counts=True)
    rows = [inv.size - np.argmax(inv[::-1] == iCnt) - 1 if i % 2 == 0 else\
        np.argmax(inv == iCnt) for iCnt in range(len(cnts))]
    return arr[rows]

Then, to get the extracted rows from each array, as a separate array
from each source array, run the following list comprehension:
extracted = [getRows(i, arr) for i, arr in enumerate(all_data)]

For your data sample the result is:
[array([[3., 1., 5.], [1., 2., 4.]]),
 array([[3., 1., 3.], [3., 2., 7.]]),
 array([[0., 0., 0.], [3., 1., 0.], [4., 2., 4.]]),
 array([[2., 2., 2.]])]

Answer: numpy's array has an usefull feature: indexing using ellipsis. Example:
arr = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
arr[...,-1]

Doks (search for ...)


Interpret ANOVA analysis of model fit IRT, TAM Package

Question: I posted this question on Stack Overflow, but was advised to post it here.
I fitted the same data set to a 1PL item response theory model (called onePL below), and then to a 2PL item response theory model (called twoPL) below.. Subsequently, I ran an ANOVA analysis to investigate which model had the best fit (using anova(onePL, twoPL). I used the TAM package. Is anybody here familiar with interperting the output of such an ANOVA analysis? In the attached picture it looks like model 1 had a better fit, but surely, that's incorrect?
I would be very grateful for any help or suggestions.

Model
loglike
Deviance
Npars
AIC
BIC
Chisq
df
p

onePL
4499.997
8999.994
7
9013.994
9050.36
46.96485
5
0

twoPL
4476.514
8953.029
12
8977.029
9039.371
NA
NA
NA
Answer: looks like your data has 6 items. In the onePL model you estimate 6 difficulty parameters and one variance parameter of the latent trait distribution, in total 7 parameters.
In the twoPL model you estimate 6 difficulty and 6 discrimination parameters (location and variance of the latent trait distribution is fixed), in total 12 parameters.
In the anova the test statistics is the differences between the deviances (which are $-2*log(likelihood)$; noted in the column Deviance). Note that the entries in the loglike-columns should be negative (check your results). The differences between the deviances is 46.965. Now check this against the $\chi^2$ distribution with 5 degrees of freedom (differences in the number of parameters; df). Using 1-pchisq(8999.994-8953.029, 5) (which results in the p column value) can be interpreted as the probability that the differences in the model fit (i.e., deviances)  is due to chance, given 5 more parameters.
Note that AIC and BIC (lower is better) agree that the 5 additional parameters help improving the model fit.
Comment: Dear @Tom, many thanks for your answer! It certainly clarifies things. I guess I was confused by the layout of the table - to me it looked like the `onePL` was significantly better given that the p-value was reported on that line. (In the original output the _loglike_ values were indeed negative (a copy error of mine). Again: thanks!


GridView with uniform column size

Question: I have this GridLayout:

        <GridLayout
            android:id="@+id/back"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:rowCount="3"
            android:columnCount="5">

            <ImageView
                android:src="@drawable/noTexture"/>

            <ImageView
                android:src="@drawable/noTexture"/>

            <ImageView
                android:src="@drawable/noTexture"/>

            <ImageView
                android:src="@drawable/noTexture"/>

            <ImageView
                android:src="@drawable/noTexture"/>

            <ImageView
                android:src="@drawable/noTexture"/>

            <ImageView
                android:src="@drawable/noTexture"/>

            <ImageView
                android:src="@drawable/noTexture"/>
            <ImageView
                android:src="@drawable/noTexture"/>

            <ImageView
                android:src="@drawable/noTexture"/>

        </GridLayout>

The images contained therein look like this:

How to make the images distribute on the screen in a uniform way, ie, occupy all the space until the end so that both have the same size?
Comment: Add title in English .
Comment: @ADM sorry for this
Comment: Your question is unclear you have more than one imageView but you are asking about only two images taking whole space.
Comment: @Prashant I mean, like, all the imageViews are organized evenly occupying the entire layout
Answer: Add the following attributes to all of the imageViews
app:layout_columnWeight="1"
app:layout_rowWeight="1"

For example:
 <GridLayout
    android:id="@+id/back"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:rowCount="3"
    android:columnCount="5">

        <ImageView
           app:layout_columnWeight="1"
           app:layout_rowWeight="1"
           android:src="@drawable/noTexture"/>

  ..............

Do as above to all imageViews.
Answer: You must set the limit for each box as follows:
  <?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>

java Code :
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this));

    gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            Toast.makeText(HelloGridView.this, "" + position,
                    Toast.LENGTH_SHORT).show();
        }
    });
}

for kotlin try this :
// references to our images
private val mThumbIds = arrayOf<Int>(
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7)

class ImageAdapter(private val mContext: Context) : BaseAdapter() {

    override fun getCount(): Int = mThumbIds.size

    override fun getItem(position: Int): Any? = null

    override fun getItemId(position: Int): Long = 0L

    // create a new ImageView for each item referenced by the Adapter
    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val imageView: ImageView
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = ImageView(mContext)
            imageView.layoutParams = ViewGroup.LayoutParams(85, 85)
            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
            imageView.setPadding(8, 8, 8, 8)
        } else {
            imageView = convertView as ImageView
        }

        imageView.setImageResource(mThumbIds[position])
        return imageView
    }
}

learn more about GridView : Click this

GridView with uniform column size


The coefficent of x

Question: I was wondering if this question is really teasing me.

$f(x)=x^2+bx+c$, where $b=-17$ and $c=52$. What is the coefficient of $x^2$ in the function $f(f(x))$?

So basically the coefficent will be 1?
Comment: You can just figure out what $f(f(x))$ is.  It would take a minute or two to do.  Then, you can see what the answer is.  I don't know what the coefficient will be, but I don't think it'll be 1.  1 would be the coefficient of $x^4$, if that's what you're thinking.
Answer: $$f(f(x))=(x^2+bx+c)^2+b(x^2+bx+c)+c=x^4+...+(b^2+b+2c)x^2+...$$
Comment: Correction: the cross-terms in $(x^2 + bx + c)^2$ give you a contribution of $2cx^2$, not $cx^2$.
Comment: Indeed, thanx...
Answer: $f(f(x)) = f(x)^2 + b f(x) + c = (x^2 + bx + c)^2 + b (x^2 + bx + c) + c$.
Now $(x^2 + bx + c)^2 = (x^2 + bx+c)(x^2 + bx + c) =$
$x^4 + 2bx^3 + (2c+b^2)x^2 + 2 b c x + c^2$.
In total, $x^2$ thus has the coefficient $2c+b^2 + b$, where the last $b$ comes from the linear term in the first line.
Comment: this is pretty clear, will try this out
Answer: No. Substitute $f(x)$ in place of $x$ and expand:
$$f(f(x))=f(x)^2+b\cdot f(x)+c = ...$$
Since now you're interested only in the coefficient of $x^2$, count only those:
something like $b^2+2c\ +b$.

The coefficent of x


Users database empty after Samba3 to Samba4 migration on different servers

Question: I have to migrate a Samba 3 to a new Samba 4 server.
My problem is that the database on the samba 3 server seems a bit empty. The secrets.dtb file is only 20K whereas the "pbedit -L |wc -l"command give me 16970 lines.
On my Samba3 /var/lib/samba is 1,5M
After I had migrate the databse (following instructions on http://dev.tranquil.it/index.php/SAMBA_-_Migration_Samba3_Samba4),  "pdbedit -L" command on the new server give me only : SAMBA4$, Administrator, dns-samba4, krbtgt and nobody.
So I tried to create a VM with a Samba3. I added some users, done the same things I did for the migration and now I can see the users created on the VM.
It's like users on the Samba 3 server are in a sort of cache.
I already migrate the /etc/{passwd,shadow,group} files and I can see users with the "getent passwd" command.
Any ideas why my users are present when I use pdbedit but the database is so empty ?
The global part of my smb.conf on the Samba 3 server :
<code>  [global]
   workgroup = INTERNET
   netbios name = PDC-SMB3
   server string = %h server
   interfaces = eth0
   obey pam restrictions = Yes
   passdb backend = smbpasswd
   passwd program = /usr/bin/passwd %u
   passwd chat = *new* %n\n *Re* %n\n *pa*
   username map = /etc/samba/smbusers
   unix password sync = Yes
   syslog = 0
   log file = /var/log/samba/log.%U
   max log size = 1000
   socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192
   add user script = /usr/sbin/useradd -s /bin/false -m '%u' -g users
   delete user script = /usr/sbin/userdel -r '%u'
   add group script = /usr/sbin/groupadd '%g'
   delete group script = /usr/sbin/groupdel '%g'
   add user to group script = /usr/sbin/usermod -G '%g' '%u'
   add machine script = /usr/sbin/useradd -s /bin/false -d /dev/null '%u' -g machines
   logon script = logon.cmd
   logon home = \\$L\%U
   domain logons = Yes
   os level = 255
   preferred master = Yes
   local master = Yes
   domain master = Yes
   dns proxy = No
   ldap ssl = no
   panic action = /usr/share/samba/panic-action %d
   invalid users = root
   admin users = admin, root, administrateur
   log level = 2
</code>
Answer: I find a way to do it.
I used "pdbedit -e smbpasswd:/root/samba-users.bak" on the Samba 3 server to export users. Then I did a "pdbedit -i /root/samba-users.bak" on the Samba 4 server where /root/samba-users.bak is the file that I copied from the Samba 3 server.
Of course, I already imported users from the old server to the new one.
Comment: correct:
pdbedit -i smbpasswd:/root/samba-users.bak


Como eu poderia substituir uma linha de vários arquivos txt que viriam de um output do ls -l?

Question: O que eu gostaria de fazer é mais ou menos isso:
ls -l | xargs sed 's/regex do padrão que quero substituir/novos dados/g'
para cada output do ls, uma substituição é feita dentro do arquivo usando o sed. Dá pra fazer? Teria um jeito mais eficiente?
Comment: `sed -i 's/dadosAntigos/novosDatas/g'  *.txt` ?
Answer: Consegui achar uma alternativa para editar todos os arquivos dentro do diretório:
sudo find . -type f -name "*.txt" | xargs sed -i "s/dadosAntigos/novosDatas/g"


Inserir valores em lista

Question: Estou fazendo um exercício de Python que pede para o usuário colocar cinco números de 1 a 5, se o usuário digitar um numero que não atenda esse critério retorne um erro e não inclua o nº na lista
fiz dessa forma:
lista = int(input("digite um numero de 1 a 5"))

if lista > 1  and  lista < 5:
    print("Excelente")
else:
    print("numero invalido")

print(lista)

mas não sei se está certo, pois o correto seria incluir uma lista entre colchetes
como posso fazer isso?
Answer: Uma maneira simples de instanciar uma lista e inserir elementos nesta lista, seria utilizando o comando condicional while.
Para criar um fluxo em que o usuário fique "preso" em um laço até que ele insira 5 elementos e esses mesmos elementos estejam dentro do intervalo de 1 a 5. Seria uma lógica bem parecida com a que já implementou, porém seria necessário algumas coisas a mais.
A lógica, descrita em linguagem natural seria:

criar uma lista vazia
verificar o tamanho da lista, caso a lista possua o tamanho menor que 5, faça
ler um número fornecido pelo usuário
verificar se o número fornecidos está no intervalo desejado [1:5], caso façam parte do intervalo adicionar na lista senão perguntar novamente
repetir passo 2, 3 e 4.

Acima descrevemos o algoritmo que queremos implementar, a partir desta lógica basta agora transformar essas informações em código Python, uma das perguntas que pode surgir ao implementar é porque utilizar o while? O motivo é que teremos um número indeterminado de repetições a fazer, desta forma é recomendado usar o while. Este número é indeterminado pois será no mínimo cinco repetições (supondo que os números digitados estejam todos dentro do intervalo e o que ao preencher não haja erros). O usuário será obrigado a preencher os números até que o tamanho da lista seja 5. Mas não temos garantia de quantas vezes o laço será repetido. Isso justifica o uso do while.
lista = []

while len(lista) < 5:
    n = int(input('Digite um numero: '))
    if 1 <= n <= 5:
        lista.append(n)
print(lista)

Verifique que assim seria uma implementação simples, existem alguns problemas em relação à tratamento de erro. Para tratar os erros devemos utilizar um bloco try ... except para evitar que o nosso programa pare a execução ao encontrar o primeiro erro.
Outro ponto é a escrita do condicional, em Python é possível escrever o condicional desta maneira:
if 1 < n < 5: # <-- Veja como estamos comparando a igualdade

Porém isso só funciona em Python, então o melhor seria utilizar como você fez, que é uma abordagem mais universal usada em todas as linguagens de programação:
if n > 1  and  n < 5:

Assim uma implementação mais robusta seria:
lista = []

while len(lista) < 5:
    try:
        n = int(input('Digite um número: '))
        if 1 <= n <= 5:
            lista.append(n)
    except ValueError:
        print('Número inválido, tente novamente')

print(lista)

Aprenda mais sobre as funções utilizadas neste código.
Função len, bloco try..except, comando while
Comment: Obrigado vou tentar aqui, mas seria uma coisa mais simples a principio, mas essa solução foi legal

Inserir valores em lista


Prove that limsup of a sum of iid random variables(with 0 expectation) is infinity

Question: Let $Y_1, Y_2, Y_3,\ldots,Y_n,\ldots$ be iid and bounded random variables with $E[Y_1]=0$. Define $X_n = Y_1+Y_2+ \cdots + Y_n$.
If $\Pr(Y_1 \neq 0) \gt 0$, then $ \limsup X_n = \infty$ with probability $1$.
The conclusion seems intuitive, but how would I approach it rigorously?
Comment: Hint: If you assume $\limsup  X_n$ is a finite number ... can you show this leads to a contradiction?
Answer: Suppose that $ \limsup X_n = b$ for some $b \in \mathbb{R}$. We know that $|Y_i| \leq c$ for some $c \in \mathbb{R}^{+}$. So $X_n \leq nc$. Now for some large $N$, $n \geq N$ means that $X_n \leq b$. But we can choose a large enough $n$ (say $m$) such that $b < X_m \leq mc$.
Note: This is just my attempt. Please feel free to continue OP.
Comment: I'm not sure if this is meant as a hint or a proof. Hints are preferred for homework-style questions. That being said, your last sentence needs motivation: perhaps the OP can supply this.


Bayesian regression dependencies

Question: I am revising Bayesian linear regression from Bishop's book and the following material. In page 275 it provides the formula for the posterior distribution, which, in Bishop's book is the following:
$$ \underbrace{p(\theta|D)}_{\text{posterior}} =\frac{\overbrace{p(\theta)}^{\text{prior}}\overbrace{p(D|\theta)}^{\text{likelihood}}}{\underbrace{p(D)}_{\text{evidence}}}=\frac{\overbrace{p(\theta)}^{\text{prior}}\overbrace{p(D|\theta)}^{\text{likelihood}}}{\underbrace{\int p(\theta)p(D|\theta)d\theta}_{\text{evidence}}} $$
which D represents our data. In the hyperlinked material the same equation it is phrased as:
$$p(\mathbf \theta |Y,X) = \frac{p(Y|X,\mathbf{\theta}) p(\mathbf{\theta})}{p(Y|X)}$$
where $\mathbf{x}_{n} \in \mathbb{R}^{D}$ is the one of the vector for the matrix $X$ with the correspondent label to be $y_{n} \in \mathbb{R}$ and $\mathbf{\theta}$ the regression parameters. I guess roughly $D = \{X, Y\}$.
My question is that I am struggling to understand the likelihood in the second equation. Why is it $p(Y|X,\mathbf{\theta})$ and not $p(Y, X| \mathbf{\theta}$). The same for the evidence. Also what exactly is the interpretation of $p(Y|X)$ and $p(X|Y)$.
Answer: Bayes rule is a way of "inverting" any joint distribution, even one conditioned on other things. Consider the joint distribution for $A$ and $B$ conditioned on $C$, which can be factored two ways:
\begin{equation}
\begin{split}
p(A,B|C) &= p(A|B,C)\,p(B|C) \\
&= p(B|A,C)\,p(A|C) .
\end{split}
\end{equation}
One way of applying Bayes rule to the two factorizations delivers
\begin{equation}
p(A|B,C) = \frac{p(B|A,C)\,p(A|C)}{p(B|C)} ,
\end{equation}
where
\begin{equation}
p(B|C) = \int p(B|A,C)\,p(A|C)\,dA .
\end{equation}
To accommodate the first example, we can let $A = \theta$, $B=D$, and (because there is no conditioning with respect to the joint distribution in the first example) $C = \varnothing$ [the empty set].
To accommodate the second example, we can let $A = \theta$, $B = Y$, and $C = X$.
The upshot is this: where a particular thing appears in Bayes rule is not determined by whether or not the thing is "data", but whether or not it is being conditioned on in the joint distribuiton.
But we are not done with the second example because something doesn't match. The second example has $p(\theta)$ but our use of the general statement produces $p(\theta|X)$. What's going on here? The answer is that the second example has a special assumption built into it:
\begin{equation}
p(\theta|X) = p(\theta) .
\end{equation}
In other words, the prior for $\theta$ doesn't depend on the "covariates" $X$. This assumption is one that is usually made, so that's not what makes it "special." The assumption is special because it asserts something beyond what Bayes rule by itself says.
Thus far I've addressed the questions about the form of the likelihood and of the evidence. Once one accepts these forms, I'm not sure what there is to say of the interpretation of $p(Y|X)$.
Comment: That is surely a very nice answer I have to admit. Thanks a lot.
Comment: For the last part of my question, I was wondering more about the verbal meaning of the conditions in the case of the ML setting. So for instance $P(X|Y)$ means sth like given that we observe labels $Y$ what is the probability to have a specific type of data $X$? Or in the case of $P(X|\theta)$: given the parameters $\theta$ what is the probability observing data $X$.

Bayesian regression dependencies


Fruityloops not playing certain notes

Question: I'm new to Fruityloops and sound editing software in general and I wanted to learn more about it. I wanted to recreate a song I like and learn from that process.
Sadly I'm already encountering problems I cant seem to fix myself. There are certain notes that Fruityloops just wont play if there's is another pattern playing at the same time.
In the video provided you can see pattern one and two playing, pattern two is mainly just some short bursts of F#4 and note 1 and 6 of pattern one are also F#4. When both both patterns need to play an f#4 at the same time pattern one stays silent. When I remove pattern two it pattern one DOES play those notes. Does anyone know what's causing this?
Here's a picture of my two patterns:

Here´s the video where you can see the problem:
Comment: So I never really found out why it didn't play, you'd think the software would understand that even if I use the same instrument that if it's a different pattern it should treat it as two instruments.

But duplicating the instrument fixed the problem for me, if anyone ever finds out why this happened and whether there is a better solution to fix this then I'd love to hear it.
Answer: It does sound like a conflict in triggers.
Some generators default to monophonic or polyphonic.  Clicking on the generator brings up a window which shows you the sample or instrument you are using.  There are tabs which allow you look through the options.  I haven't use FLStudio in a while to recall which tab it is under but my mind keeps thinking it is in the third tab.  There will be a button for MONO or POLY.
This might not be your problem and I'm thinking it is.  FLStudio and other programs do not accept simultaneous triggers on a single generator.  If in your two rolls you desire the F#4 to be played by both instances at the same time, FL Studio will throw its hands up in the air.  If you delay one channels request for that note, the note that comes last will be the note that plays until the end.  So if your 16th note comes before your quarter note by a 32nd note, the 16th note will be played for a duration of a 32nd while the quarter note will play for both.  Also note that the envelope will also be triggered, so you will notice that the tone might not be played continuously.

Fruityloops not playing certain notes


Postfix, Dovecot - connection from outside, authentication

Question: I want to run postfix + dovecot on my server. I'm doing it for first time. Postfix and Dovecot works on local - I can connect through telnet, and send/receive e-mails using commands.
When I try to connect from outside, using mail client (in my case Thunderbird), I always see in client alert: Authentication failed.
My /var/log/maillog file says:
dovecot: pop3-login: Disconnected: Shutting down (auth failed, 6 attempts): user=<test.user>, method=PLAIN, rip=xxx.xxx.xxx, lip=xxx.xxx.xxx.
Distribution is CentOS 6
EDIT (postconf -n):
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
config_directory = /etc/postfix
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
debug_peer_level = 2
home_mailbox = Maildir/
html_directory = no
inet_interfaces = all
inet_protocols = all
mail_owner = postfix
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mydomain = mydomain.com
myhostname = host.mydomain.com
mynetworks = xxx.xxx.xxx/24 127.0.0.0/8
mynetworks_style = subnet
myorigin = $mydomain
newaliases_path = /usr/bin/newaliases.postfix
queue_directory = /var/spool/postfix
readme_directory = /usr/share/doc/postfix-2.6.6/README_FILES
sample_directory = /usr/share/doc/postfix-2.6.6/samples
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
unknown_local_recipient_reject_code = 550

When I want to send an e-mail to outside host from Thunderbird, I get 5.7.1 <email@example.com>: Relay access denied.
Error log for this:
NOQUEUE: reject: RCPT from my_vps_domain[xxx.xxx.xxx.xxx]: 554 5.7.1 <email@example.com>: Relay access denied; from=<email@example.com> to=<firstname.lastname@example.com> proto=ESMTP helo=<[127.0.0.1]>
Answer: You should post the contents of your 10-auth.conf and all the auth* snippet config files. There's any number of things that can be going wrong. You can start troubleshooting here:
http://wiki2.dovecot.org/TestPop3Installation
and you can turn on debug logging with the "auth_debug" and "auth_verbose" directives.
http://wiki2.dovecot.org/Debugging/Authentication
Comment: Thank you. Dovecot problem solved, but still I have problem with sending emails from mail client. Can you look at postconf in 1st post?
Answer: Here the explanation for second part of your problem:
Here, postfix rejected attempt to send email via mail client with error "Relay access denied". It means thunderbird doesn't attempt to do SMTP AUTH so it doesn't permitted with configuration permit_sasl_authenticated.
Based on the output of postconf -n, you seems haven't enable SASL authentication in postfix. That's why Thunderbird doesn't authenticated himself thus caused email rejected.
You can find the tutorial about enabling SASL in postfix official docs.


Simple AJAX callback fired on form submission button click

Question: I am trying to fire an AJAX callback when the user presses the submit button. This is such a simple thing but trying to debug Drupal's Form AJAX API is driving me crazy. At this point I just need a fresh set of eyes to look over it. Currently, when I press the button the page just refreshes and the AJAX callback is never fired. I have a form being built with the following code:
class OnlineRevenueForm extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['resetbutton'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
        '#prefix' => '
',
        '#suffix' => '
',
        '#ajax' => array(
            'callback' => 'Drupal\revenue_projection_model\Controller\RPMController::ResetFields',
            'event' => 'click',
            'progress' => array(
                'type' => 'throbber',
                'message' => NULL,
            ),
        )
    );
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild(FALSE);
  }
}

Inside of my controller I load this form using the following code:
class RPMController extends ControllerBase implements ContainerInjectionInterface {
 public function rpm() {
    // Load the module's template file
    $TemplateFilePath = drupal_get_path('module', 'revenue_projection_model') . "/templates/revenue_projection_model.html.twig";
    $template = $this->twig->loadTemplate($TemplateFilePath);
    //Load Forms
    $OnlineRevForm = \Drupal::formBuilder()->getForm('Drupal\revenue_projection_model\Form\OnlineRevenueForm');
        $markup = [
         '#type' => 'inline_template',
         '#template' => $template->render(
            ['online_rev_form' => $OnlineRevForm]
         )
        ];
   return $markup;
 }

This form is then displayed via the twig template file. The callback that I'm trying to call is also inside of the Controller:
public static function ResetFields(array &$form, FormStateInterface $form_state) {
     $ajax_response = new AjaxResponse();
     $ajax_response -> addCommand(new AlertCommand("Testing"));
     return $ajax_response;
}

Update 1:
I have updated how the form is being return in the controller. It is now being returned as a unrendered form in a render array.
public function rpm() {
  $OnlineRevForm = \Drupal::formBuilder()->getForm('Drupal\revenue_projection_model\Form\OnlineRevenueForm');
  return [
        '#theme' => 'rpm_page',
        '#online_rev_form' => $OnlineRevForm
  ];
}

I have also added this code to the .module file:
function revenue_projection_model_theme() {
  $theme['rpm_page'] = [
    'variables' => ['online_rev_form' => NULL],
    'template' => 'revenue_projection_model',
  ];

  return $theme;
}

Comment: Why not use a form route `_form: Drupal\example\Form\ExampleForm` instead of a controller?
Comment: @4k4 There is more logic going on the page that is unrelated to the said form. Whether I'm using a controller or just a form route, I should still be able to fire the callback from the form.
Comment: No, this can't work. You lose the attachments of the form on the way and without the attached libraries there is no ajax. Don't render the form, the controller should return it unrendered. If you use a twig template, then build a render array for it, with the form placed unrendered in a template variable.
Comment: @4k4 I have updated the code to include the suggestions that you made. unfortunately, I'm running into the same problem. Any suggestions or ways to better debug this?
Comment: The controller looks good now. I think you should see some progress with the ajax js libraries. You can check this in the browser debugging tools, before and after you've changed the controller.
Comment: Remove the 'click' event.
Answer: You also need a submit function.
You can have a look here. It's a complete example with submit handler and callback. In this case I altered the form as I didn't create it but is quite similar. Also a really nice post is here
Comment: I should have made note of that in the original post. I do have a submit form function already defined. I have updated the post to reflect this.