Cpan module install fails

Question: I am trying to install the Inline::MakeMaker Perl module (including Inline::C), but it fails when installing Inline::C (seems it cannot find "make", though make is installed under /usr/bin).
This is on CentOS 6 with Perl v5.18.2 (installed from source under /usr/local/perl).
Here is the output from my installation attempt (I have divided the output in three parts to make it easier to read).
This is the first part (no errors):
[root@xyz .cpan]# cpan -i Inline::MakeMaker
Reading '/root/.cpan/Metadata'
  Database was generated on Tue, 01 Apr 2014 19:06:25 GMT
Running install for module 'Inline::MakeMaker'
Running make for S/SI/SISYPHUS/Inline-0.54.tar.gz
Checksum for /root/.cpan/sources/authors/id/S/SI/SISYPHUS/Inline-0.54.tar.gz ok

  CPAN.pm: Building S/SI/SISYPHUS/Inline-0.54.tar.gz

Checking if your kit is complete...
Looks good

Inline::C is packaged with Inline.pm because it is the most commonly used
Inline Language Support Module (ILSM).

See also: Inline::ASM, ::Awk, ::BC, ::Basic, ::Befunge, ::CPP (C++), ::CPR,
          ::Foo, ::Guile, ::Java, ::Octave, ::PERL, ::Python, ::Ruby, ::TT,
          ::Tcl and ::WebChat.

Config.pm indicates that your version of Perl was built with this C compiler:

    cc

I have located this compiler on your system.

Do you want to install Inline::C? [y] y
Writing Makefile for Inline::C
Writing MYMETA.yml and MYMETA.json
Writing Makefile for Inline
Writing MYMETA.yml and MYMETA.json
cp lib/Inline/MakeMaker/Changes blib/lib/Inline/MakeMaker/Changes
cp Inline.pm blib/lib/Inline.pm
AutoSplitting blib/lib/Inline.pm (blib/lib/auto/Inline)
cp Inline-API.pod blib/lib/Inline-API.pod
cp Inline-Support.pod blib/lib/Inline-Support.pod
cp lib/Inline/denter.pm blib/lib/Inline/denter.pm
AutoSplitting blib/lib/Inline/denter.pm (blib/lib/auto/Inline/denter)
cp lib/Inline/MakeMaker.pm blib/lib/Inline/MakeMaker.pm
cp lib/Inline/Foo.pm blib/lib/Inline/Foo.pm
cp Inline.pod blib/lib/Inline.pod
cp Inline-FAQ.pod blib/lib/Inline-FAQ.pod
make[1]: Entering directory `/root/.cpan/build/Inline-0.54-D_RUT7/C'
cp lib/Inline/C/ParseRegExp.pm ../blib/lib/Inline/C/ParseRegExp.pm
cp lib/Inline/C/ParseRecDescent.pm ../blib/lib/Inline/C/ParseRecDescent.pm
cp C-Cookbook.pod ../blib/lib/Inline/C-Cookbook.pod
cp C.pod ../blib/lib/Inline/C.pod
cp C.pm ../blib/lib/Inline/C.pm
Manifying ../blib/man3/Inline::C::ParseRecDescent.3
Manifying ../blib/man3/Inline::C::ParseRegExp.3
Manifying ../blib/man3/Inline::C-Cookbook.3
Manifying ../blib/man3/Inline::C.3
make[1]: Leaving directory `/root/.cpan/build/Inline-0.54-D_RUT7/C'
Manifying blib/man3/Inline.3
Manifying blib/man3/Inline-Support.3
Manifying blib/man3/Inline-API.3
Manifying blib/man3/Inline-FAQ.3
  SISYPHUS/Inline-0.54.tar.gz
  /usr/bin/make -- OK
Running make test
make[1]: Entering directory `/root/.cpan/build/Inline-0.54-D_RUT7/C'
Manifying ../blib/man3/Inline::C::ParseRecDescent.3
Manifying ../blib/man3/Inline::C::ParseRegExp.3
make[1]: Leaving directory `/root/.cpan/build/Inline-0.54-D_RUT7/C'
PERL_DL_NONLAZY=1 /usr/local/perl/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/00init.t ............. ok
t/01usages.t ........... ok
t/02config.t ........... ok
t/03errors.t ........... ok
t/04create.t ........... ok
t/05files.t ............ Skipping - couldn't load the Inline::Files module
t/05files.t ............ ok
t/06rewrite_config.t ... ok
t/07rewrite2_config.t .. ok
All tests successful.
Files=8, Tests=19, 12 wallclock secs ( 0.04 usr  0.01 sys +  1.28 cusr  0.05 csys =  1.38 CPU)
Result: PASS
<snip>

Here is where the error happens:
<snip>
make[1]: Entering directory `/root/.cpan/build/Inline-0.54-D_RUT7/C'
PERL_DL_NONLAZY=1 /usr/local/perl/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, '../blib/lib', '../blib/arch')" t/*.t
t/00init.t .............. ok
t/01syntax.t ............ ok
t/02config.t ............ ok
t/03typemap.t ........... ok
t/04perlapi.t ........... ok
t/05xsmode.t ............ ok
t/06parseregexp.t ....... ok
t/07typemap_multi.t ..... ok
t/08taint.t ............. 1/10 sh: make: No such file or directory

A problem was encountered while attempting to compile and install your Inline
C code. The command that failed was:
  make > out.make 2>&1

The build directory was:
/root/.cpan/build/Inline-0.54-D_RUT7/C/_Inline_test/build/_08taint_1_p_0965

To debug the problem, cd to the build directory, and inspect the output files.

 at ./t/08taint_1.p line 7.
    ...propagated at /root/.cpan/build/Inline-0.54-D_RUT7/C/../blib/lib/Inline/C.pm line 797.
BEGIN failed--compilation aborted at ./t/08taint_1.p line 7.
Compilation failed in require at t/08taint.t line 45.
# Looks like you planned 10 tests but ran 1.
# Looks like your test exited with 127 just after 1.
t/08taint.t ............. Dubious, test returned 127 (wstat 32512, 0x7f00)
Failed 9/10 subtests
<snip>

Here is the last part:
<snip>
t/09parser.t ............ This test could take a couple of minutes to run
t/09parser.t ............ ok
t/10callback.t .......... ok
t/11default_readonly.t .. ok
t/12taint_old.t ......... Skipped - applies only to perl 5.6.x
t/12taint_old.t ......... ok
t/14void_arg.t .......... ok
t/15ccflags.t ........... ok
t/16ccflagsex.t ......... ok
t/17prehead.t ........... ok
t/18quote_space.t ....... ok
t/19INC.t ............... ok
t/20eval.t .............. ok
t/21read_DATA.t ......... ok
t/22read_DATA_2.t ....... ok
t/23validate.t .......... ok
t/24prefix.t ............ ok
t/25proto.t ............. ok

Test Summary Report
-------------------
t/08taint.t           (Wstat: 32512 Tests: 1 Failed: 0)
  Non-zero exit status: 127
  Parse errors: Bad plan.  You planned 10 tests but ran 1.
Files=25, Tests=91, 30 wallclock secs ( 0.08 usr  0.02 sys + 25.88 cusr  2.11 csys = 28.09 CPU)
Result: FAIL
Failed 1/25 test programs. 0/91 subtests failed.
make[1]: *** [test_dynamic] Error 255
make[1]: Leaving directory `/root/.cpan/build/Inline-0.54-D_RUT7/C'
make: *** [subdirs-test] Error 2
  SISYPHUS/Inline-0.54.tar.gz
  /usr/bin/make test -- NOT OK
//hint// to see the cpan-testers results for installing this module, try:
  reports SISYPHUS/Inline-0.54.tar.gz
Running make install
  make test had returned bad status, won't install without force

Here is some more data from my attempt at debugging this (sorry for making the post quite long):
I manually executed the failing test in the debugger:
cd /root/.cpan/build/Inline-0.54-Rbzd5U/C
PERL_DL_NONLAZY=1
/usr/local/perl/perls/perl-5.18.2/bin/perl -d "-MExtUtils::Command::MM" "-e" "test_harness(0, '../blib/lib', '../blib/arch')" t/08taint.t

Here is an excerpt from the output:
t/08taint.t ............. 1/10 sh: make: No such file or directory

A problem was encountered while attempting to compile and install your Inline
C code. The command that failed was:
  make > out.make 2>&1

The build directory was:
/root/.cpan/build/Inline-0.54-Rbzd5U/C/_Inline_test/build/_08taint_1_p_0965

To debug the problem, cd to the build directory, and inspect the output files.

 at ./t/08taint_1.p line 7.
    ...propagated at /root/.cpan/build/Inline-0.54-Rbzd5U/C/../blib/lib/Inline/C.pm line 797.
BEGIN failed--compilation aborted at ./t/08taint_1.p line 7.
Compilation failed in require at t/08taint.t line 45.

So the file that it is failing on is t/08taint_1.p (which is required on line 45 of t/08taint.t).  08taint_1.p contains this:
BEGIN {is(${^TAINT}, 1, '1: taint_is_on');};

use Inline Config =>
    UNTAINT => 1,
    DIRECTORY => '_Inline_test';

use Inline C => <<'END_OF_C_CODE';

int add(int x, int y) {
    return x + y;
}

END_OF_C_CODE

is(add(7,3), 10, 'add_test');

1;

I gather that the test harness uses the above to construct a test, which in turn fails to find "make" for some obscure reason.
Here is /root/.cpan/build/Inline-0.54-Rbzd5U/blib/lib/Inline/C.pm (line 781-799), and it is the 2nd code line from the bottom that generates the error:
sub compile {
    my $o = shift;

    my $build_dir = $o->{API}{build_dir};
    my $cwd = &cwd;
    ($cwd) = $cwd =~ /(.*)/ if $o->UNTAINT;

    chdir $build_dir;
    # Run these in an eval block, so that we get to chdir back to
    # $cwd if there's a failure. (Ticket #81375.)
    eval {
      $o->call('makefile_pl', '"perl Makefile.PL"', 2);
      $o->call('make', '"make"', 2);
      $o->call('make_install', '"make install"', 2);
    };
    chdir $cwd;
    die if $@; #Die now that we've done the chdir back to $cwd. (#81375)
    $o->call('cleanup', 'Cleaning Up', 2);
}

So the "make" call above fails, but why?  Make is in /usr/bin, which is in the PATH.
Comment: Start by inspecting `t/08taint.t`
Comment: Did that already (stepped through with the debugger, but I am not familiar enough with perl and the test harness to figure out what is wrong).  I'll edit the question and add more details from that debugging.
Comment: @dawud I have added more data on the point it is failing at.
Answer: I did a force install (since the one failing test appeared to be faulty):
cpan -f -i Inline::MakeMaker

With this, it installed fine and I have not had any issues with it.
Answer: The problem seems to be a change in the Inline.pm "sub env_untaint{}" section.
The new test for dir writability somehow takes the path to "make" out, so of course it fails.  Notably, there is a commented-out section:
 # Was:
 #           join ':', grep...

If you restore the old Was: join code, and comment out the new join code above it in the env_untaint sub,
make clean, perl Makefile.PL, it should make test successfully, install away.

Cpan module install fails


Grails file uploading using restful-api plugin

Question: My Config.groovy file reads:
resource 'ktm-documents' config{
serviceName ='docCompositeService'
// methods = ['list']
representation {
    mediaTypes = ["application/vnd.hedtech.v1+json", "application/json", "multipart/form-data"]
    marshallers{
        jsonBeanMarshaller{
            supports net.hedtech.banner.decorator.DocDecorator
        }
        jsonBeanMarshaller{
            supports net.hedtech.banner.decorator.Indexes
        }
    }
    extractor = new  net.hedtech.banner.extractor.DocExtractor()
}
}

