text:
Q: Problems with repaint JLabel, Image application So this is our code... we´re nobs and need a bit help with getting our buttons to switch between showing hue/saturation/brigntness in height and width. Per now, our applications is only showing hue in width and saturation in height. Our buttons are not working, and we are not able to empty the view and repaint another one. Can anybody help?
package no.uib.info221.oblig1;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.github.imgur.ImgUr;
import com.github.imgur.api.album.AlbumRequest;
import com.github.imgur.api.album.AlbumResponse;
import com.github.imgur.api.model.ImageProperty;

public class ImgurViz extends JFrame {
    private static final long serialVersionUID = 7954882289770950884L;
    //private JProgressBar progressBar;
    private JButton HSbutton;
    private JButton BSbutton;
    private JButton BHbutton;
    private JPanel knappepanel;
    private JPanel bildepanel;
    public JLabel skjerm;
    int w = 0;
    int h = 1;

    /**
     * constructor
     * klassen.
     * @throws IOException
     */

    public ImgurViz() throws IOException {
        super(); //Calls the superclass
        setupInterface(); //
        fetchAndDisplayImages(); //
    }

    //Empties the panel when a new jlabel is called
    public void emptyPanel(){
        bildepanel.revalidate();
        bildepanel.removeAll();
        bildepanel.repaint();
    }

    // Creates JButtons to change the sorting of the images
    public void knapper(){
        knappepanel = new JPanel(); // Knappepanel = button panel
        bildepanel = new JPanel();      // Imagepanel = image panel
        bildepanel.setLayout(null);
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(knappepanel,BorderLayout.NORTH);
        this.getContentPane().add(bildepanel,BorderLayout.CENTER);

        //knappepanel.setOpaque(false);

        // Knapp for HUE og SATURATION KNAPP = button
        HSbutton = new JButton ("Hue og Saturation");
        knappepanel.add(HSbutton);

        //Knapp for BRIGHTNESS og SATURARION
        BSbutton = new JButton ("Brightness og Saturation");
        knappepanel.add(BSbutton);

        // Knapp for BRIGHTNESS OG HUE
        BHbutton = new JButton ("Brightness og Hue");
        knappepanel.add(BHbutton);

        // Metode for knapp for HUE og SATURATION
        HSbutton.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                emptyPanel();

                w = 0;
                h = 1;

                System.out.println("Hue: " + w + " Saturation: " + h);
            }
        });

        // Metode for knapp for BRIGHTNESS og SATURATION
        BSbutton.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {

                w = 2;
                h = 1;

                System.out.println("Brightness: " + w + " Saturation: " + h);
            }
        });

        // Metode for knapp for BRIGHTNESS OG HUE
        BHbutton.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                emptyPanel();

                w = 2;
                h = 0;
                System.out.println("Brightness: " + w + " Hue: " + h);
            }
        });

        this.setContentPane(knappepanel);
    }

    /**
     * Fetches images for an album on Imgur
     *
     * @throws IOException
     */

    public void fetchAndDisplayImages() throws IOException {
        ImgUr imgUr = new ImgUr ("4ded93e63e96762");
        AlbumResponse response = imgUr.call(new AlbumRequest("RJBiQ"));
        List<ImageProperty> images = response.getImages();
        float[] bildedata = new float[3];
        int count = images.size();

        for (int i = 0; i<count;i++){

            BufferedImage img = ImageIO.read(new URL(images.get(i).getLinks().getOriginal()));
            BufferedImage thumb = ImageIO.read(new URL(images.get(i).getLinks().getSmallSquare()));
            bildedata = pictureAnalyze (img);

            int width  = ((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth())/2; // Henter ut bredden p brukerens skjerm
            int height = ((int)Toolkit.getDefaultToolkit().getScreenSize().getHeight())/2; // Henter ut høyden p brukerens skjerm
            int posW = (int)(bildedata [w] * width);
            int posH = (int)(bildedata [h] * height);

            skjerm = new JLabel(new ImageIcon(thumb));
            skjerm.setBounds(posW, posH, width, height);
            bildepanel.add(skjerm);
            this.getContentPane().add(skjerm);
            this.getContentPane().setLayout(null);
            this.getContentPane().repaint();
            this.setVisible(true);

//          skjerm.addMouseListener(new MouseAdapter() {
//              @Override
//              public void mouseEntered(java.awt.event.MouseEvent evt) {
//                  //FAEN TA DEG!!
//              }
//          });
        }
    }

    // RGB to HSB Finds the RGB value of each image, transformes the values to HSB and finds the average
    public float[] pictureAnalyze (BufferedImage img){
        float[] result = new float[3];
        float h = 0f;
        float s = 0f;
        float b = 0f;
        for (int x = 0; x < img.getWidth(); x++){
            for (int y = 0; y < img.getHeight(); y++){
                int c = img.getRGB(x,y);
                int red = (c >> 16) & 0xff;
                int green = (c >> 8) & 0xff;
                int blue = (c & 0xff);

                float[] hsb = Color.RGBtoHSB(red,green,blue, null);

                h += hsb[0];
                s += hsb[1];
                b += hsb[2];
            }
        }

        h = h/(img.getWidth()*img.getHeight());
        s = s/(img.getWidth()*img.getHeight());
        b = b/(img.getWidth()*img.getHeight());
        result [0] = h;
        result [1] = s;
        result [2] = b;
        return result;
    }

    //      // Shannon entropi
    //      public static Double calculateShannonEntropy(List <ImageProperty> images) {
    //            Map<String, Integer> map = new HashMap<String, Integer>();
    //
    //            // tel kvar instans av verdiane
    //            for (String sequence : images) {
    //              if (!map.containsKey(sequence)) {
    //                map.put(sequence, 0);
    //
    //              }
    //              map.put(sequence, map.get(sequence) + 1);
    //            }
    //
    //            //Kalkulerer entropien
    //
    //            Double result = 0.0;
    //            for (String sequence : map.keySet()) {
    //              Double frequency = (double) map.get(sequence) / images.size();
    //              result -= frequency * (Math.log(frequency) / Math.log(2));
    //            }
    //
    //            return result;
    //
    //          }

    /**

    private void setupInterface() {
        int width  = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(); // Henter ut bredden p brukerens skjerm
        int height = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight(); // Henter ut h¯yden p brukerens skjerm
        this.setSize(width, height); // Setter st¯rrelsen p vinduet til  vÊre lik skjermens bredde og h¯yde
        this.setExtendedState(Frame.MAXIMIZED_BOTH); // Sier fra om at vinduet skal vÊre maksimert
        this.setUndecorated(true); // setter fullscreen
        this.getContentPane().setBackground(Color.BLACK ); // Setter bakgrunnsfargen p innholdspanelet (contentPane) til svart
        knapper();
        this.setVisible(true); // Viser vinduet p skjermen

    }

    public static void main(String[] args)  throws IOException {
        ImgurViz viz = new ImgurViz(); // Oppretter et nytt ImgurViz-objekt. Dette medf¯rer at det nye objektets konstrukt¯r kj¯res

    }

}

A: As shown in the HSV panel of JColorChooser, it's easier to display just two of the color space's three dimensions at a time. Whatever your goal, it will be easier to scale the palette using Color.getHSBColor(). These examples may offer some insight or help you prepare an sscce.


text:
Q: Execute command shell from php Remotely I was trying to get result from shell in a remote machine in my web page using php.
I used these lines:
<?php
$connection = ssh2_connect('192.168.10.10', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, 'whoami');
?>

I am trying to get result in my web page in windows machine and libssh2 is already included in easyphp . but the same message:
Fatal error: Call to undefined function ssh2_connect() in C:\Program Files (x86)\EasyPHP-5.3.8.0\www\testphp_ssh.php

Any idea?

A: You have to download and install the PECL extension for SSH2 from the Microsoft delegate to the PHP project: http://downloads.php.net/pierre/.
To see any errors in your applications and in the configuration of your environment, make the values of the following configuration directives look like this:
error_reporting = E_ALL|E_STRICT
display_errors = On
short_open_tag = Off
asp_tags = Off
display_startup_errors = On

output_buffering = Off
allow_call_time_pass_reference = Off
zlib.output_compression = Off
track_errors = On
register_globals = Off
session.auto_start = 0
tidy.clean_output = Off

implicit_flush = Off
log_errors = On
ignore_repeated_errors = On
report_memleaks = On

redpajama_set_name: RedPajamaStackExchange


text:
Q: Factorybot looking up by class deprecated I'm trying to create a shared_example in a rails application. It's working but I'm getting a deprecation error. I can I refactor the code to fix this?
error
Looking up factories by class is deprecated and will be removed in 5.0. Use symbols instead and set FactoryBot.allow_class_lookup = false.

source
shared_examples 'a sanatized_record' do
  subject { build(described_class) }

  describe 'stripped_attributes' do
    described_class::STRIPPED_ATTRIBUTES.each do |attr|
      it "strips whitespaces from #{attr}" do
        original = subject[attr]
        subject[attr] = " #{original} "
        subject.validate
        expect(subject[attr]).to eq original
      end
    end
  end
end

A: Related post on the topic: FactoryBot namespaced models without class_name
From the link -- updating the factory to
factory :foo_bar, class: 'foo/bar' do; end should work because of key.to_s.underscore.to_sym in this class


text:
Q: Custom function inside setInterval not working I have a function that takes an array, performs some operations and returns a number. Here's a truncated version:
function similarity(phrases){
    if(phrases.length ==2){
    //Lots of stuff
    //concerning the phrases happen here
    // and a variable called similarity is produced which
    //contains a number
        return similarity;
    }else{
        throw "Can only find similarity between 2 phrases";
    }
}

If I call this function separately it works perfectly. If, however I try to use it inside setInterval, it throws an error.
setInterval(function(){console.log(similarity(["test","test"]))},2000);

The expected outcome is "1.00000" every 2 seconds. Instead, "1.00000" is printed once and then this error is thrown:

"setInterval(function(){console.log(similarity(["test","test"]))},2000);
TypeError:String is not a function"

(pointing to the "s" on similarity).
Any ideas on what the problem is?
Thanks a lot!

A: Looks like you're saving function result in variable called same way as function (similarity). This way you are overriding function from upper scope.
Try this:
function similarity(phrases) {
    var similarity;
    /* ... */
}


text:
Q: How can we disprove that formally? Prove or disprove $2^{A\times B}=\{A'\times B'\mid A'\subseteq A, B'\subseteq B\}$.
$2^{A\times B}=\text{ set of every subset of } A\times B=\{(a,b)\mid a\in A, b\in B\}$.
So it is of the form $2^{A\times B}=\{\emptyset, \{(a_i, b_i)\}, \{(a_i, b_i), (a_j, b_j)\}, \cdots \}$, or not?
This is not of the form $\{A'\times B'\mid A'\subseteq A, B'\subseteq B\}$, is it?
But how can we disprove that formally?

