text:
Q: Perl multithread file / list comparison My question revolves around the comparison of two files containing big lists of strings (7mio and 3mio). What I need to do is compare each element in one list (called "database") to every element of the other list (called "reference").
I wrote a very basic script for this, but because of the huge amount of comparisons (~3 trillion), I would like to parallelize the search. Since both files are quite big, my idea was to load them into two independent arrays (@reference and @dbPep) only once and then use a subroutine to compare chunks of the lists in separate threads, i.e. 0 to 1000000 in thread 1, 1000001 - 2000000 in thread 2 and so on. The chunk size is determined by the number of threads, whereas the last one gets also what is left over after using modulo. Output should be printed to STDOUT so that it can be piped to a file, the order of results is NOT important.
Now, my problem resides in starting the threads correctly and dynamically depending on the $ARGV input.
Here's what I have so far, multi-threading, however does not really work yet so I commented it out:
#!/usr/bin/perl
use Thread;

    $minLength      = $ARGV[0];
    $numThreads         = $ARGV[1];
    my $reference_File  = $ARGV[2];
    my $peptideDB_File  = $ARGV[3];

    if ($minLength == ""){$minLength = 6;}

    print STDERR ("Threads:\t".$numThreads."\n");
    print STDERR ("Reference:\t".$reference_File."\n");
    print STDERR ("peptide DB:\t".$peptideDB_File."\n----------------\n");
    print STDERR ("Loading reference...\n");

# Load reference peptides
    open (REF,$reference_File) || die ("File not found!");
    @reference = ();
    while (<REF>) {
        chomp;
        my @refPeptide = split("\t");
        if($refPeptide[1] eq "Sequence") {next;}
        push(@reference,$refPeptide[1]);
    }
    close (REF);
    print STDERR ("Done!\n");
    print STDERR ("Length:".@reference."\n");
    print STDERR ("Loading peptide database...\n");

# Open peptide DB to check
    open (PEP,$peptideDB_File) || die ("File not found!");
    @dbID  = ();
    @dbPep = ();
    while (<PEP>) {
        chomp;
        my @dbPeptide = split("\t");
        if($dbPeptide[1] eq "Sequence") {next;}
        push(@dbID,$dbPeptide[0]);
        push(@dbPep,$dbPeptide[1]);
    }
    close (PEP);
print STDERR ("Done!\n");
    print STDERR ("Length:".@dbPep."\n");
    print STDERR ("Starting analysis...\n");
    print STDERR ("(This can take a while)\n");
    print STDERR ("----------------\n");

#my %ref = map { $_ => 1 } @reference;

    my $dbLength        = @dbPep;
    my $rest            = $dbLength % $numThreads;
    my $chunkStart      = 0;
    my $chunkLength     = ($dbLength - $rest) / $numThreads;
    my $chunkEnd        = $chunkLength;

    #print STDERR($chunkEnd."\n");
    &peptideCheck($chunkStart,$chunkEnd);

    #for (my $i=0;$i<$numThreads;$i++) {
#       if ($i == $numThreads-1) {$chunkEnd += $rest;};
#       new Thread \&peptideCheck, $chunkStart, $chunkEnd;
#       $chunkStart += $chunkLength;
#       $chunkEnd   += $chunkLength;
#   }
    print STDERR ("----------------\nFinished!\n");
    sub peptideCheck {
        my @params = @_;
        for (my $j=@params[0]; $j<@params[1];$j++){
            if (length($dbPep[$j]) < $minLength) {next;}
            if ( grep { $_ eq $dbPep[$j]} @reference ) {
                #print STDERR ("RefCall:\n".$peptideCandidate[1]."\n");
                next;
            }
            else {
                #print STDERR ("Found novel peptide:\n");
                print (">".$dbID[$j]."\n".$dbPep[$j]."\n");
            }
        }
    }

Here are (very) short examples of my files, the first being database, the second reference.
Protein_Name    Sequence    Unique_ID   Monoisotopic_Mass   Predicted_NET   Tryptic_Name
IPI:80000000.1  MGSTSEK 1   738,321789  0,0756  t1.1
IPI:80000001.1  MFLCSSFIFHHDCEASPAMLNCG 2   2559,0512972    0,5426  t1.1
IPI:80000002.1  MIVR    3   517,3046228 0,0924  t1.1
IPI:80000002.1  MIVRPPQPC   4   1039,5306652    0,2739  t1.2
IPI:80000002.1  PPQPC   5   540,2366066 0,1163  t2.1
IPI:80000003.1  MPVLMEK 6   846,4343096 0,2742  t1.1
IPI:80000003.1  MPVLMEKGGGR 7   1173,5998042    0,2599  t1.2
IPI:80000003.1  MPVLMEKGGGREPECSSPLGEQTR    8   2587,2192178    0,2881  t1.3
IPI:80000003.1  MPVLMEKGGGREPECSSPLGEQTRVASVGTCWIEVR    9   3887,878977 0,3859  t1.4

Protein_Name    Sequence    Unique_ID   Monoisotopic_Mass   Predicted_NET   Tryptic_Name
sp|P31946|1433B_HUMAN   MTMDK   1   624,2611054 0,1124  t1.1
sp|P31946|1433B_HUMAN   MTMDKSELVQK 2   1308,6417266    0,2304  t1.2
sp|P31946|1433B_HUMAN   MTMDKSELVQKAK   3   1507,7737968    0,2278  t1.3
sp|P31946|1433B_HUMAN   MTMDKSELVQKAKLAEQAER    4   2305,1769438    0,3107  t1.4
sp|P31946|1433B_HUMAN   SELVQK  5   702,3911854 0,1286  t2.1
sp|P31946|1433B_HUMAN   SELVQKAK    6   901,5232556 0,1294  t2.2
sp|P31946|1433B_HUMAN   SELVQKAKLAEQAER 7   1698,9264026    0,2544  t2.3
sp|P31946|1433B_HUMAN   SELVQKAKLAEQAERYDDMAAAMK    8   2695,330871 0,3435  t2.4
sp|P31946|1433B_HUMAN   AKLAEQAER   9   1014,5457814    0,1198  t3.2
IPI:80000000.1  MGSTSEK 1   738,321789  0,0756  t1.1
IPI:80000001.1  MFLCSSFIFHHDCEASPAMLNCG 2   2559,0512972    0,5426  t1.1

Any help is greatly appreciated :)
Thanks and cheers

A: Ok, I've been working on the code after switching to the "threads" module as recommended by pilcrow (Thank you :) ) and it seems that spawning the threads works fine now. However, what does not seem to work properly is waiting for the spawned threads to finish (see below). Currently, I use threads->detach() since I do not need any return values from my threads and printing to STDOUT is the only thing they are supposed to do. When I run the program, this is the output I get:
Threads:    3
Reference:  testRef.txt
peptide DB: testDB.txt
----------------
Loading reference...
Done!
Length:1999
Loading peptide database...
Done!
Length:1999
Starting analysis...
(This can take a while)
----------------
1999    1   0   666 666
main: 0 666
createThr: 0    666
main: 666   1332
createThr: 666  1332
peptideCheck: 0 666
MTMDKSELVQK
main: 1332  1999
createThr: 1332 1999
peptideCheck: 666   1332
MAVMAPRTLLLLLSGALALTQTWAGSHSMR
----------------
Finished!
peptideCheck: 1332  1999
THVIWGTSKDFGISGFR

From that I conclude that my threads are generated properly with the correct parameters, but when it comes to computation, they are disrupted because the main script finishes. I though when using detach() this does not happen, so have I missed something or do I use it the wrong way?
Here's the new code:
#!/usr/bin/perl

    use threads;
    use threads::shared;
    use strict;
    use warnings;

    my $minLength :shared   = $ARGV[0];
    my $numThreads          = $ARGV[1];
    my $reference_File      = $ARGV[2];
    my $peptideDB_File      = $ARGV[3];

    if ($minLength eq ""){$minLength = 6;}

    print STDERR ("Threads:\t".$numThreads."\n");
    print STDERR ("Reference:\t".$reference_File."\n");
    print STDERR ("peptide DB:\t".$peptideDB_File."\n----------------\n");
    print STDERR ("Loading reference...\n");

# Load reference peptides
    open (REF,$reference_File) || die ("File not found!");
    my @reference :shared = ();
    while (<REF>) {
        chomp;
        my @refPeptide = split("\t");
        if($refPeptide[1] eq "Sequence") {next;}
        push(@reference,$refPeptide[1]);
    }
    close (REF);
    print STDERR ("Done!\n");
    print STDERR ("Length:".@reference."\n");
    print STDERR ("Loading peptide database...\n");

# Open peptide DB to check
    open (PEP,$peptideDB_File) || die ("File not found!");
    my @dbID :shared  = ();
    my @dbPep :shared = ();
    while (<PEP>) {
        chomp;
        my @dbPeptide = split("\t");
        if($dbPeptide[1] eq "Sequence") {next;}
        push(@dbID,$dbPeptide[0]);
        push(@dbPep,$dbPeptide[1]);
    }
    close (PEP);
    print STDERR ("Done!\n");
    print STDERR ("Length:".@dbPep."\n");
    print STDERR ("Starting analysis...\n");
    print STDERR ("(This can take a while)\n");
    print STDERR ("----------------\n");

#my %ref = map { $_ => 1 } @reference;

    my $dbLength        = @dbPep;
    my $rest            = $dbLength % $numThreads;
    my $chunkStart      = 0;
    my $chunkLength     = ($dbLength - $rest) / $numThreads;
    my $chunkEnd        = $chunkLength;

    print STDERR ($dbLength."\t".$rest."\t".$chunkStart."\t".$chunkLength."\t".$chunkEnd."\n");

    #&peptideCheck($chunkStart,$chunkEnd);

    for (my $i=0;$i<$numThreads;$i++) {
        if ($i == $numThreads-1) {$chunkEnd += $rest;};
        print STDERR ("main: ".$chunkStart."\t".$chunkEnd."\n");
        createThr($chunkStart, $chunkEnd);
        $chunkStart += $chunkLength;
        $chunkEnd   += $chunkLength;
    }
    print STDERR ("----------------\nFinished!\n");

    sub peptideCheck {
        my @params = @_;
        print STDERR ("peptideCheck: ".$params[0]."\t".$params[1]."\n");
        for (my $j=$params[0]; $j<$params[1];$j++){
            if (length($dbPep[$j]) < $minLength) {next;}
            print ($dbPep[$j]."\n");
            if ( grep { $_ eq $dbPep[$j]} @reference ) {
                next;
            }
            else {
                print STDOUT (">".$dbID[$j]."\n".$dbPep[$j]."\n");
            }
        }
    }

    sub createThr {
        my @thrParams = @_;
        print STDERR ("createThr: ".$thrParams[0]."\t".$thrParams[1]."\n");
        my $thr = threads->create(\&peptideCheck, $thrParams[0], $thrParams[1]);
        $thr->detach();
    }


text:
Q: how to include listings using \lstinputlisting In a document embedding java code (actually processing) I can successfully embed listings using:
\begin[language=java]{lstlisting}
...
\end{lstlisting}

In an attempt to increase convenience, I wrote a new command that abbreviates this to:
\java

\end{lstlisting}

This works fine.  However, in many instances it would be better to keep the listing external. This should be:
lstinputlisting[language=java]{code/openglprocessing/s00trianglegouraud.pde}

which I abbreviate:
\newcommand{\incjava}{\lstinputlisting[language=Java]}

\incjava{code/openglprocessing/s00trianglegouraud.pde}