The extractor is:
class DocExtractor implements RequestExtractor{
@Override
Map extract(HttpServletRequest request) {
print("========== My EXTRACTOR ========")
MultipartHttpServletRequest mpr
Map responseMap = [:]
print request

try {
   print "Here's abc " + request.getParameter("abc")

   mpr = (MultipartHttpServletRequest) request;
   CommonsMultipartFile file = (CommonsMultipartFile) mpr.getFile("file");

    if (file.isEmpty()) {
        responseMap.put("error","file empty hai")
    } else {
        responseMap.put("file", file)
    }

print responseMap.values()

} catch (Exception e) {
   e.printStackTrace()
}
}
}

When trying to fetch the file which was extracted from request in the extractor inside the create() of service, I get "Cannot get property 'file' of null" error.
The create() method in service:
def create(Map params){

print params
File f = params.file

return ["File Uploaded!"]
}

Any thoughts on this please?
Answer: There was no problem with the code.
The request that was being sent from the POSTMAN REST client, had a Content-Type declared in it.
Please note that we shouldn't mention the Content-Type even while sending across a multipart/form-data request.
That worked.


A same code that will be used multiple times

Question: I'm making a system and i notice something on my codes
My code is not optimized but it's working
i want to lessen the redundancy of my codes
here an example
this is how i load
private void frmCategory_Load(object sender, EventArgs e)
    {
        //Populate
        con.Open();
        SqlCommand sc = new SqlCommand("SELECT ID,Category FROM Category WHERE Active = 1",con);
        SqlDataReader reader;
        reader = sc.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Columns.Add("ID",typeof(int));
        dt.Columns.Add("Category",typeof(string));
        dt.Load(reader);

        for(int x = 0; x <dt.Rows.Count; x++)
        {
            string ID = dt.Rows[x].ItemArray[0].ToString();
            string Category = dt.Rows[x].ItemArray[1].ToString();
            string[] row = { ID,Category };
            dgvCategory.Rows.Add(row);
        }
        con.Close();
    }

this is how i add
ry//Add
        {
            con.Open();
            SqlCommand sc = new SqlCommand("INSERT INTO Category([Category]) VALUES(@Category)", con);
            {
                sc.Parameters.AddWithValue("@Category", txtCategory.Text);
                sc.ExecuteNonQuery();
                MessageBox.Show(txtCategory.Text + " is added");
                txtCategory.Clear();
            }
            con.Close();
        }
        catch (SystemException ex)
        {
            MessageBox.Show(ex.ToString());
        }
        try//Refresh
        {
            dgvCategory.Rows.Clear();
            SqlCommand sc = new SqlCommand("SELECT ID,Category FROM Category WHERE Active = 1", con);
            SqlDataReader reader;
            reader = sc.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Category", typeof(string));
            dt.Load(reader);

            for (int x = 0; x < dt.Rows.Count; x++)
            {
                string ID = dt.Rows[x].ItemArray[0].ToString();
                string Category = dt.Rows[x].ItemArray[1].ToString();
                string[] row = { ID, Category };
                dgvCategory.Rows.Add(row);
            }
            con.Close();
        }
        catch (SystemException ex)
        {
            MessageBox.Show(ex.ToString());
        }

this is how i update
try//Update
        {
            string ID = dgvCategory.SelectedCells[0].Value.ToString();
            con.Open();
            SqlCommand sc = new SqlCommand("UPDATE Category SET Category = '" + txtCategory.Text + "' WHERE ID = '" + ID + "'", con);
            sc.ExecuteNonQuery();
            MessageBox.Show(dgvCategory.SelectedCells[1].Value.ToString() + " is updated to " + txtCategory.Text);
            con.Close();
        }
        catch (SystemException ex)
        {
            MessageBox.Show(ex.ToString());
        }
        try
        {
            dgvCategory.Rows.Clear();
            SqlCommand sc = new SqlCommand("SELECT ID,Category FROM Category WHERE Active = 1", con);
            SqlDataReader reader;
            reader = sc.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Category", typeof(string));
            dt.Load(reader);

            for (int x = 0; x < dt.Rows.Count; x++)
            {
                string ID = dt.Rows[x].ItemArray[0].ToString();
                string Category = dt.Rows[x].ItemArray[1].ToString();
                string[] row = { ID, Category };
                dgvCategory.Rows.Add(row);
            }
            con.Close();
        }
        catch (SystemException ex)
        {
            MessageBox.Show(ex.ToString());
        }

if you can i see. i always use the code from the load to populate my DGV again and that's how i refresh. i wonder if i can just make a block of code and name it LOAD then ill just use LOAD whenever i need to that code again
Comment: Refactor repeated code into methods and call the methods.  If you see only a few things varying, make those parameters that are passed in.
Comment: sorry guys. i put my code now. @duffymo
Answer: This is what you call "boilerplate". It's common for SQL code. The best example I know of for eliminating it is Spring's JdbcTemplate.
You need to look at the code in these methods and figure out how to refactor it into several classes.  Your goal should be to be able to pass in the stuff that changes into methods containing the boilerplate that doesn't change.
You have a message box doing I/O in one method.  You need to remove that.  No user interface code.
At minimum you have to be able to pass in SQL and execute it.  Start with that.


Is `while(*p++ = *(p+1));` undefined behavior?

Question: I have code that manipulate C-string with one-line while loop statement.
It works perfectly when compiled with MSVC2015, but gives different outcome when compiled with TDM-GCC (gcc (tdm-1) 5.1.0).
Here is a minimal example that shows the problem. The code overwrites current char with next char, repeat over and over again until it sets the current char to \0.
#include <stdio.h>

int main()
{
    char buf[999] = "Foobar", *p = buf;
    while(*p++ = *(p+1));
    printf("buf = %s\n", buf);
    return 0;
}

When the code is compiled with MSVC2015, the output is buf = oobar as expected. With TDM-GCC, however, the output is buf = obar.
If I change the while statement to while(*p = *(p+1)) { ++p; }, both compiler will give the expected result buf = oobar. It seems that by putting the post-increment operator inside the expression, I have triggered undefined behavior somehow.
My question is, why the code behaves differently when compiled with different compiler? Is it wrong (or non-standard) to put increment operator inside a non-trivial while statement? Did I trigger undefined behavior? If so, how should the code behave according to the C standard? If not, who is to blame here? TDM-GCC? MSVC?
UPDATE: For those in future who have the same doubt as me, the answer is: Yes, the code invokes UB. The well-defined way is to do like this: while(*p = *(p+1)){++p;}

Someone asked why would we want to code like this. Here is a scenario where this idiom can be useful.
#include <stdio.h>
#include <Windows.h>

static void EscapeDquote(char * const sz)
{
    char *p = sz;
    BOOL bs = FALSE;
    for (; *p; ++p)
    {
        if (*p == '\\') {
            bs = !bs;
            continue;
        }
        if (*p == '\"') {
            if (bs) {
                /*
                    discard prev char (backslash before dquote)
                    overwrite with next char until null-termi
                */
                char *q = --p;
                /* OLD version, not OK for GCC */
                /* while(*q++ = *(q+1)); */
                /* Safer version, works in GCC as well: */
                while(*q = *(q+1)){++q;}
            }
        }
        bs = FALSE;
    }
}

int main()
{
    /* "call \"D:\foo bar.exe\" */
    char szTest[] = "call \\\"D:\\foo bar.exe\\\"";
    printf("Before = %s\n", szTest);
    EscapeDquote(szTest);
    printf("After  = %s\n", szTest);
    return 0;
}

Comment: why writing code that way in the first place?
Comment: probably missing a sequence point somewhere, but hurts my head trying to know why. When you code stuff like this, there's already undefined behaviour in your head. If you want speed why not trying assembly? at least it's deterministic
Comment: @MartinJames Are you suggesting that if I have doubt on such code, I shall not ask it on SO? Seriously? I knew my code could be UB, that's why I asked, "Is this UB?", yet you're saying as if I'm promoting bad code by asking it here.
Comment: @rsp `p` is only modified once in the expression
Comment: The actual definition of "post", as in post-increment, is apparently left somewhat in the air. Some compilers apply it after the statement has been parsed and others after the left hand side. To be on the safe side, put p++ inside the while block so that you can guarantee what you're going to get.
Comment: @Jean Short code, and it does the job. Let's say I want to modify a string buffer so all double quotes would be removed. With this idiom I can overwrite the dquote with next char, over and over again until the end.
Comment: And I don't think I modify the `p` twice as @M.M said. It is `(p+1)` not `(++p)`.
Comment: @Mike Yeah, I think it's safer that way. BTW it seems SO really hate people write such code. I thought it's commonplace to do thing this way when you do low-level programming.
Comment: Downvoter, care to explain?
Comment: I cannot see why this question gets downvoted. It's clear and interesting.
Comment: 'and it does the job' - aparrently not, since you are asking aboout it here. 'SO really hate people write such code. I thought it's commonplace to do thing this way when you do low-level programming' - not if you want to be able to easily debug it, it's not.  'Clever' code is bad code.
Comment: @MartinJames That's why I want to confirm the correctness of such code, because I would be in big trouble if the code goes wrong due to UB. Code like `while(*p++ = *q++);` are very obscure, but at the same time they are so short and make your code clean, provided you're fully sure what it does.
Comment: 'provided you're fully sure what it does' - exactly.  You re not sure, so you ask here.  That makes is bad code, not clean code.  Imagine what some maintenance/enhancement developer thinks when hunting some obscure bug, and finds code like yours?  Such thoughts cannot be published on a public site:)
Comment: @raymai97 By all means ask on SO, and you have.  My comment on it is that your code is bad, whether correct or not.  Also, I'm not suggesting that you are promoting bad code, merely publishing it here.  If the result is that, in the future, fewer developers write code that is difficult-to-debug, and possibly incorrect, then I call that a win overall.
Comment: If you know the string length (you do know in the example scenario), use `memmove()`: `memmove(szTest, szTest+1, sizeof szTest - 1); `
Comment: Please don't edit the answer into the question, it makes it confusing for future readers. The format of the site is that you accept the answer that best answers the question
Comment: @klutt once you've read a few thousand questions about stacking increment operators with other increment/assignment operators, it is much less interesting...  "don't do that, even if you think you have it figured out, other people reading the code will be confused" applies to all such cases
Answer: Use -Wall If you are using GCC compiler. It is indeed an undefined behaviour in both C & C++.
See live demo here.
See the diagnosis given by compiler
main.cpp: In function 'int main()':

main.cpp:6:13: warning: operation on 'p' may be undefined [-Wsequence-point]

     while(*p++ = *(p+1));

            ~^~

Comment: My TDM-GCC would only show `warning: suggest parentheses around assignment used as truth value [-Wparentheses]` with the same command-line. What version of gcc do you use?
Answer: It is undefined behaviour, because the following two operations are unsequenced:

The write to p in p++
The read of p in (p+1)
Comment: Thanks, so if I put the increment operator inside the while block, the code behavior will be well-defined, right?
Comment: @raymai97 if what you mean is `while( p[0] = p[1] ) { ++p; }` yes that would be well-defined (and infinitely more readable).  I'm not sure whether you intended to increment `p` in the case that `p[0] == 0` though; if so then you'd need to write something different
Answer: It is undefined behavior as there is sequence point not defined.
Workaround would be while ((*p = *(p + 1)) && p++); if you want it in single line.
Now you will first set your pointer and if assigned value is non-zero, you will continue with defined sequence to p++ statement. If assignment value is zero, while loop will end means string was shifted.
Comment: @raymai97 This is defined way in C
Comment: If I do it this way, the behavior will be well-defined, right?
Answer: Yes, It is undefined behaviour, because Clang compiler gives following error:
source_file.cpp:6:13: warning: unsequenced modification and access to 'p' [-Wunsequenced]
    while(*p++ = *(p+1));
            ^      ~