A: You already have the right idea: namely that it is not of the form $\{A' \times B' : A' \subseteq A, B' \subseteq B\}$. To prove this you just need to come up with a counterexample.
A nice counterexample would be to take $A = B = \mathbb{R}$. That way we can get a very geometric interpretation of $A \times B$: it is just the plane $\mathbb{R}^2$. Then $\{A' \times B' : A', B' \subseteq \mathbb{R}\}$ describes the set of all (unions of) rectangles (where I count a line as an infinitely thin rectangle). Can you now think of an element of $P(A \times B)$ (i.e. a subset of the plane) that is not in $\{A' \times B' : A', B' \subseteq \mathbb{R}\}$?

A: If one of $A$ or $B$ is a singleton or the empty set, then your statement is true. However, it is false if $|A|,|B|\ge 2$.
The simplest example would be $A\times B \setminus \{(a,b)\}$ for some $(a,b)\in A\times B$: You can see that if $A_0\times B_0\subseteq A\times B \setminus \{(a,b)\}$ then either $A_0\neq A$ or $B_0\neq B$.
If $A_0\neq A$, so we have $a_0$ such that $a_0\in A\setminus A_0$, then $(a_0,y)\notin A_0\times B_0$ for all $y\in B$. However, we have $(a_0,b_0)\in A\times B\setminus\{(a,b)\}$ for all $b_0\in B\setminus\{b\}$. Therefore $A_0\times B_0\neq A\times B \setminus \{(a,b)\}$. The similar argument also works for the case $B_0\neq B$.

A: The statement you want to disprove is:
"For $every$ $A$ and $every$ $B,\; 2^{A\times B}=\{A'\times B':A'\subset A\land B'\subset B\}.$"
So you want to prove:
There exist $A$ and $B$ such that $2^{A\times B}\ne \{A'\times B':A'\subset A\land B'\subset B\}.$
To prove that, it suffices to present just one instance of such $A,B.$
Suppose $A=\{a_1,a_2\}$ and $B=\{b_1,b_2\},$ with $a_1\ne a_2$ and $b_1\ne b_2.$  Let $C= \{(a_1,b_1),(a_2,b_2)\}.$ Then $C\in 2^{A\times B}.$
But $C\ne A'\times B'$ for $any$ $A',B'.$ Because if $(a_1,b_1)$ and $(a_2,b_2)$ belong to $A'\times B',$ then $a_1\in A'$ and $b_2\in B',$ so $(a_1,b_2)\in A'\times B'$.... but $(a_1,b_2)\not \in C.$


text:
Q: Does anyone know of a way to paginate a call to GetSchema from C#? I'm using the ADO.NET provider function "GetSchema" to fetch meta data out of a Sql Server database (and an Informix system as well) and want to know if there is anyway to paginate the results. I ask because one of the systems has over 3,000 tables (yes, three thousand) and twice that many views and let's not even talk about the stored procedures.
Needless to say, trying to bring down that list in one shot is too much for the VM I have running (a mere 4GB of memory). I'm already aware of the restrictions that can be applied, these are all tables in the "dbo" schema so there isn't much else that I'm aware of for limiting the result set before it gets to my client.

A: Instead of using GetSchema I suggest to use the more flexible INFORMATION_SCHEMA system views. These views already divide the information about the Tables, StoredProcedures and Views and you can write a specific query to retrieve your data in a paginated way.
For example to retrieve the first 100 rows of table names you could write a query like this
SELECT  *
FROM    ( SELECT    ROW_NUMBER() OVER ( ORDER BY TABLE_NAME) AS RowNum, *
          FROM      INFORMATION_SCHEMA.TABLES
        ) AS TableWithRowNum
WHERE   RowNum >= 0
    AND RowNum < 100
ORDER BY RowNum

Following queries could be easily prepared changing the min and max values used by the query.
The same code could be applied for StoredProcedures (using INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE = 'PROCEDURE') or the views using INFORMATION_SCHEMA.VIEWS
Note, if you are using Sql Server 2012 and later the first query could be rewritten to use this syntax
SELECT *
FROM INFORMATION_SCHEMA.TABLES
ORDER BY TABLE_NAME
OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY

And the C# code could also use parameters for the FIRST (0) and COUNT(100) values


text:
Q: Android Date returns wrong value
I have set the milliseconds to 1390773600 in the constructor which translates to Sun, 26 Jan 2014 22:00:00. But as shown in the screenshot I keep getting 1970-01-16. What's going wrong here?

A: No it doesn't.
1390773600 seconds does; milliseconds are seconds * 1000.

*

*https://www.google.com/search?q=1390773600+milliseconds+to+days

*https://www.google.com/search?q=1390773600+seconds+to+days

*https://www.google.com/search?q=16096.9+%2F+365&oq=16096.9+%2F+365


text:
Q: Install graph-tool on Mac OS, graph drawing issue In the end, created an env to install graph-tool thru the channel vgauthier.
Thinking by now that I might have as well used earlier version of python or installed a whole new python latest version just for this.
But as it is all part of the learning process to creating dev. env.. (at the same time worrying my Mac has too many installations with much too interlinked dependencies)
Someone kindly let me know if this rings any bell or got any suggestion:
Incompatible library version states that _cairo.cpython-36m-darwin.so requires later version of libcairo.2.dylib.

A: Errors could have been from:

*

*having on .condarc file, wrong priorities btw channels, so having trouble finding the right files
(modified to the order of conda-forge > ~dir/vgauthier > default

*my having given up on installing pygobject after googling it is not supported on Mac OS (which was apparently wrong or I just wasnt searching well)

Solution to easy setup of graph-tool for conda-installed python users:

*

*Get the benefit of GUI (seriously a god option) ->

https://medium.com/@ronie/installing-graph-tool-for-python-3-on-anaconda-3f76d9004979

*

*To still continue with command line (still get the idea from GUI)
conda install -c pkgw-forge gtk3
conda install -c https://conda.anaconda.org/fallen pygobject
(if there are cairo blah blah missing, look up setup directions for igraph which has more information and help, having been an older library)

Do these before installing graph-tool, which Im still wondering why I cannot remove from the system though. ;)
For others, https://git.skewed.de/count0/graph-tool/wikis/installation-instructions#compiler-choice-in-macos-x


text:
Q: Difference between "IN" and "IN OUT" CURSOR parameter in Oracle From Oracle:
"When you declare a cursor variable as the formal parameter of a subprogram that fetches from the cursor variable, you must specify the IN or IN OUT mode. If the subprogram also opens the cursor variable, you must specify the IN OUT mode."
But, I can code that (only OUT parameter):
create or replace procedure mycur_out(mc OUT mycurpkg.mytypecur)  as
begin
    open mc for select * from mytable;
end mycur_out;

and works equal to (IN OUT parameter)
create or replace procedure mycur_inout(mc IN OUT mycurpkg.mytypecur)
as
begin
    open mc for select * from table10;
end mycur_inout;

Also, It's work fine with dynamic cursor too:
create or replace procedure mycur_out_ref(mc out mycurpkg.mytyperefcur)
as
begin
    open mc for 'select * from table10';
end mycur_out_ref;

I've tested the 3 cases directly from oracle and from VB6 with ADO, and no problems.
So, in that cases, is there any difference between IN using just "OUT" and  "IN OUT" cursors parameters?
UPDATE
The reason I'm asking:

*

