Correct format for a Base Encryption string for Oauth 1.0 for a PATCH request

Question: Does anyone know what the correct format is for a base encryption string in Oauth 1.0 for a request? I tried the formats below, I test them against a Python Oauth library, and so far I have been unable to generate the correct Oauth signature.
POST&https://api.example.com/api/v2/image?_method=PATCH&oauth_consumer_key=...
PATCH&https://api.example.com/api/v2/image?_method=PATCH&oauth_consumer_key=...
PATCH&https://api.example.com/api/v2/image?&oauth_consumer_key=...

Answer: Ok, I figured out the issue, the correct format (at least for the SmugMug API) is:
POST&https://api.smugmug.com/api/v2/image/F6qBW8x-4&_method=PATCH&oauth_consumer_key=...

And the "&" before "&_method" should not be encoded before hashing the signature. Quite confusing.


Como eu uso o addObject dentro de um Array?

Question: Eu tenho um NSMutableArray *arrayFavoritos
No log consigo ver
{
        name1 = 6;
        name2 = "Paolo Rossi\nIt\U00e1lia";
        name3 = "cartaz-1982.jpg";
        photo = "copa8.jpg";
        name4 = 24;
    },
        {
        name1 = 6;
        name2 = "Oleg Salenko\nR\U00fassia";
        name3 = "cartaz-1994.jpg";
        photo = "copa5.jpg";
        name4 = 24;
    },

EU preciso transformar essa informação:
self.tableItems = @[[UIImage imageNamed:@"photo1.jpg"],
                        [UIImage imageNamed:@"photo2.jpg"],
                        [UIImage imageNamed:@"photo3.jpg"]];

Para que esse array seja montado dinamicamente
Como eu posso fazer isso?
Comment: Você tem uma array de objetos no primeiro código certo? Qual é o valor do objeto que interessa para você compor o tableItems?
Answer: Se eu entendi corretamente, você precisa gerar um vetor de objetos UIImage baseado em um outro vetor que contém dicionários cuja chave relevante é chamada photo. Nesse caso, você pode simplesmente percorrer o vetor original, extrair a string correspondente à chave photo e usá-la para construir um objeto do tipo UIImage, adicionando-o a outro vetor:
NSMutableArray photos = [NSMutableArray array];
// arrayFavoritos contém elementos de tipo NSDictionary…
for (NSDictionary *photoData in arrayFavoritos) {
    // …e cada dictionary contém um par chave-valor com chave photo…
    NSString *photoName = photoData[@"photo"]; // nil caso não exista
    if (photoName != nil) {
        // …que é usada para construir um objeto UIImage
        [photos addObject:[UIImage imageNamed:photoName]];
    }
}
self.tableItems = photos;

Se você quiser extrair apenas os nomes das fotos, sem construir objetos UIImage, você pode usar KVC:
NSArray *photoNames = [arrayFavoritos valueForKey:@"photo"];

O vetor photoNames conterá ou strings com o valor de photo para cada elemento de arrayFavoritos, ou [NSNull null] para os casos onde não há uma chave chamada photo.


Why is 10.0.0.1/28 not a valid subnet within a VPC of 10.0.0.0/24?

Question: How to create Multiple Subnets within Range 10.0.0.0/24.
Tried creating 10.0.0.1/28 . It tells it should be within the CIDR Range.
I am sure am making something wrong . Please advise.
Answer: If you have a VPC has : 10.0.0.0/24. then you want to create some subnets are being this VPC.
If you want to create subnet with /28 so:
10.0.0.0/28
10.0.0.16/28
10.0.0.32/28
10.0.0.48/28
10.0.0.64/28
............
10.0.0.240/28

If you want to create subnet with /26:
10.0.0.0/26
10.0.0.64/26
10.0.0.128/26
10.0.0.192/26
Answer: The message is misleading. It is not like 10.0.0.1/28 is not within the CIDR range of 10.0.0.0/24, it simply is an incorrect network ID (the message could be slightly more helpful I guess).
You can only specify network ID, not a network address. In your case 10.0.0.1/28 is the first network address from range 10.0.0.0 - 10.0.0.15 where 10.0.0.0/28 is the network ID that you need to use instead. The next network ID for /28 prefix length is 10.0.0.16 as it was mentioned in the other answer.
This is given by subnetting rules. Long story short, if you need to know network IDs then just subtract the prefix, in this case 28 from 32 (32 bits of IPv4 address) which gives you 4 usable bits for hosts which translates to 2^4 = 16 block size. Therefore you can start with 10.0.0.0 and continue by adding 16 to the last number 0, 16, 32, 48, ... and the same goes for the other prefixes as well (or at least if you consider any prefix longer or equal to 24, it kind of works for shorter prefixes as well but you need to be careful which octet of IP address you are modifying).
It is also worth mentioning that the 10.0.0.1/28 is not even a usable IP address on AWS because AWS reserves first 4 and the last one IP address of each subnet (first 4, including network ID, are used for stuff such as DHCP server in your subnet which you don't directly see and the last one is broadcast address which, in general, cannot be assigned to any host, moreover AWS doesn't even support broadcasts).
So technically, when you use 10.0.0.0/28 subnet, you will end up with 11 available IP addresses ranging from 10.0.0.4 to 10.0.0.14.


fail2ban custom action to permanent ban IPs from China

Question: When a IP address gets banned how can I check if the banned IP address is from China. If yes, then add it to the permanent ban list.
I have found this nice guide which write the banned IP to file.
Reason: I am getting a lot of brute force attacks from China daily, thankfully fail2ban is helping restrict this although they appear to be getting worse and they are just changing their IP Address.
Or even better would be if there was a maintained database of known hacker IP addresses.
Example 1
Hi,

The IP 188.8.131.52 has just been banned by Fail2Ban after
4 attempts against vsftpd.

Here are more information about 188.8.131.52:

% [whois.apnic.net node-7]
% Whois data copyright terms    http://www.apnic.net/db/dbcopyright.html

inetnum:        184.108.40.206 - 22.214.171.124
netname:        CHINANET-AH
descr:          CHINANET anhui province network
descr:          China Telecom
descr:          A12,Xin-Jie-Kou-Wai Street
descr:          Beijing 100088
country:        CN
admin-c:        CH93-AP
tech-c:         JW89-AP
mnt-by:         APNIC-HM
mnt-routes:     MAINT-CHINANET-AH
mnt-lower:      MAINT-CHINANET-AH
status:         ALLOCATED PORTABLE
changed:        firstname.lastname@example.com 20040721
source:         APNIC

person:         Chinanet Hostmaster
nic-hdl:        CH93-AP
e-mail:         email@example.com
address:        No.31 ,jingrong street,beijing
address:        100032
phone:          +86-10-58501724
fax-no:         +86-10-58501724
country:        CN
changed:        email@example.com 20070416
mnt-by:         MAINT-CHINANET
source:         APNIC

person:         Jinneng Wang
address:        17/F, Postal Building No.120 Changjiang
address:        Middle Road, Hefei, Anhui, China
country:        CN
phone:          +86-551-2659073
fax-no:         +86-551-2659287
e-mail:         email@example.com
nic-hdl:        JW89-AP
mnt-by:         MAINT-NEW
changed:        email@example.com 19990818
source:         APNIC

Regards,

Fail2Ban

Example 2
Hi,

The IP 126.96.36.199 has just been banned by Fail2Ban after
4 attempts against vsftpd.

Here are more information about 184.108.40.206:

% [whois.apnic.net node-6]
% Whois data copyright terms    http://www.apnic.net/db/dbcopyright.html

inetnum:        184.108.40.206 - 184.108.40.206
netname:        CHINANET-AH
descr:          CHINANET anhui province network
descr:          China Telecom
descr:          A12,Xin-Jie-Kou-Wai Street
descr:          Beijing 100088
country:        CN
admin-c:        CH93-AP
tech-c:         JW89-AP
mnt-by:         APNIC-HM
mnt-routes:     MAINT-CHINANET-AH
mnt-lower:      MAINT-CHINANET-AH
status:         ALLOCATED PORTABLE
changed:        email@example.com 20040721
source:         APNIC

person:         Chinanet Hostmaster
nic-hdl:        CH93-AP
e-mail:         email@example.com
address:        No.31 ,jingrong street,beijing
address:        100032
phone:          +86-10-58501724
fax-no:         +86-10-58501724
country:        CN
changed:        firstname.lastname@example.com 20070416
mnt-by:         MAINT-CHINANET
source:         APNIC

person:         Jinneng Wang
address:        17/F, Postal Building No.120 Changjiang
address:        Middle Road, Hefei, Anhui, China
country:        CN
phone:          +86-551-2659073
fax-no:         +86-551-2659287
e-mail:         email@example.com
nic-hdl:        JW89-AP
mnt-by:         MAINT-NEW
changed:        email@example.com 19990818
source:         APNIC

Regards,

Fail2Ban

Example 3
Hi,

The IP 22.214.171.124 has just been banned by Fail2Ban after
4 attempts against vsftpd.

Here are more information about 184.108.40.206:

% [whois.apnic.net node-6]
% Whois data copyright terms    http://www.apnic.net/db/dbcopyright.html

inetnum:        18.104.22.168 - 126.96.36.199
netname:        LCZFFHQ
country:        CN
descr:          liaochenggovermentfanghuoqiang
admin-c:        DS95-AP
tech-c:         DS95-AP
status:         ASSIGNED NON-PORTABLE
changed:        firstname.lastname@example.com 20060122
mnt-by:         MAINT-CNCGROUP-SD
source:         APNIC

route:          18.104.22.168/14
descr:          CNC Group CHINA169 Shandong Province Network
country:        CN
origin:         AS4837
mnt-by:         MAINT-CNCGROUP-RR
changed:        firstname.lastname@example.com 20060118
source:         APNIC

person:         Data Communication Bureau Shandong
nic-hdl:        DS95-AP
e-mail:         firstname.lastname@example.com
address:        No.77 Jingsan Road,Jinan,Shandong,P.R.China
phone:          +86-531-6052611
fax-no:         +86-531-6052414
country:        CN
changed:        email@example.com 20050330
mnt-by:         MAINT-CNCGROUP-SD
source:         APNIC

Regards,

Fail2Ban

Answer: Instead of using Whois for this I would recommend to use an available GeoIP database like http://www.maxmind.com/download/geoip/database/
Most programming languages (like PHP, Python, Perl, ...) have bindings to parse those formats easily.
A "hacker IP" database wouldn't really make any sense anymore today, especially due to:

IPv4 IPs changing owners very rapidly
Ownership and usage of an IP is ambiguous due to widespread botnets
Adoption of IPv6 (finally!) makes the first problem worse and keeping a database of 2^128
addresses is pretty much a no-go (even though it would probably be sparse)


Customizar External Login do Identity em botões personalizados

Question: Estou tentando implementar o ExternalLogin em uma aplicação web com Facebook e Google, sendo que a tela de login é customizada. Como estou usando DDD e CQRS, eu tenho o Identity de forma desacoplada do projeto asp.net core 2.1. Preciso integrar os botões personalizados que criei em minha view ao Identity para que ele trate tudo para mim como é utilizado no projeto padrão asp.net. Segue os códigos:
View Login