C11: 6.5 Expressions:

If a side effect on a scalar object is unsequenced relative to either
  a different side effect on the same scalar object or a value
  computation using the value of the same scalar object, the behavior is
  undefined. If there are multiple allowable orderings of the
  subexpressions of an expression, the behavior is undefined if such an
  unsequenced side effect occurs in any of the orderings
Comment: I think I need a better compiler. My TDM-GCC just wouldn't tell me this even with `-Wall`. Thanks for showing me this.


Como relacionar um model em outro model no Django 2

Question: Estou fazendo um sistema no qual preciso mostrar dados que estão cadastrados em outro Model, que no caso é o campo Categoria que está na Model Itens e ao mostrá-las, o usuário selecionaria uma delas e o sistema mostraria os dados que estão somente vinculados à categoria selecionada.
Ex.:
Cadastro de armário
Nome:
Descrição:
Categorias: Calçados| Calças| Blusas| * Selecionei Blusas
Itens: Aqui o sistema mostra somente os itens da categoria Blusas com a opção de selecionar o item
Armário: Conterá os itens selecionados.

itens\models.py
from django.db import models

class Categoria(models.Model):
    name_categoria = models.CharField(max_length=100, null=True)

    def __str__(self):
        return self.name_categoria

class Cor(models.Model):
    cor_item = models.CharField(max_length=50, null=True)

    def __str__(self):
        return self.cor_item

class ItenManager(models.Manager):
    def search(self, query):
        return self.get_queryset().filter(
            models.Q(name__icontains=query) | \
            models.Q(cor__icontains=query)
        )

class Itens(models.Model):
    name = models.CharField('Nome:', max_length=100)
    slug = models.SlugField('Atalho:')
    categoria = models.ForeignKey('Categoria',on_delete=models.CASCADE)
    cor = models.ForeignKey('Cor', on_delete=models.CASCADE)
    image = models.ImageField(
        upload_to='itens_imagens', verbose_name='Imagem:', null=True, blank=True
    )
    objects = ItenManager()

    def __str__(self):
        return self.name

    @models.permalink
    def get_absolute_url(self):
        return ('itens:details', (), {'slug': self.slug})

    class Meta:
        verbose_name = 'Item'
        verbose_name_plural = 'Itens'
        ordering = ['name']

armario\models.py
from django.db import models

class Armario(models.Model):
    name= models.CharField('Nome',max_length=50, blank=False)
    slug = models.SlugField('Atalho')
    descricao = models.CharField('Descrição',max_length=100, blank=True)
    created_at = models.DateField('Criado em', auto_now_add=True)
    updated_at = models.DateField('Atualizado em',auto_now=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Armário'
        verbose_name_plural = 'Armários'
        ordering = ['name']

Comment: Você pode usar javascript (ajax) para enviar uma requisição para a url do django quando o usuário selecionar a categoria.
Answer: Bom, o relacionamento entre os modelos já está feito aí - não tem muito o que mexer nesse lado.
Agora é pensar como você vai apresentar essas informações. Se você está desenvolvendo uma aplicação WEB com páginas estáticas: suas views retornam templates renderizados, que são preenchidos com variáveis do Python, a única coisa que você precisa a mais (além de pensar bem suas views e templates), é colocar a opção related_name no modelo Itens. (aliás, 'itens' pode não ser um bom nome - se não achar nada melhor, pelo menos é melhor deixar no singular Item - todas as outras classes são no singular, não é?)
Mas então, dentro de itens, você declara as categorias assim:
categoria = models.ForeignKey('Categoria', related_name='itens', on_delete=models.CASCADE)

Fazendo isso, dentro de objetos da classe Categoria você pode usar o atributo itens que devolve uma sequência de todos os itens daquela categoria - isso pode ser usado direto no template, com o for:

 Categoria {{ categoria.name_categoria }} :

  {% for item in categoria.items %}

{{ item.name }}

  {% endfor %}

Isso funciona por que quando o django preenceh os dados de um template, isso ainda é feito por código Python rodando no servidor, que tem acesso a todas as variáveis e ao banco de dados.
Agora, se sua aplicação carrega dados dinâmicamente, com ajax, ou usando frameworks como angular, react, etc...  - nesse caso você vai ter views que retornam os dados dos objetos serializados como JSON.
Nesse caso, para economizar chamadas, pode ser interessante embutir alguns dos dados dos seus itens quando a pessoa solicitar uma categoria - isso pode ser feito manualmente no código da view (você cria um dicionário em Python que vai adicionar todos os dados que vão ser passados para o front-end, nesse dicionário inclui uma chave itens, e uma lista com os nomes e links para os itens, por exemplo),
from django.http import JsonResponse
def categorias_view(request):
    resposta = []
    for categoria in models.Categoria.objects.all():
        dados_categoria = {}
        dados_categoria['nome'] = categoria.categoria_name
        dados_categoria['itens'] = [item.name for item in categoria.items]
        resposta.append(dados_categoria)
    return JsonResponse(resposta)

A outra opção no caso de uma app web com chamadas dinâmicas, é dar mais um passo e vê sobre o "Django rest framework"  (DRF) - que permite que você use bem pouco ou nenhum código pra cirar esssas views que renderizam os dados dos objetos como JSON. Nesse caso, você vai criar classes associadas a cada modelo que são chamadas de "serializers". O framework dá uma porção de atalhos para você embutir os dados relacionados desejados dentro do seu JSON sem precisar ficar fazendo isso manualmente.
O uso do DRF faz muitas mágicas, que podem economizar muita digitação em sistemas grandes - mas se você tem poucos objetos, e está aprendendo, eu recomendaria fazer as views retornando json manualmente, até você entender legal o que está fazendo, e o que daria para automatizar, e aí passar para o DRF - senão ele vai ficar parecendo um monte de burocracia a mais, e no final faz uma mágica e "dá certo".


Proving inequality on functions $x-\frac{x^2}{2}<\ln(1+x)<x-\frac{x^2}{2(1+x)}$

Question: To prove: $$x-\frac{x^2}{2}<\ln(1+x)<x-\frac{x^2}{2(1+x)},\quad\forall x>0$$
I have used Taylor series expansion at 0 for both the inequalites. The greater than by expanding $\ln(1+x)$ and the less than by expanding $\int \ln(1+x)\,dx$ at 0.
Is there a cleaner / more elegant way of achieving the same?
Comment: Taylor series expansion cannot give you such inequalities, for any fixed x.
Answer: Another way to do the lower bound, for example, would be to consider $f(x) = x - \dfrac{x^2}{2} - \ln(1+x)$. $f(0) = 0$.
But also $f'(x) = 1 - x - \dfrac{1}{1+x} = \dfrac{(1-x)(1+x) - 1}{1+x} = \dfrac{1 - x^2 - 1}{1+x} = \dfrac{-x^2}{1+x} < 0$.
So since $f(0) = 0$ and $f' < 0$, $f$ is monotonically and strictly decreasing. Thus $f(x) \leq 0$, and if $x > 0$ we have that $f(x) < 0$. And this says exactly that $x - x^2/2 < \ln(1 + x)$.
Comment: Yes, Yes, absolutely! Thank you, I was looking for this kind of a solution. Much neater.
Comment: The Taylor series with either Lagrange or integral form of the remainder is fine. We get that $\ln(1+x)=x-\frac{x^2}{2}+\frac{2}{(1+c)^2}\frac{x^3}{3!}$ for some $c$ between $1$ and $x$, which yields the lower bound.
Comment: @AndréNicolas Thanks I will have a look at it.
Comment: @Soham: I wrote out a simple argument for the upper bound. One could also use a remainder term argument for that, since remainder term arguments and the more "basic-looking" sign of derivatives arguments are essentially the same.
Answer: The upper bound also yields to standard calculus methods. Equivalently, we want to prove that $(1+x)\ln(1+x) \gt x(1+x)-\frac{x^2}{2}$, or more simply that $x+\frac{x^2}{2} \gt (1+x)\ln(1+x)$.
Let $f(x)=x+\frac{x^2}{2}-(1+x)\ln(1+x)$. We have $f(0)=0$. We will show that $f$ is increasing, and hence posiive, for positive $x$. We have
$$f'(x)=1+x-(1+\ln(1+x))=x-\ln(1+x).$$
To show that $f'(x)$ is positive for $x \gt 0$, note that $f'(0)=0$. But $f'(x)$ is increasing, since $f''(x)=1-\frac{1}{1+x} \gt 0$ for $x\gt 0$.
Answer: The first inequality is easier and can be obtained by integrating the inequality $1-t<(1+t)^{-1}$ with respect to $t$ on interval $[0,x]$. For the second inequality note that $$\frac{1}{1+t}-1=-\frac{t}{1+t}<-\frac{t}{1+x}$$ whenever $0<t<x$. Integrating the above with respect to $t$ on $[0,x]$ gives the second inequality.


Will static synchronized method help to resolve race condition in Microservice environment which has multiple instances of the same pod

Question: In a microservice environment, if multiple instances of the same pod are present, will separate classes be created for each instance or the class resource is read from a common place for both the instances?
I was thinking since Static Synchronized method locks the class level we can prevent race condition. Any input would be helpful.
Answer: The 'static' or 'synchronized' keywords apply only for a single process.
As soon as you run multiple instances it won't help, no matter if on the same machine, same container or different containers/pods or machines.
This might be helpful as alternative: https://www.jobrunr.io/en/ or https://github.com/lukas-krecan/ShedLock


What is shortest path between two points $P (0,0)$ and $Q (12,16)$ such that the path doesn't cross the circle $(x-6)^2 +(y-8)^2 = 25$?

Question: What is shortest path between two points
$P (0,0)$ and $Q (12,16)$ such that the path doesn't cross  the circle
$(x-6)^2 +(y-8)^2 = 25$ ?
Edit
Here is a graph of path of length $10+5\pi$
and this value  is one of the options in the problem
The others are
 $10\sqrt {3}$   ,  $10\sqrt {5}$  , $10\sqrt {3} +\frac {5\pi} {3}$  ,
$\frac {40*\sqrt{3}}{3}$
Comment: Have you tried anything, like drawing a picture, perhaps?
Comment: There are some symmetries such that the points and the center of the circle (0,0), (6,8), (12,16) being co-linear, and  the points being on perfect opposite sides of the circle, and the linear distance between start and end being 20 while the radius of the circle is 5. Thus you can simplify the numerics by rotations and scaling.

I'm going to start with the problem of start and end points (0,0) and (4,0) with the circle at (2,0) with radius 1.
Answer: The path that you are taking has length $= 10 + 5\pi = … = 25.7050$.

Note that the shaded triangle is equilateral and the circle is inscribed in a rhombus of sides $\dfrac {20 \sqrt 3}{3}$; (which can be found through the "30-60-90" special angled triangle).
If we go along the green paths, the distance travelled is $\dfrac {40 \sqrt 3}{3} = … = 23.0940$.
Answer: HINT
"Does not cross "means also that it is tangential. Start with a sketch. Assume that the shortest path is a circle tangent to it.
So find the tangent slope $ =\dfrac{16}{12}  =\dfrac{4}{3} $
Differentiate circle equation and the above slope in:
$$ 2 (x-6) + 2 (y-8) y^{'}=0$$
$$ 3x+4 y= 50 $$

whose intersections with circle obtained when solved are  $ (10,5),(2,11) $ Now discard second wrong solution and find minor arc length shown.
Comment: @Narasimham  can you have a look to the edit  , please
Comment: Please look at my sketch of continuous circular arc and compute minor segment length that  seems to shorter than what you sketched.
Comment: I get your point, but another curve can be shorter than following a circle ?
Comment: We can  vary curvature arbitrarily large and the shortest solution  introduces a discontinuity, So I suggested (an unstipulated uniform) curvature.


How many words of length $7$ can we assemble if each letter should appear at least twice.

Question: From the letters "a,b,c" we assemble words with $7$ letters, how many words can we assemble if each letter should appear at least twice.
My attempt:
There are $7$ places: $\color{blue}{*******}$
$1)\color{red}{a}\color{blue}{b}\color{green}{c}\color{red}{a}\color{blue}{b}\color{green}{c}\color{red}{a}$
$2)\color{red}{a}\color{blue}{b}\color{green}{c}\color{red}{a}\color{blue}{b}\color{green}{c}\color{blue}{b}$
$3)\color{red}{a}\color{blue}{b}\color{green}{c}\color{red}{a}\color{blue}{b}\color{green}{c}\color{green}{c}$
$\Longrightarrow\boxed{ 3\cdot \binom{7}{3}\cdot \binom{4}{2}\cdot \binom{2}{2}}$
English is not my first language, so feel free to correct
Comment: The answer $3\cdot\binom{7}{3}\cdot\binom{4}{2}$ looks fine to me.
Comment: @JackD'Aurizio ok thanks
Comment: The answer is ok, but the explanation simply isn't there. For all I know, you could have peeked your solution from someone else, so I would still give 0 marks for this.
Answer: The answer is ok, but you might  use another approach if you like it.
Choose the extra letter, and permute all $7$, so $\left(3\cdot\dfrac{7!}{3!2!!2!}\right)$


check port open without telnet

Question: What do people use when Telnet is not installed to check a port is open and reachable?  E.g. I used to use the technique of telnet <destination> and know it was there, even if telnet could not interact with the system on the other end.
With Windows 2008 telnet is not installed so I've been a bit lost.  So what can I use instead.  And something if its not there in Linux or Solaris, too please.
I am a consultant who works on different sites.  For a number of reasons (access rights, change control times, if I install it someone uses it next year we have some liability, etc) I cannot install on someone else's server. But a USB or other self contained, non-installed tool would be wonderful ...
Comment: Why don't you just install it?
Comment: http://joncraton.org/blog/46/netcat-for-windows/
Comment: Its a shame this was closed as Off Topic - I have just used one of the answers provided.  Luckily the solution was not a product or service that I could not get past the firewall.  I did learn something though so maybe it could be considered learning material.  But if so no question could ever be posted - someone learns something from each of them.
Comment: See: [check status of one port on remote host](http://stackoverflow.com/q/1168317/55075) at SO
Comment: How is this possibly off topic?
Comment: Or install something like `nmap`...
Comment: Try using [nmap](http://www.nmap.org)
Comment: Yet another utility, PortQryUI.  http://www.microsoft.com/en-us/download/details.aspx?id=24009
Comment: `echo > /dev/tcp/localhost/11211 && echo Port open || echo Port closed
`
Comment: Telnet client is available as a Feature in all Windows Server versions. You can install it by running the Add Features wizard.
Answer: Here are several different ways to test a TCP port without telnet.
BASH (man page)
# cat < /dev/tcp/127.0.0.1/22
SSH-2.0-OpenSSH_5.3
^C

# cat < /dev/tcp/127.0.0.1/23
bash: connect: Connection refused
bash: /dev/tcp/127.0.0.1/23: Connection refused

cURL
# curl -v telnet://127.0.0.1:22
* About to connect() to 127.0.0.1 port 22 (#0)
*   Trying 127.0.0.1... connected
* Connected to 127.0.0.1 (127.0.0.1) port 22 (#0)
SSH-2.0-OpenSSH_5.3
^C

# curl -v telnet://127.0.0.1:23
* About to connect() to 127.0.0.1 port 23 (#0)
*   Trying 127.0.0.1... Connection refused
* couldn't connect to host
* Closing connection #0
curl: (7) couldn't connect to host

Python
# python
Python 2.6.6 (r266:84292, Oct 12 2012, 14:23:48)
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> clientsocket.connect(('127.0.0.1', 22))
>>> clientsocket.send('\n')
1
>>> clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> clientsocket.connect(('127.0.0.1', 23))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused

Perl
# perl
use IO::Socket::INET;
$| = 1;
my $socket = new IO::Socket::INET(
  PeerHost => '127.0.0.1',
  PeerPort => '22',
  Proto => 'tcp',
);
die "cannot connect to the server $!\n" unless $socket;
print "connected to the server\n";
^D
connected to the server

Comment: +1 Was not aware of the curl method, very cool!  :)
Comment: this helped me notice that I have curl in vanilla windows 10 so thank you
Answer: Use Powershell like a boss

Basic code
$ipaddress = "18.104.22.168"
$port = 53
$connection = New-Object System.Net.Sockets.TcpClient($ipaddress, $port)

if ($connection.Connected) {
    Write-Host "Success"
}
else {
    Write-Host "Failed"
}

One Liner
PS C:\> test-netconnection -ComputerName 22.214.171.124 -Port 53

Turn it into a cmdlet
[CmdletBinding()]
Param(
  [Parameter(Mandatory=$True,Position=1)]
   [string]$ip,

   [Parameter(Mandatory=$True,Position=2)]
   [int]$port
)

$connection = New-Object System.Net.Sockets.TcpClient($ip, $port)
if ($connection.Connected) {
    Return "Connection Success"
}
else {
    Return "Connection Failed"
}

Save as a script and use all the time
Then you use the command in your powershell or cmd prompt like so:
PS C:\> telnet.ps1 -ip 188.8.131.52 -port 53
or
PS C:\> telnet.ps1 22.214.171.124 53
Comment: You can also just execute: New-Object System.Net.Sockets.TcpClient("IP or DomainName", 80)  And you'll get an error if it can't connect, or information on the created object if the connection succeeded.
Comment: How does that work in terms of closing the socket? For example I know if I open a webrequest to IIS, but don't close the connection, it will reach a limit and I won't be able to test anymore.
Comment: If you don't want to worry about leaving the the socket open for a while you can do this: (New-Object System.Net.Sockets.TcpClient($ip, $port)).Close  Same deal as before; Error if you can't connect, but it'll print this out if it connected then closed the port successfully: void Close()
Comment: Good question. I imagine it does the same thing as in your answer (since you/we don't dispose of it or close the socket manually); The TcpClient should get garbage collected at some point, or the socket will hit a read timeout before that. Just a guess, haven't tested it!

check port open without telnet


Can you pass a SwiftUI ForEach identifer as a parameter?

Question: I have a generic struct that takes a list of objects, and displays a list of checkboxes. This uses generics so I can pass in any type of object (the struct also takes a function parameter to tell it how to get the display text from the object).
The ForEach uses id:\.self as the identifier, and this works fine as long as the objects are identifiable and hashable.
However, this is part of a KMM project, and sometimes the objects I'm working with aren't identifiable/hashable. I can work around this by using an explicit identifier (e.g. id:\.uuid), but this is resulting in a bunch of duplicated code as I can't use my generic view.
Is it possible to pass the identifier to the struct as a parameter with self being the default? I.e. I'd like to do something like:
var forEachIdentifier = T.self and then use it like ForEach(options, id: forEachIndentifier){...
Here's the full struct:
struct SelectMultipleChoiceDialog<T:Hashable>: View {
    var onDismissRequest: () -> Void
    var title: String
   var  options: [T]
   var  selectedOptions: [T]
   var  text: (T) -> String
   var  onCheckedChange: (T, Bool) -> Void
    var body: some View {
        NavigationStack{
            ScrollView{
                LazyVStack {
                    ForEach(options, id:\.self){option in

                        HStack{
                            Toggle(isOn: Binding(get: {
                                selectedOptions.contains(option)
                            }, set: { value in
                                onCheckedChange(option, value)
                            })){
                            }
                            .toggleStyle(iOSCheckboxToggleStyle())

                            Text(text(option))
                        }
                        .padding(.vertical, 6)

                    }
                }
            }
            .navigationTitle(title)
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarItems(trailing: Button("Done"){
               onDismissRequest()

            })
        }
    }
}

Answer: You can use small View structs to reuse code instead.
Best just remove Hashable and id: /.self and you won't have this problem. ForEach is designed to use Identifiable so when options change it can do a diff and update the underlying UIViews.
You said "objects" rather than values though, in that case you don't even need Identifable since objects are already identified by their pointer.
Seems to me you want to write to the options, the syntax for that is:
ForEach($options){ $option in

If you put the Toggle in a custom View then you can use onChange to do your action and don't need the closure.
Comment: The problem with this is that it requires $option to be identifiable, and as I mentioned, I am sometimes working with objects that aren't identifiable. However, I think I've found the answer using   `ForEach(Array(options.enumerated()), id:\.offset){index, option in...`
Comment: Objects are identifiable by default. You can't use ForEach with indicies like that, it'll crash.
Comment: If I use your way I get an error `Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'T' conform to 'Identifiable'` - if I use the indicies approach it works perfectly with no crashes.
Comment: It will crash when the options array changes because an index is not an identifier so when you look up the array by index it can be out of range.


C# How to Display Image(resource) array in TabPage

Question: Goal: when the application starts I want to generate a button per each picture in my resources (6 for testing, 128 final build), in side of a TabPage.
Here is where i am at so far:
private void tabPage1_load(object sender, EventArgs e)
{
    ResourceSet rs = new ResourceSet("");
    IDictionaryEnumerator id = rs.GetEnumerator();
    List<Bitmap> CIcons = new List<Bitmap>();
    while (id.MoveNext())
    {
        if (id.Value is Bitmap)
            CIcons.Add((Bitmap)id.Value);
    }
}

this doesn't seem to do the trick, any suggestions would be greatly appreciated
Edit(addition): the issue is when the application starts I'm not seeing the images listed int "tabPage1".
also yes i do have 6 images added to my "Resource Folder" inside Visual Studios.
Just for future folks i wanted to add the finished working code:
        // Button list start
        // Credit to Jcl
        ResourceSet rs = Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
        IDictionaryEnumerator id = rs.GetEnumerator();
        List<Bitmap> CIcons = new List<Bitmap>();
        while (id.MoveNext())
        {
            if (id.Value is Bitmap)
                CIcons.Add((Bitmap)id.Value);
        }

        int yposition = 0;
        foreach (var bmp in CIcons)
        {
            Button button = new Button();
            button.Location = new Point(0, yposition);
            button.Size = new Size(125, 125);
            button.Visible = true;
            button.BackgroundImage = bmp;
            tabPage1.Controls.Add(button);
            yposition += 125;

        }
        //Button list end

Comment: Did you add the images to `Resources.resx` file?
Comment: I do have the images in the resource folder,  my issue is im not seeing the end result on the form when it loads. what would be a good way to isolate weather the issue is being called from resource or being "rendered" on the form when loaded?
Comment: Don't you use a `.resx` file? Did you set your images as embedded resources? It's unclear what you are asking. Also it's unclear if you have problem with reading the images or problem with adding them as buttons to the `TabPage`.
Comment: Break your question to smaller parts and set your first goal to read images from resources. Then for your second goal (in fact your second question if you need) try to add images as buttons to `TabPage`. Describe all required information which may help to solve the problem and share errors that you have received when you run the program.
Answer: If you want to generate a button, I'd say something like:
private void tabPage1_load(object sender, EventArgs e)
{
    ResourceSet rs = new ResourceSet("");
    IDictionaryEnumerator id = rs.GetEnumerator();
    List<Bitmap> CIcons = new List<Bitmap>();
    while (id.MoveNext())
    {
        if (id.Value is Bitmap)
            CIcons.Add((Bitmap)id.Value);
    }

    // Vertical aligned: i'll let you figure out how to position them
    int yposition = 0;
    foreach(var bmp in CIcons)
    {
       var button = new Button();
       button.Location = new Point(0, yposition);
       button.Size = new Size(50, 20); // for example
       button.Visible = true;
       button.BackgroundImage = bmp;
       tabPage1.Controls.Add(button);
       yposition += 20; // height of button

    }
}

Update
As noted in the comments (I thought it was example code, but seems it's not), you also need to specify where to get the ResourceSet from. In your case, change:
ResourceSet rs = new ResourceSet("");

for
ResourceSet rs = Properties.Resources.ResourceManager.GetResourceSet(
                                  CultureInfo.CurrentUICulture, true, true);

Code legibility bonus
All this code:
IDictionaryEnumerator id = rs.GetEnumerator();
List<Bitmap> CIcons = new List<Bitmap>();
while (id.MoveNext())
{
    if (id.Value is Bitmap)
        CIcons.Add((Bitmap)id.Value);
}

Is equivalent to:
List<Bitmap> CIcons = new List<Bitmap>();
foreach(var bmp in rs.OfType<Bitmap>())
  CIcons.Add(bmp);

And since you can create a list from an enumerable, you could simply do:
List<Bitmap> CIcons = new List<Bitmap>(rs.OfType<Bitmap>());

But also, since you are not using your bitmap list for anything else than creating the buttons, you could just not define it, and then your whole code becomes:
var rs  = Properties.Resources.ResourceManager.GetResourceSet(
                         CultureInfo.CurrentUICulture, true, true);
int yposition = 0;
foreach (var bmp in rs.OfType<Bitmap>())
{
    var button = new Button()
    {
        Location = new Point(0, yposition),
        Size = new Size(125, 125),
        Visible = true,
        BackgroundImage = bmp,
    };
    tabPage1.Controls.Add(button);
    yposition += 125;
}

This could be further optimized: if I was you, instead of positioning by calculating the pixel location of each component, I'd use a FlowLayoutPanel to arrange the buttons. Usage of the FlowLayoutPanel is way outside the scope of this question though, I'm just mentioning it just in case you want to investigate and google further
Comment: i attempted this and i'm still not seeing buttons/images in the tabpage. maybe my event/call is all wrong?
Comment: Sorry, did it from head... change `this.Controls.Add(button)` to `tabPage1.Controls.Add(button)`. See update
Comment: Btw, I assumed this was example code, but you are not specifying a filename nor getting your `ResourceSet` from a `ResourceManager`... I was hoping the resources part was already right and your problem was adding the controls to the tabpage... but if you are creating your `ResourceSet` passing an empty string, there's no way there'll be any resource loaded from it. You need to either pass it a filename or get it from the generated `ResourceManager`
Comment: I got the same thing, i attempted to throw it in Public Form1() { the code}, and got a error at "ResourceSet rs = new ResourceSet("");"  saying: "empy path name is not legal"
Comment: Yes, that's what I was commenting: where are you putting your resources?
Comment: I see from the update: the resources folder is not enough to get resources compiled for winforms (or to get a `ResourceSet`)... you should be generating a resource file (`.resx`) which links those images in your resources folder. After that, you'll have a class generated with the name of the `resx` file plus the default namespace of your project... then you can do `ResourceSet rs = ResourceClassName.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);` with `ResourceClassName` being the generated class
Comment: i guess we posted right at the same time on that one xD. as far as my resource location Project_name/Resources/  (note im using visual studios, so i added them to the project via the gui).   also i thought by creating the resource set i was calling all files with a "name" in resources
Comment: i went back over my project and i do have a Resources.resx file. with fun and exciting code like:  internal static System.Drawing.Bitmap Akali {
            get {
                object obj = ResourceManager.GetObject("Akali", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }
Comment: The class name i mentioned should be on top of that file
Comment: Okay, im really a dummy... how do i do that?
Comment: @StromReedy I added the explanation, and some bonus "code-optimization" tips :-)


RESTful URLs, master pages, and PreviousPage woes

Question: I'm am building my asp.net web application using MVC (Preview 5),
and am also using the Master pages concept.
My PageA and PageB are both content pages. I'm doing a form submit
in a method via JavaScript from PageA to PageB.
PageB has its PreviousPageType attribute set to PageA, but when I access the
PreviousPage property in PageB, it returns null.
Am I missing out on something here?
Answer: I assume you want to access data of PageA in PageB.  You can wrap the data in an object and use the Model Binders as described in Form Posting Scenarios by Scott Gu to pass it to the controller.  You can then redirect to show PageB.
HTH,
Sunil Unnithan
Answer: You can use TempData to store an object that your next request will need access to, this is how I avoid passing big lumps of data between sequence pages.


What can impact the throughput rate at tcp or Os level?

Question: I am facing a problem, where running the same application on different servers, yields unexpected performance results. For example, running the application on a particular faster server (faster cpu, more memory), with no load, yields slower performance than running on a less powerful server on the same network.
I am suspecting that either OS or TCP is causing the slowness on the faster server. I cannot use IPerf , unless i modify it, because the "performance" in my application is defined as
Component A sends a message to Component B. Component B sends an ACK to component A and ONLY then Component A would send the next message. So it is different from what IPerf does, which to my knowledge, simply tries to push as many messages as possible.
Is there a tool that can look at OS and TCP configuration and suggest the cause of slowness?
Answer: With a "ping-pong" type of protocol like that, I think I would start by looking at latency between the two endpoints.  If you can only have a single message in-flight, small changes in latency can have pretty large impact on total throughput.
I don't know of a particular tool that I would use to benchmark the particular sort of behavior that you have.  A packet capture, as always, might be illuminating.


ARP responds with single MAC address on Linux server with multiple interfaces on the same network

Question: Linux server has 2 active network interfaces:
<code>IF:eth1    IP:192.168.1.1/24    MAC:11:11:11:11:11:11   (1GbE)
IF:eth2    IP:192.168.1.2/24    MAC:22:22:22:22:22:22   (10GbE)
</code>
The idea is that the 10GbE interface (eth2) is the primary interface for communication with hosts on the network. I want to leave the second 1GbE interface (eth1) up as a failsafe. In the event that the 10GbE interface goes down: I'd still have an easy way in, can update DNS so hosts can connect, etc.
While observing interface statistics I noticed that all traffic was sending/receiving on the eth1 instead of eth2 despite the fact that all hosts on the network are addressing this interface. I confirmed DNS A record points to the IP of the correct interface. Additionally, I confirmed that addressing the interface by IP instead of FQDN produces the same result.
I cleared the ARP cache on my machine and pinged the eth1 interface by IP address. I inspect my ARP table and find the MAC address of eth1. I cleared the ARP cache again and pinged the eth2 interface by IP address. Again, I inspect my ARP table and find the MAC address of eth1 (not eth2).
If I bring down eth1, physically disconnect the interface, or put it on a different logical network - I get the expected behavior, traffic goes over my eth2 interface.
My question: Why does this happen? I am seeing some evidence that this is expected behavior on the linux kernel due to its "weak host model."
How can I keep both interfaces up, on the same network, and have them work in the way that I expect.
Answer: Linux is designed to respond to ARP requests on any interface. It is assumed that the host owns the IP address and not the particular interface. What you are seeing is called ARP Flux.
You can change this behavior using sysctrl

arp_ignore - INTEGER
Define different modes for sending replies in response to
  received ARP requests that resolve local target IP addresses:
0 - (default): reply for any local target IP address, configured
  on any interface
1 - reply only if the target IP address is local address
  configured on the incoming interface
2 - reply only if the target IP address is local address
  configured on the incoming interface and both with the
  sender's IP address are part from same subnet on this interface
3 - do not reply for local addresses configured with scope host,
  only resolutions for global and link addresses are replied
Comment: You are correct on both counts. Set it to 1 or 2 and you should see the correct ARP replies on the client.
Comment: This makes perfect sense. Quick follow up question to see if I understand the arp_ignore options correctly. I presume this parameter is set for the kernel and not per-interface? If this is correct, will arp_ignore 1 produce the results I am seeking - where arp will reply with the MAC address of the interface of which it is assigned?
Answer: If your switch supports it, I would use 802.1ad link aggregation for providing failover.
With this feature, you bond the two interfaces together, and you can set one as active and one as passive interface. Your IP address would reside on the bonding interface, so there would be no IP address changes if one NIC fails.
Comment: +1, this was my first instinct when reading the question, as it would be a more desirable solution as long as the switch supports it.
Comment: Thank you, this is a great idea. I didn't know that 802.1ad had an option for active/passive. Is it not a problem to mix a gigabit and 10gig interface in the bond? If that works, I will use this solution going forward.
Comment: I haven't tested the setup with different speed interfaces myself, but I don't see anything that would prevent it from working.
Comment: @TeroKilkanen after doing some additional research it appears as though most, if not all, 802.1ad implementations require identical speed links for members in the bond.


Can I retrieve certificate information from ClickOnce deploy files?

Question: I have a ClickOnce application that has been deployed to many users that was signed with a certificate that was located on a previous developer's computer. The certificate has expired since that developer left the company. In order to re-publish the application from another machine we need to be able to find the original certificate and update it with an extension. I have access to the previous developer's computer, but I cannot locate the original .pfx file to copy and update the certificate. I also have access to all of the previously deployed files.
We attempted to deploy the application and received the error:

The deployment identity does not match the subscription.

My best guess is that it is, in fact, the different certificate causing this error based on an MSDN forum question and response, Deployment identity does not match the description. However, it is worth noting that we have both changed the machine from which the code is being deployed and also updated the solution to Visual Studio 2010 (the platform and configuration are the same though).
How do I retrieve the original certificate information from the previous developer's machine or the deploy files? Or are we possibly going down the wrong hole trying to resolve this?
Comment: We ended up resolving this by republishing to a different file share, as we needed to do that anyway, and sending out a link to all of the users to re-install.
Answer: If the physical access to the machine/user account is available, it should not be a problem to retrieve the certificate, provided it was not protected with a custom password at the time of import. The export wizard can be launched from Internet Explorer Options as shown on the picture. Look up the desired certificate in one of the tabs (typically, in Personal tab). Use PFX format to export both private and public keys.

Another way to access the Export wizard is through the MMC snap-in.
[UPDATE] For the answer's completeness sake, it is impossible to retrieve the private key from a signed deployment file as it only contain the public part of the encryption key. Perhaps, in the OP's case the private key is still there, buried somewhere in the file system of the development machine (as .PVK file), although it'd be a bad practice to store it like that. More details about certificate file types can be found here. I would rather expect both private and public keys to be found in the machine's certificate store, as described above.


Drupal multisites share modules and libraries?

Question: I want to duplicate a drupal site to make subsites where each site will utilise the same basic modules and core but just have slight variations in theme and need own database on a dedicated server. To save memory I want to avoid having subsites all containing same modules, I have only briefly read the documentation for drupal multisites where they share the one core but is it possible to share sites/all/modules and libraries as well?
Answer: Yes.
In a multisite setup anything in sites/all is shared.
This means sites/all/modules, sites/all/themes, sites/all/libraries are all shared.
In addition to that, if you have things that are specific to a subsite, for example, a sub-theme, or a module or library, you can add them in sites/subsite_name/modules, sites/subsite_name/themes, sites/subsite_name/libraries.
Comment: Thxank you!!!!!


What is the DB2 equivalent of DUMP function in Oracle?

Question: The dump function in Oracle displays the character set and bitwise representation of how data is stored.
Does anybody know if there is an equivalent command in DB2 please? Thank you.
Answer: Using the following query and the functions below up might be able to come up with a UDF to do what you need.
<code>    SELECT NAME, VALUE
    FROM SYSIBMADM.DBCFG
    where NAME in ('codepage','codeset','collate_info')

    BITAND
    BITOR
    BITXOR
    BITNOT
    BITANDNOT
</code>


Laurent series of $\frac{1}{(z-1)(z-2)}$

Question: How can I compute the Laurent series of $$f(z)=\frac{1}{(z-1)(z-2)}$$ on the circular ring $A(0;1,2)=B(0,2)\setminus \overline{B(0,1)}$?
I tried to take the Cauchy product of geometric series but these series don't converge in the area.
Comment: Hint:
$$f(x)=\frac{(z-1)-(z-2)}{(z-1)(z-2)}=\frac1{z-2}-\frac1{z-1}.$$
Can you do those two terms separately? And see [this](http://math.stackexchange.com/q/228529/11619)
Answer: So you want $\;1<|z|<2\;$:
$$\frac1{(z-1)(z-2)}=\frac1{z-2}-\frac1{z-1}=\frac12\cdot\frac1{1-\frac z2}-\frac1z\cdot\frac1{1-\frac1z}$$
Now use the well known developments of geometric series with ratio less than one, and observe that both
$$\left|\frac z2\right|<1\;,\;\;\;\left|\frac1z\right|<1$$
Answer: First rewrite $f$ as
$$ -\frac{1}{2}\frac{1}{1-\frac{z}{2}}+\frac{1}{1-z}$$
Now, the first you can rewrite using geometric series as long as $|\frac{z}{2}|<1\iff|z|<2,$ so in particular in your domain $A$.
The second would converge only in $|z|<1.$ The trick is to rewrite it as (which is geometrically sort of doing circle inversion https://en.wikipedia.org/wiki/Inversive_geometry#Circle_inversion)
$$-\frac{1}{z}\frac{1}{1-\frac{1}{z}},$$
so that now its GS again converges if $|\frac{1}{z}|<1\iff1<|z|$. I.e. in particular in your domain $A$.
Now sum the two and you are done
Answer: The constraints are $1 < \lvert z \rvert < 2$, which can be rewritten $\lvert z/2 \rvert < 1$ and $\lvert 1/z \rvert < 1$.
Using partial fraction decomposition, we obtain $$f(z) = \frac{-1}{2}\frac{1}{1-z/2} - \frac{1}{z}\frac{1}{1-1/z}.$$
Therefore $$f(z) = \frac{-1}{2}\sum_{i=0}^\infty \left(\frac{z}{2}\right)^i - \sum_{i=-1}^{-\infty} z^{i}.$$


K-fold cross validation and F1 score metric

Question: I have to classify and validate my data with 10-fold cross validation. Then, I have to compute the F1 score for each class. To do that, I divided my X data into X_train (80% of data X) and X_test (20% of data X) and divided the target Y in y_train (80% of data Y) and y_test (20% of data Y).  I have the following questions about this:

Is it correct to run cross validation with only training data, or I have to run it with all data X?
Is it correct to divide data in training and test parts to compute the F1 score, or is there a way to obtain F1 score for each class with all data?

For reference, here is the code I wrote:
X_df = pd.read_csv('X.csv', skipinitialspace=True, sep=',', header=None)
X = X_df.values
Y_df = pd.read_csv('Y.csv', header=None)
Y = Y_df[0].values

X_train_df = pd.read_csv('X_train.csv', skipinitialspace=True, sep=',', header=None)
X_train = X_train_df.values
y_train_df = pd.read_csv('Y_train.csv', header=None)
y_train = y_train_df[0].values

X_test_df = pd.read_csv('X_test.csv', skipinitialspace=True, sep=',', header=None)
X_test = X_test_df.values
y_test_df = pd.read_csv('_Y_test.csv', header=None)
y_test = y_test_df[0].values

######################## RandomForest #################################"

clf = RandomForestClassifier(n_estimators=100, n_jobs=1, criterion="gini")
clf.fit(X_train, y_train)

cv = np.mean(cross_val_score(clf, X_train, y_train, cv=10))
print ("Accuracy using RF with 10 cross validation : {}%".format(round(cv*100,2)))
y_predict_test = clf.predict(X_test)

#F1_score

score_test = metrics.f1_score(y_test, y_predict_test,
                              pos_label=list(set(y_test)), average = None)

print score_test

The code works perfect but I'm not certain about the results. So I wanted to verify with you.
Comment: Be aware the questions that are just about software / code are generally off topic here. You have substantive statistical / machine learning questions that are on topic, but the big block of code is making some people think this is an off topic question about code. I will edit this to make your questions more salient.
Answer:
It is correct to run cross validation on only the training data. You want to keep your test set completely separate from the training set, which is used to tune the model. This way you get an unbiased estimate of model performance because the model has never been exposed to the data. The test set should not be used to tune the model any further.
It is correct to divide the data into training and test parts and compute the F1 score for each- you want to compare these scores. As I said in answer 1, the point of using a test set is to evaluate the model on truly unseen data so you have an idea of how it will perform in production. If you see a large drop in performance between the training score and test score it is likely due to the model overfitting.


Proof of Motzkin numbers recurrence

Question: I know the Motzkin numbers are given as $$M_n=\sum_{k=0}^{\lfloor n/2\rfloor}{n \choose 2k}C_k,$$ where $$C_k=\frac{1}{1+k}{2k\choose k}.$$
The recurrence relation is given as $M_n=M_{n-1}+\sum_{k=0}^{n-2}M_kM_{n-2-k}$. Is there a direct way to prove this recurrence using either Pascal's identity or summation by parts?
Comment: The [combinatorial interpretation](https://en.wikipedia.org/wiki/Motzkin_number) in terms of paths makes the recurrence relation pretty trivial.
Comment: We can simplify a bit: $\frac{1}{k+1}\binom{n}{2k}\binom{2k}{k} = \frac{1}{k+1}\binom{n}{k}\binom{n-k}{k} = \frac{1}{n+1}\binom{n+1}{k+1}\binom{n-k}{k}$. The first transformation uses $\binom{r}{m}\binom{m}{k} = \binom{r}{k}\binom{r-k}{m-k}$. The second uses $\frac{1}{k+1}\binom{n}{k} = \frac{1}{n+1}\binom{n+1}{k+1}$
Comment: We can give a direct combinatorial proof. Motzkin numbers count Motzkin paths. To construct a Motzkin path of length $n$, do the following. (1) Choose the $2k$ positions for the up and down steps in $\binom{n}{2k}$ ways. The subsequence of those steps is a Dyck path of semilength $k$, so the number of such sequences is $C_k$. Then (2) Insert level steps in the remaining positions.
Answer: One possible approach starts from
$$M_n = \sum_{k=0}^{\lfloor n/2\rfloor} {n\choose 2k} C_k.$$
This is
$$\sum_{k=0}^{\lfloor n/2\rfloor} {n\choose n-2k} C_k
\\ =  \sum_{k=0}^{\lfloor n/2\rfloor} C_k [z^{n-2k}] (1+z)^n C_k
= [z^n] (1+z)^n  \sum_{k=0}^{\lfloor n/2\rfloor} C_k z^{2k}.$$
Now  when  $2k\gt n$  there  is  no  contribution to  the  coefficient
extractor and hence we may extend the sum to infinity:
$$[z^n] (1+z)^n  \sum_{k\ge 0} C_k z^{2k}.$$
Using the generating function of the Catalan numbers this becomes
$$[z^n] (1+z)^n  \frac{1-\sqrt{1-4z^2}}{2z^2}$$
which is
$$\mathrm{Res}_{z=0} \frac{1}{z^{n+1}}
(1+z)^n  \frac{1-\sqrt{1-4z^2}}{2z^2}.$$
With $z/(1+z) = w$ we have $z = w/(1-w)$ and $dz = 1/(1-w)^2 \; dw$
and obtain
$$\mathrm{Res}_{w=0}
\frac{1}{w^n} \frac{(1-w)^3}{2w^3} (1-\sqrt{1-4w^2/(1-w)^2})
\frac{1}{(1-w)^2}
\\ = \mathrm{Res}_{w=0}
\frac{1}{w^{n+1}} \frac{1-w-\sqrt{1-2w-3w^2}}{2w^2}.$$
This shows that
$$M_n = [w^n] \frac{1-w-\sqrt{1-2w-3w^2}}{2w^2},$$
which is also the LHS of the recurrence. We get for the RHS
$$[w^{n-1}] \frac{1-w-\sqrt{1-2w-3w^2}}{2w^2}
+ [w^{n-2}] \frac{(1-w-\sqrt{1-2w-3w^2})^2}{4w^4}
\\ = [w^{n}] \frac{2w-2w^2-2w\sqrt{1-2w-3w^2}}{4w^2}
+ [w^{n}] \frac{(1-w-\sqrt{1-2w-3w^2})^2}{4w^2}.$$
The numerator is
$$2w-2w^2-2w\sqrt{1-2w-3w^2} + 2 - 4w - 2w^2
- 2(1-w)\sqrt{1-2w-3w^2}
\\ = 2 - 2w - 4w^2 - 2 \sqrt{1-2w-3w^2}.$$
We therefore conclude that the RHS is
$$[w^n] \left(-1 + \frac{1-w-\sqrt{1-2w-3w^2}}{2w^2}\right),$$
which is the same as the LHS when $n\ge 2,$ as claimed.

Proof of Motzkin numbers recurrence


Get custom parameter inside AppKernel

Question: I'm trying to include custom values for the cache and logs directories. The reason is to make it work fast with Vagrant.
This is the cache method with a static value (inside app/AppKernel.php):
public function getCacheDir()
{
    if (in_array($this->environment, array('dev', 'test'))) {
        return '/dev/shm/project/app/cache/' .  $this->environment;
    }

    return parent::getCacheDir();
}

and I'd want to do something like:
public function getCacheDir()
{
    if (in_array($this->environment, array('dev', 'test'))) {
        return $this->getContainer()->getParameter('cache_dir') .  $this->environment;
    }

    return parent::getCacheDir();
}

and then, in parameters.yml:
 cache_dir: '/dev/shm/project/app/cache/'

But $this->getContainer() is returning null here. I've tried to get the container inside other kernel methods without success. Any idea if it's possible?
Answer: You could always try to define the class that allows you to get the cache directory as a service and then pass the service container into that class.
services:
  your_cache_dir_service:
      class: Acme\TestBundle\Services\CacheHelper
          arguments: [@service_container]

Comment: AppKernel as a service?

Get custom parameter inside AppKernel


Calling Session.close() on HibernateDaoSupport

Question: HiI'm using HibernateDaoSupport for my application to do hibernate related actions(Save, update etc).
Well I'm getting the hibernate session by calling getSession() to create a criteria.
 After getting my result should I call session.close(); or will it automatically get released?
Answer: An idiomatic way to use Session in HibernateDaoSupport is to call execute() or executeFind() on HibernateTemplate obtained from getHibernateTemplate(). With this approach you won't need to manage your session manually.
Comment: Thanks I think I could use `executeFind()` for my need


In Codeigniter : How to get url if i clicked on the fetched data from database

Question: I get this data through one controller in a list in my view files,and  i also want to show in every page a different meta title. How it is Possible ?
  View
<?php
      $data = "";
             foreach($items_data as $row){

                    $data .=  '

                                item_id).'">'.$row->item_name.'

';

                }
                echo $data;
                ?>

Suppose i got four items like

Books
Pens
Computers

All of my items are showing these urls which is pretty good.

www.xyz.com/1
www.xyz.com/2
www.xyz.com/3

But i want to show my item names in every url. along with different meta tag title name.
Now when i click on any listed items my url will show something like these
This is possible or not , Because above list are getting from database.

www.xyz.com/computers
www.xyz.com/Books
www.xyz.com/Pens

Here is my controller which is fetching data from database.
Controller
function index() {
            $data['items_data'] = $this->Visa_mdl->get_items_name();
            $data['title']  = "Hotels";
            $this->load->view('include/header');
            $this->load->view('hotels/visa',$data);
            $this->load->view('include/footer');
        }

This Controller is Linked to other Pages.
function ls($item_name = NULL) {

            $data['title']  = "Company Lists";
            $result = $this->Visa_mdl->get_items_company_list($item_name);
            $result1 = $this->Visa_mdl->get_items_name_in_dash($item_name);

             $data['items_data'] = $this->Visa_mdl->get_items_name();
            // $data['items_company_data'] = $this->Visa_mdl->get_items_company_list($id);
            $this->load->view('include/header',$data);
            $this->load->view('hotels/dashboard',$data);
            $this->load->view('include/footer');
        }

Answer: Instead of this:
item_id).'">'.$row->item_name.'

try
item_name).'">'.$row->item_name.'

and try again.
In your code you have passed $row->item_id which shows item id in url, instead of that pass $row->item_name then it will show item name in url.
Comment: Thank you ..its working .. But  Sorry i did not mention there for what title i want to show . i want to show meta tag  title description in every items pages.is  meta tag is possible  or not
Comment: I think you have to implement ```slug``` for your pages, and save meta description, tags in your database, when your url hits, you can get the data using slug and load it in your view.
Comment: Yes, it is possible pass that value instead of `$row->item_name`
Comment: Hey @MayankPandeyz  as i wanted to get the name of my item in my url , i get that, But Problem is if my items contains white spaces then white space converted into %20, and also my other pages are linked to these item name , So my linked pages are not getting data for further pages.
Comment: @vishalkumar convert your all `$row->item_name` of table to **slug string** and save it at the same table with **slug field** and use it as `$row->slug` in anchor tag


GCC pure/const functions that accept a pointer argument

Question: Can someone please clarify whether (and why) a function can be attributed pure or const if it has a pointer parameter.
According to the GCC documentation:

Some of common examples of pure functions are strlen or memcmp.

The whole point of a pure function is that it need only be called once for the same parameters, i.e. the result can be cached if the compiler thinks it fit to do so, however how does this work for memcmp?
for example:
char *x = calloc(1, 8);
char *y = calloc(1, 8);

if (memcmp(x, y, 8) > 0)
    printf("x > y\n");

x[1] = 'a';
if (memcmp(x, y, 8) > 0)
    printf("x > y\n");

The parameters to the second call to memcmp are identical to the first (the pointers point to the same address), how does the compiler know not to use the result from the first call, if memcmp is pure?
In my case I want to pass an array to a pure function, and calculate the result based on the array alone. Someone reassure me that this is okay, and that when values in the array change but the address does not, my function will be called correctly.
Answer: If I understood the documentation correctly, a pure function can depend on values of the memory, where the compiler knows whenever the memory changes. Moreover, a pure function can not change the state of the program, such as a global variable, it only produces a return value.
In your example code, memcmp can be a pure function. The compiler sees that the memory is changed between the calls to memcmp, and can not reuse the result of the first call for the second call.
On the other hand, memcmp can not be declared as a const function, since it depends on data in memory.
If it was const, the compiler could apply more aggressive optimizations.
For this reason, it seems safe to declare the function that you want to implement as pure (but not const).
Answer: With respect to pure we can see from the article Implications of pure and constant functions that pure means that the function does not have side effects and only depends on the parameters.
So if the compiler can determine that the arguments are the same, and memory has not changed between subsequent calls it can eliminate the subsequent calls to the pure function since it knows the pure function does not have side effects.
Which means the compiler has to do analysis to be able to determine if the arguments to the pure function could have been modified before it can decide to eliminate subsequent calls to a pure function for the same arguments.
An example from the article is as follows:
int someimpurefunction(int a);
int somepurefunction(int a)
  __attribute__((pure));

int testfunction(int a, int b, int c, int d) {

  int res1 = someimpurefunction(a) ? someimpurefunction(a) : b;
  int res2 = somepurefunction(a) ? somepurefunction(a) : c;
  int res3 = a+b ? a+b : d;

  return res1+res2+res3;
}

and it shows the optimized assembly generated which shows that somepurefunction was only called once and then says:

As you can see, the pure function is called just once, because the two references inside the ternary operator are equivalent, while the other one is called twice. This is because there was no change to global memory known to the compiler between the two calls of the pure function (the function itself couldn't change it – note that the compiler will never take multi-threading into account, even when asking for it explicitly through the -pthread flag), while the non-pure function is allowed to change global memory or use I/O operations.

This logic also applies to a pointer, so if the compiler can prove the memory pointed to the pointer has not been modified then it can eliminate the call to the pure function so in your case when the compiler sees:
x[1] = 'a';

it can not eliminate the second call to memcmp because memory pointed to by x has changed.
Comment: Thanks for the article link, interesting. But my question was specifically about pointer arguments to pure functions.
Comment: So what happen if 8 and 1 are not known at compile time? E.g. they are variable?
Comment: @kata: if the compiler cannot prove the memory has not been mutated, it must assume that it might have been. So it will not perform the (unsafe) optimization.
Comment: Okay, it' clear now. This answer should be accepted :)
Comment: I will accept this answer if you add a small section at the end explaining that the same logic applies to pointers (I just want to ensure people landing here via google and not reading these comments feel their question is answered)


Zimbra several DNS names

Question: We have Zimbra 8.0.3 OS edition server. Our server has several A-entries in DNS-server. Let's suppose they are aaa.mydomain.com, bbb.mydomain.com and ccc.mydomain.com. Could anybody say what I should do to redirect users to page 404 when they use bbb.mydomain.com, ccc.mydomain.com and server IP-address but give them access to mail web-client if they use aaa.mydomain.com?
Thanks in advance.
Comment: Sorry. I forgot to tell I was using Jetty.
Comment: Do you really want a 404 or to redirect them to the right location using a 302 redirect?  Also is jetty out in front or is apache in the mix somewhere?  You will need to pick where you want to handle the redirects or 404.
Comment: I don't really know if jetty is behind apache or not in zimbra. I haven't much experience with web servers.
And yes, I want 404 page to be used.
Answer: You could do something like this:
<code>  RewriteEngine on
  RewriteCond %{HTTP_REFERER} ^bbb.mydomain\.com$ [NC]
  RewriteRule .*  - [R=404]
</code>
You could also try a general forbidden error, like this:
<code>  order allow,deny
  deny from bbb.mydomain.com
  allow from all
</code>
Comment: Sorry! I didn't tell that I was using Jetty =)
Comment: as far as I know zimbra use Jetty behind Apache .
Comment: I'm not sure, but it seems they are independent in Zimbra.
Answer: So I have solved this problem. You should add following lines into jetty.xml.in in directive < New id="zimbra" class="org.eclipse.jetty.webapp.WebAppContext" >...<  /New> :
<code>   <Set name="virtualHosts">
       <Array type="java.lang.String">
         <Item>aaa.mydomain.com</Item>
       </Array>
   </Set>
</code>
Thanks everyone =)

Zimbra several DNS names


Dynamically generate text inside 'content' of a CSS pseudo-class

Question: I want to dynamically generate the text within 'content' of a CSS pseudo class in the proper way. I have filled a working jsfiddle with my example so far. This picture shows better how I want to achieve this:

This is the relevant code (it's in the fiddle also):
[part of] index.php:

  <input type="checkbox" value="None" id="slideThree" name="check"/>

[part of] style.css:
.checkbutton:before
  {
  content: 'Hombre';
  float: left;
  width: 60px;
  text-align: center;

  /* 28 es la altura total */
  font: 12px/28px Arial, sans-serif;
  color: CornflowerBlue;
  z-index: 0;
  font-weight: bold;
  }

I want to be able to reuse that code for two purposes:

Dynamically and internally translate it with PHP.
Different buttons with similar style.

This means, I want to be able to create a similar button but with different names, or just translate it without extra markup. I have no idea how to do this properly. Here's why:

The CSS is in a unique .css file, separated from the content. Obviously, this doesn't execute php.
It's not possible to have CSS pseudo elements inside inline styles
No JavaScript. While this could be achieved with javascript, I prefer to avoid it where possible.

How can I achieve it? I find it odd that I need to use CSS for
Comment: gap between posting question and posting own (long) answer is?
Comment: As read in the link I just put, **`it is not merely OK to ask and answer your own question, it is explicitly encouraged.`**
Comment: what do you mean, @Waygood ?
Comment: You constructed your question and posted it, then a few seconds later posted the answer! Did you have it already prepared?
Comment: No, I wrote the answer slowly after the question since it occurred to me while writing it. There's a checkbutton while you are writing a question called "Answer your own question" as suggested in the [official stackoverflow blog](http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/) that expands the page and let's you answer it in the same spot. Hope that downvote wasn't yours and for me answering my own question...
Answer: As long as you have the ability to set the content you want as an attribute, you can make use of the attr() function to abstract your styles:
http://tinker.io/bda2e
.checkbutton:before {
  content: attr(data-checked);
}

  <input type="checkbox" value="None" id="slideThree" name="check"/>

Custom attributes with the prefix of data- are a part of HTML5:  Embedding custom non-visible data with the data-* attributes
Comment: For 2 elemts I could do ``, right?
Answer: After writing the question and how much trouble it took me to find a solution, I post it in case someone finds it useful. It's in this fiddle and the relevant code here:
[part of] index.php:

  <input type="checkbox" value="None" id="slideThree" name="check" checked />

  <?= "Hombre"; ?>
  <?= "Mujer"; ?>

[part of] style.css:
.checkbutton .leftcheck
  {
  position: absolute;
  left: 0px;
   width: 50%;
  text-align: center;
  line-height: 28px;
  color: CornflowerBlue;
  }

Of course, if you have a better method, please write it as an answer.


Lower Exponent P Central Series

Question: The lower exponent $p$-central series for a $p$-group $G$ is defined by $G=P_1(G) > P_2(G) > \ldots > P_c(G) = 1$, where $$P_i(G)=[P_{i-1}(G), G] P_{i-1}(G)^p.$$ If $G_i=G/P_i(G)$ and
$A:G_{i+1} \to G_i : g P_{i+1}(G) \mapsto g P_i(G)$, then $\ker(A) = P_i(G)/P_{i+1}(G)$.
Notice $\ker(A) \leq G_{i+1}$. Is $\ker(A) = P_i(G)/P_{i+1}(G) \cong P_i(G_{i+1})$?
Comment: It is a vector space over Z/pZ, call it Vi. Its rank depends on G. There is a linear transformation from Vi to V(i+1) that takes a coset gP(i+1)(G) to the coset g^p P(i+2)(G), and a biinear transformation from Vi x Vj to V(i+j) taking cosets g x h to the coset of [g,h]. The direct sum of the Vi then becomes a "restricted Lie algebra."  The individual Vi are not too interesting by themselves. V1 is G/Phi(G), the Frattini quotient.
Comment: Thnks Jack Schmidth for your brief comments, is it true that KerA=Pi(G)/Pi+1(G) is isomorhic to Pi(Gi+1)
Comment: Yes. Commutators and p'th powers work very predictably in quotient groups.
Comment: Thanks, i need the proof of this isomorphism, i tried by myself but it did not works, if possible please send me its proof
Comment: if possible please snd me the proof that KerA=Pi(G)/Pi+1(G) is isomorhic to Pi(Gi+1)
Comment: Hi, Jack Schmidth, i am still waiting
Comment: Hi Jack Schmidt, Thanks for your reply on Email, but my question was that as Auto(G_2)=GL(d,p), can we prove that PowerAuto(G_2)=GL(d,p), i need its proof
Answer: This is a routine verification. Fix a prime $p$.
Proposition: $P_j(G)/N = P_j(G/N)$ for all groups $G$, positive integers $j$, and normal subgroup $N \unlhd G$ with $N \leq P_j(G)$.
Proof: This is clearly true for $j=1$ since both sides are $G/N = G/N$. Suppose by induction that $1 < j$ and  $P_{j-1}(G)/N = P_{j-1}(G_i)$. Then
$$P_{j}(G/N) = [ P_{j-1}(G/N), G/N ] P_{j-1}(G/N)^p = [ P_{j-1}(G)/N, G/N ] \left( P_{j-1}(G)/N\right)^p$$
Notice that $[H/N,K/N] = [H,K]N/N$ and $(H/N)^p = H^pN/N$ since commutators and quotients work predictably in quotients: $[hN,kN] =[h,k]N$ and $(hN)^p = h^p N$ by definition of multiplication in a quotient group. Hence
$$P_{j}(G/N) = [ P_{j-1}(G), G ] \left( P_{j-1}(G)\right)^p N/N = P_j(G) N/N = P_j(G)/N. \qquad \square$$
Corollary: $P_j(G_i) = P_j(G)/P_i(G)$ for all groups $G$ and positive integers $1 \leq j \leq i$.
Proof: Take $N=P_i(G)$. Then $P_i(G) \leq P_j(G)$ since $j \leq i$. $\square$
Comment: Thanks allot, Jack Schmidt

Lower Exponent P Central Series


What is the right way to count filled multi value field values in drupal?

Question: I've a term reference multi value field.  What is the right way to count filled values which is also portable to D8, D9 etc.
The dsm output shows like this:
Comment: Are you just trying to count the number of items in a `$node->field_name`, or are you trying to count the inputted values during form validation/submit?
Comment: I mean whenever hook_form_alter is called, I need to count the values.
Answer: $wrapper = entity_metadata_wrapper('entity_type', $entity);
dpm($wrapper->{FIELD_NAME}->count());

Dealing with entity reference field you can get the identifires like this:
dpm($wrapper->{FIELD_NAME}->value(array('identifier' => TRUE)));

Comment: `$wrapper->{FIELD_NAME}->count()` method doesn't exists.
Comment: Just use it, It does exist. Also the `dpm($wrapper->{FIELD_NAME}->value(array('identifier' => TRUE)));` is good to get all ids from a multivalue field taxonomy reference
Comment: Out of interest, I tested the ->count() it and it works fine.
Answer: Using Entity Metadata Wrapper, you can achieve it this way.
$wrapper = entity_metadata_wrapper('node', $node);
$count = count($wrapper->{FIELD_NAME});

Answer: It really depends on the type of field, and on when you are trying to retrieve the values.
During hook_form_alter() for checkboxes, radios, and select fields, the values you are referring to are typically set via the #options property. Example: $form['artist_tags']['und']['#options']. You can wrap that in count() to get the number of values.
During hook_form_validate() or hook_form_submit() or a function called from the $form['#after_build'] property, you will also have access to the number of selected values via $form_state['values']['artist_tags']['und'] (or when $form_state['submitted'] is TRUE, check $form_state['input']['artist_tags']['und']).


Unwanted white-spaces after printing arrays. I am using perl

Question: I wrote a script to parse an input text file and output three new text files. The input file has a header line, which is left out of each of the three output files. Each line of the output files gets the first three entries of every input file line, then gets only a portion of the entries in the input line. All files are tab delimited.
My problem is that I keep getting an extra white-space at the end of my output lines. I can see this white-space at the end of the lines of my output files when viewing in VIM. I can't see these extra white-spaces when viewing in excel.
Previously, using an earlier version of my script, I could see extra white-space at the end of my lines using excel, but only by using the "select all" feature. The data displayed in excel was the result of my perl script printing an array, where I coded print $outfile "@array". I learned elsewhere on stackoverflow that typing print "@array" causes a kind of interpolation that adds in white-spaces to my lines. White-spaces resulting from this interpolation were not immediately visible in excel, but could be seen when "select all" was used to highlight the data. So, I changed my code from print $outfile "@array" to print $outfile @array. This change results in output files that still maintain a white-space at the end of each output line, a white-space visible in VIM but not in excel. This is where I am stuck.
Here is my script below. The first part just opens and reads the input file. Then some arrays are declared. Next, a for loop is begun to begin parsing the input file line by line, and pushing appropriate content into appropriate arrays. A substitution is implemented for one array. Again, all files are tab delimited. Finally, the arrays are printed to three outfiles, using the phrasing print $outfile @array and not print $outfile "@array".
Do you see the problem? Thanks!
#!/usr/bin/perl
use strict; use warnings;

die "usage: [ imputed genotype.file ]\n" unless @ARGV == 1;

my $imputed = $ARGV[ 0 ];
open ( my $FILE, "<$imputed" );
my @data  = <$FILE>;

my @ADD = ();
my @DOM = ();
my @IMP = ();

for ( my $i = 1; $i < scalar @data; $i++ ) ### for each line data[i], and use $i = 1 to
                                           ### skip header, 0 to include it output
    {
     my $line = $data[ $i ];
     chomp $line;

     my @entries = split( '\t', $data[ $i ] );

     push( @ADD, "$entries[ 0 ]\t$entries[ 1 ]\t$entries[ 2 ]\t" );
     push( @DOM, "$entries[ 0 ]\t$entries[ 1 ]\t$entries[ 2 ]\t" );
     push( @IMP, "$entries[ 0 ]\t$entries[ 1 ]\t$entries[ 2 ]\t" );

     for ( my $i = 3; $i < scalar @entries - 1 ; $i+=3 ) ### for each entry per line
         {
          push( @ADD, "$entries[ $i ]\t" );
          push( @DOM, "$entries[ $i + 1 ]\t" );

          if ( $entries[ $i + 2 ] eq 'NA' ) ### to replace any occuring "NA"s with blanks
             {
              $entries[ $i + 2 ] =~ s/NA//;
             }

          push( @IMP, "$entries[ $i + 2 ]\t" );
          }

    push( @ADD, "\n" );
    push( @DOM, "\n" );
    push( @IMP, "\n" );

   } ### for loop

open my $Afile, ">$imputed" . "_ADD.txt" or die $!;
print $Afile @ADD;
close $Afile;

open my $Dfile, ">$imputed" . "_DOM.txt" or die $!;
print $Dfile @DOM;
close $Dfile;

open my $Ifile, ">$imputed" . "_IMP.txt" or die $!;
print $Ifile @IMP;
close $Ifile;

Comment: what is the significance of the double vs single quotes? in my review of the use of split, usually single quotes `' '` are used (or `/ /`, depending on context).
Comment: Double quotes interpolate variables within the string.  Single quotes do not.
Answer: Your problem in using \t at the end of the array element. Use function
join( "\t", ...)

instead.
I mean, just create output array, and then use
print join "\t", @output;

There is untested example:
#!/usr/bin/perl
use strict; use warnings;

die "usage: [ imputed genotype.file ]\n" unless @ARGV == 1;

open my $Afile, ">$imputed" . "_ADD.txt" or die $!;
open my $Dfile, ">$imputed" . "_DOM.txt" or die $!;
open my $Ifile, ">$imputed" . "_IMP.txt" or die $!;

<>; #skip header
while(<>){
      chomp;
      my @entries = split( '\t', $_ );

      my @ADD = ();
      my @DOM = ();
      my @IMP = ();

      push( @ADD, $entries[ 0 ], $entries[ 1 ], $entries[ 2 ]);
      push( @DOM, $entries[ 0 ], $entries[ 1 ], $entries[ 2 ]);
      push( @IMP, $entries[ 0 ], $entries[ 1 ], $entries[ 2 ]);

      for ( my $i = 3; $i < scalar @entries - 1 ; $i+=3 ) { ### for each entry per line
          push( @ADD, $entries[ $i ] );
          push( @DOM, $entries[ $i + 1 ] );

      $entries[ $i + 2 ] =~ s/^NA$//;

          push( @IMP, $entries[ $i + 2 ] );
      }

      print $Afile join( "\t", @ADD) , "\n";
      print $Dfile join( "\t", @DOM) , "\n";
      print $Ifile join( "\t", @IMP) , "\n";

} ### for loop

close $Afile;
close $Dfile;
close $Ifile;

Comment: can you be a little more explicit? could you guide me where the join command should go? i put it in my final `print` statements as `print $Afile join "\t", @ADD;`. But this scrambled things up.
Comment: You can make join( "\t", ...) for every element in the row, and join( "\n", ...) for every row, or just print output row by row with "\n" at the end of the row.
Comment: i still don't understand. could you embed your idea into the code above?
Comment: push( @ADD, $entries[ $i ] );
Comment: print $Afile join( "\t", @ADD);
Comment: if i want to push multiple $entries into the array at a particular step, can i type `push( @ADD, $entries[ $i ],$entries[ $i +1 ], $entries[ $i + 2] );`?
Comment: Yes, you can push list of entries to array: http://perldoc.perl.org/functions/push.html
Comment: still getting a white-space at the end. i changed each instance of `push( @ADD...)` and still a white-space.
Comment: wow, @user1883592, thanks! that works. plus, it is so much faster in while running my text files. maybe it is about twice as fast.  the only thing i need to add was an explicit package name for "imputed" by declaring `my $imputed = $ARGV[0];`. Otherwise, it looks like it is working. And I also learned some other tricks, too. Thanks!
Comment: Try AWK, it's even faster for this kind of probmem.
Comment: so, @user1883592, if I wanted to make my outfiles .csv files, I am seeing that changing all the `join( "\t", @arrays)` to `join( ",", @arrays)` doesn't quite work. I get two extra commas at the end. Do you see why?
Comment: Only if you have an empty values in last columns in input file.
Comment: Hi @user1883592, so it kind of seems like I have now come full circle. That is, I started with a problem where I was getting additional and unwanted white-space at the ends of my lines. Thank you for helping me that! However, in trying to use commas, instead of tabs, to make a cvs type file, I am finding two additional spaces at the ends of my lines. The input file is "clean", in that it has no further characters or white-spaces after its lines, which I checked using both excel and VIM. How else might they enter? I can send you input file if you have time and patience to see.
Answer: push( @ADD, "$entries[ 0 ]\t$entries[ 1 ]\t$entries[ 2 ]\t" );

These lines always add a tab at the end, which is probably what you're seeing.  Also, consider using a join and an array slice instead of string interpolation, like:
push( @ADD, join( "\t", @entries[0..2] ) );

Comment: i think i see that working for the first three elements that go into my arrays. how would you use the `join` in the second `for loop`, the one embedded in the first loop?
Comment: hey, @frezik, shouldn't that be `join( '\t'` instead of `join( "\t" ` ?
Comment: @eric - frezik is correct, else you'd be `join`ing using the string literal `'\t'` and not a tab character.
Comment: hi @kenosis, but I have been using `'\t'` and it has been tab delimiting my entries for me. My data are numeric, and so there are no t's to split with. Plus, most examples of `join` I see online use single quotes.