*We read data using routines similar
to the examples (just open the
cursors). The cursor parameters
always are "IN OUT" (Don't ask me
why, I'm trying to figure out)

*The routines are invoked with ADO/VB6

*Now, we are trying to use some of the routines from JDBC, but the
adapter apparently just accepts OUT
parameters in this cases.

*Finally, the main reason, I want to change the cursor parameters on DB
routines to only OUT, but first I
want to know the collaterals effects
of that change.

Thanks!

A: In the text you quote from the manual, note that it is specifically talking about "a subprogram that fetches from the cursor variable".  None of your examples do this, so the quote is not relevant to them.
However, it nonetheless appears that there's nothing wrong with using OUT only in such a situation, if the subprogram both opens and fetches from the cursor variable:
SQL> variable c refcursor

SQL> set serveroutput on
SQL> create or replace procedure no_good (c  OUT sys_refcursor)
  2     as
  3        my_dummy  dual.dummy%type;
  4     begin
  5       open c for select dummy from dual union all select dummy from dual;
  6       fetch  c into my_dummy;
  7       dbms_output.put_line( my_dummy );
  8     end;
  9  /

Procedure created.

SQL> exec no_good( :c )
X

PL/SQL procedure successfully completed.

SQL> print c

D
-
X

I think the the text is actually trying to make two points that are somewhat independent of each other.  Firstly, if you want to pass any already-opened cursor variable into a subprogram, which will fetch from it, the parameter must be declare IN or IN OUT.  Secondly, if you want to pass a cursor variable into a subprogram, which will then open it, the parameter must be declared OUT or IN OUT.  This is true regardless of whether you actually care about passing the value of the cursor variable back to the caller:
SQL> create or replace procedure no_good (c  IN sys_refcursor)
  2     as
  3        my_dummy  dual.dummy%type;
  4     begin
  5       open c for select dummy from dual;
  6       fetch  c into my_dummy;
  7       dbms_output.put_line( my_dummy );
  8       close c;
  9     end;
 10  /

Warning: Procedure created with compilation errors.

SQL> show error
Errors for PROCEDURE NO_GOOD:

LINE/COL ERROR
-------- -----------------------------------------------------------------
5/6      PL/SQL: SQL Statement ignored
5/11     PLS-00361: IN cursor 'C' cannot be OPEN'ed

This error can be fixed by changing the parameter mode, but actually it would seem to make more sense to simply make the cursor variable a local variable rather than a parameter.

A: If I understand the question right, the difference is that with the IN OUT version you can pass in a cursor from outside the procedure, and then change that variable (similar to the difference between OUT and IN OUT for a simple numeric variable).
The OUT parameter cursor starts out as a NULL value / closed cursor.
The IN OUT parameter version starts with whatever state is passed in from outside.
You may want to retry your procedure calls repeatedly passing in the same cursor variable - the OUT version should replace the existing value, the IN OUT version should give an exception on the second time round that you are trying to open an open cursor.
Another thing the IN OUT approach allows, that the OUT approach does not, is to take action based on the passed in cursor, and change the returned cursor.
PROCEDURE lp_test2 (mc IN OUT mycurpkg.mytypecur)
IS
  lr table10%ROWTYPE;
BEGIN
   IF mc%ISOPEN THEN
      FETCH mc INTO lr;
      IF mc%NOTFOUND THEN
         CLOSE mc;
         /* Switch cursor to alternative table */
         open mc for select * from schema2.table10;
      END IF;
   END IF;
END lp_test2;

I am just struggling to think of a real situation where you might want to (take in a cursor variable, cast it back into a SQL statement, append some extra dynamic SQL, and return the whole lot back as the same cursor??).


text:
Q: calculating a date and returning the week number depending on the start date in php? im trying to create a function that takes a $start_date as parameter and it should calculate which week number we are in i.e
for instance $start_date equals 2012-08-16
private function get_week_number($start_date){
        // get current date
        // caluculate the difference between start_date and current_date
        // determine which week we are in 1, 2 or 3
        // return $week
    }

how can i implement this in php? thanks

A: I think what you need is merely date_diff.

A: function get_week_number($start_date){
    $date = date('U', strtotime($start_date));
    $now = date('U');
    return ceil(($now-$date)/60/60/24/7);
}

echo get_week_number('2012-08-16');

A: private function get_week_number($start_date){
    return date('W') - date('W', strtotime($start_date));
}


text:
Q: Cannot figure Async/Await and Promises to work I'm trying to learn about async/await and Promise functions. However after a lot of effort and research, I cannot find any simple way to get a proper way to use my 4 for loops.
I give you the code how it's supposed to be if Javascript if it wouldn't be asynchronous. Can you tell me where (and how) can I put promises to get my code to work as intended?
function (courses) {
    var lines = [];
    for (var i = 0; i < courses.length; i++) {
        var course = courses[i];
        var sessions = course.sessions;
        var students = course.students;
        var skills = course.skills;
        console.log('\nCourse : ' + course);

        for (var j = 0; j < sessions.length; j++) {
            var session = sessions[j];
            console.log('\nSession : ' + session);

                for (var k = 0; k < students.length; k++) {
                    var student = students[k];
                    console.log('\nStudent : ' + student);

                    for (var l = 0; l < skills.length; l++) {
                        var skill = skills[l];
                        console.log('\nSkill : ' + skill);
                        Evaluation.findOne({
                            student_id: student._id,
                            session_id: session._id,
                            skill_id: skill._id
                        }).exec(function (err, eval) {
                            console.log('\nStudentID : ' + eval);
                            console.log('\nSessionID : ' + eval);
                            console.log('\nSkillID : ' + eval);
                            console.log('\nEval : ' + eval);
                            var line = [];
                            line.push(course.name);
                            line.push(session.date);
                            line.push(student.firstname);
                            line.push(student.name);
                            if (eval) {
                                line.push(eval.name);
                                line.push(eval.mark);
                            }
                            else {
                                line.push(skill.name);
                                line.push('Not Evaluated');
                            }
                            lines.push(line)
                        })
                    }
                }
            }
        }
    return lines;
}

A: Assuming that you use mongoose, all you need to change is replacing

Evaluation.findOne({
    student_id: student._id,
    session_id: session._id,
    skill_id: skill._id
}).exec(function (err, eval) {
    console.log('\nStudentID : ' + eval);
    console.log('\nSessionID : ' + eval);
    console.log('\nSkillID : ' + eval);
    console.log('\nEval : ' + eval);
    var line = [];
    line.push(course.name);
    line.push(session.date);
    line.push(student.firstname);
    line.push(student.name);
    if (eval) {
        line.push(eval.name);
        line.push(eval.mark);
    } else {
        line.push(skill.name);
        line.push('Not Evaluated');
    }
    lines.push(line)
})

by
const eval = await Evaluation.findOne({
//           ^^^^^
    student_id: student._id,
    session_id: session._id,
    skill_id: skill._id
});
console.log('\nStudentID : ' + eval);
console.log('\nSessionID : ' + eval);
console.log('\nSkillID : ' + eval);
console.log('\nEval : ' + eval);
var line = [];
line.push(course.name);
line.push(session.date);
line.push(student.firstname);
line.push(student.name);
if (eval) {
    line.push(eval.name);
    line.push(eval.mark);
} else {
    line.push(skill.name);
    line.push('Not Evaluated');
}
lines.push(line)

as all methods return promise-like objects already that you can directly await, instead of using exec and passing a nodeback.

A: It looks like you're trying to do two things here: you want to asynchronously loop through courses/sessions/students/skills and do a fairly time-intensive Evaluation.findOne call.
I recommend replacing some or all of your for loops with async.forEach. You could also put the Evaluation.findOne block into a helper function wrapped in a Promise, but given that it's pushed into lines after it's executed it's an optional move.
Do something like this:  the skills iteration now uses async.forEach and the line builder is in a promise.
function (courses) {
    var lines = [];
    for (var i = 0; i < courses.length; i++) {
        var course = courses[i];
        var sessions = course.sessions;
        var students = course.students;
        var skills = course.skills;
        console.log('\nCourse : ' + course);
        for (var j = 0; j < sessions.length; j++) {
            var session = sessions[j];
            console.log('\nSession : ' + session);
            for (var k = 0; k < students.length; k++) {
                var student = students[k];
                console.log('\nStudent : ' + student);
                skills.forEach(function(skill) {
                    console.log('\nSkill : ' + skill);
                    buildStudentLine(student, session, skill, course)
                        .then((line )=> {
                            lines.push(line);
                        })
                        .catch((error) => {
                            console.log(error);
                        })

                });
            }
        }
    }
    return lines;
}

function buildStudentLine(student, session, skill, course) {
    return new Promise((resolve, reject) => {
    Evaluation
        .findOne({
            student_id: student._id,
            session_id: session._id,
            skill_id: skill._id
        })
        .exec(function (err, evaluated) {
            var line = [];
            line.push(course.name);
            line.push(session.date);
            line.push(student.firstname);
            line.push(student.name);
            if (evaluated) {
                line.push(evaluated.name);
                line.push(evaluated.mark);
            } else {
                line.push(skill.name);
                line.push('Not Evaluated');
                // possibly put this in here if you don't want the line to enter the lines array:
                // reject('Not Evaluated');
            }
            resolve(line);
        });
    });
}


text:
Q: problem configuring react-router-dom for admin area I have a client area with login, and the login has a different template dashboard.
when finished I already have a rendering error: "Failed prop type: The following properties are not supported: location,computedMatch. Please remove them
But still he rendered normal". Now comes my problem, I want to add an administrative area
with another template. but I can not.

So I have a  component and in this component I check if the client is logged in, if not I make a redirect to
login page. In my other admin area component I don't use this  but I am still redirected to the client login screen.
<Router>
<Switch>
    {/* area client */}
    <Route component={Login} path='/login' />

    <MuiThemeProvider theme={theme}>
        <Layout>
            <Route exact path='/' component={Dashboard} />
            ...

        </Layout>
    </MuiThemeProvider>
    {/* area admin */}
    <MuiThemeProvider theme={theme}>
        <>
            <Route path='/admin/login' component={LoginAadmin} />
            <Route path='/admin' component={Admin} />

        </>
    </MuiThemeProvider>
</Switch>

could someone help me fix these routes?

A: I managed to solve by following this post: Multiple Nested Routes in react-router-dom v4
from @Igor Stetsiura
it was like this:
    render() {
    return (

        <MuiThemeProvider theme={theme}>
            <Switch>
                <Route path='/admin/login' component={LoginAadmin} />
                <Route path='/login' component={Login} />

                <Route path='/admin/' component={({ match }) =>
                    <LayoutAdmin>
                        <Route exact path='/admin' component={Admin} />
                    </LayoutAdmin>
                } />

                <Route path='/' component={({ match }) =>
                    <Layout>
                        <Route exact path='/' component={Dashboard} />
                        ...

                    </Layout>
                } />

            </Switch>

        </MuiThemeProvider>

    );
}


text:
Q: node: protocol for imports I see a new feature in nodejs, the new node: protocol, but I don't see any use case (other than disambiguating core modules)
for what do we can really really need to use this feature?


text:
Q: Flutter : Vertically center column How to vertically center a column in Flutter? I have used widget "new Center". I have used widget "new Center", but it does not vertically center my column ? Any ideas would be helpful....
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text("Thank you"),
    ),
    body: new Center(
      child: new Column(
        children: <Widget>[
          new Padding(
            padding: new EdgeInsets.all(25.0),
            child: new AnimatedBuilder(
              animation: animationController,
              child: new Container(
                height: 175.0,
                width: 175.0,
                child: new Image.asset('assets/angry_face.png'),
              ),
              builder: (BuildContext context, Widget _widget) {
                return new Transform.rotate(
                  angle: animationController.value * 6.3,
                  child: _widget,
                );
              },
            ),
          ),
          new Text('We are glad we could serve you...', style: new TextStyle(
              fontSize: 16.0,
              fontWeight: FontWeight.w600,
              color: Colors.black87),),
          new Padding(padding: new EdgeInsets.symmetric(vertical: 5.0, horizontal: 0.0)),
          new Text('We appreciate your feedback ! !', style: new TextStyle(
              fontSize: 13.0,
              fontWeight: FontWeight.w200,
              color: Colors.black87),),
        ],
      ),
    ),
  );
}

A: CrossAlignment.center is using the Width of the 'Child Widget' to center itself and hence gets rendered at the start of the page.
When the Column is centered within the  page body's 'Center Container' , the CrossAlignment.center uses page body's 'Center' as reference and renders the widget at the center of the page

Code
import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
    title:"DynamicWidgetApp",
    home:DynamicWidgetApp(),

));

class DynamicWidgetApp extends StatefulWidget{
  @override
  DynamicWidgetAppState createState() => DynamicWidgetAppState();
  }

class  DynamicWidgetAppState extends State<DynamicWidgetApp>{
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Center(
     //Removing body:Center will change the reference
    // and render the widget at the start of the page
        child: Column(
            mainAxisAlignment : MainAxisAlignment.center,
            crossAxisAlignment : CrossAxisAlignment.center,
            children: [
              Text("My Centered Widget"),
            ]
          ),
      ),
      floatingActionButton: FloatingActionButton(
        // onPressed: ,
        child : Icon(Icons.add),
      ),
      );
    }
  }

A: Try:
Column(
 mainAxisAlignment: MainAxisAlignment.center,
 crossAxisAlignment: CrossAxisAlignment.center,
 children:children...)

A: For me the problem was there was was Expanded inside the column which I had to remove and it worked.
Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Expanded( // remove this
              flex: 2,
              child: Text("content here"),
            ),
          ],
        )

A: Solution as proposed by Aziz would be:
Column(
  mainAxisAlignment: MainAxisAlignment.center,
  crossAxisAlignment: CrossAxisAlignment.center,
  children: [
    //your widgets here...
  ],
)

It would not be in the exact center because of padding:
padding: EdgeInsets.all(25.0),

To make exactly center Column - at least in this case - you would need to remove padding.