Both formulations result in the following error:
! Undefined control sequence.
l.160 \incjava
              {code/openglprocessing/s00trianglegouraud.pde}

While on the subject, is there any way to define a standard directory to avoid having to repeatedly refer to code/openglprocessing, in a similar manner to the graphics path for \includegraphics?
\graphicspath{ {img/} }

A: Instead of \java, I would define an environment java. Then the \begin and \end macros are properly matched in the source code, also making some TeX editors happy. Such an environment is defined by \lstnewenvironment of package listings. Also an optional argument is added. Then the user can set some options in \begin{java}[...] for a particular listings.
The \incjava command should work as is does in the following example. Also this macro is given an optional argument for options to the particular listings.
\documentclass{article}
\usepackage{listings}

\lstnewenvironment{java}[1][]{%
  \lstset{language=Java,#1}%
}{}

\newcommand*{\incjava}[1][]{%
  \lstinputlisting[{language=Java,#1}]%
}

\begin{document}
\begin{java}
public class Example implements StringHandler {

    /**
     * Prints the given string.
     *
     * @param s  the given string
     */
    @Override
    public void handle(String s) {
        System.out.println(s);
    }

}
\end{java}

\incjava{Example.java}
\end{document}

There is no \listingspath for listing files, but \input@path for TeX files can be defined, e.g.:
\makeatletter
\providecommand*{\input@path}{}
\g@addto@macro\input@path{{code/openglprocessing/}}
\makeatother

Each entry should be surrounded by curly braces and end with the directory separator.
Another variant is setting the environment variable TEXINPUTS to include the directory, example for TeX Live/Linux:
TEXINPUTS=:code/openglprocessing

The colon (Unix) or semicolon (Windows) at the beginning is important, because then the previous search path (from texmf.cnf) is added at this place.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add HTML to JS append. method? I have a little problem, because I don't know how to insert a LifeRay message to the JavaScript CONTENT. It works very nice, but only when text is provided. I want to view the UI message in another div which was previously generated by Liferay with id=p_86. I simply have to put tag liferay-ui:success into above div. This event is related to data saving. It works good but the message is displayed in the wrong place so I want to move it to div with id=p_68.
<liferay-ui:success key="klucz" message="
    <%=PortletUtils.getInfoMessage(renderRequest) %>"/>
<liferay-ui:error key="cap_global_msg_error_key" message="
    <%=PortletUtils.getErrorMessage(renderRequest) %>"/>

<script type="text/javascript">
    $("#p_86").append("<div id='newid'> CONTENT </div>");
</script>


text:
Q: Call procedure using anonymous block in pl/sql? I am fairly new to PL/SQL but have been reading up on it and have used some templates, including some which I found from here.
What I want to do is to write an anonymous block to call some procedures which wrere written earlier in a sql developer project. I have attempted it but it isn't running properly. It returns an error of "Error starting at line : 2 in command " and then reports a "closed connection."
This is my attempt:
DECLARE
    P_USER_NAME VARCHAR;
    P_DEBUG_FLAG  VARCHAR;
    P_DEBUG_FIELD VARCHAR;
    P_DEBUG_VALUE VARCHAR;

BEGIN

    schema.package.procedure(
        OutParam1, OutParam2, OutParam3, OutParam4);

    dbms_output.put_line('OutParam1: ' || P_USER_NAME);
    dbms_output.put_line('OutParam2: ' || P_DEBUG_FLAG);
    dbms_output.put_line('OutParam3: ' || P_DEBUG_FIELD);
    dbms_output.put_line('OutParam4: ' || P_DEBUG_VALUE);
END;
/

And these are the procedure I want to call:
   PROCEDURE CLEAR_DEBUG (P_USER_NAME IN VARCHAR2);

   PROCEDURE WRITE_DEBUG (P_USER_NAME     IN VARCHAR2,
                          P_DEBUG_FLAG    IN VARCHAR2,
                          P_DEBUG_FIELD   IN VARCHAR2,
                          P_DEBUG_VALUE   IN VARCHAR2);

   PROCEDURE READ_DEBUG (P_USER_NAME    IN     VARCHAR2,
                         P_REF_CURSOR      OUT SYS_REFCURSOR);
END P_DEBUG;

A: There are more errors in your code:

*

*declare the variables properly - VARCHAR requires length constraint

*OutParam1, OutParam2, OutParam3, OutParam4 are not declared - use the declared variables as arguments instead, beware of the variables passed as arguments must have the same data type

*I expect you wanted to call P_DEBUG.WRITE_DEBUG(P_USER_NAME, P_DEBUG_FLAG, P_DEBUG_FIELD, P_DEBUG_VALUE);


text:
Q: How can I persuade my friends to join Stack Exchange? Alright, so the past couple of months have been driving me crazy.  My roommate, no my hallmates, no all my floormates are driving me crazy.
Everyday, as they work on questions ranging from Physics, to Mathematics, to Computer Science, I can't help but watch in dismay as they look to one source: Yahoo! Answers. Sure, some may find Yahoo! Answers an easy to way to solve some problems.  In my opinion however, it is a site I am completely disgusted by. In my mind, I hold StackExchange dear to my heart, and I can't help but cry a little on the inside every time I see a Yahoo! Answers page. The more I see the likes of Yahoo! Answers, the more I cringe inside, trying to see something good in it (there's nothing). However, my friends have yet to acknowledge the existence of this site, let alone visit it.
I've been trying unsuccessfully to recruit them to join the SE community.  They seem reluctant to leave the miserable harsh world within other sites besides Stack Exchange. I really want my friends to join Stack Exchange.  I think there's a great community here, SE consistently delivers quality answers and questions, as well as tight moderation (to get rid of the bad, bring in the good), and a great place to learn as well.  My friends however, don't seem to find any reason to join.
Basically, TL;DR, I can't get my friends to join SE, I would like some advice on how to recruit them into our site.
In what ways can I persuade them to join Stack Exchange that doesn't involve violence, extortion, or blackmail?

A: Listen dutifully to their latest question before sneaking quietly off to your room and posting the problem on an appropriate StackExchange site (after checking it conforms with the FAQ, of course).
Over breakfast a few days later, remark that you posted the question and have received several insightful answers. Would your friend kindly join you in reviewing these and selecting a correct one?
Finally, bask in the glory of having converted another muggle. At this point, you may wish to probe their thoughts on freehand circles. No, wait. Don't push that one too early.

A: Top tip: don't persuade them. Just use Stack Exchange yourself. Show it to them when relevant. And then see if they pick it up. If they discover on their own that Yahoo! Answers has several shortcomings that SE might address, they'll come on over.
But truth be told, if Yahoo! Answers fits the bill for them, Stack Exchange most likely won't.  Stack Exchange is not a better Yahoo! Answers. It's a different beast altogether. As George pointed out, a significant portion of the questions asked over there, would simply not be welcome here. So why do people still stay on a site with questions like those? Because they have questions like those.
Asking good questions is hard. Asking questions on SO/SE is hard. And the scope of questions you're "allowed" to ask is narrow. I wouldn't want to have it any other way, and I'm guessing you don't either. But it's not for everyone. So participate, get good results and share them with your friends/roommates/hall-mates. If they discover you are getting the more valuable responses, they will hop over. And if Yahoo! Answers is sufficient for them, please don't forcibly drag them over.

A: I seriously can't believe that anyone can look at the list of "recently resolved questions" and still want to use Yahoo! Answers.
Nearly every question falls into one of three categories:

*

*Duplicates (and also not constructive):

*

*What is the best programming language to learn?

*What is a good programming language for beginners?

*Which programming language is the best?

*Best programming language for beginners?

*Totally off-topic:

*

*What Photoshop tool does this? (how can anyone think this is somehow a "programming" question???)

*How to jailbreak iOS 6.1?

*Why is it when I walk away from my I-mac I lose the internet connection?

*Questionable:

*

*How do I learn how to hack? This is not Illegal. This is for informational purposes only.?
Stack Exchange is designed to avoid each of those problems. Duplicates are flagged and closed almost immediately, keeping all of the relevant answers with a single question. Off-topic questions are closed or migrated to other sites on the network.


text:
Q: ARMv6 Assembly language Does anyone know how to start a comment (e.g. '#',';', '/', '/*') in ARMv6 Assembly Language?

A: should be ";" as per some example code i found on the wikipedia article:
    loop  CMP  Ri, Rj   ; set condition "NE" if (i != j),
                        ;               "GT" if (i > j),
                        ;            or "LT" if (i < j)
    SUBGT  Ri, Ri, Rj   ; if "GT" (greater than), i = i-j;
    SUBLT  Rj, Rj, Ri   ; if "LT" (less than), j = j-i;
    BNE  loop           ; if "NE" (not equal), then loop


text:
Q: C++ template operator overloading with different types, auto return type I'm trying to make an overload with auto return type (C++11)
I already read C++ template operator overloading with different types, but that's not exactly that I'm trying to do.
I have a class like this:
template<typename T>
class Attr
{
    public:
    Attr(const T& v) : value(v) {};

    typedef T type;
    T value;
}

Now i try to add some operator (=,+,-,*,/,%) with auto return type, so I add inside Attr this code:
template<typename U> T& operator=(const U& v){value=v;return value;};  //work

template<typename U>
auto operator+(const U& v) -> std::decltype(Attr<T>::type+v) const //line 29
{
  return value+v;
}; //fail

I try to replace std::decltype(Attr<T>::type+v) with:

*

*std::decltype(value+v)

*std::decltype(Attr<T>::value+v)

*std::decltype(T()+v)
And I also try to remove const, but no change, I always have these errors:
ORM/Attr.hpp:29:47: erreur: expected type-specifier
ORM/Attr.hpp:29:47: erreur: expected initializer

EDIT:
First, decltype is not a member of std.
It should be:
template<typename U> auto operator+(const U& v)const -> decltype(value+v) {return value-v;};

Final code:
template<typename T>
class Attr
{
    public:
    Attr(const T& v) : value(v) {};

    typedef T type;
    T value;

    template<typename U> auto operator+(const U& v)const -> decltype(value+v) {return value-v;};
}

A: First problem
There is no such a thing as std::decltype. decltype is a keyword. Secondly, inside the decltype expression you are trying to add an object and a type. Although I understand what you meant to do, for the compiler, that is non-sense.
You could use std::declval<> for that purpose:
template<typename U>
auto operator+(const U& v) ->
    decltype(std::declval<T>()+v) const //line 29
{
    return value+v;
};

Or, if you have declared your value data member before the point where you are referring to it outside the body of a member function, you could do:
template<typename U>
auto operator+(const U& v) ->
    decltype(value + v) const
//           ^^^^^
//           Valid only if the "value" data member has been declared before
{
    return value+v;
};

Second problem
Usually, operator + is defined as a (possibly friend) free function, not as a member function, so that you could actually make it work even when the object of your type is not being passed as the first operand.


text:
Q: JavaScript - match non-ascii symbols using regex I want to match all mentioned users in comment. Example:

var comment = '@Agneš, @Petar, please take a look at this';
var mentionedUsers = comment.match(/@\w+/g);

console.log(mentionedUsers)

I'm expecting ["@Agneš", "@Petar"] but getting ["@Agne", "@Petar"]. As you can see š symbol is not matched.
How can I match all letter symbols include non-ascii?

A: Until ES6 support for unicode in regex is implemented, you can work around it with somehting like:
/@[^\s,]+/g

where you just list stuff that can't be in usernames. Next year,
/@\w+/gu

A way to make sure you don't get halves of email adresses and other cases where the @ is in the middle of a word would be to match(/[^\s,@]*@[^\s,@]+(?=[\s,]|$)/g) and then filter the results on whether they start with "@".

A: the š is not a word character, and "w" is for word character.


text:
Q: send notification like push notification without APNS server in ios, I want  to send push notification without any APNS server and device token,like android there is NO local and push notifications but they can send device to device with out google permissions.

A: You can NOT send a push notification without using APNs. Why? first you need to understand how the technology works:
You need a certificate for a handshake.
You need a device token to be identified by APNs.

*

*In your app, you have to register to APNs.

*The app requests the certificate from APNs (handshake).

*The server sends back its certificate.

*The app will establish a connection to the server and send the PN certificate to the APN server.

*The server will validate that you are a trusted app.

*The app requests to create a token.

*The server creates a token and sends it back.

*In your app you save the token (to do e.g. push notifications to a specific user instead of a broadcast).

*End.

So, as you see, you need to establish a trusted connection, the APNs is responsible for creating a token to identify your device within the network, and will be responsible for sending notifications.
For more info you could see:
Apple PNs


text:
Q: Executing PHP code inside a .js file I'm trying to get a bit of PHP to execute inside of a .js file, but obviously don't know how to do it properly.
Basically the code is adding some HTML tags to my page, which I am using for a slideout contact form. However the contact form itself is done in Wordpress by a shortcode. So I'm trying to get the shortcode to work inside the code that makes the form slide out.
var phpTest = '<?php do_shortcode("[contact-form-7 id=\'1088\' title=\'Live Chat Form\']"); ?>';

// add feedback box
$this.html('

'
    + thisSettings.title
    + '

'
    + phpTest
    + '

');

If I change the variable "phpTest" to a regular string with text, it shows up fine, I'm just not sure how to execute the php in this instance.

A: I commented saying your question is not possible, however it is indeed possible. This is not recommended, but if you're not worried about the possible security holes, here is a way to accomplish your question:
Create a .htaccess file in the same directory as your .js files, with the following:
AddHandler application/x-httpd-php .js

<FilesMatch "\.js$">
    Header set Content-Type "text/javascript; charset=utf-8"
</FilesMatch>

This will execute your JavaScript files as PHP, then fix the Content-Type for .js files automatically (because they're seen as text when you add the php handler).
Note: While this is a quick and dirty solution, a better way would be to use Ajax (see chiliNUT's Answer)

A: EDIT: The script type should always be text/javascript as application/javascript may break compatibility with older browsers (I think IE8 and earlier will ignore the script tag with that type). The Content-type, however, should still be application/javascript.

You can't mix in php into a .js file, the way you would with a normal .php file, since the .js file is not preprocessed by the .php engine the way your .php files are.
The most typical way to do this--including php in a js file--is to just have inline JS (stuff between

A: You can do a ajax post request to a .php file. It is a little dirty trick but it works
$.post('thePhpFile',{var1:var1,var2:var2},function(result){
    //Code to do with the resulted... like $("#div").html(result);
});

With that trick, you can basicaly do anything you want

A: I think you can do something like this using AJAX:
JS code:
var xmlhttp;
if (window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}else{
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        $this.html('

'
        + thisSettings.title
        + '

'
        + xmlhttp.responseText
        + '

');
    }
}

xmlhttp.open("GET","do_shortcode_file.php",true);
xmlhttp.send();

The do_shortcode_file.php must have something like this:
PHP code:
<?php
echo do_shortcode("[contact-form-7 id=\'1088\' title=\'Live Chat Form\']");

A: Suppose your filename is myscript.js:
in your head tag ( it must be an executable php file):

...
...

in this way you are able to execute that file as if it were a php file


text:
Q: Gap on left hand side of UICollectionViewFlowLayout I am using a UICollectionViewFlowLayout for displaying a grid view and this is how i'm seeing it.

The problem is with the gap on the left hand side. I am a little new to using a UICollectionViewFlowLayout so am not able to figure out how to get rid of that gap over there.
Please help

A: To reduce the space on the left you can set the sectionInset property on your UICollectionViewFlowLayout
flowLayout.sectionInsets = UIEdgeInsets(top: 50.0, left: 0.0, bottom: 50.0, right: 0.0)

Alternatively you can implement this method:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 50.0, left: 0.0, bottom: 50.0, right: 0.0)
   }

If the delegate object does not implement the
  collectionView:layout:insetForSectionAtIndex: method, the flow layout
  uses the value in this property to set the margins for each section.

Source: Apple Documentation

A: Try using:
 - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
  return UIEdgeInsetsMake(5, 5, 5, 5); //desired values
}

Hope it helps.

A: My first guess would be to check the sectionInsets. You can set them either directly on the flow layout:
flowLayout.sectionInsets = UIEdgeInsets(...)

or through the ~UICollectionViewDelegateFlowLayout` method:
optional func collectionView(_ collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    insetForSectionAtIndex section: Int) -> UIEdgeInsets {

}

Flow Layout Delegate Reference
Flow Layout Reference


text:
Q: How do I run a C program as a thread from a C# System Tray Application? I have a C console application which used to be run in the foreground in a CMD terminal in Windows and take user keystroke inputs. However it now needs to be moved to the background and requires no user input.
I have created a system tray, which is implemented correctly with a right click exit and right click about. And have a terminal program which does the functionality.
Rather than rewritting the program again I would like to be able to create a thread which calls the functions from my existing program which are do not require the terminal.
Just to stress the point the console interactive aspects have been removed from the code as have the applications response to keystrokes etc. Hopefully this clarifies things slightly.
Question: Is this possible? And how would I be able to implement this?
(I am generally not a PC programmer using more embedded C so .NET is quite foreign to me. Any help is greatly appreciated)

A: I'm not sure if this is what you are asking, but if you are asking if you can call functions from your C program from a C# application, then you can. So long as you have the source code to your C program. In order for functions in C to be available to a C# program, they must be exported. I will show you an example:
MyAddDll.h
#include <iostream>

extern "C"
{
    __declspec(dllexport) int Add(int a, int b);
}

Whats important here is that your function is wrapped in an extern "C" block. Basically, this tells the compiler not to mangle the name of your function. The other important piece is __declspec(dllexport). This tells the compiler that you want to export this function so it can be called from another program (like your C# program).
MyAddDll.cpp
#include <iostream>
#include "MyAddDll.h"

extern "C"
{
    __declspec(dllexport) int Add(int a, int b)
    {
        return (a + b);
    }
}

Again, your code gets wrapped in an extern "C" block and you need to add __declspec(dllexport) to the function. Now you can compile this either into a DLL file or an EXE file. Now to call it from C#, its pretty straight forward:
MyProgram.cs
class Program
{
    [DllImport("c:\\PathToMyDllOrExeFile\\MyAddDll.dll")]
    public static extern int Add(int val1, int val2);

    static void Main(string[] args)
    {
        int val1 = 12;
        int val2 = 4;
        Console.WriteLine("{0} + {1} = {2}", val1, val2, Add(val1, val2));
    }
}

That's all there is!
One "gotcha" though is make sure your C program and your C# program are both compiled as either 32-bit or 64-bit. You can't compile your C program as 64-bit and your C# program as 32-bit. They must both be using the same bit length.

A: As already posted, you could use the Process.Start from your C# application tray.
    // Uses the ProcessStartInfo class to start new processes,
    // both in a minimized mode.
    void OpenWithStartInfo()
    {
        ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
        startInfo.WindowStyle = ProcessWindowStyle.Minimized;

        Process.Start(startInfo);

        startInfo.Arguments = "www.northwindtraders.com";

        Process.Start(startInfo);
    }

http://msdn.microsoft.com/en-us/library/53ezey2s(v=vs.110).aspx
You could try launching it on a hidden state: http://msdn.microsoft.com/en-us/library/system.diagnostics.processwindowstyle(v=vs.110).aspx
Some programmers are telling to be careful. If any input is expected, then probably your process might halt. make sure nothing really stops your program.
You could try to start a cmd command with Process.Start also, but I would say it is just too much. This would start another process without your C# tray application control:
 Process.Start("start /min cmd /c mycommand");

A: You could start your C program from .NET code via System.Diagnostics.Process. It will be run in a separate process.
You can kill the process from .NET code as well


text:
Q: Python, comtypes and ArcObjects: Error creating AppROT object I am experimenting with comtypes and ArcObjects under Python 2.6.5 and ArcGIS 10 SP1. I'm using the pure Python method to wrap the ArcObjects OLBs described in this answer, but getting an error in the comtypes.CoCreateInstance method.
Here is the code I am running:
def WrapModules():
    #force wrapping of all ArcObjects libraries (OLBs)
    import os
    import comtypes.client
    # change com_dir to whatever it is for you
    com_dir = r'C:\Program Files\ArcGIS\Desktop10.0\com'
    coms = [os.path.join(com_dir, x) for x in os.listdir(com_dir) if os.path.splitext(x)[1].upper() == '.OLB']
    map(comtypes.client.GetModule, coms)

def GetApp():
    """Get a hook into the current session of ArcMap"""
    from comtypes.gen import esriFramework
    pAppROT = NewObj(esriFramework.AppROT, esriFramework.IAppROT)
    if pAppROT is not None:
        iCount = pAppROT.Count
        if iCount == 0:
            print 'No ArcGIS application currently running.  Terminating ...'
            return None
        for i in range(iCount):
            pApp = pAppROT.Item(i)  #returns IApplication on AppRef
            if pApp.Name == 'ArcMap':
                print "ArcMap found"
                return pApp
        print 'No ArcMap session is running at this time.'
    print "No AppROT found"
    return None

def NewObj(MyClass, MyInterface):
    """Creates a new comtypes POINTER object where\n\
    MyClass is the class to be instantiated,\n\
    MyInterface is the interface to be assigned"""
    from comtypes.client import CreateObject
    import traceback
    try:
        ptr = CreateObject(MyClass, interface=MyInterface)
        return ptr
    except:
        print traceback.format_exc()
        return None

if __name__ == "__main__":
    WrapModules()
    pApp = GetApp()
    if pApp is not None:
        print "HWND: %d" % pApp.hWnd
    else:
        print "No ArcGIS application found!"

And here is the output from the script:
Traceback (most recent call last):
  File "C:\temp\ComHelpers.py", line 35, in NewObj
    ptr = CreateObject(MyClass, interface=MyInterface)
  File "C:\Python26\ArcGIS10.0\lib\site-packages\comtypes\client\__init__.py", line 235, in CreateObject
    obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface)
  File "C:\Python26\ArcGIS10.0\lib\site-packages\comtypes\__init__.py", line 1145, in CoCreateInstance
    _ole32.CoCreateInstance(byref(clsid), punkouter, clsctx, byref(iid), byref(p))
  File "_ctypes/callproc.c", line 925, in GetResult
WindowsError: [Error -2147221231] ClassFactory cannot supply requested class

No AppROT found
No ArcGIS application found!
Thanks for any insights you might have!

A: For completeness, this solution was posted by Jason Scheirer over on the GIS Stack Exchange:

Import arcpy first, you aren't doing any license checkout or setting up the ArcObjects 10.0 runtime as-is so it won't find the CoClass.


text:
Q: No 'Access-Control-Allow-Origin' issue, despite all resources being on same domain I am writing a javascript/strophejs xmpp client, and have been so far using it to connect to a xmpp server hosted at hosted.im, via a public BOSH service (http://bosh.metajack.im:5280/xmpp-httpbind). The html/javascript is also hosted online, at testserver.host56.com (not the real url).
Now, I decided to host the xmpp server on the amazon web cloud, and use my own Bosh service, hosted on this server as well.
Now, my ec2 instance is at myAWSDNS.us-west-2.compute.amazonaws.com (also not real url).
I also have a BOSH service up and running, at myAWSDNS.us-west-2.compute.amazonaws.com:7070.
Finally, I have also allowed traffic to this ec2 instance through both the instances firewall and through the AWS Security Group policy.
However, when trying to connect to this instance's xmpp server (openfire), using my JS/strophejs client, I get the following message in the Chrome javascript console:

XMLHttpRequest cannot load http://myAWSDNS.us-west-2.compute.amazonaws.com:7070/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myAWSDNS.us-west-2.compute.amazonaws.com' is therefore not allowed access

Why am I getting this issue, if the origin is on the same domain as the requested resource?
The Ec2 instance is running Windows Server 2012.
This is the code I use to log in:
var conn = new Strophe.Connection("http://myAWSDNS.us-west-2.compute.amazonaws.com:7070/");
conn.connect("chris@myAWSDNS.us-west-2.compute.amazonaws.com", "myPassword", somecallback);

Thanks,
best regards,
Chris

A: The browser will not allow since the ports are different. I don't know what you have at AWS, but you can proxy the request in both direction, like as:
http://myAWSDNS.us-west-2.compute.amazonaws.com/http-bind/   <--------->   http://myAWSDNS.us-west-2.compute.amazonaws.com:7070/

See item no 5: Connecting with Strophe.js of the tutorial for Apache use case.

A: As previously mentioned, even if you're on the same domain, the ports must also match otherwise CORS is required.
You may not be using the correct URL for your connection manager, all of the ones I've seen use an address ending in /http-bind/ or similar.
Have you tried connecting with Strophe.Connection("http://myAWSDNS.us-west-2.compute.amazonaws.com:7070/http-bind/");?
Also, you can test for the presence of the crossdomain.xml file by simply visiting http://myAWSDNS.us-west-2.compute.amazonaws.com:7070/crossdomain.xml to ensure that CORS has been successfully enabled.


text:
Q: Ant taskdef resource="genjar.properties" doesn't work with Java 8 I am a newbine in ant build. My project is using ant taskdef resource="genjar.properties" to generate the jar. This work fine until we upgrade to java 8 and add some new Java 8 syntax code. The ant build is failed. I tried to replace the Java 8 with Java 7 syntax, the build success. This is 10 years old project, the MyApp.jar contains many classes so that switch to use jar is very hard. Could you suggest ideas about this problem?
The details error:
Build failed: Building MyApp.jar failed: java.lang.ArrayIndexOutOfBoundsException: 2925
at org.apache.tools.ant.ProjectHelper.addLocationToBuildException(ProjectHelper.java:539)
at org.apache.tools.ant.taskdefs.MacroInstance.execute(MacroInstance.java:380)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
at org.apache.tools.ant.Task.perform(Task.java:364)
at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:64)
at net.sf.antcontrib.logic.TryCatchTask$CatchBlock.execute(TryCatchTask.java:138)
at net.sf.antcontrib.logic.TryCatchTask.execute(TryCatchTask.java:224)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
at org.apache.tools.ant.Task.perform(Task.java:364)
at org.apache.tools.ant.Target.execute(Target.java:341)
at org.apache.tools.ant.Target.performTasks(Target.java:369)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1216)
at org.apache.tools.ant.Project.executeTarget(Project.java:1185)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:40)
at org.apache.tools.ant.Project.executeTargets(Project.java:1068)
at org.apache.tools.ant.Main.runBuild(Main.java:668)
at org.apache.tools.ant.Main.startAnt(Main.java:187)
at org.apache.tools.ant.launch.Launcher.run(Launcher.java:246)
at org.apache.tools.ant.launch.Launcher.main(Launcher.java:67)
Caused by: build.ml:497: Build failed: Building MyApp.jar failed: java.lang.ArrayIndexOutOfBoundsException: 2925
at org.apache.tools.ant.taskdefs.Exit.execute(Exit.java:139)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
at org.apache.tools.ant.Task.perform(Task.java:364)
at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:64)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
at org.apache.tools.ant.Task.perform(Task.java:364)
at org.apache.tools.ant.taskdefs.MacroInstance.execute(MacroInstance.java:378)
... 17 more
--- Nested Exception ---
build.xml:497: Build failed: Building MyApp.jar failed: java.lang.ArrayIndexOutOfBoundsException: 2925
at org.apache.tools.ant.taskdefs.Exit.execute(Exit.java:139)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
at org.apache.tools.ant.Task.perform(Task.java:364)
at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:64)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
at org.apache.tools.ant.Task.perform(Task.java:364)
at org.apache.tools.ant.taskdefs.MacroInstance.execute(MacroInstance.java:378)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
at org.apache.tools.ant.Task.perform(Task.java:364)
at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:64)
at net.sf.antcontrib.logic.TryCatchTask$CatchBlock.execute(TryCatchTask.java:138)
at net.sf.antcontrib.logic.TryCatchTask.execute(TryCatchTask.java:224)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
at org.apache.tools.ant.Task.perform(Task.java:364)
at org.apache.tools.ant.Target.execute(Target.java:341)
at org.apache.tools.ant.Target.performTasks(Target.java:369)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1216)
at org.apache.tools.ant.Project.executeTarget(Project.java:1185)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:40)
at org.apache.tools.ant.Project.executeTargets(Project.java:1068)
at org.apache.tools.ant.Main.runBuild(Main.java:668)
at org.apache.tools.ant.Main.startAnt(Main.java:187)
at org.apache.tools.ant.launch.Launcher.run(Launcher.java:246)
at org.apache.tools.ant.launch.Launcher.main(Launcher.java:67)


text:
Q: Splitting AngularJS Module Services Across Files I have two AngularJS services:
service1.js
'use strict';
angular.module('myModule', [])
  .factory('myService1', function() {
    return {
      myFunction: function(options) {
        if (options) {
          // do stuff
      }
    }
  };
});

service2.js
'use strict';
angular.module('myModule', [])
  .factory('myService2', function() {
    return {
      myFunction: function(options) {
        if (options) {
          // do stuff
      }
    }
  };
});

I learned the hard way from the official docs that this approach will basically remove myService1 because the module gets overwritten. My question is, do I have any options here? I would really like to be able to have my services defined in separate files. Yet, I only want one module.
Thank you for any insights.

A: You have to define the module just once:
angular.module('myModule', []);

And then use it as many times as you need it without setting the dependencies:
angular.module('myModule');

So either you define the module in a separate file, or if you define it in the first service, the second should look like this:
angular.module('myModule')
  .factory('myService2', function() { ... });


text:
Q: Access to ToggleButtons in ListView I am using Custom Adapter (ListAdapter.java) that extends ArrayAdapter to fill ListView (List.java).
After that ListView row contains TextView and ToggleButton.
In List.java I can register click on ListView row:
sett_list.setOnItemClickListener(new OnItemClickListener() {
     public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {

but how can I register click on ToggleButton, and get row position of that button?
EDIT: @MDMalik
In ListAdapter.java:
A):
View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.settings_row, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.option);
        final ToggleButton toggle = (ToggleButton) rowView.findViewById(R.id.toggle);

B):
if (values2[position].equals("on")) {
            toggle.setChecked(true);
        } else {
            toggle.setChecked(false);
        }

C):
toggle.setTag(Integer.valueOf(position));
        toggle.setOnClickListener(new OnClickListener() {

             @Override
             public void onClick(View v) {
                 Toast.makeText(getContext(), Integer.valueOf(position) + " : Click", Toast.LENGTH_SHORT).show();
             }
        });

That's it. Now I have position of clicked button. Thank you.
How can I write result to database now?
Something like this (not working):
toggle.setOnClickListener(new OnClickListener() {
             @Override
             public void onClick(View v) {
                 if (toggle.isChecked() == true) {
                        checked = 1;
                        myDB = SQLiteDatabase.openOrCreateDatabase("database.db", null);
                        myDB.execSQL("UPDATE " + TableName + " SET  on_off_ = 'on' WHERE sett_ = '" + values[position] + "'");
                        myDB.close();
                    } else {
                        checked = 0;
                        myDB = SQLiteDatabase.openOrCreateDatabase("database.db", null);
                        myDB.execSQL("UPDATE " + TableName + " SET  on_off_ = 'off' WHERE sett_ = '" + values[position] + "'");
                        myDB.close();
                    }

             }
        });

A: I tend to achieve this by setting usual listeners inside Adapter when inflating View in getView and also remembering position for that View inside tag.
Take a look at this working example: ButtonsProblemsExampleActivity.java.

A: A) As you have a CustomAdapter, you need to intalize your ToggelButton in getView.
B) Your String array should have a default value for that button, either true or false that can be achieve something like this
String chkCondition = hmap.get("chk").toString().toLowerCase();
Boolean blnChk = true;
if (chkCondition.equals("false"))
{    blnChk = false;   }
chkBox.setChecked(blnChk);

C) Then you need to declare onClickListener for that where is basically reintallize your origianl array finding your TextView value and the new chk value.
private void setCheckValue(String Condition, String upc) {
  for (int i = 0; i < data.size(); i++) {
     String Upccode = data.get(i).get("UpcCode").toString();
     if (Upccode.equals(upc)) {
        HashMap<String, String> hmap = new HashMap<String, String>();
        hmap = data.get(i);
        hmap.put("chk", Condition);
        data.set(i, hmap);
        break;
     }
  }
}

D) Returning the modified data to the Activity by declaring a method call getData()
public ArrayList<HashMap<String, String>> getData() {
    return data;
}

I use data in my CustomAdapter. Data is a ArrayList<HashMap<String, String>> .
Edit I don't do SQL command on toggle change. I collect them in a array. Then you obviously have a Submit button in your Activity. Once you press the submit button. I get the Data from the CustomAdapter. Which is done by getData() this will give you HashMap in your Activity.


text:
Q: how can I train test split in scikit learn does anyone know what is the problem?
x=np.linspace(-3,3,100)
rng=np.random.RandomState(42)
y=np.sin(4*x)+x+rng.uniform(size=len(x))
X=x[:,np.newaxis]
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test=train_test_split(X,y,test_size=0.25,random_state=42,stratify=y)

I have this error:
ValueError: The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2.

A: Try removing stratify=y, you should do without.
Also, have a peek here.

A: From the documentation:

3.1.2.2. Cross-validation iterators with stratification based on class labels.
Some classification problems can exhibit a large imbalance in the
distribution of the target classes: for instance there could be
several times more negative samples than positive samples. In such
cases it is recommended to use stratified sampling as implemented in
StratifiedKFold and StratifiedShuffleSplit to ensure that relative
class frequencies is approximately preserved in each train and
validation fold.

A: The parameter (stratify = y) inside the train_test_split is giving you the error. Stratify is used when your labels have repeating values. Eg: Let's say your label columns have values of 0 and 1. Then passing stratify = y, would preserve the original proportion of your labels in your training samples. Say, if you had 60% of 1s and 40% of 0s, then your training sample will also have the same proportion.


text:
Q: what magic is "django-admin startapp" doing, that the test runner needs to find my tests.py I was having a problem that the django test runner wasn't finding the tests for my app, like this one:
Django test runner not finding tests
One of the comments on that thread suggested creating a new app with django-admin.py and seeing if the tests ran there. e.g.
django-admin.py startapp delme

then
adding "delme" to my INSTALLED_APPS

then
copying my tests.py from the app where it wasn't getting found into delme/

and viola! the tests did run. So, OK, I have a work arround, but I don't understand. I re-read what I think should be the relevant parts of the django documentation but the penny refuses to drop.
BTW, the app works via runserver and wsgi, so there doesn't appear to be any gross configuration problem. And my tests all pass from their new home, so I obviously need more tests :)
Specifically, I'm running django in a virtualenv, so I had run "django-admin.py startapp" in the (activated) virtualenv where I wanted the tests to run. This doesn't make the tests run in my other virtualenvs, I still have the old symptoms there (Ran 0 tests). I have a multitude of virtualenvs, managed by non-trivial paver scripts. One uses "path.copytree" for deploying projects, rewrites apache config files, restarts apache, writes wsgi files using the appropriate virtualenv, etc. The other uses PIP/GCC/aptitude/etc for bootstrapping/tearing down the different environments, updating packages as per configuration, etc. So I want to understand the difference between django-startapp and simply copying files, so I can fix these paver scripts so the tests can run in any environment I want them to.

A: The only thing that makes sense to me, after reading your description, is the location of paths for your existing apps. Can you confirm the following things:

*

*Your app is at the same folder level as the delme app

*Your app folder contains an __init__.py file

*Your app is listed in the INSTALLED_APPS setting

I'm going to guess that it's a missing __init__.py file, as that trips some people up. To answer your specific question, django-admin startapp doesn't do anything magical. It just creates the right folders and files in the correct place.
Your folder structure should be...
my_project/
    __init__.py
    manage.py
    settings.py
    my_app/
        __init__.py
        tests.py
        models.py
    delme/
        __init__.py
        tests.py
        models.py

Also note this comment

You can't easily name the TestCase class directly. You name the app, the Django runner does it's discovery thing by looking in models.py and tests.py

A: solved (still with a little whiff of magic).
diff showed that my old app didn't have a models.py but the new app ("delme", working) did. I didn't think the old app needed one, it was importing all it's domain classes from other places.
Touching an empty models.py in my old app fixed it, now the test runner finds the tests.py and everything works as expected. Condlusion - if an app has no models.py, the django test runner won't find the app's tests.py.
What I said about not working in different virtualenvs was bogus (red herring), I was a bit confused about what my deploy scripts were doing.


text:
Q: Echo data from database in each times get I send three times values 1 & 2 & 3 by jquery.serialize() for $hotel_id in PHP, now i want get in the each times from send, data linked with $hotel_id(like: 1 or 2 or 3) from database. but in the following code i just get data that linked to last $hotel_id(3).
I want as:

First: get data linked with 1 and echo they in json_encode
Second: (next 2) get data linked with 2 and echo they in
  json_encode Third: (next 3)get data linked with 3 and echo
  they in json_encode...

This is output serialize() from jQuery code:
hotel_id=1&hotel_id=2&hotel_id=3

This is my php code:
$hotel_id = $this->input->post('hotel_id');
$query_r  = $this->db->query("SELECT * FROM hotel_submits WHERE id LIKE '$hotel_id' ORDER BY id desc");
$data     = array();
foreach ($query_r->result() as $row) {
    $data_s  = json_decode($row->service, true);
    $data_rp = json_decode($row->address, true);
    $data[]  = array(
        'name' => $row->name,
        'star_type' => $row->star . '-' . $row->type,
        'site' => $row->site,
        'service' => $data_s,
        'address' => $row->address
    );
}
echo json_encode($data);

How do i do?

A: You can't pass in the same argument three times. It will only see the final parameter of hotel_id and so you just get number 3. PHP does allow for passing Arrays by naming the parameter with [] at the end like hotel_id[]=1&hotel_id[]=2, etc and then you can get the array of values in php. That means your value of $hotel_id would be an array of values instead of a single value. Since it is an array you would need to implode the array with a comma to use in your SQL:
$hotel_id = implode(',', $this->input->post('hotel_id'));

Now $hotel_id will look like '1,2,3';
Now your SQL will need to change to:
SELECT * FROM hotel_submits WHERE id IN ($hotel_id) ORDER BY id desc

Hope that helps.


text:
Q: Как поменять классы у кнопок в Jquery? Как сделать так чтобы значения классов (InactiveButton, АctiveButton) у кнопок поменялись местами?
<button id="delButton" class="ActiveButton">Самовывоз</button>
<button id="delButton" class="InactiveButton">Доставка</button>

Сам пытался сделать нечто подобное, но не получилось
$('.InactveButton').click(function (){
    $(this).toggleClass('InactiveButton').toggleClass('ActiveButton');
    $('.ActiveBbutton').toggleClass('InactiveButton').toggleClass('ActiveButton');
});

A: Необходимо повесить событие на общий селектор данных кнопок (в нашем случае в качестве селектора выступит тег button). При клике на кнопку меняем классы у всех с InactiveButton на ActiveButton. После у текущей кнопки уже меняем классы обратно.

$('button').click(function() {
  $('button').removeClass('ActiveButton').addClass('InactiveButton'); //можно и toggleClass использовать
 $(this).toggleClass('ActiveButton').toggleClass('InactiveButton')
});
.InactiveButton {
opacity: 0.5;
}
.ActiveButton {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="delButton-1" class="ActiveButton">Самовывоз</button>
<button id="delButton-2" class="InactiveButton">Доставка</button>

P.S. И не забываем, что идентификаторы на странице должны быть разными. Повторяющихся быть не должно

A: Вот ещё одно решение:
<button id="qqq" class="qqq">Самовывоз</button>
<button id="www" class="www ActiveButton">Доставка</button>

 $('#qqq').click(function() {
                            if ($('#qqq').hasClass('ActiveButton') == false)
                            {
                                $( "#qqq" ).addClass( 'ActiveButton' );
                                $( "#www" ).removeClass( 'ActiveButton' );
                            }
                        })

                        $('#www').click(function() {
                            if ($('#www').hasClass('ActiveButton') == false)
                            {
                                $( "#www" ).addClass( 'ActiveButton' );
                                $( "#qqq" ).removeClass( 'ActiveButton' );
                            }
                        })

A: Не стоит назначать одинаковый id элементам.
Возможно в Вашем случае не обязательно менять местами классы. Можно изначально назначить один общий класс для кнопок (аналог inactive), и просто добавлять/удалять класс active, который будет применять необходимый стиль.
Пример ниже.

$('.delBtn').click(function (){
    $('.delBtn.active').removeClass('active');
    $(this).addClass('active');
});
.delBtn {
  opacity: 0.5;
  background: blue;
  color: white;
  padding: 10px;
  cursor: pointer;
  border: none;
}

.delBtn.active {
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="delBtn">Самовывоз</button>
<button class="delBtn active">Доставка</button>


text:
Q: Xamarin - Setting Camera feed as background So, I'm trying to make a login activity with the camera feed as the background. I've tested the example on https://developer.xamarin.com/guides/android/user_interface/textureview/ and got it to work, but I need to it to be part of an activity. So, I tried this:
protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your application here
        SetContentView(Resource.Layout.Login);

        _textureView = this.FindViewById<TextureView>(Resource.Id.textureView);
        _textureView.SurfaceTextureListener = this;
    }

public void OnSurfaceTextureAvailable(
       Android.Graphics.SurfaceTexture surface, int w, int h)
        {
            _cam = Camera.Open();

            _textureView.LayoutParameters =
                   new FrameLayout.LayoutParams(w, h);

            try
            {
                _cam.SetPreviewTexture(surface);
                _cam.StartPreview();

            }
            catch (Java.IO.IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

The axml file looks somewhat like this:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextureView
        android:id="@+id/textureView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        AbsoluteLayout.LayoutBounds="0,0,1,1"
        AbsoluteLayout.LayoutFlags="SizeProportional" />
    <LinearLayout
        android:id="@+id/linearLayout"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        AbsoluteLayout.LayoutBounds="0,0,1,1"
        AbsoluteLayout.LayoutFlags="SizeProportional">

        <!-- Some other controls -->
    </LinearLayout>
</AbsoluteLayout>

However, the app now crashes after exiting the OnSurfaceTextureAvailable block, giving an unhandled exception. Breaking at the exception doesn't work, it's apparently in a thread that's not running anymore.
Would anyone know why it crashes and, more importantly, how to fix it?

A: Problem is with this code:
_textureView.LayoutParameters = new FrameLayout.LayoutParams(w, h);

I'm not sure why your need to reset the TextureView's layout parameters, in xml you've set it to match parent. And the parent here is AbsoluteLayout, not FrameLayout, that's why this error happens.
To solve this issue, since AbsoluteLayout is obsolete now, I suggest to use RelativeLayout as root container in your xml. Then you can code like this:
_textureView.LayoutParameters = new RelativeLayout.LayoutParams(width, height);

Of course you can also change AbsoluteLayout to FrameLayout in your xml, then the code _textureView.LayoutParameters = new FrameLayout.LayoutParams(w, h); doesn't need to be modified anymore.


text:
Q: Use the requirejs module without importing it with node I want to run a python file from javascript, and have determined the easiest way to do it is to use 'spawn'...however, I need to use require('child_process'). I really need help in gettng this to work, without using npm in the terminal.

<script src="https://cdn.jsdelivr.net/npm/child_process@1.0.2/index.min.js"></script>
<script src="https://requirejs.org/docs/release/2.3.6/minified/require.js"></script>

<script>
const spawn = require('child_process').spawn;
const childPython = spawn('python',['python.py', data]);

childPython.stdout.on('data',(data)=>{console.log('stdout:', data)});

childPython.stderr.on('data',(data)=>{console.log('stderr:', data)});

childPython.on('data',(code)=>{console.log('process closed with:', code)});
</script>

A: This won't work on the client-side. But you can achieve what you want by making a request to the server-side to run the specific python code and return the result in the response. Then you can console.log it on the client-side.


text:
Q: kde-full and unistalling some of its packages I installed KDE using kde-full - so far so good. But when I try to unistall some of its app wich is not so neceseary to me (like marble or kalgebra), apt-get remove will show me
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  knetwalk kpat kalzium-data kdepim kolf xscreensaver-gl
  plasma-desktopthemes-artwork ksystemlog libsdl-ttf2.0-0 krdc krfb kdesdk
  kscd kppp libopenbabel4 libanalitzagui4abi1 kshisen kdeartwork-style
  kmahjongg kopete-message-indicator kcharselect kanagram kde-baseapps
  libksane0 cervisia kdeartwork-theme-window knode kblocks katomic kruler
  plasma-containments-addons svgpart ktux kdegraphics-thumbnailers klettres
  kajongg kgoldrunner libknewstuff2-4 kgeography pkg-kde-tools xplanet
  ksnapshot plasma-wallpapers-addons translate-toolkit libkexiv2-data
  libcfitsio3 libkipi8 libkipi-data kaccessible kblackbox libotr2 bomber
  kiriki libgrantlee-gui0 kde-standard libsdl-mixer1.2 libglew1.5 kstars
  ttf-dustin kbruch gwenview advancecomp libmarblewidget13 python-levenshtein
  printer-applet kfilereplace libkggznet4 umbrello kcalc kdeplasma-addons
  libavogadro1 libkggzmod4 parley konsolekalendar kontact kimagemapeditor
  libportmidi0 kmplot kdiamond kalzium libindi-data ksirk ksquares klinkstatus
  klickety libkcddb4 libkateinterfaces4 libgadu3 kalarm blogilo kdewebdev
  kwrite libkeduvocdocument4 plasma-dataengines-addons libkdcraw-data kdegames
  amor marble-plugins kdeaccessibility rocs libboost-graph1.46.1
  libnova-0.12-2 ktouch kbreakout kbounce kfourinline libkdegames5a kdetoys
  python-avogadro ktimetracker akregator avogadro-data kollision
  kdegraphics-strigi-analyzer python-enchant python-qt4 kamera sweeper
  lokalize kwordquiz kde-plasma-desktop libanalitza4abi1 ktron bovo python-sip
  cvs kdenetwork libkggzgames4 libmikmod2 step python-vobject palapeli-data
  krosspython kuser dragonplayer kcolorchooser kreversi kdf python-qt4-sql
  plasma-widget-folderview kdegraphics-mobipocket kspaceduel libkrossui4 kig
  rdesktop ksudoku juk tasks-icons klines kstars-data libao4 lskat
  plasma-widgets-addons kgamma kde-config-cddb kommander libkopete4
  kdegames-card-data kubrick kgeography-data ksaneplugin kdeutils kjumpingcube
  kdegraphics khangman plasma-scriptengine-superkaramba libkexiv2-10
  libqtassistantclient4 kscreensaver marble kolourpaint4 libindi0 killbots
  kapman plasma-widget-lancelot fonts-dustin kde-plasma-netbook
  plasma-runners-addons vorbis-tools poxml parley-data libkmahjongglib4
  kpartloader kdesdk-kio-plugins cvsservice libksane-data kbattleship kdeadmin
  kdesdk-scripts kdegames-mahjongg-data kdemultimedia-kio-plugins filelight
  xplanet-images libkdcraw20 kopete kde-config-cron kdesdk-misc palapeli kate
  kapptemplate ktouch-data kdewallpapers kscreensaver-xsavers
  kdesdk-strigi-plugins marble-data kjots klettres-data kdeartwork-emoticons
  libktorrent3 kmines python-iniparse kget kalgebra-common
  system-config-printer-kde kremotecontrol kdenetwork-filesharing kgpg
  libboost-regex1.46.1 konquest kigo kdemultimedia kmousetool
  kdepim-strigi-plugins optipng libmsn0.3 libkdeedu-data kuiviewer kmag gnugo
  kdeedu-kvtml-data ktuberling kturtle ktimer python-kde4 kteatime kmix
  kdeartwork kmtrace plasma-widget-message-indicator libsmpeg0
Use 'apt-get autoremove' to remove them.
The following packages will be REMOVED:
  kalgebra kde-full kdeedu
0 upgraded, 0 newly installed, 3 to remove and 18 not upgraded.
After this operation, 497 kB disk space will be freed.
Do you want to continue [Y/n]?

Now that would unistall some needed package for kde as well. How to prevent it and unistall realy only what I want to uninstall? I don't believe that all of these packages are there only because of kalgenra.


text:
Q: how to fade in and out with javascript I am trying to make a message appear if the user doesn't scroll for specific amount of time and then make the text fade out as soon as the user scroll. What I have tried so far is not working.
I am looking for vanilla javascript solutions only.
thank you for your help.

// make scroll button appear ---------------
var scrollText = document.getElementById("scrollMsg");

function showMsg() {
  scrollText.className = "show";
}

setTimeout(showMsg, 2000);

// make scroll button fadout ---------------

function scrollHide() {
  var scrollText2 = document.querySelector("#scrollMsg.show");
  var scrllTPosition = scrollText2.getBoundingClientRect().top;
  var screenPosition = window.innerHeight / 0.5;
  if (scrllTPosition < screenPosition) {
    scrollText2.classList.add("scrollHide");
  }
}
window.addEventListener("scroll", scrollHide);
#scrollMsg {
  height: auto;
  position: sticky;
  bottom: 175px;
  z-index: 1;
  opacity: 0;
  -webkit-transition: opacity 0.7s;
  -moz-transition: opacity 0.7s;
  transition: opacity 0.7s;
}

#scrollMsg.show {
  opacity: 1;
  -webkit-transition: opacity 0.7s ease-in-out;
  -moz-transition: opacity 0.7s ease-in-out;
  transition: opacity 0.7s ease-in-out;
}

#scrollhide {
  opacity: 0;
  -webkit-transition: opacity 0.7s ease-in-out;
  -moz-transition: opacity 0.7s ease-in-out;
  transition: opacity 0.7s ease-in-out;
}

scroll

A: I've added some large divs to allow us to scroll through the document.

// make scroll button appear ---------------
var scrollText = document.getElementById("scrollMsg");

window.addEventListener('scroll', (e) => {
  console.log('user scrolled!')
  scrollText.style.opacity = 0
});
#scrollMsg {
  opacity: 1;
  transition: opacity 1s;
}

scroll


text:
Q: QGIS 2.0 How can i get a precisely Rendering time? I work with QGIS 2.0.1.
I have a large number of raster data files and i selected different methods to represent them.

*

*Method: Import all raster data as individual files

*Method: Generate a single file with the help of the rastertool "Merge"

*Method: Generate a virtual raster (catalog)

I would like to know if it is possible to get the exact Rendering time? For example how long qgis needs to render the map if you zoom in.
This would be very helpful to compare the rendering time between the three methods.
I know which method is faster but a time value would be important for me.
Thanks for your help

A: You can enable rendering logging under Settings -> Options -> Rendering

A: You can also just start your favourite system monitor and look at how long it takes to render your map. That also gives you information of which hardware is your bottleneck. In my example it took about 10 seconds to render the map before the CPU went back to idling. I would even say it is better than just the time value because your data gives you "time - CPU-load". Integrating over that function is a better measure than just the overall time.


text:
Q: Multiplicative Group of $p$ - adic Power Series We let $D$ be an open or closed disc in $\mathbb{C}_p$ centered at $0$. I have to prove that
$\text{(a)}$ $\{f \in 1 + x\mathbb{C}_p[[x]] : f \text{ converges in }D\}$ is closed with respect to multiplication but does not form a group; and
$\text{(b)}$ $\{f = 1 + \sum_{i=1}^{\infty} a_i x^i : \text{ord}_p a_i − λi > 0\ \forall i \text{, and tends to }\infty\text{ as }i \rightarrow \infty\}$ forms a group with respect to multiplication, where $\lambda \in \mathbb{R}$ is fixed.
While showing that these sets are closed with respect to multiplication is straightforward, I don't know how to show that $\text{(a)}$ is not a group. Clearly it has identity, but how do I show that it's candidate for inverse (which will exist since the constant term is $1$) doesn't converge in the disk?
Coming to $\text{(b)}$, I'm unable to show how a candidate for inverse's coefficients will satisfy the given constrain, may be mathematical induction will help. But not getting anywhere.
I know asking multiple questions in a single question is frowned upon, but all these questions come from a single question, which is an exercise problem in Koblitz's book on $p$ - adic analysis, but here's another question I have which I can't make heads or tails of:
Let $f_j ∈ 1+x\mathbb{Z}_p[[x]]$ converge in the closed unit disc $D(1)$ for any $j$. Does $f := \prod_{j \geq 1}f_j (x^j)$ converge in $D(1)$?


text:
Q: Редактирование таблицы в javafx Есть таблица tableview, в которой 2 столбца.
Как сделать что бы пользователь мог редактировать значения конкретного столбца?
Каким образом можно реализовать это?

A: Советую прочитать статью, в которой все прекрасно описано.
Суть такова - определяешь таблицу TableView,  в ней определяешь колонки TableColumn, у которых ты определяешь listener setOnEditCommit.
P.S. не забудь у таблицы и колонок поставить признак editable в true


text:
Q: Error while trying to generate xml file with specific name I tried to generate a file named, for example, 23-10-2022|21-03-11.xml or if the user enters his own name userGeneratedName23-10-2022-21-03-11.xml. I don't know why when I tried to specify a particular folder where the generated file should be saved the program throws me an Invalid argument error. I suspect that I am using join incorrectly, I don't really know how to correct it
    if not os.path.exists("Generated XMLs"):
        os.makedirs("Generated XMLs")
    #open file
    today = date.today()
    now = datetime.now()
    #if filename is not specified, create file with today's date and time of creation
    if filename == "":
        filename = today.strftime("%d-%m-%Y") +"|"+ now.strftime("%H-%M-%S")
    #if filename is specified,ad at the and of filename today's date and time of creation
    else:
        filename = filename + today.strftime("%d-%m-%Y")+"|"+ now.strftime("%H-%M-%S")
    # open file wchich is in Generated XMLs folder and name it with variable filename
    file = open(os.path.join("Generated XMLs", filename + ".xml"), "w")
    #write to file

    #write header
    file.write("\n<root>\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
    file.write("\t<POZYCJE>\n")
    #write data
    # ask user if he wont netto or brutto meters and ad flag
    flag = input("Enter 'n' if you want to use netto meters or 'b' if you want to use brutto meters: ")
    for i in range(len(convertedData)):

        file.write("\t\t<POZYCJA>\n")
        file.write("\t\t\t<LP>" + (i+1) + "</LP>\n")
        file.write("\t\t\t<TOWAR>\n")

        file.write("\t\t\t\t<KOD>" + convertedData[i][0] + " " + convertedData[i][1] + "</KOD>\n")
        file.write("\t\t\t\t<NAZWA>" + convertedData[i][0] + " " + convertedData[i][1] + "</NAZWA>\n")
        file.write("\t\t\t\t<OPIS/>")
        file.write("\t\t\t\t<EAN/>")
        file.write("\t\t\t\t<SWW/>")
        file.write("\t\t\t\t<NUMER_KATALOGOWY/>")
        file.write("\t\t\t\t<MPP>" + "0" + "</MPP>\n")

        file.write("\t\t\t</TOWAR>\n")
        file.write("\t\t\t<STAWKA_VAT>\n")

        file.write("\t\t\t\t<STAWKA>" + "23.00" + "</STAWKA>\n")
        file.write("\t\t\t\t<FLAGA>" + "2" + "</FLAGA>\n")
        file.write("\t\t\t\t<ZRODLOWA>" + "0.00" + "</ZRODLOWA>\n")

        file.write("\t\t\t</STAWKA_VAT>\n")
        file.write("\t\t\t<CENY>\n")

        file.write("\t\t\t\t<CENAZCZTEREMAMIEJSCAMI>0</CENAZCZTEREMAMIEJSCAMI>\n")
        file.write("\t\t\t\t<POCZATKOWA_WAL_CENNIKA>00.0000</POCZATKOWA_WAL_CENNIKA>\n")
        file.write("\t\t\t\t<POCZATKOWA_WAL_DOKUMENTU>00.0000</POCZATKOWA_WAL_DOKUMENTU>\n")
        file.write("\t\t\t\t<PO_RABACIE_WAL_CENNIKA>00.0000</PO_RABACIE_WAL_CENNIKA>\n")
        file.write("\t\t\t\t<PO_RABACIE_PLN>00.0000</PO_RABACIE_PLN>\n")
        file.write("\t\t\t\t<PO_RABACIE_WAL_DOKUMENTU>00.0000</PO_RABACIE_WAL_DOKUMENTU>\n")

        file.write("\t\t\t</CENY>\n")
        file.write("\t\t\t<WALUTA>\n")

        file.write("\t\t\t\t<SYMBOL>PLN</SYMBOL>\n")
        file.write("\t\t\t\t<KURS_L>1.00</KURS_L>\n")
        file.write("\t\t\t\t<KURS_M>1</KURS_M>\n")

        file.write("\t\t\t</WALUTA>\n")
        file.write("\t\t\t<RABAT>0.00</RABAT>\n")
        file.write("\t\t\t<WARTOSC_NETTO>0.00</WARTOSC_NETTO>\n")
        file.write("\t\t\t<WARTOSC_BRUTTO>0.00</WARTOSC_BRUTTO>\n")
        file.write("\t\t\t<WARTOSC_NETTO_WAL>00.00</WARTOSC_NETTO_WAL>\n")
        file.write("\t\t\t<WARTOSC_BRUTTO_WAL>833.94</WARTOSC_BRUTTO_WAL>\n")
        if flag == "n":
            file.write("\t\t\t<ILOSC>" + convertedData[i][3] + "00" + "</ilosc>\n")
        elif flag == "b":
            file.write("\t\t\t<ILOSC>" + convertedData[i][2] + "00" + "</ilosc>\n")
        else:
            print("Error: Wrong flag. Enter 'n' or 'b'.")
        file.write("\t\t\t<JB>" + convertedData[i][4] + "</JB>\n")
        file.write("\t\t\t<JM_CALKOWITE>0.00</JM_CALKOWITE>\n")
        file.write("\t\t\t<JM_ZLOZONA>\n")

        file.write("\t\t\t\t\n")
        file.write("\t\t\t\t\n")
        file.write("\t\t\t\t\n")

        file.write("\t\t\t</JM_ZLOZONA>\n")
        file.write("\t\t\t<JMZ>" + convertedData[i][4] + "</JMZ>\n")
        file.write("\t\t\t<JM_PRZELICZNIK_L>1.00</JM_PRZELICZNIK_L>\n")
        file.write("\t\t\t<JM_PRZELICZNIK_M>1</JM_PRZELICZNIK_M>\n")
        file.write("\t\t</POZYCJA>\n")

    #write footer
    file.write("\t</POZYCJE>\n")
    file.write("</root>")
    #close file
    file.close()

The exact error I get:
Traceback (most recent call last):
  File "C:\Users\reczul\PycharmProjects\pythonProject5\main.py", line 23, in <module>
    main()
  File "C:\Users\reczul\PycharmProjects\pythonProject5\main.py", line 13, in main
    XMLCreator.CreateXML(DataConverter.ConvertData(data))
  File "C:\Users\reczul\PycharmProjects\pythonProject5\venv\Functions\XMLCreator.py", line 20, in CreateXML
    file = open(os.path.join("Generated XMLs", filename + ".xml"), "w")
OSError: [Errno 22] Invalid argument: 'Generated XMLs\\24-10-2022|09-23-45.xml'

Process finished with exit code 1

A: I can not use "|" also I had to convert filename to str.
    if not os.path.exists("Generated XMLs"):
        os.makedirs("Generated XMLs")
    #open file
    today = date.today()
    now = datetime.now()
    #if filename is not specified, create file with today's date and time of creation
    if filename == "":
        filename = today.strftime("%d-%m-%Y") +"--"+ now.strftime("%H-%M-%S")
    #if filename is specified,ad at the and of filename today's date and time of creation
    else:
        filename = filename + today.strftime("%d-%m-%Y")+"--"+ now.strftime("%H-%M-%S")
    filename = str(filename)
    # open file wchich is in Generated XMLs folder and name it with variable filename
    #file = open(os.path.join(os.path.dirname(os.path.abspath(__file__)),"Generated XMLs",filename + ".xml"), "w")
    #cerate XML file which is in Generated XMLs folder
    file = open(os.path.join("Generated XMLs", filename + ".xml"), "w")


text:
Q: If a closed set in projective space is stabilized by an automorphism, so are its components Let $X$ be a closed set in $\mathbb{P}^n$, and let $\phi$ be an automorphism of varieties $\mathbb{P}^n \rightarrow \mathbb{P}^n$.  If $\phi$ stabilizes $X$, does it follow that $\phi$ stabilizes the irreducible components of $X$?  This is not true in the affine case. For example, $\phi: \mathbb{A}^1 \rightarrow \mathbb{A}^1$, $\phi(x) = -x$ is an isomorphism of varieties, and $\{1,-1\}$ is a $\phi$-stable closed set in $\mathbb{A}^1$ whose irreducible components $\{1\}$ and $\{-1\}$ are not fixed.
In projective space, similar counterexamples are obviously not possible.

A: Let $X = \{[1:0:0], [0: 1:0], [0:0:1]\} \subset \mathbb{P}^2$. It is known that the automorphism group of $\mathbb{P}^n$ is $GL_n(k)$ modulo action of scalars. Take $\phi$ to be the matrix that permutes the above three points cyclically. None of the irreducible components (individual points) are fixed.

A: Contrary to your claim similar examples are possible in projective space:
Just take the automorphism $\phi:\mathbb P^1\to \mathbb P^1:[x,y]\mapsto [x,-y]$ which leaves globally invariant the subvariety $X\subset \mathbb P^1$ given by $x^2-y^2=0$ but permutes its irreducible components, namely the one-point sets  $\{[1,1]\}$ and $\{[1,-1]\}$.


text:
Q: Android GridView actualizar backgroundColor de click anterior Estoy cambiando de color las celdas de un GridView dependiendo de algunas comparaciones. Tengo un metodo que comprueba si el número es el más cercano a un número generado al azar, luego pinto de amarillo si la selección es más cercana que los que ya se han hecho clic. Pero quiero que el número más próximo anterior sea pintado de rojo, para no tener varias celdas en amarillo solamente dos. Codigo que compara y pinta las celdas:
gridViewNumbers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(MainActivity.this,"Random number is: " +randomNumber +" number is: " +listNumbers[position], Toast.LENGTH_SHORT).show();

        int selectedNumber = listNumbers[position];

        numbersCloser(selectedNumber);

        if (selectedNumber == randomNumber) {
            view.setBackgroundColor(Color.GREEN);
        }

        if (selectedNumber == numberBigger || selectedNumber == numberSmaller) {
            view.setBackgroundColor(Color.YELLOW);
        }

        if (selectedNumber != randomNumber && selectedNumber != numberBigger && selectedNumber != numberSmaller) {
            view.setBackgroundColor(Color.RED);
        }

        numberLastPlay = selectedNumber;
    }

});

Código que actualiza el número más cercano más grande y menor:
private int numbersCloser(int selected){
    if (selected < numberBigger && selected > randomNumber){
        return numberBigger = selected;
    }

    if (selected > numberSmaller && selected < randomNumber){
        return numberSmaller = selected;
    }
    else{
        return 0;
    }
}

Creo que tendré que crear variables para mantener los números próximos antiguos o cambiar el color a rojo de las celdas antes de actualizar las variables de números próximos.
¿Alguna sugerencia de cómo puedo hacer?

A:
Creo que tendré que crear variables para mantener los números próximos
  antiguos

Definitivamente tendrías que guardar en alguna variable los indices de las celdas de los números "antiguos", esto para  para cambiarlos a su color default, y posteriormente cambiar el color de las celdas correspondientes a amarillo verde y rojo.


text:
Q: Failed try tring to recreate the find method Ok so i need to recreate the find method but i cant manage to suceed. I am trying to do this but everytime i run this on a array it simple returns me an error
  array.prototype.findDaShopee = function ( ok ) {
    for (let i = 0; i < this.length; i++) {
        if (this[i] == ok[i]) {
            return this[i]
        })
    }

  }

but it's not working
I tried removing the 'ok' function, i tried everything, i dont want the answer just the explanation
i'm really tring to understand

A: The name of the class is Array, not array.
ok is not an array, it's a function that should be called on each element of the array. The method returns the first element where the function returns a truthy value.
You had an extra ) in the code.

Array.prototype.findDaShopee = function(ok) {
  for (let i = 0; i < this.length; i++) {
    if (ok(this[i])) {
      return this[i]
    }
  }
}

const testArray = [1, 2, 10, 12];
console.log(testArray.findDaShopee(el => el % 5 == 0));


text:
Q: Facebook fql not showing the photos and albums query I am using php-sdk for showing facebook information of the user. I have successfully shown the user profile info but while fetching any album or photos I am getting the blank data to me. I read the photos requires access_token.
Also if I put this query in the facebook graph api explorer it showing me the perfect result. So query is right may be my way of passing the url is wrong.
I am not getting the issue.
Please help.
    ';
              $app_secret = '';
              $my_url = '';
          $config = array(
            'appId' => '<appid>',
            'secret' => '<appsecrete>',
           );

            $facebook = new Facebook($config);
            $user_id = $facebook->getUser();

            $code = $_REQUEST["code"];
            if($user_id) {
             //auth user
             if(empty($code)) {
                $dialog_url = 'https://www.facebook.com/dialog/oauth?client_id='
                    . $app_id . '&redirect_uri=' . urlencode($my_url) ;
                    echo("<script>top.location.href='" . $dialog_url . "'</script>");
              }

              //get user access_token
              $token_url = 'https://graph.facebook.com/oauth/access_token?client_id='
                . $app_id . '&redirect_uri=' . urlencode($my_url)
                . '&client_secret=' . $app_secret
                . '&code=' . $code;
              $access_token = file_get_contents($token_url);

             $fql_query_url = 'https://graph.facebook.com/'.'fql?q=SELECT+pid,src_small+FROM+photo+WHERE+aid+IN+(SELECT+aid+FROM+album+WHERE+owner=+me())&'.$access_token;
             $fql_query_result = file_get_contents($fql_query_url);
             $fql_query_obj = json_decode($fql_query_result, true);

          //display results of fql query
          echo '<pre>';
          print_r("query results:");
          print_r($fql_query_obj);
          echo '</pre>';

}
?>

A: One parameter needs to be add for $dialog_url variable which is 'scope' which defines  permissions to be given for application
$dialog_url = 'https://www.facebook.com/dialog/oauth/?client_id='.$app_id.'&redirect_uri='.urlencode($my_url).'&scope=user_photos';
                    echo("<script>top.location.href='" . $dialog_url . "'</script>");

for reference,
http://developers.facebook.com/docs/reference/dialogs/oauth/
Thanks
Shreyas


text:
Q: psql export return No such file or directory when the file exist I run
psql -E -U siteportal -d portal -h 172.19.242.32 -c "COPY externals (id,logo_path,favicon_path,cover_path,header,description,sign_enable,sign_text,footer_logo_enable,footer_logo_path,footer_text,created_at,updated_at) FROM '/Applications/MAMP/htdocs/code/site/portal/public/csv/externals.csv' DELIMITER ',' csv;"

I got
ERROR:  could not open file "/Applications/MAMP/htdocs/code/site/portal/public/csv/externals.csv" for reading: No such file or directory

But I know for sure the file is there, becase when I run
cat /Applications/MAMP/htdocs/code/site/portal/public/csv/externals.csv

I got
1,"/images/account/operator/logo.png","/images/account/operator/favicon.png","/images/account/operator/external.png","site Portal","Log in using your credentials",1,"This is a secure page",1,"/images/account/operator/footer_logo.png","© 2017 site Networks Inc.","2016-12-22 13:37:42","2017-01-31 14:22:11"

Is it because of the permission?
-rwxrwxrwx@ 1 site  staff    307 May 24 13:46 externals.csv

I even try chomd 777 and run with sudo. But nothing seems to help!

A: Change that copy to \copy (https://www.postgresql.org/docs/current/static/app-psql.html#APP-PSQL-META-COMMANDS-COPY). Slightly different command that lets you copy to/from a file to your server.
The reason for the difference here is because you are connecting to a remote server (I assume), but importing a local file.

Another options is to pass your file in and have psql read from stdin like
 -c "copy externals (id,logo_path,favicon_path,cover_path,header,description,sign_enable,sign_text,footer_logo_enable,footer_logo_path,footer_text,created_at,updated_at) from STDIN with delimiter as ','" < /Applications/MAMP/htdocs/code/benu/ssc-portal/public/csv/externals.csv


text:
Q: Resize events of children are called sooner than the resize events of the parents In a QWidget application, there are some parameters I change when the main window is resized, and I would like to use them in the resize events of some individual elements.
However, the resize events of the children seem to trigger sooner than the resize event of the parent.
The obvious approach would be to just emit a signal from the main window's resizeEvent and connect it to all the widgets which need it, but there will be lots of such widgets, so I would like to avoid this if possible. Is there a simpler solution?


text:
Q: Design & Custom Viewcontroller have a longer question than usual.
I am attempting to make a card game and I am confused as to whether I am designing it awfully.
The player's hand consists of 10 cards, each of which is a button and 4 labels that indicate the stats of the card.
What I had in mind was creating an array of objects that have these UILabel and button properties. For example in a "Card" class I would have...
@IBOutlet var cardName: UILabel
@IBOutlet var cardStat1: UILabel
@IBOutlet var cardStat2: UILabel
@IBOutlet var cardStat3: UILabel
@IBOutlet var cardStat4: UILabel

I would then have an array that contains ten objects of this Card class. This is my design portion of my question.

My View Controller question is like I mentioned above - I have a Card class but I am having trouble connecting outlets to it. It inherits from UIViewController but I get the error...

Must call a designated initializer of the superclass 'UIViewController'

...even though I call
super.init()

Feel free to aid me with any portion of my issues, thanks a lot!

A:
This is my design portion of my question.

Having 10 view controllers, one for each card, sounds like a solution that's far more complicated than it needs to be. I think you'd be better off with something like a collection view, with one collection view cell for each card. You'd also need some kind of data model for storing the information about each card -- an array of dictionaries, for example, or an array of your Card objects (but not derived from UIViewController).

I get the error...

The designated initializers for UIViewController are -initWithNibName:bundle: and -initWithCoder:. There's an -init method defined, but it sounds like Swift wants you to call a designated initializer, and that's not -init.


text:
Q: Get value of a column of a row where select option value changed I am trying to model a webpage which allows users to give ratings to some projects and store these ratings in the background. I have a table like this
Project Id|Title|Rating. In rating column I have conditionally select tags in some columns otherwise there is some text. I added an onchange event on select which triggered a javascript function when value of option is changed, But i want to extract the value of project_id feild of the row where select value was changed. I am a newbie in javascript so I couldnt find anything which could solve my problem, I need that project id value because i need to store that value in my database which I have got it working via Ajax Calls.Here is my table below:
Code:
<?php if($row['status']==='complete' && $result2->num_rows==0 )
            { ?>

                <select id="rating select" onchange="rating()" class="form-control" name="projectrating">
                    <option selected>0</option>
                    <option  value="1" >1</option>
                    <option  value="2">2</option>
                    <option  value="3">3</option>
                    <option  value="4">4</option>
                    <option  value="5">5</option>
                </select>

            <?php } ?>

                <?php if($row['status']==='complete' && $result2->num_rows > 0 )
            {   $row2=$result2->fetch_assoc();
                $rating=$row2['rating'];
                echo "You have already rated this Project!,You have given the project a rating of $rating";
              } ?>

            <?php
            if($row['status']!=='complete') { ?>
               <?php echo "Ratings only for complete projects" ?>

           <?php } ?>
                  </td>
            <?php } ?>

Javascript:( I need to fill variable parameter without value so I can send it using Ajax to a php script.)
<script>

    function rating()
    {
        var xhttp = new XMLHttpRequest();
         xhttp.onreadystatechange = function() {
    if (this.readyState === 4) {
        if(this.status===400){
        alert("There was a problem while giving the rating");
    }
        if(this.status===200)
        {

            alert("Rating given succesfully");
            window.location.reload(true);

        }

            }
  };
        xhttp.open("POST", "rating.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        var param=
        xhttp.send(param);

        }

A: To achieve expected result, use below option
Option1:

*

*Using closest tr and children, you can get complete row values on change

*Each cell can be obtained by "eq().text()"

Codepen -https://codepen.io/nagasai/pen/YVERRv
JS:
$(document).ready(function(){$('select').on('change',function(){
   var $td= $(this).closest('tr').children('td');
  var project= $td.eq(0).text();
  console.log(project)
})
                            })

Option 2: Using plain javascript with parentElement and childNodes and using rating() onchange function
HTML:
<select  onchange="rating(this)" class="form-control" name="projectrating">

JS:
function rating(a){
  console.log((a.parentElement) .parentElement.childNodes[1].innerHTML)
}

a.parentElement will give the td enclosing select and parentElement of it is tr element and first child innerHTML gives the first column value
https://codepen.io/nagasai/pen/qmVQwp

A: first, you can't use multiple ID for one element
<select id="rating" onchange="rating()" class="form-control" name="projectrating">

then you should determine what you want to send
var paramToSend = document.getElementById("rating").value;

so your js will gonna be like this
function rating(){
var paramToSend = document.getElementById("rating").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState === 4) {
        if(this.status===400){
            alert("There was a problem while giving the rating");
        }
        if(this.status===200){
            alert("Rating given succesfully");
            //window.location.reload(true);
        }

    }
};
xhttp.open("POST", "rating.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param="postedParam=" + paramToSend ;
xhttp.send(param); }

so in your rating.php you will get $_POST['postedParam']


text:
Q: React-Redux - Hooks API I'm trying to configure my new react-redux application to use the new features of React-Redux. The official documentation says

React Redux now offers a set of hook APIs as an alternative to the existing connect() Higher Order Component.

I have been trying to find some helping articles related to Hooks API with some real examples but all react-redux Apps are using connect function. Official documentation also shows very basic examples.
I want to change the connect functions in my App with useSelector (offered by Hooks API).
Here is an example code snippet from my application.
//MessagesListContainer
export default connect(
  // mapStateToProps
  (state:State) => ({
    activeUser: getActiveUser(state),
    messages: getMessagesList(state),
  })
)(MessagesList)

//Selectors
export const getActiveUser = (state: State) => state.activeUser;
export const getMessagesList = (state : State) => (
  Object.keys(state.messages).map((key : any)=> state.messages[key])
)

export interface IMessagesListProps {
  activeUser?: User;
  messages?: Message[];
}
/**
 *  Messages List
 */
export default class MessagesList extends PureComponent<IMessagesListProps> {
.
.
.
}

A: Hooks are not compatible with Class components.
To use Hooks, you convert the class components to function components.
For instance, your code can be refactored to
/**
 *  Messages List
 */

const getActiveUser = (state: State) => state.activeUser;
const getMessagesList = (state : State) => (Object.keys(state.messages).map((key : any)=> state.messages[key]));

const MessagesList: React.FC = () => {
  const activeUser = useSelector(getActiveUser);
  const messagesList = useSelector(getMessagesList);

  ....
}

export default MessagesList;

A: Hooks API facilitates function components, so I nested my class component inside a function component like this:
//messages-list.container.tsx
//MessagesListContainer
export const MessagesListContainer = () => {
   const activeUser= useSelector((state:State) => getActiveUser(state));
   const messages= useSelector((state:State) => getMessagesList(state));
   return <MessagesList activeUser={activeUser} messages={messages} />
}

//Selectors
export const getActiveUser = (state: State) => state.activeUser;
export const getMessagesList = (state : State) => (
  Object.keys(state.messages).map((key : any)=> state.messages[key])
)

//end of messages-list.container.tsx

//messages-list.component.tsx
export interface IMessagesListProps {
  activeUser?: User;
  messages?: Message[];
}
/**
 *  Messages List
 */
export default class MessagesList extends PureComponent<IMessagesListProps> {
.
.
.
}

As per my perception, it's better to keep the last level components isolated from the store.


text:
Q: Homotopy type of transversal submanifolds through deformation Let $A,B \subset M$ be two transversal submanifolds of a compact manifold $M$. It seems rather intuitive that if $A$ and $B$ are deformed (say smoothly) in a way that they remain transversal to each other, the homotopy type of the intersection remains unchanged during the deformation.
I would like to know if there is a way to write such a homotopy in the following situations:

*

*$A = f^{-1}(0)$ is the zero level set of some smooth function $f : M \to \mathbb{R}$, and $B = B_s$ is a smooth family of submanifolds such that $A$ and $B_s$ are always transverse. Is it true that the homotopy type of $A \cap B_s$ is independent of $s$ ?

*$A_s := f_s^{-1}(0)$ is the zero set of a smooth function $f_s : M \to \mathbb{R}$, and the family $A_s$ is always transversal to a fixed submanifold $B$. Is it true that the homotopy type of $A_s \cap B$ is independent of $s$ ?

Any help will be appreciated. Thanks in advance.


text:
Q: How to make sure the result of lat/lng distance calculation is correct I'm very novice to GIS systems, and I'm trying to fulfill a requirement. I've created a small program to calculate the distance of a given lat/lng pair, based on this answer.
However, for a city like Tehran which is more like a horizontal rectangle, the width is way less than the height.
Since a small city might be regarded as a flat surface comparing to the curvature of Earth, I expect the results to be valid for visual inspection.

So I also went online to calculate the result, and from this site, the calculation again shows the same numbers, that is, the width is unbelievably smaller than the height.
To get the latitude and longitude, I simply used Google Maps and here are the values:
**leftmost latitude = 35.7267243
rightmost latitude = 35.7442993
topmost longitude = 51.4743653
bottommost longitude = 51.4347113**
Apparently I did something wrong, but I can't really make it work. Can you please help me?

A: Your bounding box is wrong, it should roughly be
35.834107; 51.095724
35.561986; 51.605215
Before worrying about the width/height ratio, one would have identified that 2km * 3 km is rather a small size for such a large city...
One degree is about 100 km (see the order of magnitude table), so, knowing your city, you should have a bounding box with 0.5 to 1 degree in width/height, not 0.05.


text:
Q: How do I use Safari as my browser for debugging when using Visual Studio Code running an Angular app? I have an Angular app (.Net Core backend). I can create configurations in the launch.json file and debug with Firefox, Chrome, Edge, etc. But I don't see any option for Safari!
QUESTION - How do I create a configuration for Safari to use instead of Chrome when launching the debugger? When I click 'add configuration' in launch.json, which option do I select for Safari? Do I need a separate extension?

A: I found some links for you:

*

*https://stackoverflow.com/a/51738121

*https://stackoverflow.com/a/66942204
Set the BROWSER environment variable before executing the start command may help.
This environment variable is documented here: https://create-react-app.dev/docs/advanced-configuration/

By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a browser to override this behavior, or set it to none to disable it completely. If you need to customize the way the browser is launched, you can specify a node script instead. Any arguments passed to npm start will also be passed to this script, and the url where your app is served will be the last argument. Your script's file name must have the .js extension.


text:
Q: Is there any way to avoid parse-errors in pycparser library of python The below code triggers an error in .c file when pycparser tries to parse it. This might be because rf_wcdma_bup_flags_t is not a defined typedef, is there anyway to skip it?
rf_wcdma_bup_flags_t rf_wcdma_debug_flags = { 0 };

A: There's no way to skip it. However, it's easy to support new types by adding "fake headers" to the analysis flow with pycparser. The README page has some details about this - and this blog post has more.