Entrar com

            <form id="external-account" method="post">

                Facebook

              <button class="btn btn-neutral btn-icon" name="provider">

                                Google
                            </button>
            </form>

            Ou entre com suas credenciais

          <form asp-route-returnUrl="@ViewData[" ReturnUrl "]" method="post" role="form" id="login-form">

                <input asp-for="Email" class="form-control" placeholder="Email" type="email" name="email">

                <input asp-for="Password" class="form-control" placeholder="Senha" type="password" name="password">

              <input asp-for="RememberMe" class="custom-control-input" id=" customCheckLogin" type="checkbox" name="remember-me">

                                Lembrar-me

              <button type="submit" class="btn btn-primary my-4" id="btn-login-submit">Entrar</button>

          </form>

          Esqueceu a senha?

          Registrar usuário

Class Startup.cs

public void ConfigureServices(IServiceCollection services)
{
   ....

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o =>
                {
                  o.LoginPath = new PathString("/login");
                  o.AccessDeniedPath = new PathString("/home/access-denied");
                })
                .AddFacebook(o =>
                {
                 o.AppId = Configuration["Authentication:Facebook:AppId"];
                 o.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
                 o.CallbackPath = new PathString("/signin-facebook");
                 o.AuthorizationEndpoint = FacebookDefaults.AuthorizationEndpoint;
                 o.TokenEndpoint = FacebookDefaults.TokenEndpoint;
                 o.SaveTokens = true;
                })
                .AddGoogle(googleOptions =>
                {
                 googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
                 googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
                 googleOptions.CallbackPath = new PathString("/signin-google");
                 googleOptions.AuthorizationEndpoint = GoogleDefaults.AuthorizationEndpoint;
                 googleOptions.TokenEndpoint = GoogleDefaults.TokenEndpoint;
                 googleOptions.SaveTokens = true;
                });
}

Até tudo seguindo os mesmos passos de inúmero exemplos na internet. A questão é: como posso na View associar ao meu botões a chamada para que todo o ExternalLogin funcione?
Answer: Olá, Você primeiro precisa associar o schema a cada botão e cada um submeter ao uma action e como resultado gerar um Challenge para o provider especifico (google, facebook etc.)
Exemplo do Botão: (Estou usando Razor Tradicional)

                                    @provider.DisplayName

O Array de Providers configurados pode ser obtido no controller usando e injetando o SignInManager assim:
private readonly SignInManager<IdentityUser> _signInManager;
public IList<AuthenticationScheme> ExternalLogins { get; set; }

public ConstrutorDoController(SignInManager<IdentityUser> signInManager)
{
    _signInManager = signInManager;
}

No seu Get você pode passar através do model para a pagina o array obtido dos schemas configurados no startup assim:
 ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

Um exemplo do ExternalLoginController da action Challenge do botão:
  [HttpGet]
        public  Task<IActionResult> Challenge(string provider, string returnUrl)
        {

            // start challenge and roundtrip the return URL and scheme
            var props = new AuthenticationProperties
            {
                RedirectUri = Url.Action(nameof(Callback)),
                Items =
                {
                    { "returnUrl", returnUrl },
                    { "scheme", provider },
                }
            };

            return Challenge(props, provider);

        }

E o callback informado nas propriedades acima através do returnUrl:
  [HttpGet]
        public async Task<IActionResult> Callback()

 var info = await _signInManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                ErrorMessage = "Error loading external login information.";
                return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
            }
// Codigo omitido, faça sua logica aqui, mande para o cadastro ou faça o login...
        {
}

Espero que isso ajude, o código não está completo com todos os tratamentos de exceções, mas acredito que lhe dará um norte.
Comment: Muito obrigado. Entendi e deu tudo certo.


What's the best practice to reverse engineering a binary file in windows?

Question: In my case it's written in c/c++,if that matters.
Comment: it doesn't matter, you will be hard pressed to get anything back besides assembly code.
Comment: @Anders, kinda like saying you'd be hard pressed to get anything back but a-z from a book on Shakespeare.
Comment: @GalacticJello imagine getting a book of Shakespeare where every other line says to be continued on another page and having the pages in a pile on the floor and the only thing you know about the book is that its about a king of some sort.
Comment: @anders: google 'hex-rays decompiler comparison'
Comment: @Igor, I didn't say it couldn't be done but its normally a tremendous effort for any larger more complex programs if you want make sense of the code without any context info or comments.
Comment: As for assembly, just look for a lot of "call , cmp eax, 0" followed by "jne" statements...  That's basically "int resultCode = CheckPassword();  if (resultCode != SUCCESS) LogError();" type-of-pattern.
Comment: Voting to close as too broad. There is an entire SE site for that now :-)
Answer: IDA rocks.
IDA Disassembler
Answer: Most reverser's are still gurus. You should first ask yourself why am I reversing?
There are a few main reasons I can think of.

You are trying to crack a copy protection mechanism, pirate software, or cheat in a video game.
You work for an Antivirus Company and need to understand the virus or the latest threat. Or are a government trying to prevent war or espionage.
You are beginning in programming, and are erroneously taking the approach of learning by tinkering.
You are a competitor and cannot figure out something (usually small) that they did.

In all of these cases, the true objective is small (a single algorithm for example), even though the ammount of code is large.
#1 Hacking / Cracking / and Cheating

This is pretty easy actually. You just need to defeat the multiple anti circumvention measures. Without getting caught. The penalties for getting caught are high. DMCA violations, getting CD KEY banned from game, lawsuits... Any good debugger will do. Wikipedia has a good article on Windows debuggers. Some are free, some are not. Be sure to enable all anti circumvention measures and hack with your network disabled.

#2 Professional Researcher

They have asked what you asked, a long time ago.

#3 Beginner Programmer

Computer programming is not for the this looks easy I'll figure it out types... Even the most experienced programmers fail without documentation, samples, and examples. At the least, understand the Windows API, the docs are on MSDN.microsoft.com. This will teach you what you need to know.

#4 Competitor

This is the most debated form of reverse engineering. You will need extensive knowledge of APIs used in the system. In this case, you need to know some of Windows APIs by heart. If you don't reversing a competitors code will be very difficult. What you do, is figure out educated guess which known API the program must use to do a speciffic task.
For example, if it prints a message box to the screen, set a breakpoint on the Windows API: MessageBoxW. Then look at the callstack to see where the code was executed from in the program, and step back through the code (with your brain..) and figure out what you need to know.

Reverse engineering takes hours
Antivirus authors likely have automated the Windows API (which could take years) to look for stuff that is common in malicious code. Tools that are under $100 are usually not very automated, so you'll use your brain alot.
Comment: I'd like to add (as happening to myself) "recovering compatibility with legacy file format that the no-longer-available programmer left undocumented"...
Comment: There is a fifth option, that has become increasingly common, especially in games.  You want to modify an existing piece of software to do something it wasn't originally written for, and the original developer did not create an explicit way to do this.  (I.e. you want to create a [mod](http://en.wikipedia.org/wiki/Mod_(video_gaming)).)  This is often done with either the implicit or explicit blessing of the original author.
Comment: This is a weak answer. It doesn't answer the direct question at all and in fact, it seems like to just tries to discourage someone from learning reverse engineering. It is not realistic or substantiated in any way. For example, I find RE *easier* than "regular" programming, and a lot more rewarding. Of course he can't just "learn by playing", but OP made no reference to doing this at all. Reverse engineering is a real profession and it's not just for freaks of nature, prodigies, or weirdos, and in fact the best way to learn is by playing and being curious.
Answer: you missed a few more reasons,
curiosity to learn how things are done where they are not publicly documented,
sometimes its the Himalayas appeal for us nerds out there, why do it because its there,
and mistrust paranoia, are they doing the right thing, are they ethical to the mass populous?
All the ones you listed are probably the more common though sadly.
It is a lot of effort but if the reason is learning, Any tool is good, I am definitely no guru (some of the people I have seen out there are oh so fast), but I find if you take the approach, decompile, copy a sections at a time in essence re-writing the system while stubbing calls that have not yet been copied you can reverse the design and determine algorithms used.
Answer: OllyDbg is another free tool for reverse-engineering on Windows alongside IDA. You can find plenty of tutorials and plugins, scripts etc. from Tuts 4 You for both tools ("Lena's reversing for newbies" series is a great introduction to using Olly).
Comment: @wamp your question does not state the requirement that the given solution is free, only the best practice. If the most efficient use of time & money is to buy a tool to do the job, then the 'best practice' is non-free.
Comment: I guess you should update your question to be "what's the best way to reverse engineer a game I'm playing to get around the copy protection" instead of "What's the best practice to reverse engineering a binary file in windows".  lol
Comment: @wamp actually there's a freeware version, which is quite enough to deal with most of Win32 binaries
Comment: OllyDbg is good.  But similar to "The Most Interesting Man in the World" prefers Dos Equis, I can state that I have used both, and while not as interestng, "I prefer IDA".


Can plugin be defined as a dependency in Maven POM?

Question: Hi I'm new to stackoverflow community, I'm learning maven for automation perspective. Here if I add maven surefire_report plugin as dependency in POM then I get
<code>Exception in thread "main" java.lang.NoSuchMethodError: 'void com.google.common.base.Preconditions.checkState(boolean, java.lang.String, java.lang.Object, java.lang.Object, java.lang.Object)'
</code>
But It works fine when I mention the same within the plugin tags. So I wanted to understand

Do they have some rules for what can be defined as plugin and what goes as a dependency in POM?

Is it even possible to define plugin as dependency some how, as if mention maven surefire plugin in dependency it works fine every time?
<code>         <dependencies>
     <dependency>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-surefire-plugin</artifactId>
         <version>3.0.0-M5</version>
         <type>maven-plugin</type>
 </dependency>

 <dependency>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-surefire-report-plugin</artifactId>
     <version>3.0.0-M4</version>
     <type>maven-plugin</type>
 </dependency>
 <!-- https://mvnrepository.com/artifact/junit/junit -->
 <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.13</version>
     <scope>test</scope>
 </dependency>
 <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
 <dependency>
     <groupId>org.seleniumhq.selenium</groupId>
     <artifactId>selenium-java</artifactId>
     <version>4.0.0-alpha-5</version>
 </dependency>
</code>

     2.3.2

             org.apache.maven.plugins
             maven-compiler-plugin
             ${maven-compiler-plugin-version}

                 1.8
                 1.8

Comment: Using a plugin as a dependency make usually no sense cause you don't use code of a the plugin in your own code.Defining a plugin in plugin tags make sense...to define which plugins in which version are being used.
Answer: Dependencies are those artifacts that your program will use for compilation and runtime.
Plugins are a different kettle of fish. They are run during the build to e.g. process resources, run tests etc.
So using the surefire plugin as dependency means that you want to use it in your program (not during the build). And this is probably not what you want.


List module releases that are "Recommended by the project's maintainer."

Question: On the project page of a Drupal module there is a list of releases.  The project owner can set for each one whether it is recommended, and the page displays that fact.  For example if there are releases 2.0 and 3.0, it's possible for either one to be recommended or both.
I would like to know which releases are recommended without having to visit the project page of each module one-by-one.  I would be interested in any type of answer: GUI, command line, API, etc.
I have already tried

The GUI (/admin/reports/updates).  It lists releases that are "also available" but does not indicate which are recommended.
composer.  It seems to have no idea of recommended.  With my settings, it appears to pick the newer release except if it is less stable.
drush.  In drush 8, the rl command lists recommended releases but seems to be broken with current Drupal 8.  Newer drush does not have this command.
Code.  The return value of update_get_available() or update_calculate_project_data() don't seem to contain this information.
Answer: As described in Update status XML, Drupal.org returns information about project releases, including the recommended major version, as XML output. For example, the first XML elements returned from https://updates.drupal.org/release-history/imagemagick/8.x are the following one.
<title>ImageMagick</title>
<short_name>imagemagick</short_name>
<dc:creator>sun</dc:creator>
<type>project_module</type>
<api_version>8.x</api_version>
<recommended_major>3</recommended_major>
<supported_majors>3</supported_majors>
<default_major>3</default_major>
<project_status>published</project_status>

<recommended_major>3</recommended_major> is referring to any version matching 8.x-3.*.
Unfortunately, that information isn't returned from https://updates.drupal.org/release-history/imagemagick/current or any URL matching https://updates.drupal.org/release-history/*/current.
<title>ImageMagick</title>
<short_name>imagemagick</short_name>
<dc:creator>sun</dc:creator>
<type>project_module</type>
<supported_branches>8.x-3.</supported_branches>
<project_status>published</project_status>
<link>https://www.drupal.org/project/imagemagick</link>

Comment: Thanks that's interesting even if not especially easy to make use of.  It's interesting that is puts recommended_major as a singular but it's possible to set multiple recommended releases.

List module releases that are "Recommended by the project’s maintainer."


Modify the date popup to only accept special days

Question: I may need your help please. I have installed the "Date" module and using it with the date popup (datepicker). I need to have the popup just accepting Wednesdays and Fridays as dates.
Can anybody give me some help on this issue?
Thanks alot!
Answer: You can use Date Restrictions in conjunction with Weekdays to acomplish this.
Just download both projects and enable weekdays_date_restrictions module. Then edit the date field and go to "More settings and values" > "Date Restrictions" > "Allowed values" > Choose restriction type: weekdays.
Answer: Found a solution. Just use jQuery and it's beforeShowDay attribute to check out if a date should be valid.


Static function receives wrong parameters

Question: I have this strange behaviour with a static function and can't find a solution. This is from a computer player I am writing for a school project. For the context: Board and Evaluation are classes used by my logic but their functionality is not of importance here.
I have a Class MatchUnit which has a method to create an instance and a constructor assigning local fields:
static void MatchUnit::CreateInstance(Board& realBoard, Board& altBoard, unsigned char turn, char currentPlayer)
{
    // [P2]
    _instance = new MatchUnit(realBoard, altBoard, turn, currentPlayer);
    return _instance;
}

MatchUnit::MatchUnit(Board& realBoard, Board& altBoard, unsigned char turn, char currentPlayer)
{
    _realBoard = &realBoard;
    _altBoard = &altBoard;
    _turn = _moveNr = turn;
    _currentPlayer = currentPlayer;
}

The fields an methods are defined in in MatchUnit.h
class MatchUnit {
public:
    static MatchUnit* CreateInstance(Board& realBoard, Board& altBoard, unsigned charturn, char currentPlayer);
private:
    Board* _realBoard;
    Board* _altBoard;
    uchar _turn;
    uchar _moveNr;
    char _currentPlayer;
    MatchUnit(Board& realBoard, Board& altBoard, unsigned char turn, char currentPlayer);
};

MatchUnit is a singleton but I left the getter and the field of the instance out, because I don't think they matter here.
Board contains a non static private evaluation pointer (Evaluation* _eval)
In my main function I now call the problematic method:
Board* realboard = new Board();
Board* altboard = new Board();

// Internally the board constructors assigned their field pointers:
// _eval = new Evaluation();

// [P1]
MatchUnit::CreateInstance(*realboard, *altboard, 0, currentPlayer);

If I use the debug view of VS2015 and pause at [P1] I can see that the _eval fields of the boards are not pointing to null. But when I continue to point [P2] they are pointing to null! Other fields of the boards also have strange values, a bool set to true before is false and integers seem to have random values, different from each other!
Why are the parameters of CreateInstance totally different from what I gave them?
Comment: Missing return type for `MatchUnit::CreateInstance` definition...
Comment: @Genuigr Okay let me see if I have got your question right once you call the function
MatchUnit::CreateInstance(*realboard, *altboard, 0, currentPlayer);
And reach [P2] in the code the parameter values at P1 and P2 are different which should be same as you are passing the same thing as parameter.
Comment: @Xtreme_Enigma Yes you got it right.
I corrected the return type. It returns nothing, it just creates an instance and set the static _instance field
Comment: @Genuigr Can you share results at point [p1] and [p2]??? Also if possible the values of the _eval fields after the function has been executed? A possible [p3] if you may?
Comment: You should write a [mcve].
Comment: I got the values you asked for and then at [p3] that point after invoking the function the _eval fields were correctly set. I propably debugged wrong. Strangely I still (later on when running my program) _eval is null again. The bug is somewhere else in the code.This question should be deleted :/
Answer: The signature of the function CreateInstance differs in your header and source. In your source, you declare the third parameter to be of the type uchar, whereas you declare it as unsigned (int) in your header (probably due to mistyping a space). When you call your function, the compiler generates code that matches the parameters in your header, while your function uses the parameters as defined in your source. Due to a mismatch in the sizes of the parameters, your function seems to receive the wrong values. You can solve this by simply editing either one of the parameter definitions.
Comment: I corrected that thank you. In my program that is not the problem this was just a fault in me copying my code. Thanks.
Comment: It was an implausible explanation.  Depending on the platform, the argument will be passed in a register (in which the other values are undisturbed), or on the stack (where stack values will tend to be kept at least 32-bit aligned).  Of course, the typo would have been undefined behaviour, but it was unlikely to provoke a run-time error.  It was *very* likely to provoke compile or link-time errors though.


Find all methods which depend on third-party library

Question: I use ILSpy to explore assemblies. Now I have a task to find all methods in the investigated assembly which depend on a third-party assembly. In other words, I want to know what methods in my assembly call methods in third-party assembly. Is it possible somehow using ILSpy or another software?
Answer: I am not aware of a tool that automates the depends on analysis.
If the third party assembly is small enough you could load it and the investigated assembly and use the Find Usages feature of JustDecompile on all the types in the assembly and start from there. The investigated assembly will have to be of manageable size too.
You could also automate it but you'll have to write some code to do that. Both JustDecompile and ILSpy engines are open source. You can create a plugin that does that.
Last but not least you can upvote this - https://justdecompile.uservoice.com/forums/113277-justdecompile-feature-suggestions/suggestions/1772437-provide-depends-on-analysis so that this feature gets higher on the backlog of JustDecompile.


Laravel Eager Loading | Query for specific User

Question: I have some trouble to display results that are made by a specific user.
With the code below I receive all entries ($restaurantmenue), instead I only need the entries that are made by the specific user. How can I query only for the user that creates the entry?
//Restaurant Profile Page
public function showrestaurants($id) {
  $restaurant = User::findOrFail($id);
  //$restaurant->addclick();

  $restaurantmenue = User::with(['articles' => function ($q){
    $q->nowpublished();
  }])->get();

  return view('pages.profile')->withRestaurant($restaurant)->withRestaurantmenue($restaurantmenue);
}

nowpublished() Scope in Article.php:
public function scopeNowPublished($query) {
  $zero = Carbon::today()->addHours(23)->addMinutes(59)->addSeconds(59);
  $query->whereBetween('published_at',[Carbon::today(),$zero])->orderBy('published_at','desc');
}

My View:
@foreach($restaurantmenue as $daily)
                  @foreach($daily->articles as $menue)

                              <button type="button" class="btn btn-neutral btn-round">
                                   SMÄCKT MIR
                              </button>

                                     Best of

{{$menue->title}}

{{$menue->body}}

                                    {{$menue->price}} €

                  @endforeach
                @endforeach

Answer: If I understood you correctly, you should do something like this:
$restaurantmenue = User::where('id', $id)->with(['articles' => function ($q) {
    $q->nowpublished();
}])->get();


jQuery: remove certain elements from HTML document

Question: I'd like to strip certain elements from my HTML document.
It seems that removing some tags simply doesn't work.
For example - strip all stylesheets:
$("style",this._doc.body).remove();

I'd also like to remove comments or something like weird winword tags like:


How to quickly remove a set of outdated packages?

Question: I have a newly installed CentOS 5.7 machine and mistakenly installed PHP 5.1 when I needed 5.2+.
Now I cannot seem to install PHP 5.3 (using "yum install php53") until I remove PHP 5.1.
I found this tutorial, which has you type:
yum remove package1 package2 package...

But it takes so long that way.
Is there a faster way, something like:
rpm -qa | grep php -exec yum remove {} \;

?
Thank you
Answer: Using the link you provided, you can first find what php-related packages you have installed by using :

yum list installed | grep php | cut -d' ' -f1 | tr "\n" " "

you can use this command output and feed it to yum remove, the simplest example is as follows

yum remove `echo bind`

the backtick symbol (`) is located to the left of the "1" key on standard US keyboards.
and echo bind should be replaced with the yum list command.
so the command should be:
yum remove `yum list installed | grep php | cut -d' ' -f1 | tr "\n" " "`
I'm on ubuntu so cannot test this very well, but hope this works on your box,.
Comment: Very well done! I entered your code and it works perfectly. I'm not sure if it's better than "yum remove php-\*" though. What do you think?
Also, your explanation is really good but I was confused for a second by your comment about ` so I'm going to propose an edit.
Comment: Thanks for the editing. I don't see any difference between the two since we are both finding packages that match the pattern. And to further automate this process, the -y option could be used which skips the confirmation process.
Answer: yum remove php\*

I had previously tried
yum remove php*

which obviously didn't work
Comment: With the command "yum remove php*", you may have had files in the current working directory that matches the glob (since you said you're working on package upgrades). In that case, shell expansion would have resulting in the actual command being "yum remove php-blah-blah-blah.rpm" or whatever was in that directory, which would have failed because there'd be no such installed package. The "\" would have escaped the "*" and stopped the shell expansion.


Why using cross validation is not a good option for Lasso regression?

Question: I watched the lecture about Lasso and at the end of this module (between 00:40 and 01:25) she explains how to choose the regularization parameter Lambda and it sounds like using  (K-fold)Cross Validation technique is not a good option for Lasso. But, I don't understand why? What's the problem?
Answer: So, the point is that when you define an optimal value of $\lambda$ you must ask optimal for what? In the case of the LASSO, there are two possible goals:

Estimate $\lambda_{\text{pred}}$, the value of $\lambda$ that leads to the best prediction error.
Estimate $\lambda_{\text{ms}}$, the value of $\lambda$ that produces the correct model (or at least something that is close to it).

As Dr. Fox correctly notes, in general it is not the case that $\lambda_{\text{pred}} = \lambda_{\text{ms}}$, and typically $\lambda_{\text{pred}} < \lambda_{\text{ms}}$. But choosing $\lambda$ by cross-validation is using prediction error, and hence one would expect it to estimate $\lambda_{\text{pred}}$. Consequently, if you choose $\lambda$ by cross validation, you may select a $\lambda$ which leads to a model which is too big. If your goal is recovery of the true model, it follows that one should be careful applying cross validation.
I personally encounter this issue a lot when writing papers whenever I do a simulation study looking at the lasso for variable selection. Invariably, using cross-validation to select $\lambda$ is a disaster. I have had much better luck applying Lasso$(\lambda)$ to select the model and then fitting by least squares, then applying cross-validation to this entire procedure to select $\lambda$. It's still not ideal, but it is a big improvement.
That's not to say that cross-validation is completely off the table for model selection, it's just that you need to think carefully about what $\lambda$ your method is estimating. For example, lets consider ignoring the lasso and just think of a low-dimensional linear regression. In this case, leave-one-out cross validation is known to be more or less equivalent to some variant of AIC, and AIC is well-known to be inconsistent for model selection. Similarly, BIC is generally associated with leave-$V$-out cross validation where $V$ is some function of the size of the data, and it is well-known that variants of BIC are model selection consistent. Hence, there is some way of doing cross-validation that we would expect to be consistent for model selection, but leave-one-out is not.
Comment: There is huge incorrect folklore on this matter. The best predictive model with KL divergence IS the best model selection. Contrary to common belief AIC messes up on small samples rather than large samples. On large samples consistency is measured strangely with coefficients that are so small and practically should be considered 0, but instead counted as a higher dimensional model.
Comment: @MatthewDrury in the context of variable selection procedures, I would say model selection generally means "find the relevant predictors." There are problems where this might make sense to do, such as some genomics problems. In real data, you cannot check that you found the correct model obviously; you have to rely on simulation experiments to understand what the procedures are doing unfortunately. There have been some attempts to estimate things like the $F$-score in real-data, but it seems extremely tough to have faith in that.
Comment: (+1) Is that generally how these terms are used: "model selection" is jargon for "find the correct model"?  When you say "have had better success" with this, how do you check if you have found the correct model in a real scenario?
Comment: @AdamO It is not my personal view that the the $\lambda$ that minimizes prediction error is different from the $\lambda$ that selects the true model, it is a mathematical fact. If your goal is prediction, using $\lambda_{\text{MS}}$ will cause your coefficients to be shrunk beyond what is optimal, and if your goal is model selection then using $\lambda_{\text{pred}}$ then will select models which are too dense. And I don't know what is endorsed in the ML sphere, I am a statistician.
Comment: I know this is an endorsed viewpoint in the ML sphere, but I do not endorse it. I cannot distinguish $\lambda_{pred}$ from $\lambda_{MS}$ if the basis for selecting $\lambda$ is on predictive accuracy. We prefer what you are calling $\lambda_{MS}$ because it provides *sparse* predictions in that many of the coefficients are set to 0. Choosing $\lambda$ in the wrong fashion makes the choice overly small and leads to overfitting.
Comment: @CagdasOzgenc It's not "incorrect folklore" that AIC is model-selection inconsistent. Formally, the goal is support recovery, i.e., estimate the non-zero entries of $\beta_0$. In the case of a GLM, the proof of inconsistency of AIC is about two lines long. It sounds like you have a problem with the formal definition of model-selection consistency. But that's your personal opinion about what the goalposts should be, and is unrelated to the mathematics.
Comment: As someone new to this topic (find the true model), it'd be helpful to have a few references so I can read up on what y'all are discussing.
Comment: IIRC these issues with cross-validation are asymptotic results?   I have never been *that* comforted by asymptotic properties as I seem to be perennially working with small samples (relative to the model), I'd be much more comforted by small-sample theoretical results. Also one of the advantages of cross-validation is that it still "works" when the model is mis-specified.  However the fundamental issue is "optimal for what?" - all to often we (i.e. them ;o) fail to think about the real needs of the exercise and just read recipies from the stats cookbook (+1).
Comment: BTW I quite like integrating the regularisation parameter out using a Bayesian prior, although it isn't always that clear exactly the right way to do that.
Comment: @DikranMarsupial Right, the most straight-forward way to prove something formal is to use asymptotic consistency because it makes a lot of the details go away; more fine-grained results, even finite sample ones, are possible with some loss of generality and uglier statements. Going Bayes and integrating out tuning parameters is a nice solution as well, especially in small samples, and I guess it errs on the predictive side of the prediction-selection gap (it averages of $\lambda$'s that make the marginal likelihood large, which is a predictive criterion).
Answer: The lecturer's meaning is not entirely clear. She says:

But in the case of LASSO, I just want to mention that using these types of procedures, assessing the error on a validation set or using cross validation, it's choosing lambda that provides the best predictive accuracy. But what that ends up tending to do is choosing a lambda value that's a bit smaller than might be optimal for doing model selection.

Cross-validation can be used in two ways in LASSO: to choose an optimal $\lambda$ and to assess the predictive error. To the best of my knowledge doing these things together in a single fold is not best practices. That's because you've chosen the $\lambda$ value that's optimal for a particular cross-validation fold, this naturally leads to overfitting which favors smaller values of $\lambda$.
I think better practices would be either to apply nested CV: so that for the particular training fold, CV is applied again to find an optimal $\lambda$ in that iteration; or apply CV in two batches, first a set of optimization-CV to find an optimal $\lambda$ then fix that value when fitting LASSO models in a another batch set of validation-CV steps to assess model error.
Comment: I've been pondering over which of the two choices that you mentioned is best. Do you have any insight?
Comment: The latter is more computationally efficient, but I don't know what the implications of that are for accuracy.
Comment: @24n8 having had a chance to rethink the problem, the other meaning may be that since k-fold cross validation is a split-sample procedure, you identify the $\lambda$ that is optimal for an e.g. $9/10 n$ sample supposing a 90/10 train/test split. One would think the result would be picking a $\lambda$ that's TOO LARGE, relative to what would be optimal in a full sample of size $n$ validated externally, in other words the added precision should reduce the need for penalization.
Answer: lasso regression is capable of producing "sparse" models – models that only include a subset of the predictor variables, but you loose the control on what features are being eliminated (as zero weight) VS ridge regression, when the coefficients of each predictor are shrunken towards zero but none of them can go completely to zero.
Example here

The disadvantages of LASSO, however, are that we cannot use linear
algebra to find the parameters. The penalty imposes a nonlinear
behavior to the objective function, so we must use an iterative
solver. For features that are correlated, we have no control over
which feature is eliminated. Different initial guesses may lead to
different feature elimination. If the features are really correlated,
this will not affect the fit quality, but it will mean some models
favor one feature over another. This is less of a problem in
polynomial models, but often a problem in models based on physical
properties that are correlated, e.g. high melting points of materials
tend to be correlated with how hard they are. With LASSO, one model
could favor the melting point and another could favor the hardness.

What regularization method to choose against multicollinearity & overfitting? - It depends

In cases where only a small number of predictor variables are
significant, lasso regression tends to perform better because it's
able to shrink insignificant variables completely to zero and remove
them from the model. However, when many predictor variables are
significant in the model and their coefficients are roughly equal then
ridge regression tends to perform better because it keeps all of the
predictors in the model.

Still, I consider feature_selection logically by the scientist/engineer & proper design of experiment (if possible) is the best choice for getting trustfull results for statistical inference
And besides, for Lasso linear_model there are some other techniques of Cross-Validation, not K-fold, e.g.  Least Angle Regression algorithm ( LassoLarsCV) & Information-criteria based model selection (according AIC/BIC)
P.S. Often I saw recommendations to estimate different scores (R2, AIC, BIC etc) & choose the model by the aggregate value, if you doubt what scores to prefer for cross-validation. Concerning IC-score:

However, such criteria need a proper estimation of the degrees of
freedom of the solution, are derived for large samples (asymptotic
results) and assume the correct model is candidates under
investigation. They also tend to break when the problem is badly
conditioned (e.g. more features than samples).
Answer: If the goal is to perform model selection and LASSO with cross validation will not work well, then the problem is not cross validation, but the problem is LASSO which is trying to perform two tasks at once

model/parameter selection
shrinking and bias/variance optimisation

These two may not be both optimal for the same regularisation parameter. Depending on the optimal bias/variance balance, the parameter selection might be done with a smaller or larger lambda than optimal*.
One can use something like relaxed LASSO to optimize both tasks seperately (see: Advantages of doing "double lasso" or performing lasso twice?). Alternatively one can also use a different prior, like elastic net regression or a horseshoe prior.
* If the optimal shrinkage is large, then the parameter selection may be too severe (ending up with less parameters than optimal). If the optimal shrinkage is small, then the parameter selection may be too low (ending up withore parameters than optimal).
Answer: Here is a very simple explanation of why there is a difference between modeling for research and modeling for prediction. I'll get into how this relates to cross-validation and Lasso by the end.
Let's say you have three possible models for a problem:
1.) A good predictive approximation with a mixture of true and accidental variables with parameters tuned for prediction and very little theory behind it (the proverbial "black box").
2.) The true model with all of and only the true variables and perfectly tuned parameters (i.e. the ground truth).
3.) A good approximation of the true model with only true variables but not all of them and parameters that are close to the true parameters (the ground truth minus some missing information)
1 and 3 are possible in practice, 2 almost always isn't. 3 is a better approximation to understanding 2, but very often 1 is actually better at predicting future values. Why? Because the "false" variables and parameters of 1 in some sense encode information that is present in 2 but not in 3 (maybe they are confounding variables in some sense).
It is very unintuitive, because if you had model 2 you would obviously do better in both understanding and prediction. But you don't have model 2. In practice you have to choose between a functional approximation and a first principles approximation. A motorcycle is a reasonable functional approximation of a car, a car that is missing a wheel is a terrible functional approximation while still being much closer in reality to a car.
Lasso regression combined with cross-validation is a great way of generating models in the first category. The problem is that there is no principled reason to think that it will get you closer to 2 or even 3. Maybe it will or maybe it won't, but you will do better being much more aggressive in your regularization than predictive accuracy would suggest if you want to get close to 3. Of course eventually all approximations approach the ground truth, a very impressive predictive accuracy is some evidence of having a true model.


Is it possible to access variable data with appium?

Question: My objective is to check the list content and click an element according to  its boolean variable state.
I wonder whether it is possible.
Answer: Yes, assuming the state is stored as an attribute you can read and act upon it.
See http://appium.readthedocs.io/en/latest/en/commands/element/attributes/attribute/.
Answer: It depends on what exact attribute you want to get. If Appium can parse it, then of course you can.
Here is an example with list of checkboxes:

So I want to click the ones that have checked=true:
List<WebElement> options = driver.findElementsById("android:id/text1");
options.stream()
    .filter(e -> Boolean.valueOf(e.getAttribute("checked")) == true)
    .forEach(e -> e.click());


Php Result page to be displayed on same page

Question: This is my coding for the search form:

<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>

    <form action="https://excelforth.com/search1.php" method="GET">
        <input type="text" name="query" />
        <input type="submit" value="Search" />
    </form>

The thing is , When I submit this form on my web page , It goes to the php Results page and displays the results. But the thing is that it is just a plain page with just the results displayed.
My search page :
www.mysite/test/certification-database-search/

The Php file is located in my webroot folder . I was told that for wordpress , the individual subpages cannot be edited .
How do I :
1.Display the results on the same page as the search page. Not a completely new page.
2.Retain the page layout and theme / headers/ footers of the page
3.If possible run the .php file in  /certification-database-search/ and query it from there. instead of using the one in my webroot folder.
THANKS!!
Comment: Put your form and PHP in one page, PHP on top with HTML below, then use `action=""` - use the variables from the inputs as `$var=$_GET['var'];` then `echo $var;` for example (in a nutshell)
Comment: You're welcome. You can wrap your PHP inside a conditional statement, such as `if(isset($_GET['submit'])){ // code }` then name your submit button ``
Answer: Put your form and PHP in one page, PHP on top with HTML below, then use action=""
Use the variables from the inputs as $var=$_GET['var']; then echo $var;
Sidenote: If you want to stop a process, you can use die(); or exit();
You can put a message inside it; i.e.: die("Enter a search term");
A basic example:
<?php
if(isset($_GET['submit'])){
$query=$_GET['query'];
echo $query;
}
?>

<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>

    <form action="" method="GET">
        <input type="text" name="query" />
        <input type="submit" name="submit" value="Search" />
    </form>

An alternative, showing an error message if field is empty:
<?php
if(isset($_GET['submit'])){
  if(empty($_GET['query'])){
echo "Enter a search term";
  }

$query=$_GET['query'];
echo $query;
}
?>

<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>

    <form action="" method="GET">
        <input type="text" name="query" />
        <input type="submit" name="submit" value="Search" />
    </form>


Binomial Theorem Help

Question: In my assignment I have the following question:

Alan
Comment: For some basic information about writing math at this site see e.g.
[here](//meta.math.stackexchange.com/q/5020),
[here](//meta.stackexchange.com/a/70559),
[here](//meta.math.stackexchange.com/q/1773) and
[here](/help/notation).
Comment: Thank you. Is it bad I'm writing it the way I did?
Comment: The problem is that it's not searchable, doesn't show up in the question preview (front page "teaser" of the body) and looks pixelated. Also it consumes more bandwidth than necessary so, yes the format is bad. However, the question itself is asked nicely, so I'm convinced you'll learn MathJax and keep posting good questions like this one ;)
Comment: Thank you! I will study the format, and I thank you for your tips!
Comment: Also note that you can inspect any Math $\mathfrak{such\ as\ this}$ with a right-click and "Show Math As $\blacktriangleright$ TeX commands". Try it out with my answer for example ;)
Answer: Use a more straight-forward approach:
$$4^n = (1+1)^{2n} = \sum_{i=0}^{2n} \binom{2n}i 1^i 1^{2n-i} = \sum_{i=0}^{2n} \binom{2n}i$$
Now since binomial coefficients are nonnegative, we get
$$4^n \ge \binom{2n}i \qquad \forall 0\le i\le 2n$$
Especially for $i=n$.
Comment: This is definitely the way the hint suggests.
Answer: In this answer, a simple argument shows that
$$
\binom{2n}{n}\frac{\sqrt{n+\frac13}}{4^n}
$$
is decreasing. Therefore, for any $n\ge0$, we have
$$
\binom{2n}{n}\le\frac{4^n}{\sqrt{3n+1}}
$$
Answer: Alan.Here is my suggestion.
consider $(1+x)^{2n}$, then the coefficient of $x^n$ is $\binom{2n}{n}$.
we notice $(1+x)^{2n}$=$\sum_{i=0}^{2n}\binom{2n}{i}x^i$,and $\binom{2n}{i}\geq 1$.
So if we let x=1, then we have $\binom{2n}{n}\leq\sum_{i=0}^{2n}\binom{2n}{i}1^i=\sum_{i=0}^{2n}\binom{2n}{i}$.
and when x=1,$\sum_{i=0}^{2n}\binom{2n}{i}=(1+1)^{2n}=2^{2n}=4^n$.
Finally, we have $\binom{2n}{n} \leq 4^n$.

Binomial Theorem Help


How to store test images as data in a package?

Question: I'm writing a package that helps to quantify images using R. I would like to store example images that people can use to test the package but I'm not sure how to store them. Can anyone help?
Answer: In general you can put anything you want into the inst/ directory of a package.  Let's say you make a directory inst/images in your source package, with files foo1.png, foo2.jpg, and foo3.tif. When the package is installed, you can find them via system.file(), e.g. list the available files via
list.files(system.file("images",package="your_pkg"))

or access them via e.g.
get_image <- function(fn) {
   system.file("images",fn,package="your_pkg")
}
png::readPNG(get_image("foo1.png"))

The only possible pitfall I can think of is that CRAN is not enthusiastic about packages with very large footprints, which could be a problem if (1) you have a lot of large images and (2) you want to submit to CRAN.


Variável do javascript dentro da Tag do EJS

Question: Como coloco uma variável do javascript dentro da Tag do EJS?
Por exemplo, desejo fazer um for pelo EJS e um if comparando:
<% for (var i = 0 ; i < objeto.lenght; i++ ) { %>
    <% if (objeto[i].index == variável_externa) { %>
        .....
    <% } %>
<% } %>

'''
Meu código está abaixo:
Eu quero colocar uma váriavel do javascript dentro de uma EJS
'''
document.getElementById("indicadores1").addEventListener('change', (event) => {
// Aqui eu obtenho meu value
let indicador_atual = event.target.value;
console.log(indicador_atual);
// Agora preciso colocar esse valor dentro de uma váriavel EJS

Por exemplo :<% x %>= indicador_atual

Answer: Você pode utilizar <%= variavel %>, similar ao PHP.
<% for (var i = 0 ; i < objeto.lenght; i++ ) { %>
    <% if (objeto[i].index == variável_externa) { %>
        <%= objeto[i].nome %>
    <% } %>
<% } %>

Answer: Você pode usar <%= variavel %> ou <%- variavel %>.
A diferença entre os dois modos é que <%- variavel %> interpreta códigos HTML, enquanto <%= variavel %> não.
Fonte


Clarifying lag number selection in AR,VAR, VECM etc. models

Question: When it comes to optimum lag length selection, we are supposed to comply with certain information criteria such as Akaike, Schwarz etc. As far as I know, either of them suggest the proper lag number that we should embed in our model, which they are implicitly supposed to be in serial order.
For instance, if we have a VAR(3) of $Y_t$ and $X_t$ variables, we are supposed to embed in the model $Y_{t-1}$, $Y_{t-2}$, $Y_{t-3}$ and $X_{t-1}$, $X_{t-2}$, $X_{t-3}$ respectively. And here is my question:
Why should the lagged values always be consecutive? Is it prohibitive (according to economic and statistic theory) for a model to include non serial lagged values such as that below?
E.g.,
$$
Y_t = a + bY_{t-1} + cY_{t-3} + dY_{t-5} + eX_{t-1} + fX_{t-3} +gX_{t-5} + e_t
$$
Comment: Precise and explicit answer. Thank you very much Christoph!
Comment: You should post this under the answer, otherwise Christoph will not get notified of your comment.
Comment: Thank you for the guidance Richard, since I'm a new member of this community. I still have so much to learn!
Comment: You are very welcome here!
Answer: You are right that there is no firm theoretical reason for intermediate lags to always be included.
My interpretation of the tradition to nevertheless proceed in this fashion is that, even for a simple AR model with maximum lag $p_{\max}$, one would need to compare $2^{p_{\max}}$ models when combinations of intermediate lags need not enter the model, while we only need to compare $p_{\max}$ models when the search is only performed over the maximal lag.
Suppose you entertain lags at "business cycle frequencies" of a few years in quarterly data, so something like 20 lags. Then, $2^{20}=1048576$ need to be compared. While the computational cost of doing so may be less prohibitive nowadays, it still somewhat of a burden, and the benefits to finding models with missing intermediate lags may be limited.
Of course, there are even many more models to be compared in the case of a VAR.
Comment: In addition to the good points in the answer, if you increase the number of models in the comparison, the winner's curse becomes important: there is an increasing probability that the best model is the best in sample (but not in population) mainly due to chance. See Hansen ["A Winners Curse for Econometric Models: ..."](http://www.tse-fr.eu/sites/default/files/medias/stories/SEMIN_10_11/ECONOMETRIE/hansen.pdf) (2010). See also [this thread](https://stats.stackexchange.com/questions/211069/aic-model-selection-and-overfitting?noredirect=1).
Comment: Precise and explicit answer. Thank you very much Christoph!
Comment: @Christoph Hanck I came across this today as I'm new to all of this.  How does one account for seasonal lag like in a situation where you have daily observations but you want to test lag on the calendar quarter (3 months)?  Isn't that essentially what OP is asking?  Am I misinterpreting what you're both saying or is it true that measuring the effect of seasonal lag on data with a more precise sample rate very expensive?
Comment: It would probably be expensive if you indeed, as we discuss in this post, included all intermediate lags. But if you have good reasons to only include that seasonal lag, that saves those intermediate coefficients to be fitted (and/or a complex model building exercise). You could also google for seasonal arima models, which do something like that automatically.


Receber parâmetro em requisição delete

Question: Estou tentando passar um parâmetro para minha requisição DELETE, eu tentei fazer o seguinte:
Usar da mesma forma que uso no GET (onde funciona normal).
app.delete('/contatos', function(req, res){
    var obj = req.body;
    console.log(obj);
});

Porém no console do NodeJS este .log() imprime apenas {}.
Eu também tentei desta forma (encontrei no SOen):
app.delete('/contatos',function(req, res){
    var obj = req.body.data;
    console.log(obj);
});

Mas a mesma coisa aconteceu.
Talvez a implementação do DELETE seja diferente de GET e POST e eu tenha ignorado algum passo.
Estou fazendo a requisição à API pelo AngularJS, com o seguinte serviço:
angular.module("lista").factory("contatosAPI", function($http){
    var _saveContato = function(contato){
        return $http.post("http://localhost:3412/contatos", contato);
    };

    var _deleteContato = function(contato){
        console.log(contato); //Aqui o objeto está normal
        return $http.delete("http://localhost:3412/contatos", contato);
    };

    return {
        saveContato: _saveContato,
        deleteContato: _deleteContato
    };
});

No controller eu chamo o serviço, desta forma:
$scope.apagarContatos = function(contato){
    contatosAPI.deleteContato(contato);
};

Comment: Como está fazendo a requisição?
Comment: @RafaelTelles editado
Answer: o serviço delete do método $http, te retorna uma promisse ou seja, para acessar dados do retorno do servidor, deve ser implementado da seguinte forma.
o serviço de delete não aceita um OBJETO para ser enviado, por que o mesmo no final realiza um Get para o servidor, ou seja as informações devem ir na URL, assim você só pode passar parâmetros, e não um objeto completo.
 $http.delete("http://localhost:3412/contatos/" + contato.ID).success(function (data, status) {
                console.log(data); // Retorno seu Data
            });

Comment: `você não consegue recuperar o objeto do outro lado` - Isso não é completamente verdade. Dependendo da implementação, o *endpoint* pode realizar um GET antes, para obter o valor a ser excluído, prepará-lo para retorno, e em seguida excluir o elemento ORM.
Comment: @OnoSendai, se você está trabalhando orientado a serviço, você tem um JSON ou Objeto do lado Client, do lado do servidor você não possui nenhuma informação, utilizando o serviço $http.delete ele não consegue passar um JSON ou Objeto como parametro, o que ele consegue fazer é colocar cada propriedade como parametro das url, o que não está passando o objeto em si, e sim parâmetro a parametro, agora do lado do servidor há N implementações que podem ser realizadas com essa informação, porém utilizando o $http.delete() creio ser a unica saída sim.
Comment: @RenanDegrandi O que você acabou de descrever está de acordo com que mencionei. Eu não me referi aos valores mapeados entre a requisição e o endpoint (onde, corretamente, você apontou que apenas uma propriade é passada - o identificador) mas a respeito da implementação, que pode sim retornar a representação serializada do objeto que foi excluído.
Comment: @RenanDegrandi Sem estresse, só queria clarificar este ponto para um futuro leitor da sua resposta. Só por curiosidade, o `$http.delete` permite sim a passagem de um objeto completo (`$http.delete('/endpoint/'+ id, {prop1: val1});`) - mas é um *antipattern* - o objeto vai todo serializado na querystring.
Comment: Realizei uma alteração com desmostração tanto para um exemplo de request com parametros e response callback sucess @JéfersonBueno
Comment: Não chamei duas vezes, fiz um exemplo de request com params, e um exemplo de retorno, vou editar .. o que estou querendo dizer é que a request Delete é como um GET, você não pode passar um objeto somente parametros pela url essa url ficaria http://localhost:3412/contatos/1  <-- 1 (ID), você não consegue recuperar o objeto do outro lado entendeu ?
Comment: Boa, saquei. E tem alguma forma de enviar vários `ids` na mesma `url`? Algo como, `http://localhost:3412/contatos/1+2+3`, para enviar os `ids` 1, 2 e 3
Comment: Cara o que eu faria, ao invez de utilizar $http.delete, eu utilizaria o $http.post onde como parametro eu implementaria para receber um list de IDs (List) no meu caso C# - webapi2 (servidor), e la dentro eu trataria minha regra para realizar os deletes entende ?
Comment: deu certo ? @JéfersonBueno
Comment: a sim claro, me referi a Request e não a Response quando disse (recuperar o objeto do outro lado) "servidor", na response posso retornar o que quiser e recuperar na promisse. @OnoSendai. acho que foi uma falha na comunicação.

Receber parâmetro em requisição delete


Partial consistency of Peano Arithmetic

Question: Let $p(n)$ be the sentence $\neg Prf_{\text{PA}}(\underline n,\lceil 0=1\rceil)$, which means that the sentence $0=1$ can't be proved in Peano arithmetic with length $\leq n$.
Assuming $\text{Con}(\text{PA})$, $p(n)$ can be proved in $\text{PRA}$ with $O(n\cdot2^n)$ length, by enumerating all possible proofs with length $n$, and check them doesn't prove $0=1$ one by one.
But is it the lowest bound? Are there one way to prove $p(n)$ in fewer length, such as $O(n)$?
Comment: I've gone ahead and [asked this on MO](https://mathoverflow.net/questions/417484/proving-short-consistency-can-we-do-better-than-brute-force-search) (with minor modifications).
Answer: Emil Jerabek's MO answer addresses this question quite thoroughly; I've very briefly summarized it here. I've made this CW to avoid reputation gain, and if Emil adds his own answer here I'll delete this one. Also, apologies to Emil of course if I got any of this wrong!

Let's start by replacing $\mathsf{PRA}$ with $\mathsf{PA}$, here - that is, we're looking at how difficult it is for $\mathsf{PA}$ to tell that $\mathsf{PA}$ has no contradictions of length $n$. At this point a metatheorem of Pudlak can be directly applied. The following is a quote from his 1984 paper On the lengths of finitistic consistency statements in first-order theories:

"The main results ... can be roughly stated as follows: Let $\mathsf{Con}_T(x)$ be a reasonable formalization of "there is no proof of contradiction in $T$ whose length is $\le x$." Then for reasonable $T$ there exist $\varepsilon>0$ and $k\in\omega$ such that
(1) any proof of $\mathsf{Con}_T(\underline{n})$ in $T$ has length $\ge n^\varepsilon$;
(2) there exists a proof of $\mathsf{Con}_T(\underline{n})$ in $T$ with length $\le n^k$."

(Re: attribution, Pudlak states in a footnote that the lower bound result was independently achieved by H. Friedman.) So there is a broadly-applicable metatheorem ... in exactly the opposite direction to what I expected!
But you ask about what the theory $\mathsf{PRA}$ proves about short contradictions in $\mathsf{PA}$ instead - in the language of the MO post linked above, you're asking about $p_\mathsf{PRA}$ instead of $p_\mathsf{PA}$ - and this is more complicated. In fact, even seemingly-"obvious" conjectures around this topic are wide open.
For more details, including sources, see Emil's above-linked answer.

Partial consistency of Peano Arithmetic


OrientDB Graph API: process results of SQL query

Question: I'm exploring ways of interacting with OrientDB graphs. I'm writing java code, so I'm using some kind of java API. Since tinkerpop is described as the "JDBC" of graph databases, I naively assumed there would be an equivalent of executing a query and then processing the result set.
From a graph, I can call something like:
graph.command(new OCommandSQL("SELECT FROM class")).execute();

Then what? The "execute" method returns an Object, not very helpful. By printing out the class name of the result object, it seems to be a "OrientDynaElementIterable", whatever that is.
So I'm not sure I understand how I run a query and then iterate over the results. In general I actually don't understand tinkerpop, as I'm dealing with a load of OrientDB specific classes that are curiously part of the tinkerpop specification, so how does that make my code portable across graph databases?
Answer: From a graph command you retrieve an Iterable of Vertex.
for (Vertex v : (Iterable<Vertex>) graph.command
                       (new OCommandSQL("SELECT FROM class").execute()) {
     // Do something with vertex v
}

The documentation can be retrieved here where you can find the following example
for (Vertex v : (Iterable<Vertex>) graph.command(
            new OCommandSQL("SELECT EXPAND( out('bought') ) FROM Customer WHERE name = 'Jay'")).execute()) {
    System.out.println("- Bought: " + v);
}

Comment: Yes, but how do I know that? I mean how do I actually even know that I'll get Vertex instances back, rather than anything else? I can find no documentation on this at all, and it seems like the most basic operation I'd want to do. Using the console is all very well for exploration, but in reality you need the API, and as far as I can see that's largely undocumented
Comment: @TomQuarendon I added a reference to the documentation in the answer
Comment: Fair enough, I missed that example. I've looked through loads of the documentation, but I missed that bit.


Views Editing Section Missing

Question: I upgraded a site from D6 to D7 and am coming across an interesting error with being able to edit my existing views. My views are all listed, but when I click on the edit button to edit a view the whole configuration section is missing- all the edit page shows is:

Breadcrumb
Title of view
Auto preview
  Preview with contextual filters:
  Separate contextual filter values with a "/". For example, 40/12/10.
  Update Preview

New views do have the configuration area. Any help or ideas on what I might use to search for a solution to someone else that might have had this issue would also be appreciated. I haven't been able to come up with the right search terms to help find the answer. Thanks!
Answer: It turns out the problem was that the views were content panes and I hadn't enabled content panes in the CTools module. As soon as I turned that on they worked fine again.

Views Editing Section Missing


How to use Fermat's little theorem to solve this problem?

Question: $(25^{1202} + 3)^2$ mod $61$
I know to how solve the form of $a^{p-1}$ mod $p$, but don't know how to reduce $(25^{1202} + 3)^2$ into the form.
Comment: Use the formula $(a+b)^2=a^2+b^2+2ab$ and you are good.
Comment: You could simplify the $25^{1202} $ inside the parentheses first, using $25^{60}=1$ since $1202=60k+2.$
Comment: ...or you can work the other way.  If a = x mod p then a + b = x + b = y mod p and (a+b)^m = y^m mod p.  But cr001's suggestion is probably more efficient.
Answer: By Fermat's Little theorem, we have
$25^{60} \equiv 1 \pmod {61}$
$\left(25^{60}\right)^{20} \equiv 1^{20} \pmod {61}$
$25^{1200} \equiv 1 \pmod {61}$
$25^{1202} \equiv 25^2 \equiv 625 \equiv 15 \pmod {61}$
$25^{1202}+3 \equiv 18 \pmod {61}$
$\left(25^{1202}+3\right)^2 \equiv 18^2 \equiv 324 \equiv19 \pmod {61}$
$\left(25^{1202}+3\right)^2 \equiv19 \pmod {61}$
The answer is $19$.
Answer: Reducion modulo $61$ is a ring homomorphism, hence
$$\bigl(25^{1202}+3\bigr)^2=\bigl(5^{2404}+3\bigr)^2\equiv\bigl(5^{2404\bmod60}+3\bigr)^2=628^2\equiv 18^2=324\equiv19\mod61.$$


Multiple average chances or one better then average chance?

Question: is 52 chances at 30/5,489,031,744 odds better then 1 chance at 1560/5,489,031,744 odds
or is it the same?
Comment: They are the same, assuming these are completely independent events (30*52=1560).
Comment: Better in what sense?
Answer: They are almost the same, but I don't think they're quite exactly the same.
But we can check it using the binomial distribution. Let p denote the probability of success in 1 average chance.
Then $\mathbb{P}$(at least 1 success)$ = 1 - \mathbb{P}$(no successes)$ = 1 - (1-p)^{52}$.
The alternative is $52p$ for the higher chance probability.
Bernoulli's inequality says for $x \geq -1, (1+x)^n \geq 1+nx$.
So we know that $1-(1-p)^{52} \geq 1-(1-52p) = 52p$
SO the probability obtained from lots of smaller chances is almost the same as one larger chance (due to $p$ being so small), but there is a very very small difference between them.


How to find the IP adress of my EKS cluster

Question: I have created an EKS cluster and deployed an API. My API needs to connect to a database that is not in AWS. In order to allow my API to use this database, I must authorize it's IP address in a whitelist. My problem is : I don't know how to get this IP adress since applications can be re-deployed and IP adresses can change... I'm not very familiar with networking notions and any detailed help can be very helpful since I don't only want the solution but also to understand how it works..
Thanks
Answer: My subnets are public...
You can associate an Elastic IP address with the worker node, adjust the security group where applicable, then specify nodeSelector in your spec to run the special pod on the node. Finally you add the EIP to the whitelist.
Comment: My subnets are public and I'm not in the case that you provided :/
Comment: Checkout the updated answer.


Regex para validar determinado formato de data

Question: Estava modificando uma regex para um programa em c++ que que validar o seguinte formado de entrada das datas 29/feb/2000. Atualmente ela estava aceitando somente 29/02/2000 ou 30/03/2017.
Tentei adicionar para os outros meses mas nao estou conseguindo. Como fazer para que seja possivel 30/mar/2017 ou 20/dec/2018?
Segue a regex:
"^(?:(?:0[1-9]|1[0-9]|2[0-8])(?:/|.|-)(?:0[1-9]|1[0-2])|(?:(?:29|30)(?:/|.|-)(?:0[13456789]|1[0-2]))|(?:31(?:/|.|-)(?:0[13578]|1[02])))(?:/|.|-)(?:[2-9][0-9]{3}|1[6-9][0-9]{2}|159[0-9]|158[3-9])|29(?:/|.|-)(?:02|feb|Feb)(?:/|.|-)(?:(?:[2-9](?:04|08|[2468][048]|[13579][26])|1[6-9](?:(?:04|08|[2468][048]|[13579][26])00)|159(?:2|6)|158(?:4|8))|(?:16|[2468][048]|[3579][26])00)$"

Comment: As observações feitas nas respostas [desta sua outra pergunta](https://pt.stackoverflow.com/q/245172/64969) se aplicam aqui, conforme o próprio Jsbueno ressaltou
Comment: O Boost possui umas bibliotecas interessantes, sugiro utilizá-las para validação: [Format Date Parser](http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html#io_objects.format_date_parser). Porque Regex precisaria de algo mais complexo para validar por exemplo: `29/02/2018` ou `29/02/2020`. Em que o primeiro é inválido e o segundo válido.
Answer:
Regex definitivamente não é a ferramenta certa para resolver este problema. No entanto, li nos comentários que você está estudando regex... Então, só por diversão

Regex
^(?:(?:(0?[1-9]|1\d|2[0-8])([-/.])(0?[1-9]|1[0-2]|j(?:an|u[nl])|ma[ry]|a(?:pr|ug)|sep|oct|nov|dec|feb)|(29|30)([-/.])(0?[13-9]|1[0-2]|j(?:an|u[nl])|ma[ry]|a(?:pr|ug)|sep|oct|nov|dec)|(31)([-/.])(0?[13578]|1[02]|jan|ma[ry]|jul|aug|oct|dec))(?:\2|\5|\8)(0{2,3}[1-9]|0{1,2}[1-9]\d|0?[1-9]\d{2}|[1-9]\d{3})|(29)([-/.])(0?2|feb)\12(\d{1,2}(?:0[48]|[2468][048]|[13579][26])|(?:0?[48]|[13579][26]|[2468][048])00))$

⟶       ⟶       ⟶       ⟶         ⟶         ⟶           ⟶                 ⟿                     ∞
Vamos ver o Debuggex para desenrolar:

Ou explicado com variáveis:
std::string regexData() {
    std::string
        sep                = "/",

        dia1a28            = "(0?[1-9]|1\\d|2[0-8])",
        dia29              = "(29)",
        dia29ou30          = "(29|30)",
        dia31              = "(31)",

        mesFev             = "(0?2|feb)",
        mes31diasNum       = "0?[13578]|1[02]",
        mes31diasNome      = "jan|ma[ry]|jul|aug|oct|dec",
        mes31dias          = "("+mes31diasNum+"|"+mes31diasNome+")",
        mesNaoFevNum       = "0?[13-9]|1[0-2]",
        mesNaoFevNome      = "j(?:an|u[nl])|ma[ry]|a(?:pr|ug)|sep|oct|nov|dec",
        mesNaoFev          = "("+mesNaoFevNum+"|"+mesNaoFevNome+")",
        mesTudoNum         = "0?[1-9]|1[0-2]",
        mesTudoNome        = mesNaoFevNome+"|feb",
        mesTudo            = "("+mesTudoNum+"|"+mesTudoNome+")",

        diames29Fev        = dia29+sep+mesFev,
        diames1a28         = dia1a28+sep+mesTudo,
        diames29ou30naoFev = dia29ou30+sep+mesNaoFev,
        diames31           = dia31+sep+mes31dias,
        diamesNao29Feb     = "(?:"+diames1a28+"|"+diames29ou30naoFev+"|"+diames31+")",

        ano001a9999        = "(0{2,3}[1-9]|0{1,2}[1-9]\\d|0?[1-9]\\d{2}|[1-9]\\d{3})",
        anoX4nao100        = "\\d{1,2}(?:0[48]|[2468][048]|[13579][26])",
        anoX400            = "(?:0?[48]|[13579][26]|[2468][048])00",
        anoBissexto        = "("+anoX4nao100+"|"+anoX400+")",

        dataNao29Fev       = diamesNao29Feb+sep+ano001a9999,
        data29Fev          = diames29Fev+sep+anoBissexto,

        dataFinal          = "(?:"+dataNao29Fev+"|"+data29Fev+")";
    return dataFinal;
}

Usando diferentes separadores de data
Pode usar algo como:
^(dia)[-/.](mês)[-/.](ano)$

dia = match[1]; mes = match[2]; ano = match[3];

Mas isso permitiria uma data como 1.2/2000.
Para forçar uma coincidência usando o mesmo separador, deve usar um grupo para pegar o primeiro e, no segundo, usar um retrovisor (backreference) para coincidir com o texto capturado por esse grupo:
^(dia)([-/.])(mês)\2(ano)$

dia = match[1]; mes = match[3]; ano = match[4];

Código
#include <iostream>
#include <regex>

int main() {
    constexpr char text[]{"29/feb/2020"};
    std::regex re(R"((?:(?:(0?[1-9]|1\d|2[0-8])([-/.])(0?[1-9]|1[0-2]|j(?:an|u[nl])|ma[ry]|a(?:pr|ug)|sep|oct|nov|dec|feb)|(29|30)([-/.])(0?[13-9]|1[0-2]|j(?:an|u[nl])|ma[ry]|a(?:pr|ug)|sep|oct|nov|dec)|(31)([-/.])(0?[13578]|1[02]|jan|ma[ry]|jul|aug|oct|dec))(?:\2|\5|\8)(0{2,3}[1-9]|0{1,2}[1-9]\d|0?[1-9]\d{2}|[1-9]\d{3})|(29)([-/.])(0?2|feb)\12(\d{1,2}(?:0[48]|[2468][048]|[13579][26])|(?:0?[48]|[13579][26]|[2468][048])00)))");
    std::cmatch match;
    bool valid = std::regex_match(text, match, re);

    if (valid) {
        std::cout << "Data válida: " << match[0] << std::endl
                  << "Dia: " << match[1]  << match[4]  << match[7]  << match[11] << std::endl
                  << "Mês: " << match[3]  << match[6]  << match[9]  << match[13] << std::endl
                  << "Ano: " << match[10] << match[14] << std::endl;
    } else {
        std::cout << "Data inválida!!";
    }
    return 0;
}

Resultado
Data válida: 29/feb/2020
Dia: 29
Mês: feb
Ano: 2020

Exemplo no Ideone
Comment: caraca coisinha chata de se entender, faz tempo já que estava pesquisando como resolver este problema alem de algums outros na mesma agora esta tudo certo obrigado pela ajuda e atenção..
Comment: Interessante mas nao entendi pq vc usou "constexpr char text"ao invés de "const char text"? testei sua regex e ela esta validando formatos como 29-02.2000 ao invés de somente ser 29/02/2000 ou 29-feb-200 ou 29.2.200 tentei algo como [-|/|.] mas mesmo assim continua validando 29-02.2000..
Comment: eu tinha tentado algo parecido tambem com isso coloquei a sua sugestão e mesmo assim nao deu certo ainda continua validando: do mesmo jeito.
O meu codigo é este: https://pastebin.com/uztcDi7J
Comment: @dark777 Porque você não está usando uma [backreference](https://www.regular-expressions.info/backref.html) para o segundo separador. Veja a diferença em que usei `(?:\2|\5|\8)` e `\12` no meu padrão
Comment: entao eu tentei sem o backreferense e mesmo assim nao deu certo. ([-/.]) tentei usar assim tambem (?:[-/.]) ou ([-|/|.]) ou (?:[-|/|.])e mesmo assim nenhum deles deu certo.
Comment: @dark777 Talvez eu não estivesse suficientemente claro. Você DEVE usar uma backreference. Este é o seu código, editado com o regex correto: https://wandbox.org/permlink/nlctMLXJaGUFfNdu (e verifique as correções em `print()`)
Answer: Enquanto que seja possível fazer isso por meio de expressões regulares, eu não acredito que seja o melhor caminho em qualquer linguagem de programação.
(Não sei por que cargas d'água respondi a pergunta achando que era de Python também - mas a maior parte da resposta, exceto o código exato do exemplo, se aplica)
Nomes de meses vão ser bem mais fáceis de checar, verificar, e sobretudo - "pegar o número do mês", para ter um objeto date real se você verificar esses nomes de mês por fora da expressão regular.
Igualmente se sua aplicação em algum momento for funcionar em outra língua além do português: há frameworks para transformar programas em programas multi-lingua, e em geral eles dependem de você colocar todas as strings de seu programa dentro de uma chamada de função (muitas vezes com um nome destinado a ser quase transparente como _()). Essa funçao então busca sua string na língua desejada na base de traduções. Se os nomes dos meses estiverem hardcoded dentro da expressão regular, você teria que passar a regexp inteira para o engine de tradução.
Claro que seria possível montar um template da expressão regular, com os nomes dos meses em variáveis externas, e juntar tudo usando interpolação de strings, antes de se chamar a função de expressões regulares - isso é uma das vantagens de em Python expressões regulares serem utilizáveis através de chamadas de função normais, sem ter uma sintaxe especial.
Mas expressçõe regulares já são bem difíceis de ler e manter em código. Expressões regulares alteráveis em runtime seriam ainda mais complicadas de ler.
A minha dica, como no primeiro parágrafo, seria usar a expressão regular para obter os grupos com dia, mês e ano, e em seguida, um mecanismo mais tranquilo, com dicionários e if's para extrair o "mês real".
E aproveitar esse ensejo, para fazer a validação de dias do mês, ano, e etc...também fora do contexto da expressão regular. Vou colocar um exemplo em Python, que é um ótimo pseudo-código para C++  - mas você vai poder ter uma ideia do problema:
Então, em vez de:
def validate_date(text):
    if re.search(super_complicated_auto_validating_regexp, text):
        return True
    return False

É possível escrever algo como:
short_months = {"jan": 1, "fev": 2,...,"dez": 12}

def days_per_month(month, year):
    data = {1: 31, 2: 28, 3: 31, 4:30, ...}
    if month == 2 and year % 4 == 0 and (not year % 100 == 0 or year % 400 == 0):
            return 29
    return data[month]

def parse_date(text):
    match = re.search(r"(\d{1,2})/(.{1,3})/(\d{2,4})", text)
    if not match:
        raise ValueError("Invalid date format")
    day, month, year = [match.group[i] for i in (1,2,3)]
    day = int(day.lstrip("0"))
    if not month.isdigit():
       month = short_months[month.lower()]
    month = int(month.lstrip("0"))
    year = int(year):
    if year < 50:  # assume 2 digit years < 50 are in XXI
          year += 2000
    elif year <= 99:
         year += 1900
    if day > days_per_month(month, year):
        raise ValueError(f"Invalid day {day} for month {month}")
    result = datetime.date(year=year, month=month, day=day)

Perceba que são necessárias mais ou menos 20 linhas de código programático para fazer o parsing  e a validação da data. Com a abordagem que você tem de expressão regular, você quer comprimir toda  a lógica dessas 20 linhas em uma única 'linha', que na verdade é um mini-programa numa linguagem que não é amigável a manutenção.
Dito tudo isso, a forma mais normal de se fazer parsing e validação de datas "reais" nos vários formatos loucos que usuários possam digitar, ou estar em arquivos, é usar uma biblioteca especializada para isso. Nela, várias pessoas, durante centenas de horas, já deram uma pensada em como tornar a coisa mais amigável e mais a prova de erro - você teria que duplicar esse trabalho no seu código (com chances de fazer errado - veja a sutileza para calcular corretamente anos bissextos - que até a microsoft errou nas primeiras versões do Excel, por exemplo)
Em Python, temos a excelente dateparser, que permite que você faça simplesmente:
>>> import dateparser
>>> dateparser.parse("25/fev/2018", languages=["pt"])

datetime.datetime(2018, 2, 25, 0, 0)

Ela permite muitos outros formatos de data do que o separado por /, inclusive datas escritas por extenso em mais de 20 línguas - e não é propensa a erros por conta de "corner cases".
Em C++ eu buscaria por módulos complementares de data de algum framework que você já poderia estar usando para prover mais funcionalidades à linguagem - deve haver "natural date parsers" usando Qt ou Boost, por exemplo.
Comment: Respostas, mesmo que em linguagens divergentes da requisitada, são bem vindas. Imagina se eu pegar um problema semelhante em Python? Ou não ter um compilador C++ disponível para fazer um código para reconhecer datas? A propósito, gostei muito da resposta
Comment: A pergunta está rotulada com [tag:c++].
Comment: é - nem sei por que resondi como se fosse Python. A maior parte do texto em português se aplica no entanto - infelizmente não o exemplo de código. Vou manter a resposta, adicionadas as ressalvas.
Answer:
validar o seguinte formado de entrada das datas 29/feb/2000 [...]

Se você quer validar somente o formato de entrada tente essa regex de validação:
\d{2}\/[a-zA-Z]{3}\/\d{4}|\d{2}\/\d{2}\/\d{4}

Porém se você quer fazer uma validação que aceite somente os meses do ano, sugiro que você não use regex, tente fazer uma comparação na entrada do dia e mês analisando se é igual as entradas permitidas (Se for esse o caso, comente que posso modificar a resposta).

Explicação
Valida se a sequencia for:

2 Dígitos
1 /
3 Caracteres de a até z
1 /
4 Dígitos
Ou
2 Dígitos
1 /
2 Dígitos
1 /
4 Dígitos

Você também pode ver um exemplo dessa regex funcionando aqui.
Comment: interessante mas como estou estudando a std::regex do c++ estava tentando fazer isso com ela, tenho uma que faz a verificação doa anos bisextos e aceita de  2000/jan/30 a 2000/dec/30 ou 2000/01/30 a 2000/dec/30 ela faz verificação de anos bisextos corretamente mas valida yyyy/mm/dd estava tentando fazer o contrario para validar dd/mm/yyyy consegui mas agora precisava inserir os as strings dos meses nela.
Comment: @dark777 entendi, então você quer validar os meses agora? validar somente meses como jan, fev, mar, abr? Você pode usar varios "|" (ou's) aninhados na regex, porém ela vai virar um monstro de grande kkkk


Como converter pattern do regex do C# para C++?

Question: Eu estou tentando usar o regex do C++ mas estou tendo algumas dificuldades, uma delas é que o pattern estava em um código C#, e eu não sei praticamente nada de regex em C++, e por isso o código não funciona como deveria em C++
Aqui vai o trecho do código que não funciona como deveria:
if (!std::regex_match("BLUS31029", std::regex("^B[LC][JUEAK][SM]\d{5}$")))
    print_error("Invalid game id: " + game_id);
else
    ::id_ = game_id;
}

PS: Eu já troquei o regex_match por regex_search e mesmo assim não funcionou
Comment: "não funciona" significa que aparece algum erro ao compilar o programa, ou o resultado não é o esperado? Qual compilador você está utilizando?
Comment: @Gomiero Não funciona no sentido de dar o resultado esperado q no caso é true, e estou usando o Visual Studio 2019
Answer: Na string da expressão regular, o caractér \d é reconhecido pelo compilador
de forma incorreta como um escape sequence (sequência de escape).
Em várias linguagens, a barra invertida \ seguida de um
símbolo, é utilizada para representar caractéres que não
podem ser impressos ou que possuem significados especiais.
Exemplo: \n representa a ação "Nova Linha".
Para representar o caractér barra invertida, é necessário utilizar
duas barras \\, para indicar ao compilador que não se trata de uma
sequencia de escape.
Dependendo da configuração do Visual Studio (2019), durante a compilação,
ele deve ter emitido um aviso informando uma sequencia não
reconhecida:

warning C4129: 'd': unrecognized character escape sequence

O trecho do programa na pergunta, com a expressão regular corrigida, fica da seguinte forma:
if (!std::regex_match("BLUS31029", std::regex("^B[LC][JUEAK][SM]\\d{5}$")))
    print_error("Invalid game id: " + game_id);
else
    ::id_ = game_id;
}

Comment: O problema está na string em si, não no pattern, eu descobri isso dps, a string que eu coloco no regex tem algo errado que faz com o que o resultado do match dê false, com o pattern tá tudo certo


WPDB always returning array(0)?

Question: The below query is always returning an empty array i have checked that the $_POST is working but i am unsure what is going on?
$database = new wpdb(QLBBackendUser, QLBBackendPass, QLBBackendDB, DB_HOST);

if (isset($_POST['register-user'])):
    $user = $database->get_results('SELECT * FROM users WHERE email='.$_POST["user_email"]);
    var_dump($user);
endif;

Please note this is for Wordpress using WPDB Class.
Comment: You should never call the `wpdb` class directly...Use the global `$wpdb` object instead...Read more [in the codex](https://codex.wordpress.org/Class_Reference/wpdb)
Answer: You should never call the wpdb class directly...If you must, use the global $wpdb object instead. In addition, make sure the user_email has been POSTed (I'm not sure why you're checking for register-user being set and not user_email). Also, it's highly unlikely that the table you should be querying is called users (without a prefix). It's likely wp_users if you're using the default prefix.
Finally, there is a handy function that already does what you're trying to re-implement, called get_user_by:
$user = get_user_by( 'email', $_POST['user_email'] );

I recommend using the above, instead of trying to re-invent the wheel.
Comment: In addition, I would only suggest if @Elevant wants to keep the custom query, they can rewrite it as follows: `$wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->users} WHERE email=%s", $_POST['user_email'] ) );`. I believe it's important to point out the security hole that they had in their original query(using `$_POST` directly), even if it doesn't serve them now it is an important lesson to learn.
Comment: Are there security concerns in regards to calling wpdb directly? I have done it like that for a lot of pages. Also I didn't know about that function I should read more about them. Thanks
Comment: Also can you show me an example without calling wbdb directly? Or does it just mean to use the functions given like get user by function?
Comment: It's not unsafe to use the `$wpdb` object directly...however, it is unsafe to pass `$_POST` data directly to `$wpdb`. Instead you should [sanitize this data](https://codex.wordpress.org/Function_Reference/sanitize_text_field), before passing it to `$wpdb`. And yes, using functions like `get_user_by()` is the way to do it withough `$wpdb`

WPDB always returning array(0)?


if statement befor creating a node

Question: I need to set an if statement before creating a specific content type's node.
How can I stop the creation process if the condition returns false, and get back to the creation page with error message to let the user to correct the wrong value.
Is there a function to get it work?
Comment: Does the data you need to validate come from a field?
Comment: not exactly i want to test if there is a match from field value in creating node with field value from the referenced node.
if there is a match i want to stop the creation.
Comment: Either of the answers below should help you with that. You might also want to look at the [Field Validation](http://drupal.org/project/field_validation) module, in case you can do what you need to with that (no code necessarily required).
Comment: @Clive man..I use Field Validation on most of my sites..I can't believe I forgot it :@
Comment: @Chapabu It's friday, these things happen ;)
Answer: Another option would be to use hook_node_validate.

Perform node validation before a node is created or updated.
This hook is invoked from node_validate(), after a user has has
  finished editing the node and is previewing or submitting it. It is
  invoked at the end of all the standard validation steps, and after the
  type-specific hook_validate() is invoked.
To indicate a validation error, use form_set_error().

Something like the following would work:
function mymodule_node_validate($node) {
  if ($node->type == 'mynodetype') {
    if ($node->myfieldsvalue != 'what it should') {
      form_set_error('field_name', t('Your error message'));
    }
  }
}

References:
hook_node_validate
form_set_error
Comment: Not sure why this was downvoted, seems a perfectly good answer to me
Comment: I thought so...my personal preference would be to use `hook_node_validate` over Rules as this would give me more flexibility and keep everything in code.  Everyone's a winner.  Oh well.
Answer: I would try the Rules module.  For example, you can write a rule that fires on the event Before saving new content with the condition data comparison (on the relevant field's value) and an action of print status message.  You can of course further customize this to get it to do exactly what you want.

if statement befor creating a node


Axios giving error: 404 (not found) with all the requests

Question: I'm working in vuejs, and using axios. The axios is giving me the error 404 (not found). Banging my head around since 2 days and still cannot find the solution. The following is the code for axios and the error.
Comment: can you try from postman once check the endpoint is active?
Comment: i have checked it on the postman already, working fine there @saifali
Answer: Your URL is missing either a scheme (http:// or https://) or the double slash (//) that indicates it should be resolved relative to the current scheme.
Consequently, the IP address is taken as a relative path and the request is made to the same server for a path that doesn't exist.
You can see this in the error message that tells you the 404 error is coming from http://localhost:8080/188.8.131.52/etc!
Don't omit the scheme.
Comment: There's really nothing to elaborate on. It's a simple problem with a simple solution. I've no idea what is different with the other project.
Comment: I have also worked on a similar project, everything seems to be working perfectly there, but, causing the trouble here. Can you please elaborate a little.