A: You could use.
mainAxisAlignment:MainAxisAlignment.center
This will the material through the center in the column wise.
`crossAxisAlignment: CrossAxisAlignment.center'
This will align the items in the center in the row wise.
Container( alignment:Alignment.center, Child: Column () )
Simply use.
Center ( Child: Column () )
or rap with Padding widget . And adjust the Padding such the the column children are in the center.

A: Try this one. It centers vertically and horizontally.
Center(
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: children,
  ),
)

A: With Column, use:
mainAxisAlignment: MainAxisAlignment.center

It align its children(s) to center of its parent Space vertically

A: You control how a row or column aligns its children using the mainAxisAlignment and crossAxisAlignment properties. For a row, the main axis runs horizontally and the cross axis runs vertically. For a column, the main axis runs vertically and the cross axis runs horizontally.
 mainAxisAlignment: MainAxisAlignment.center,
 crossAxisAlignment: CrossAxisAlignment.center,

A: Another Solution!
If you want to set widgets in center vertical form, you can use ListView for it.
for eg: I used three buttons and add them inside ListView which followed by

shrinkWrap: true  -> With this ListView only occupies the space which needed.

import 'package:flutter/material.dart';

class List extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final button1 =
        new RaisedButton(child: new Text("Button1"), onPressed: () {});
    final button2 =
        new RaisedButton(child: new Text("Button2"), onPressed: () {});
    final button3 =
        new RaisedButton(child: new Text("Button3"), onPressed: () {});
    final body = new Center(
      child: ListView(
        shrinkWrap: true,
        children: <Widget>[button1, button2, button3],
     ),
    );

    return new Scaffold(
        appBar: new AppBar(
          title: Text("Sample"),
        ),
        body: body);
  }
}
void main() {
  runApp(new MaterialApp(
    home: List(),
  ));
}

Output:

A: While using Column, use this inside the column widget :
mainAxisAlignment: MainAxisAlignment.center
It align its children(s) to the center of its parent Space is its main axis i.e. vertically
or,
wrap the column with a Center widget:
Center(
  child: Column(
    children: <ListOfWidgets>,
  ),
)

if it doesn't  resolve the issue wrap the parent container with a Expanded widget..
Expanded(
   child:Container(
     child: Column(
       mainAxisAlignment: MainAxisAlignment.center,
       children: children,
     ),
   ),
)

A: You can also wrap the Column widget by Align.
Align(
    alignment: Alignment.center,
    child: Column(
        children: [
            Container(
                width: 300,
                margin: const EdgeInsets.fromLTRB(0, 70, 0, 0),
                child: TextFormField(decoration: const InputDecoration(hintText: "First Name"))
            ),
            ...
        ]
    )
)

Checkout this website for different ways of centering a widget: Link

A: In Addition, If you used

mainAxisAlignment: MainAxisAlignment.start

for centering all children but you still one of the children to be centered , Simply use Center() widget on the children.


text:
Q: Why am I getting a \omit error? Apologies if any of the formatting is wrong in this- first time using stack exchange.
I am attempting to use a mix of tabular/multicolumn to make a 3 part figure: one plot that spans the entire width of the document, and two plots beneath it that span half the width.
However, I am getting  "misplaced \omit" error and I'm not sure why. I've searched around the existing ones, but none of their errors seem to apply in my case.
The relevant code is the following:
\documentclass[a4wide]{article}
\usepackage[demo]{graphicx}
\usepackage{float}

\begin{document}

\begin{figure}[h!]
\centering
\begin{tabular}{c c}
\centering
\multicolumn{2}{c}{\includegraphics[width=.9\textwidth]{Figure1.pdf}}\\
\multicolumn{2}{c}{\footnotesize(a)} \\
\includegraphics[width=.5\textwidth]{Figure2.pdf} &\includegraphics[width=.5\textwidth]{Figure3.pdf}\\
{\footnotesize(b)} & {\footnotesize(c)}
\end{tabular}
\caption{\textbf{I'd really love if this worked}}
\end{figure}

\end{document}

I've tried removing/adding the "\" between lines to no avail as well.
Any help would be greatly appreciated!
Edit: Ah apologies for missing the extra bits in code- my bad!

A: The demo option is only to show the result without having your pictures.
\documentclass{article}

\usepackage[demo]{graphicx}
\begin{document}

\begin{figure}[h!]
\centering
\begin{tabular}{cc}
%\centering
\multicolumn{2}{c}{\includegraphics[width=.9\textwidth]{Figure1.pdf}}\\
\multicolumn{2}{c}{\footnotesize(a)} \\
\includegraphics[width=.5\textwidth]{Figure2.pdf} &\includegraphics[width=.5\textwidth]{Figure3.pdf}\\
{\footnotesize(b)} & {\footnotesize(c)}
\end{tabular}
\caption{\textbf{I'd really love if this worked}}
\end{figure}

\end{document}

A: Why not use subfigures?
Code
\documentclass{article}
\usepackage{subcaption}
\usepackage{graphicx}
\usepackage{mwe} % provides images in this example

\begin{document}

\begin{figure}[h!]
  \begin{subfigure}[b]{\textwidth}
    \includegraphics[width=\linewidth]{image-a}
    \caption{Image A}
  \end{subfigure}
  \vskip10pt % add vertical space
  \begin{subfigure}[b]{.48\textwidth} % make less than .5\textwidth to avoid overfull \hbox
    \includegraphics[width=\linewidth]{image-b}
    \caption{Image B}
  \end{subfigure}
  \hfill
  \begin{subfigure}[b]{.48\textwidth} % make less than .5\textwidth to avoid overfull \hbox
    \includegraphics[width=\linewidth]{image-c}
    \caption{Image C}
  \end{subfigure}
  \caption{This works!}
\end{figure}

\end{document}

Output


text:
Q: tkinter GUI with multiple independent GUI files I've currently got a tkinter app with one window and lots of buttons on it.
As just a snippet, the code is approximately:
import tkinter as tk

def openWindow():
    window = tk.Toplevel(root)

root = tk.tk()

~ ~ ~ ~

root.mainloop()

It is likely that the window generated with the openWindow() function is going to be quite a complicated window alongside my main program. Instead of having one very large python file, I'd prefer it if I had another separate python file which can be opened independently, or imported into my main program and opened when clicking the appropriate button.
How exactly would I do that?
Thank you

A: Consider creating separate classes for major areas of the GUI.
Lets say you have a Label, Entry and a Button widgets that act like a file select widget, when you click on the button, it opens a dialog to select a file, the selected file path is then shown in the Entry field.
All of this code can exist together and it defines the behavior and appearance of all the elements of the widget.
This could be implemented as a standalone widget as shown below.
from tkinter import *
from tkinter import filedialog

class FileSelect(Frame):
    def __init__(self,master,label="",**kw):
        Frame.__init__(self,master)
        self.configure(**kw)
        self.file = StringVar()

        self.Label = Label(self, text=label)
        self.Label.config(width=10,anchor=E)
        self.filenamebox = Entry(self,text=self.file)
        self.filenamebox.config(width=50)
        self.btnBrowse = Button(self,text='Browse',command=self.browse_file)
        self.btnBrowse.config(width=10)
        self.Label.grid(row=0,column=0,pady=5,sticky=E)
        self.filenamebox.grid(row=0,column=1,pady=5)
        self.btnBrowse.grid(row=0,column=2,pady=5,padx=5)

    def browse_file(self):
        filename = filedialog.askopenfilename(filetypes=[('All File','*.*')])
        self.file.set(filename)

    def get_filename(self):
        return self.file.get()

def main():
    root = Tk()
    root.title("Example Widget")

    FileSelect(root,label="My File").grid()
    root.mainloop()

if __name__ == '__main__':
    main()

We could also include this functionality in a larger section of GUI code.
from otherFile import FileSelect
....
fileSelect = FileSelect(root,label="Select New File")
fileSelect.grid()

(otherFile is the name of the python file containing the FileSelect widget)
Using this method, you can create smaller sections of code for your GUI in separate code file and build them up in to a more complicate example.
If your have sections of code that perform "non-gui" functions, reading a file for example, put these in to separate functions or classes that you can import in to your main code.

A: Partial answer:

*

*Try to seperate your "business logics" into classes and modules and put those into one or more .py files.  One way to make sure your business modules are pure is not to import tkinter in them.

*Try to put all your UI in classes and modules and keep them free of business logic. Scan your codes for any lines that involve computations and operations and ask yourself if those lines of code should be moved over to a class as mentioned.

*To keep each UI file size under manage, group related widgets into your own subclass of tk.frame. This also allow you to reuse those code in future projects.
I had GUI-phobia before, but after learning and coding in tk and ttk for couple weeks I managed to create a superwidget that is practically reused in two unrelated projects.


text:
Q: Sample Google endpoints client for C# I followed the example for creating google endpoints, and I can see that they work properly in the apis explorer. I then generated the C# library using the google-apis-client-generator python script, and after a bit of tweaking it builds properly. Does anyone have a sample C# project that utilizes the generated library? Thanks.

A: This endpoints sample might help you:
https://github.com/peleyal/peleyal/tree/master/TicTacToe
More documentation about the .NET client library for Google APIs is available at: https://developers.google.com/api-client-library/dotnet/
Our samples are available at: https://github.com/google/google-api-dotnet-client-samples
What else? :)


text:
Q: fullPage.js dynamical slides with ACF last slide I am creating a dynamic full page slider with fullPage.js and Advanced Custom fields plugin for Wordpress.

    <?php if(get_field('slide')): ?>
            <?php while(has_sub_field('slide')): ?>

                    <?php the_sub_field('slide_text'); ?>

            <?php  endwhile; ?>
    <?php endif; ?>

The slider also has a down-arrow to show down movement and I would like for it to change to up-arrow icon when I reach the last slide, something like this:
   if($(window).scrollTop() === 0) {
        $('.ion-chevron-up').addClass('ion-chevron-down').removeClass('ion-chevron-up');
   } else if($(window).scrollTop() + $(window).height() >= $(document).height() - 15) {
        $('.ion-chevron-down').addClass('ion-chevron-up').removeClass('ion-chevron-down');
    } else {
    // nothing
    }

How can I determine the last slide of fullPage.js dynamically and achieve this?
EDIT
I ended up using
.fp-viewing-1 .ion-chevron-down {
  display: none;
}
.fp-viewing-0 .ion-chevron-up {
  display: none;
}

Although this is not dynamic since on the client side there can be slides added so this is not really the solution. I'd really need a class fp-viewing-x which would be for the last slide, whatever the number would be.

A: Do not use scrollTop unless you use scrollBar:true .(Read the fullPage.js FAQs for more info).
Use instead the callbacks provided by the plugin such as afterLoad.
Then check that the section with the active class is the last one with something like:
if ( $('.section.active').is(':last-child'))

Or you can even use the class fp-viewing-xxx added to the body element to your site and just deal with CSS. (which would be my option)


text:
Q: Download test links are working in Brackets' live preview, but not when I test in dedicated browser window I am building a site in Brackets and everything is working 100% how it should in live preview, including a button that downloads something. However, when I test the page in Edge or even a dedicated window in Chrome, it doesn't do anything. My live preview is in Chrome, ftr. Any idea why I'm not getting anything when I test outside of live preview? The download button relies on javascript files, if that helps. Javascript is enabled on all sites in my browser settings. I'm stumped.

A: please give more details about this issue
you didn't post the code behind your buttons.
most probably the problem related to your code in the download bottom indicating the wrong path for the file which you are downloading , the reason behind this working on your live preview browser that files are indicating correct path locally.
to find the exactly problem i would check the java error by pressing f12 on the browser when  i try outside the server .
if you could place the code on the button i will edit this post and give you better answer based on the details you provided .
good luck

A: After checking the console log, it appears to be an issue with "Tainted Canvas" and local disk files, security, etc. I could set up a local web server for testing (and I will eventually) which should fix the problem, but for now, since its working in Brackets' live preview, I am going to assume everything is fine and I'll verify that all upon deployment.


text:
Q: jQuery for each 24 over a number I have this code
if ($('input#grommet').is(':checked')) {
     if (width <= 96) {
           var grommetQTY = 4;
     } else if (width > 96) {
            grommetQTY = (Math.floor(width / 24));
            grommetQTY = grommetQTY - 4;
            grommetQTY = grommetQTY * 2;
            grommetQTY = grommetQTY +4;
     }
}

and I need to add 2 to the grommetQTY for each whole 24 inches (2 feet) over 96 width. Is there a way to do this?
What this is attempting to accomplish is giving the pricing for a banner. We add 2 more grommets at 2 feet intervals, but because this is custom sizing, it could be 96 feet wide, and I don't want to have to write an else if statement for each two foot interval. I am hoping there is a way to only add two to the quantity everytime the width goes another 24 inches over the standard 96 inch width so if width is 96 or less, qty is 4, at 120 its 6, at 144 its 8, etc

A: Rather than coming up with the equation for this, here is a for loop that will do what you need:
var grommetQTY = 0;
for(var i = 96; i < n; i++)
    if(i%24 == 0)
        grommetQTY += 2;

where n is the length. This is terrible inefficient and could be sped up by just doing:
var grommetQTY = 0;
for(var i = 96; i < n; i+=24)
    grommetQTY += 2;

This is nicer but still not ideal. The ideal solution in your case would be an equation.
P.S - The equation is Math.floor( Math.max((n - 96), 0) / 24 ) * 2 + 4 if I understand you correctly.

A: Math.pow(2, grommetQTY) * (Math.floor(96 / 24))
2 to the grommetQTY for each whole 24 inches in 96. Is that what you need?
Math.pow(a, b) gives a to the power of b

Edit:
var qty = (Math.floor(n / 24)) * 2
Where n is the pixels (96 in your example).

Edit:
var qty = 4 + ((width > 96) ? ((Math.floor((width - 96) / 24) * 2) : 0);

Is that it?

A: You could do something like this:
var extra = width - 96
var grommetQTY = 4;
if (extra > 0) {
  grommet += Math.floor((extra / 24)) * 2;
}

The variable extra holds, as the name implies, extra length that you would want to take into consideration. If it's 0 or below that means it's 96 and under.
Then, for extra > 0 you could alternatively change it to extra >= 24 as any extra value less than 24 will return 0.


text:
Q: Empty <> before C# class name I need to repair C# code that was decompiled on with .NET 4. Unfortunately, on my workstation there is only .NET 3.5 installed and that might be the reason why the following code  won't compile:
ReportPage.<>c__DisplayClass26 <>c__DisplayClass = new ReportPage.<>c__DisplayClass26();

What <> construct means here?
There are no c__DisplayClass26 strings anywhere in the code except this line. This might mean that this name is constructed from some metainformation that was missed during decompilation.

A: The C# compiler sometime has to introduce variables/fields/classes. When he has to do it, he prepends them <> to their name, so there won't be a name collision (with the C# compiler, it's illegal to name something with those two characters). This happens for example for auto generated properties, the yield keyword, lambda & anonymous functions/delegates, the new async keyword (the one that is introduced in the Async CTP and that will probably be present in C# 5.0)...
Now... It's strange that you have the c__DisplayClass26 only there. Perhaps your decompiler wasn't up to the par. Try looking at the code with IlSpy.
Look at this pastebin: http://pastebin.com/pTRVyVdp (it isn't mine). There is an example with c__DisplayClass. In the first half of the text there is the "original" code, in the second half the decompile one. You see, in this case it's used for a closure. At lines 32/33 there is a [CompilerGenerated] private sealed class <>c__DisplayClass2. You should have it too in your code.
Mmmh... IlSpy is a little too much good :-) Often it's able to reconstruct the "original" code from the CompilerGenerated code.

A: xanatos is correct; you are looking at a class that was automatically generated to implement closure semantics.
My handy guide to interpreting the magic names that the C# compiler generates when it has to make something on your behalf is here:
Where to learn about VS debugger 'magic names'
But again let me emphasize that you should not rely upon this; this is for entertainment purposes only. We reserve the right to change this scheme at any time.

A: This was a compiler-generated class.  It was most likely created from an anonymous delegate or lambda inside of a method of the ReportPage class.
You should be able to see where this is used in your decompiled code, and try to figure out what it's doing to back it out.


text:
Q: Keep sequential primary key in error insert My create table command in mysql is
CREATE TABLE `map` (
  `id`  int(4) AUTO_INCREMENT NOT NULL,
  `city`    varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE = InnoDB;

CREATE UNIQUE INDEX `map_city_idx`
  ON `map`
  (`city`);

Intial value, like:
id(1),city('Banda Aceh')
id(2),city('Medan')

The next insert is city('Medan'), so it's error because city column is unique. The next insert is city('Bengkulu'), and the final table result is
id(1), city('Banda Aceh')
id(2), city('Medan')
id(4), city('Bengkulu')

It's not id(3) but id(4) instead. So how could I keep sequential primary key eventhough there was/were insert error before?
id(1), city('Banda Aceh')
id(2), city('Medan')
id(3), city('Bengkulu')

A: That looks like InnoDB behaviour. InnoDB rolls back the transaction, but autoincrement key can not be restored because it might be used by someone else. This doesn't happen in MyISAM tables, but with InnoDB you have the power to prevent it using transactions. I'll write this in php, but you can repeat it in any language you want:
mysql_query('START TRANSACTION');
//query if it exists and lock the record
$r = mysql_query('SELECT id FROM map WHERE city="Medan" FOR UPDATE');
if(mysql_num_rows($r)>0){
  //already exists
  // there are better ways to do this, buy you got the idea.
  list($id) = mysql_fetch_row($id);
  mysql_query('ROLLBACK'); // release the lock
}else{
  // does not exists - insert it
  mysql_query('INSERT INTO map(city) VALUES("Medan")');
  $id =  mysql_insert_id();
  mysql_query('COMMIT'); //commit and release the lock
}
//... here $id will be id of 'Medan' city regardless if it is inserted now
//  or it is duplicate and there will be no autoincrement key holes


text:
Q: Summary of the method documentation is not showing in Swagger UI I have added the content in the summary tag but it not showing in the swagger ui in .NET 6 Web Api project.

    /// <summary>
    /// Check if the trading account already closed
    /// </summary>
    /// <param name="nric">xxxxxx-xx-xxxx</param>
    /// <returns></returns>
    [HttpGet]
    public async Task<ActionResult> IsAccountClosed(string nric)
    {
     // code is removed for brevity
    }

This is default code in Program.cs
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

But in .NET Core 3.1 Web Api project, it shows.

A: Here's what worked on my side (in a sample .NET 6 Web Api project):

*

*Go to the properties of your project => Build => General => Output section => Tick the checkbox 'XML Documentation file'

*Edit the AddSwaggerGen service configuration by adding the following:
builder.Services.AddSwaggerGen(c =>
{
   ...

   var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
   var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
   c.IncludeXmlComments(xmlPath);
});

PoC:

Does this approach work for you?


text:
Q: Python "header.py" module I've split one large python file containing a bunch of methods into several smaller ones. However, there's one problem: I'd like all of these small files to import almost the same modules.
I've tried to create a header.py file where I just pasted the common header. I've then added from header import * on the other ones, but it seems to me that this would only import the methods listed on header.py, rather than the actual modules.
I know one solution is to figure out which libraries each small file depends on, but isn't there a faster way to do that?

A: It is very important and useful to have all dependencies in a .py file to be listed in the import statements. That way we can easily trace back the source of all modules used.
Say if you are using module1.method somewhere and want to check where this method came from, you'll always find in the import statements at the top. This is the reason why from module1 import * is highly discouraged.
We can do what you need in neat way.
In your header.py
import module1
import module2

In your other files,
import header

header.module1.method() #make all the function calls via header module.

If you think its making your code writing tedious because of longer function names, then may be try this.
import header as h
h.module1.method()

But please make sure you don't have untraceable modules in your python files.


text:
Q: Struggling to build multi dimensional arrays with unique ids Lets say I have some db rows that looks something like this:
group    version  tool         info
group_a  m        screwdriver  for screwing things
group_a  m        hammer       for hitting things
group_a  l        screwdriver  for screwing things
group_a  xl       screwdriver  for screwing things
group_b  m        screwdriver  for screwing things
group_b  m        hammer       for hitting things
group_b  m        wrench       for wrenching things
group_b  l        screwdriver  for screwing things
group_b  xl       wrench       for wrenching things

and from that I want to create and array that looks something like this:
array(
    array( 'id' => 'group_a',
        array( 'id' => 'm',
            array( 'id' => 'screwdriver',
                'info' => 'for screwing things'
            ),
            array( 'id' => 'hammer',
                'info' => 'for hitting things'
            ),
        ),
        array( 'id' => 'l',
            array( 'id' => 'screwdriver',
                'info' => 'for screwing things'
            ),
        ),
        array( 'id' => 'xl',
            array( 'id' => 'screwdriver',
                'info' => 'for screwing things'
            ),
        )
    array( 'id' => 'group_b',
        array()
    )
    ~~~~~~~ etc ~~~~~~~
);

For a bit of context I'm passing this as JSON from Zend to BackboneJS that will then consume these arrays into a Group Collection, which contains n number of Version Collections which contains n number of Tool Models.
Any help greatly received, happy to clarify any points.
Cheers.

A: I dont really like this as it will throw notices like crazy.  But the end result would be something like this:
$array = array();
while($row = fetch($query) {
  $array['id'][$row['group']]['id'][$row['version']]['id'] = $row['tool'];
  $array['id'][$row['group']]['id'][$row['version']]['info'] = $row['info'];
}

I would make it more elegant with issets, and checks to prevent things from being overwrote and appended to instead.
I would probably use the actual ID as a key instead of the word to help with the uniqueness as well.
Anyway this should help you get thinking in the right direction.

A: Transform your data into a three dimensional temporary array.
$temparray=array();
foreach ($rows as $row) {
  $temparray[$row['group']][$row['version']][$row['tool']]=$row['info'];
}

This temporary array will look similar to what you're trying to achieve, but not quite:
Array
(
    [group_a] => Array(
            [m] => Array(
                    [screwdriver] => for screwing things
                    [hammer] => for hitting things
                )
            [l] => Array(
                    [screwdriver] => for screwing things
                )
            [xl] => Array(
                    [screwdriver] => for screwing things
                )
    )
    [group_b] => Array(
            [m] => Array(
                    [screwdriver] => for screwing things
                    [hammer] => for hitting things
                    [wrench] => for wrenching things
                )
            [l] => Array(
                    [screwdriver] => for screwing things
                )
            [xl] => Array(
                    [wrench] => for wrenching things
                )
    )
)

Now either that's enough for your needs or you have to reproduce the exact structure you'vw shown. In the latter case, just loop over that temporary array to acheive your goal:
foreach ($temparray as $groupid=>$groupdata) {
  $grouparray=array('id'=>$groupid);
  foreach ($groupdata as $versionid=>$versiondata) {
    $versionarray=array('id'=>$versionid);
    foreach ($versiondata as $toolid=>$tooldata) {
      $toolarray=array('id'=>$infoid,'info'=>$tooldata);
      $versionarray[]=$toolarray;
    }
    $grouparray[]=$versionarray;
  }
  $targetarray[]=$grouparray;
}

And you're done :)
BTW, arrays that have 'id',0,1,2,... as index are a bit awkward. I don't know BackboneJS, but any script that uses such a format (rather than what the temptable looks like) look quite suspicious to me.


text:
Q: WPF VB.net Listview How can I display the Value of the Selected Cell first of all, I'm new in programming with WPF and I have some difficults with the listview in WPF.
I already have a ObservableCollection and want to display the value of the selected Cell in a MsgBox.
My Question is, how should I do that ?
This doesn't work for me:
mylistview.SelectedItem()

My Code:
 XAML
<ListView x:Name="mylistView" Margin="10,31,10,149.714" SelectionMode="Multiple" ItemsSource="{Binding}" Grid.ColumnSpan="3" Background="#FFA4A4A4" BorderThickness="2" BorderBrush="#FF6A6F77">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Path=Track}" Width="100" Header="Track"/>
            <GridViewColumn Width="auto" Header="" >
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Image Width="50" Height="50" VerticalAlignment="Center" HorizontalAlignment="Center" Source="{Binding Path=Image}"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn DisplayMemberBinding="{Binding Path=Endung}" Width="100" Header=" Container"/>
            <GridViewColumn DisplayMemberBinding="{Binding Path=Album}" Width="100" Header="Album"/>
            <GridViewColumn DisplayMemberBinding="{Binding Path=Bitrate}" Width="100" Header="Bitrate"/>
            <GridViewColumn DisplayMemberBinding="{Binding Path=Pfad}" Width="100" Header="Pfad"/>
        </GridView>
    </ListView.View>
</ListView>

Code-Behind
Dim files As New ObservableCollection(Of Austauscher)

    Public Structure Austauscher
    Private _track As String
    Private _album As String
    Private _pfad As String
    Private _bitrate As String
    Private _endung As String
    Private _image As BitmapImage

    Property Track() As String
        Get
            Return _track
        End Get
        Set(ByVal Value As String)
            _track = Value
        End Set
    End Property
    Property Album() As String
        Get
            Return _album
        End Get
        Set(ByVal Value As String)
            _album = Value
        End Set
    End Property
    Public Property Pfad As String
        Get
            Return _pfad
        End Get
        Set(ByVal Value As String)
            _pfad = Value
        End Set
    End Property
    Property Bitrate As String
        Get
            Return _bitrate
        End Get
        Set(ByVal Value As String)
            _bitrate = Value
        End Set
    End Property
    Property Endung As String
        Get
            Return _endung
        End Get
        Set(ByVal Value As String)
            _endung = Value
        End Set
    End Property
    Property Image As BitmapImage
        Get
            Return _image
        End Get
        Set(ByVal Value As BitmapImage)
            _image = Value
        End Set
    End Property

End Structure

And I add files with:
files.Add(New Austauscher With {.Track = "Track", .Pfad = path, .Album = "Album", .Bitrate = "kbs", .Endung = "extension"})

A: The problem is with the listView, as you have discovered it lacks a "selectedCell" property.
You may find you can get the functionality you require by using the datagrid control, I have made a version that should work in the same way as your listview example;
        <DataGrid Name="myGridView"  SelectionMode="Extended" SelectionUnit="Cell" ItemsSource="{Binding}" Grid.ColumnSpan="3" Background="#FFA4A4A4" BorderThickness="2" BorderBrush="#FF6A6F77" AutoGenerateColumns="False">
        <DataGridTextColumn Header="Track" Binding="{Binding Path=Track}" Width="100"/>
        <DataGridTemplateColumn Header="">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Width="50" Height="50" VerticalAlignment="Center" HorizontalAlignment="Center" Source="{Binding Path=Image}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Binding="{Binding Path=Endung}" Width="100" Header=" Container"/>
        <DataGridTextColumn Binding="{Binding Path=Album}" Width="100" Header="Album"/>
        <DataGridTextColumn Binding="{Binding Path=Bitrate}" Width="100" Header="Bitrate"/>
        <DataGridTextColumn Binding="{Binding Path=Pfad}" Width="100" Header="Pfad"/>
    </DataGrid>

The datagrid offers more control over your selections and contains a property called selectedCells, it is a collection because (as in your example) you can select many cells. If you want to have only one selected cell then you should set the SelectionMode property to single (allowing you to select only a single item and set the SelectionUnit (as in my example) to Cell. Alternitively you can use the CurrentCell property that returns the the cell that has focus;
myGridView.CurrentCell

I hope this helps.


text:
Q: When is every closed set (/singleton) the zero set of complex valued functions? We know some things for real valued functions. Let $X$ be a topological space, and call $Z \subset X$ a zero set if there exists a continuous function $f:X \rightarrow \mathbb{R}$ s.t. $f^{-1}(0) = Z$.
We know:

*

*Every closed is a zero set iff $X$ is perfectly normal

*Every closed is an intersection of zero sets iff $X$ is Tychonoff

*If $X$ is compact Hausdorff, then every singleton is a zero-set iff $X$ is first countable.
So my question is: Do the same results hold true if we consider zero sets of complex valued functions $f:X \rightarrow \mathbb{C}$? Or what does change?
The motivation is, that for a compact Hausdorff space $X$, I would like to understand which closed sets are zero sets of complex continuous functions $f:X \rightarrow \mathbb{C}$. Or under what hypotheses every closed (/singleton) is such a zero set.

A: Nothing changes: for any space $X$, the zero-sets of continuous complex-valued functions on $X$ are precisely the zero-sets of continuous real-valued functions on $X$. Call the former complex zero-sets and the latter real zero-sets for short.
If $Z\subseteq X$ is a real zero-set, then certainly $Z$ is a complex zero-set. Now suppose that $Z$ is a complex zero-set, i.e., that $Z=f^{-1}[\{0\}]$ for some continuous $f:X\to\Bbb C$. Let
$$g:X\to\Bbb R:x\mapsto\big(\operatorname{Re}f(x)\big)^2+\big(\operatorname{Im}f(x)\big)^2\;.$$
then $g$ is continuous, and $g(x)=0$ iff $\operatorname{Re}f(x)=\operatorname{Im}f(x)=0$ iff $f(x)=0$, so $Z$ is a real zero-set.


text:
Q: Paint voronoi plot over a map I'm trying to plot a voronoi plot over a map, to see the voronoi areas over the map.
I have read the next post of other user, but I'm not able of achieve a similar result: Image and Voronoi diagram on the same figure
I have the following map with points:

Points are made with coords and the same with the overall map.
This is the map without the points:

And here is the voronoi_plot:

This was made with this code:
from scipy.spatial import Voronoi, voronoi_plot_2d
vor = Voronoi(coords)
voronoi_plot_2d(vor)

So when I try to put both the map and voronoi in the same plot with the next code:
fig = plt.figure(figsize=(20,20))
ax = fig.add_subplot(111)
valdevevas.plot(ax=ax,color='white', edgecolor='grey')
voronoi_plot_2d(vor, point_size=10, line_colors='red', ax=ax)
plt.show()

It looks like this:

It has the map, but it's only the voronoi "part" of the map.
I'd like to achieve the complete map with the voronoi areas over it.
Is it posible the way I'm doing or should I try other way?
Thanks


text:
Q: Minimax: what to do with equal scores in endgame? As far as I understood, the Minimax algorithm in its simplest form works the following way: traverse the game tree bottom-up and if it's the player's turn, assign the maximum score of all child nodes to the current node, else the minimum score. Leaves are scored according to the game output, let's say +1 for win, 0 for draw, -1 for loss. Finally choose the move which leads to the node with the highest score.
Of course it is impractical to traverse the whole game tree, so a heuristic is used. But assume we are near the end of the game. Then I have found some problems with this simple approach.
For example, we are playing chess and the player (playing white) has reached this position:

It is the players turn. So there is a mate in one with Qg7, the node for Qg7 thus gets a score of 1. But for instance, Ke1 is also a legal move. The only reply is c5, then Qg7# is still available. And because Qg7 gets a score of 1, so does c5, so does Ke1.
So we have at least two moves with a score of 1 (Ke1 and Qg7). Let's say the algorithm considers king moves first and chooses the first move with the highest score. That would mean, that in this position, the player would not checkmate the opponent, but would do random King moves until the opponent could actually prevent the checkmate (with queening the pawn).
The fundamental problem is, that a checkmate in one (Qg7) has the same score as a checkmate in two (Ke1), so there is no reason for the player, to actually go for the checkmate in one.
This can be prevented with a simple modification to the Minimax algorithm: in case of equal score, choose the shorter path to the position with this score. So a checkmate in one would be prefered.
My question is: I have not found any mention of this in any Minimax-related source, so is there some misunderstanding of Minimax on my part? If not, is this the usual way to solve this or are there superior ways?

A: I'm pretty sure you understand minimax correctly.
The thing I would probably do is to simply pass down the current distance in the minimax function, and weight the wins / losses according to that. A faster win (to reduce the possibility of unseen situations) and a slower loss (to allow for mistakes by the opponent) should generally be preferred. Whether the win is 1, or any positive value, it doesn't matter too much - it will still get picked as better than 0 or -1.
If you have a win be the largest possible value in your heuristic - you can still do something similar - just weight it by increasing or decreasing it a little, but still have it be larger than all other non-win values.
For your example, it probably doesn't really matter, as, when the pawn gets close to promoting, you'd detect that a draw is coming and then you'd make the winning move. But it can certainly be a problem if:

*

*There's a sequence of inevitable moves beyond the search depth that results in a worst outcome for you (which is a pretty common problem with minimax, but if it's likely avoidable, it's obviously better to do so)

*There's a time constraint on your side

*You don't cater for all draw conditions (e.g. 3 repeated positions)


text:
Q: Mirroring USB data to multiple computers/hosts simultaneously I want to mirror the data sent to (and/or from) a USB device to multiple host computers at the same time (i.e no physical switches to select one host or the other). Here are two scenarios to describe what I'm trying to do from a device's perspective:

*

*Send Data: A USB microphone is hooked up to two computers such that when spoken into, the mic level on both computers increases simultaneously

*Receive Data: An audio signal from each computer is transmitted over USB and "merged" before entering a DAC for external processing, effectively combining each computer's audio signal

My (limited) understanding of the USB protocol and other similar posts on StackExchange (1, 2, 3, 4) tell me that this isn't really possible, however, during my research on this topic I stumbled on these videos:

*

*1:2 USB Barcode Scanner Splitter

*USB Keyboard Mouse Splitter at the same time
These seem to demonstrate that what I'm trying to do is possible, at least for sending data from the device. Can USB data really be mirrored in this fashion if it's done via RS232 connections? I've found the product page here, however I'm still skeptical of this and would like to see other examples of similar devices. Does anyone know what the generic name for a device like this is/know of any other examples of devices like this?

A: The device described in the video is perhaps similar to the
USB Barcode Scanner Splitter (UBS-120P),
however it doesn't help with your problem.
This works for RS232 sources, but you can't split USB signals like this.
USB is a
Serial communication
device that employs a
USB (Communications)
protocol.
USB uses two way digital communication where the device talks to the computer
to tell it how it can send its data to the computer.
The computer and the device perform a handshake where they agree on the format
of the data that the device will be sending.
You can't connect the same USB device to two computers at the same time,
because the device cannot do a handshake with two computers.
The most you can do is broadcast the audio to be picked by other
computers via the network.

A: Those USB splitters are device specific.  They work by decoding the input from a USB HID (human interface device) devices, splitting it out, and emulating duplicate HID devices to the connected computers.  They will not work for anything other than USB HID devices.  If you are wanting to mix and split audio signals then it would be far easier to do this with the audio than with the USB devices.  If the goal is to maintain signal quality by keeping this digital as long as possible in the data path then doing so anywhere other than the USB part of the path would be far easier.
The use of RS-232 connectors on the devices you linked to has nothing to do with how the input signal is duplicated.  The way they are using RS-232 is non-standard and is a good way to ruin hardware if someone wasn't very careful in using those cables.


text:
Q: How can I identify the cause of an E4 plugin not starting I have created a simplemost E4 plugin based on the example templates in Eclipse. I have made no changes. When starting a new Eclipse instance depending only on the plugins transitive dependencies, the menu appears correctly. When I try to install it into my running instance, the model spy shows that the fragment has not merged. The command is missing. There are no error messages pertaining to E4 as far as I can see.
How would I debug such a situation? I have not found any information on this, and most tutorials seem to assume that I want to build a complete application. However, I merely want to provide a contribution to on an existing E4 application.


text:
Q: sanitizing xss in asp.net mvc What is the best way to sanitize the user input in asp.net mvc without throwing "potentially dangerous request.form" exception and still preventing the xss attack for the post requests which contains dangerous tags.
Edit:
I tried the AntiXss and created custom encoder which encodes all the submitted values at runtime but the problem is that it is still throwing the exception. Actually I am not figuring out that exactly where (which event) I can ensure that the request contains nothing dangerous and if it contains something dangerous, I can redirect it to another Action rather than throwing exception.

A: Disable the automatic form checking, and use Microsoft Anti-Cross Site Scripting Library to manually check each relevant field for XSS.
Of course, in MVC some of the checks come out of the box. If, for example, your action method contains an int parameter called productID, and the user submits a form with a productID field, it's automatically populated by MVC's model binder mechanism and you get a "strong" int which you can count on. No text inside, no problems.
So all you have to check are the text-based fields.


text:
Q: DateRange picker design flutter How to design date-Range Picker in flutter
here is my image

A: One of the most popular date pickers is date_picker_timeline
Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: <Widget>[
      DatePicker(
        DateTime.now(),
        initialSelectedDate: DateTime.now(),
        selectionColor: Colors.black,
        selectedTextColor: Colors.white,
        onDateChange: (date) {
          // New date selected
          setState(() {
            _selectedValue = date;
          });
        },
      ),
    ],
)

use can also use this one in alert box https://pub.dev/packages/calendar_date_picker2


text:
Q: Изменения яркости цвета (RGB, HSV, ITU BT.709) Стандарт ITU BT.709 позволяет вычислить относительную — видимую — яркость цвета. Пространство HSV, в свою очередь, предоставляет возможность изменять абсолютное значение яркости. Появился вопрос, как связать эти величины. Скажем, в пространстве HSV яркость цвета x равна 90%, тогда как по формуле относительной яркости — 70%. Как рассчитать величину изменения яркости в пространстве HSV, чтобы относительная яркость, скажем, уменьшилась до 60%?
Смог дойти лишь до банального варианта — перебор, но хочется найти более эффективное решение.


text:
Q: char-to-char substituion with sed I am trying to make a monoalphabetic substitution decoder in bash: I have a set of characters that form an alternative alphabet like
real alphabet -> ABCDE ...
my alphabet   -> DGHJK ...

I want sed (or another tool, but I think sed can handle it) to replace "A" with "D", "B" with "G" and so on. Is it possible, without using the "-e" argument in sed (and typing all the alphabet) to perform such a substitution?

A: Try:
$ echo ABCDBAD | sed 'y/ABCD/DEFG/'
DEFGEDG

y/string1/string2/ causes sed replace all occurrences of characters in string1 with the corresponding characters in string2.

A: Instead of sed, use tr:
tr 'A-Z' 'DGHJK...' < input


text:
Q: Concurrent build of the same build definition with tfs What's the best way to allow only one build of the same build definition at a time?
I searched but found nothing related to concurrent build of the same build definition.


text:
Q: jQuery - tolerance: 'fit' of a droppable does not care about border-setting of droppable I'm developing a little tool and it works so far, but I interfere with the fact that the droppable (with option 'tolerance' set to 'fit') obviously doesn't care about the border of a droppable.
See here: http://jsfiddle.net/scraddy/8geEB/20/
Relevant javascript extracted from fiddle:
$("#dropzone").droppable({
    hoverClass: "ui-drop-hover",
    tolerance: "fit",
    drop: function(event, ui) {
        $("#dropzone p").hide();
        $("#pix img").draggable("disable").hover(function() {
            $(this).css({
                cursor: "default"
            });
        });
    }
});

$("#pix img").draggable({
    cursor: "move",
    revert: "invalid",
    helper: "clone",
    stop: function(event, ui) {
        if ($("#dropzone p").is(":hidden")) {
            $(ui.helper).clone().appendTo($("#dropzone")).resizable({
                handles: 'se',
                maxHeight: 200,
                minHeight: 25,
                aspectRatio: true,
                ghost: true,
                autoHide: true,
                stop: function(event, ui) {
                    var ximg = ui.position.left + ui.size.width;
                    var xdrop = $("#dropzone").offset().left + $("#dropzone").width();
                    var yimg = ui.position.top + ui.size.height;
                    var ydrop = $("#dropzone").offset().top + $("#dropzone").height();
                    if (ximg > xdrop || yimg > ydrop) {
                        $(this).position({
                            my: "right bottom",
                            at: "right bottom",
                            of: "#dropzone",
                            offset: ((xdrop - ximg) < 0 ? 0 : -(xdrop - ximg)) + " " + ((ydrop - yimg) < 0 ? 0 : -(ydrop - yimg))
                        });
                    }
                }
            }).parent().draggable({
                disabled: false,
                helper: "original",
                containment: "#dropzone",
                create: function(event, ui) {
                    if ($("#testing").size() === 0) {
                        $("#dropzone div.ui-wrapper").append('<img id="testing" src="http://palmenhandel-witten.de/img/close.png" width="16" height="16" alt="Bild entfernen" />');
                        $("img#testing").click(function() {
                            $("#dropzone p").fadeIn(350);
                            $("#dropzone div.ui-wrapper").resizable('destroy').draggable('destroy');
                            $(".ui-draggable-dragging").fadeOut(350, function() {
                                $(this).remove()
                            });
                            $("#pix img").draggable("enable").hover(function() {
                                $(this).css({
                                    cursor: "move"
                                });
                            });
                        });
                    }
                    $("#dropzone div.ui-wrapper").bind("mouseenter mouseleave", function(event) {
                        $("img#testing").toggleClass("over");
                    });
                }
            });
        }
    }
}).hover(function() {
    $(this).css({
        cursor: "move"
    });
});

When you drag an image to the droppable it should only be accepted when it's completely over the droppable and no part of it over the droppable's border. The border belongs to the droppable, of course, but I ask myself if there is maybe a workaround for this?
I thought of manually reposition the draggable after dropping, but this will be cumbersome, I guess.

A: I solved my issue with manually reposition the draggable after adding to the droppable. Here is the edited fiddle: http://jsfiddle.net/scraddy/8geEB/27/


text:
Q: Drag and Drop with a custom User Control I have to make a program which has 3 forms and each form contains 2 custom user controls.
I have to make the user controls switch places (one with another).
I'm using the drag & drop event, so by mouseDown event I catch the first user control,
though, I don't know how to catch the second control, which the mouse is
being dropped on.
basically, Iv'e created (in the class) a temp variable which is a custom eventArgs (derives from
EventArgs),
The custom EventArgs class contains 2 variables (usercontrol1 and usercontrol2)
and in the mouseDown event Iv'e initialized the usercontrol1 with the sender object.
So basically, the question is- how do I intiazlize the usercontrol2 variable with the
usercontrol which the mouse is being dropped on.
NOTE:  I HAVE 6 Controls - 3 forms- so it's dynamic!! Which means, that I may want to exchange the control's places between the forms- I have to save the 2 controls I WANT to exchange between!.
Thanks!


text:
Q: Argparse: Default values not shown for subparsers I have the problem that I am not seeing any default values for arguments when specifying them via add_argument for subparsers using the argparse Python package.
Some research said that you need non-empty help-parameters set for each add_argument step and you need ArgumentDefaultsHelpFormatter as formatter_class as described here:
Argparse: Way to include default values in '--help'?
That's not working for me, however. I suspect that somehow the subparser defaults are suppressed.
Here's an example:
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter

parser = ArgumentParser(description="Sample script", formatter_class=ArgumentDefaultsHelpFormatter, version="sample version")

# Initialize Subparsers

subparsers = parser.add_subparsers(help="", dest="command")

# foo command

fooparser = subparsers.add_parser('foo', help='Do foo')
fooparser.add_argument('files', action='store', help='Foo file(s)' , nargs="+")
fooparser.add_argument("-5", "--Do5", type=int, required=False, dest="do5", help="Do 5 subprocedure.")
fooparser.add_argument("-n", "--topn", type=int, required=False, dest="topn", default=1, help="Show topn")

# bar command

barparser = subparsers.add_parser('bar', help='Do bar')
barparser.add_argument('files', action='store', help='Bar file(s)' , nargs="+")
barparser.add_argument("-mq", "--min-mq", type=int, required=False, default=2, dest="mq", help="Minimum MQ")
barparser.add_argument("-mi", "--min-identity", type=float, required=False, default=0.95, dest="identity", help="Minimum identity")

args = parser.parse_args()

A: Specify formatter_class when adding sub-parsers.
subparsers = parser.add_subparsers(help="", dest="command")

fooparser = subparsers.add_parser('foo', help='Do foo',
                                  formatter_class=ArgumentDefaultsHelpFormatter)
...

barparser = subparsers.add_parser('bar', help='Do bar',
                                  formatter_class=ArgumentDefaultsHelpFormatter)
...

Output of python argparse_test.py --help foo:
usage: argparse_test.py foo [-h] [-5 DO5] [-n TOPN] files [files ...]

positional arguments:
  files                 Foo file(s)

optional arguments:
  -h, --help            show this help message and exit
  -5 DO5, --Do5 DO5     Do 5 subprocedure. (default: None)
  -n TOPN, --topn TOPN  Show topn (default: 1)


text:
Q: Fade in background that is in the javascript along with video Currently only the video fades in.
How do I fade in the background that is in the JavaScript along with the video?
What would need to be adjusted in the code for this to work?
How it works is, clicking on the play image fades in the background along with the video.
https://jsfiddle.net/7syrbnht/
CSS:
.hide {
  display: none;
  opacity: 0;
}

.container:not(.hide){
   opacity:0;
   animation: fade 5s ease 0s forwards;
}

@keyframes fade {
  0% {
    opacity: 0
  }

  100% {
    opacity: 1
  }
}

javascript:
 (function iife() {
   "use strict";

   function show(el) {
     el.classList.remove("hide");
   }

   function coverClickHandler(evt) {
     const cover = evt.currentTarget;
     const thewrap = cover.parentElement.querySelector(".container");
     show(thewrap);
     document.body.style.backgroundImage = "linear-gradient(teal 5px, #0000 5px), linear-gradient(90deg, teal 5px, #0000 5px), linear-gradient(black 10px, #0000 10px 160px, black 160px), linear-gradient(90deg, black 10px, #0000 10px 160px, black 160px), linear-gradient(orange 15px, #0000 15px 155px, orange 155px), linear-gradient(90deg, orange 15px, #0000 15px 155px, orange 155px), linear-gradient(black 20px, #0000 20px 150px, black 150px), linear-gradient(90deg, black 20px, #0000 20px 150px, black 150px), linear-gradient(teal 25px, #0000 25px 145px, teal 145px), linear-gradient(90deg, teal 25px, #0000 25px 145px, teal 145px), linear-gradient(black 30px, #0000 30px 140px, black 140px), linear-gradient(90deg, black 30px, #0000 30px 140px, black 140px), linear-gradient(orange 35px, #0000 35px 135px, orange 135px), linear-gradient(90deg, orange 35px, #0000 35px 135px, orange 135px), linear-gradient(black 40px, #0000 40px 130px, black 130px), linear-gradient(90deg, black 40px, #0000 40px 130px, black 130px), linear-gradient(teal 45px, #0000 45px 125px, teal 125px), linear-gradient(90deg, teal 45px, #0000 45px 125px, teal 125px), linear-gradient(black 50px, #0000 50px 120px, black 120px), linear-gradient(90deg, black 50px, #0000 50px 120px, black 120px), linear-gradient(orange 55px, #0000 55px 115px, orange 115px), linear-gradient(90deg, orange 55px, #0000 55px 115px, orange 115px), linear-gradient(black 60px, #0000 60px 110px, black 110px), linear-gradient(90deg, black 60px, #0000 60px 110px, black 110px), linear-gradient(teal 65px, #0000 65px 105px, teal 105px), linear-gradient(90deg, teal 65px, #0000 65px 105px, teal 105px), linear-gradient(black 70px, #0000 70px 100px, black 100px), linear-gradient(90deg, black 70px, #0000 70px 100px, black 100px), linear-gradient(orange 75px, #0000 75px 95px, orange 95px), linear-gradient(90deg, orange 75px, #0000 75px 95px, orange 95px), linear-gradient(black 80px, #0000 80px 90px, black 90px), linear-gradient(90deg, black 80px, #0000 80px 90px, black 90px), linear-gradient(teal, teal)";
     document.body.style.backgroundSize = "165px 165px";
     videoPlayer.play();
   }

   const cover = document.querySelector(".play");
   cover.addEventListener("click", coverClickHandler);
 }());


text:
Q: What is the derivative of $x!^{x!^{x!^{x!^{x!^{x!^{x!^{.{^{.^{.}}}}}}}}}}$ What is the derivative of $$x!^{x!^{x!^{x!^{x!^{x!^{x!^{.{^{.^{.}}}}}}}}}}$$

My effort:
Let $$g(x)=x!^{x!^{x!^{x!^{x!^{x!^{x!^{.{^{.^{.}}}}}}}}}}\implies g(x)=x!^{g(x)}$$
Taking natrual log on both sides,
$$\ln(g(x))=g(x)\cdot\ln(x!)$$
Differentiating,
$$\frac{1}{g(x)}\cdot g'(x)=g'(x)\cdot\ln(x!)+g(x)\cdot\frac{1}{x!}\cdot x!\cdot\psi^{(0)}(x+1)$$
$$\implies g'(x)\left[\frac{1}{g(x)}-ln(x!)\right]=g(x)\cdot\psi^{(0)}(x+1)$$
So does isolating $g'(x)$ give me the correct solution? If not, how can I solve for the differential?
Edit: The gamma function is indeed implicitly assumed when the factorial function is used.

A: Your definition of $g(x)$ does not make sense for $x! \gt e^{(1/e)} \approx 1.44467$ because it does not converge as seen in the answer to this question and this question.  It is less than this in about the ranges $-4.970 \lt x \lt -4.103$ and  $-0.380 \lt x \lt 1.614$.  Within those ranges, you are doing fine.

A: I would say that everything looks fine, as long as you define that $x! = \Gamma(x+1)$.

A: If you define $x!$ to be equal to $\int_{0}^{\infty}e^{-t}t^x \mathrm{d}t$, then you can say the following:
$y = (x!)^{y} = (\int_{0}^{\infty}e^{-t}t^x \mathrm{d}t)^y$
Raising both sides to the power of $\frac{1}{y}$:
$y^\frac{1}{y} = \int_{0}^{\infty}e^{-t}t^x \mathrm{d}t$.
Since the derivative of $y^\frac{1}{y}$ with respect to $y$ is $-y^\frac{1}{y}(\ln(y)-1)$, and by the Leibniz rule, the derivative of $\int_{0}^{\infty}e^{-t}t^x \mathrm{d}t$ with respect to $x$ is $\int_{0}^{\infty}\ln(t)e^{-t}t^x \mathrm{d}t$, implicit differentiation tells us that:
$-y^\frac{1}{y}(\ln(y)-1)\mathrm{d}y = (\int_{0}^{\infty}\ln(t)e^{-t}t^x \mathrm{d}t)\mathrm{d}x$
We can solve for $\frac{\mathrm{dy}}{\mathrm{dx}}$:
$\frac{\mathrm{dy}}{\mathrm{dx}} = \frac{\int_{0}^{\infty}\ln(t)e^{-t}t^x \mathrm{d}t}{-y^\frac{1}{y}(\ln(y)-1)}$
We can simplify the denominator. Since $y=(x!)^y$, we can conclude that $y^\frac{1}{y}=x!$ and also that $\ln(y)=y\ln(x!)=x!^{x!^{x!^{.^{.^.}}}}\ln(x!)$. Substituting this into the denominator gives:
$\frac{\mathrm{dy}}{\mathrm{dx}} = \frac{\int_{0}^{\infty}\ln(t)e^{-t}t^x \mathrm{d}t}{-x!(x!^{x!^{x!^{.^{.^.}}}}\ln(x!)-1)}$
And there's the derivative.


text:
Q: Draw an automaton with more states and bent arrows I want to draw this automaton:

But I drew it with a bad way !!
\documentclass{article}
\usepackage{pgf}
\usepackage{tikz}
\usetikzlibrary{arrows,automata}
\usepackage[latin1]{inputenc}
\begin{document}
\begin{tikzpicture}[->,>=stealth',shorten >=1pt,auto,node distance=2.8cm,semithick]
\node[initial,state] (A) {$1$};
\node[state] (B) [right of=A] {$2$};
\node[state] (C) [right of=B] {$3$};
\node[state] (D) [right of=C] {$4$};
\node[state,accepting] (E) [right of=D] {$5$};
\node[state,accepting] (F) [below of=E] {$6$};
\node[state,accepting] (G) [below of=D] {$7$};
\node[state,accepting] (H) [below of=G] {$8$};
\node[state,accepting] (I) [below of=H] {$9$};
\node[state] (J) [below of=A] {$10$};
\node[state,accepting] (P) [below of=J] {$16$};
\node[state] (K) [below left of=I] {$11$};
\node[state] (L) [right of=K] {$12$};
\node[state,accepting] (M) [right of=L] {$13$};
\node[state,accepting] (N) [below of=L] {$14$};
\node[state,accepting] (O) [below of=M] {$15$};
\node[state,accepting] (Q) [below of=B] {$17$};
\path (A) edge node {X}(B)
          edge node{I} (C)
          edge node{V} (J)
      (B) edge [loop above] node {X}(B)
          edge node{I} (C)
          edge node{V} (J)
          edge node{<>I,<>V} (Q)
      (C) edge node {X}(H)
          edge node{I} (D)
          edge node{V} (G)
          edge node{Autre} (I)
      (D) edge node {I}(E)
          edge node{<>I} (F)
      (J) edge node {I}(K)
          edge node{<>I} (P)
      (K) edge node {I}(L)
          edge node{<>I} (N)
      (L) edge node {I}(M)
          edge node{<>I} (O);
\end{tikzpicture}
\end{document}

A: quite late, but here is your answer ;)
\begin{tikzpicture}[shorten >=1pt,auto,node distance=2.8cm,semithick]
\node[state,initial] (A) {$1$};
\node[state] (B) [right of=A] {$2$};
\node[state] (C) [right of=B] {$3$};
\node[state] (D) [right of=C] {$4$};
\node[state,accepting] (E) [right of=D] {$5$};
\node[state,accepting] (F) [below of=E] {$6$};
\node[state,accepting] (G) [below of=D] {$7$};
\node[state,accepting] (H) [below of=G] {$8$};
\node[state,accepting] (I) [below of=H] {$9$};
\node[state] (J) [below of=A] {$10$};
\node[state,accepting] (P) [below of=J] {$16$};
\node[state] (K) [below left of=I] {$11$};
\node[state] (L) [right of=K] {$12$};
\node[state,accepting] (M) [right of=L] {$13$};
\node[state,accepting] (N) [below of=L] {$14$};
\node[state,accepting] (O) [below of=M] {$15$};
\node[state,accepting] (Q) [below of=B] {$17$};
\path[->]
      (A) edge [bend left=45] node {$X$}(B)
          edge [bend left=80] node{$I$} (C)
          edge node{$V$} (J)
      (B) edge [loop above] node {$X$}(B)
          edge [bend left=45] node {$I$} (C)
          edge node {$V$} (J)
          edge node {$<>I,<>V$} (Q)
      (C) edge [bend left=-5] node {$X$} (H)
          edge [bend left=45] node {$I$} (D)
          edge [bend left=15] node {$V$} (G)
          edge [bend left=-25] node {Autre} (I)
      (D) edge [bend left=45] node {$I$}(E)
          edge node {$<>I$} (F)
      (J) edge [bend left=15] node {$I$}(K)
          edge node {$<>I$} (P)
      (K) edge [bend left=45] node {$I$}(L)
          edge node {$<>I$} (N)
      (L) edge [bend left=45] node {$I$}(M)
          edge node{$<>I$} (O);
\end{tikzpicture}

A: You can add bend left or bend right or bend left=<degree> or bend right=<degree> to the edges. Here is an example:
\usetikzlibrary{positioning,automata}
\begin{tikzpicture}[shorten >=1pt,node distance=2cm,on grid]
  \node[state,initial]   (q_0)                {$q_0$};
  \node[state]           (q_1) [right=of q_0] {$q_1$};
  \node[state,accepting] (q_2) [right=of q_1] {$q_2$};
  \path[->] (q_0) edge                node [above] {0} (q_1)
                  edge [loop above]   node         {1} ()
                  edge [bend left=45] node [below] {1} (q_2)
                  edge [bend right]   node [below] {0} (q_2)
            (q_1) edge                node [above] {1} (q_2);
\end{tikzpicture}

Result: