text:
Q: How do you know how much space to allocate with malloc()? I'm a total C newbie, I come from C#. I've been learning about memory management and the malloc() function. I've also came across this code:
char *a_persons_name = malloc(sizeof(char) + 2);

What I don't understand is how much space this is allocating for a_persons_name. Is it allocating 2 characters (eg. AB) or something else?
I also know that you can sometimes get "lucky" with malloc and use unallocated space (which can result in data corruption and seg faults). So how do I know how much space I'm allocating and how much I will need?

A: Well, for a start, sizeof(char) is always 1, so you could just malloc(3).
What you're allocating there is enough space for three characters. But keep in mind you need one for a null terminator for C strings.
What you tend to find is things like:
#define NAME_SZ 30
: : :
char *name = malloc (NAME_SZ+1);

to get enough storage for a name and terminator character (keeping in mind that the string "xyzzy" is stored in memory as:
+---+---+---+---+---+----+
| x | y | z | z | y | \0 |
+---+---+---+---+---+----+

Sometimes with non-char based arrays, you'll see:
int *intArray = malloc (sizeof (int) * 22);

which will allocate enough space for 22 integers.

A: malloc() will allocate a block of memory and return a pointer to that memory if successful, and NULL if unsuccessful. the size of the block of memory is specified by malloc's argument, in bytes.
the sizeof operator gives the size of its argument in bytes.
char *someString = malloc(sizeof(char) * 50)

this will allocate enough space for a 49 character string (a C-style string must be terminated by a NULL ('\0') character) not including the NULL character, and point someString at that memory.
It looks like that code in your question should be malloc(sizeof(char) * 2);, as sizeof(char) + 2 doesn't make sense.
note that sizeof(char) is guaranteed to always equal 1 (byte) -- but the memory representation of other types (such as long) may vary between compilers.
The way that you get (un)lucky with dynamically allocated memory is if you try to read/write outside of memory you have allocated.
For example,
char *someString = malloc(10);
strcpy(someString, "Hello there, world!");
printf("%s\n", someString);

The first line allocates enough room for 9 characters, and a NULL character.
The second line attempts to copy 20 characters (19 + NULL) into that memory space. This overruns the buffer and might cause something incredibly witty, such as overwriting adjacent memory, or causing a segfault.
The third line might work, for example if there was allocated memory right beside someString, and "Hello there, world!" ran into that memory space, it might print your string plus whatever was in the next memory space. If that second space was NULL terminated, it would then stop--unless it wasn't, in which case it would wander off and eventually segfault.
This example is a pretty simple operation, yet it's so easy to go wrong. C is tricky -- be careful.

A: That snippet is allocating enough space for a 2-character name.
Generally the string buffer is going to be filled from somewhere, i.e. I/O. If the size of the string isn't known ahead of time (e.g. reading from file or keyboard), one of three approaches are generally used:

*

*Define a maximum size for any given string, allocate that size + 1 (for the null terminator), read at most that many characters, and error or blindly truncate if too many characters were supplied. Not terribly user friendly.

*Reallocate in stages (preferably using geometric series, e.g. doubling, to avoid quadratic behaviour), and keep on reading until the end has been reached. Not terribly easy to code.

*Allocate a fixed size and hope it won't be exceeded, and crash (or be owned) horribly when this assumption fails. Easy to code, easy to break. For example, see gets in the standard C library. (Never use this function.)

A: Your call to malloc will allocate 3 bytes of memory. sizeof(char) is 1 byte and 2 bytes are indicated explicitly. This gives you enough space for a string of size 2 (along with the termination character)

A: This will allocate three bytes; 1 for sizeof(char), plus two.  Just seeing that line out of context, I have no way of knowing why it would be allocated that way or if it is correct (it looks fishy to me).
You need to allocate enough memory to hold whatever you need to put in it.  For example, if you're allocating memory to hold a string, you need to allocate enough memory to hold the longest string expected plus one byte for the terminating null.  If you're dealing with ASCII strings, that's easy: one byte per character plus one.  If you're using unicode strings, things get more complicated.

A: First point - it is a good habit to never put absolute numbers in the argument to malloc, always use sizeof and a multiple. As said above, the memory allocated for some types varies with compiler and platform. In order to guarantee gettin enough space for an array of type 'blob' it is best to use something like this:
blob *p_data = malloc(sizeof(blob) * length_of_array);

This way, whatever the type is, however it looks in memory you'll get exactly the right amount.
Secondly, segfaults etc.
C, as a low level language, has no bounds checking. This means that there is nothing to check you are looking at an index not actually in the array. In fact it doesn't stop you accessing memory anywhere even if it doesn't belong to your program (although your operating system might, thats what a segfault is). This is why, whenever you pass an array around in C you need to pass its length as well, so that the function receiving the array knows how big it is. Don't forget that an 'array' is really just a pointer to the first element.
This is very unhelpful when passing strings around - every string argument would become two arguments, so a cheat is used. Any standard C string is NULL terminated. The last character in the string should be ASCII value 0. Any string functions work along the array until they see that and then stop. This way they don't overrun the array, but if its  not there for some reason, they will.
That being understood
strlen("Hello")

is 5, but to store it you need one more character. E.g.:
const char str1 = "Hello";
char *str2 = malloc(sizeof(char) * (strlen(str1) + 1));
strcpy(str2, str1);

And yes, sizeof(char) is unnecessary because it is defined to be 1, but I find it clearer and it is definitely a good habit.


text:
Q: PHP Form No Errors Not Inserting I have a form, below, that was working for a while, however for some reason the code has now stopped inserting what the user would input via the form. Once the form was working, the only things I changed were the style, and nothing on the database site, or with the insertion of the data.
I get zero errors when I hit the Submit button, and it takes me to the page that I want the form to take the user too.
<form action="insert.php" method="post">

    First Name:
    <input type="text" name="name" id="Name">

    Email Address:
    <input type="text" name="email" id="email">

<input type="submit" value="Submit">

and my PHP code is:
<?php
$link = mysqli_connect("localhost", "root", "root", "travelsite");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_REQUEST['name']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);

// attempt insert query execution
$sql = "INSERT INTO subscribe (name, email) VALUES ('$name', '$email')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// close connection
   mysqli_close($link);
   ?>

A: Try using $_POST['name'] and $_POST['email'].
Also as mentioned on the comments: you got your variables mixed up. (thx @NitinP)
Try also using a prepare statement like:
/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "INSERT INTO subscribe (name, email) VALUES (?, ?)")) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "ss", $name, $email); /*or $first_name*/

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

For more information see the link under Procedural style

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery Fade image above and change CSS background-image behind I have multiple icon IMG's listed side by side in a UL with css/background-images.
When you hover over a single icon the IMG fades to 0 and then the css/background-image becomes visible.
I can get it to fade back fine, but the background-image stays visible and shows a few pixels behind the IMG (lets say the main IMG is black and the css/background-image is orange).
If I set the background-image position to 0 0 then it disappears before the fadeTo of the IMG is finished.
So basically I want the background-position to change once the "normal, 1" has finished.
I hope that makes sense.
Can anybody help?
Here is the code:
$("ul.socials li").hover(function() { //On hover...

    var thumbOver = $(this).find("img").attr("src"); //Get image url and assign it to 'thumbOver'

    //Set a background image(thumbOver) on the <a> tag - Set position to bottom
    $(this).find("a.thumb").css({'background' : 'url(' + thumbOver + ') no-repeat 0 -37px'});

    //Animate the image to 0 opacity (fade it out)
    $(this).find("span").stop().fadeTo('normal', 0 , function() {
        $(this).hide() //Hide the image after fade
    });
} , function() { //on hover out...
    //Fade the image to full opacity
    $(this).find("span").stop().fadeTo('normal', 1).show();
    $(this).find("a.thumb").css({'background-position' : '0 0'});
});

A: "If I set the background-image position to 0 0 then it disappears before the fadeTo of the IMG is finished. So basically I want the background-position to change once the "normal, 1" has finished."
Change your background position on fadeTo callback:
//Fade the image to full opacity
var $li = $(this);
$(this).find("span").stop().fadeTo('normal', 1, function() {
   $li.find("a.thumb").css({'background-position' : '0 0'});
}).show();

or
//Fade the image to full opacity
var $li = $(this);
$(this).find("span").stop().fadeTo('normal', 1, function() {
   $(this).parent().find("a.thumb").css({'background-position' : '0 0'});
}).show();

A: you want to add a callback to .show() and change background position after the show is completed like so
$(this).find("span").stop().fadeTo('normal', 1).show('slow', function() {
    $(this).find("a.thumb").css({'background-position' : '0 0'});
  });


text:
Q: Altering the appearance of cflayout tabs in CF9 I'm trying to overide the default appearance of cflayout tabs.
By putting an edited background sprite into the website images folder I can alter the hover appearance, but I cannot seem to get the text to turn white on hover by referencing the built in .x-tab-strip-over class.
In action here
    <style type="text/css">
    div.x-tab-panel-header, ul.x-tab-strip-top {
        background-image: none;
        background-color: transparent;
        padding-bottom: 0px;
    }
    div.x-tab-panel-header {
        border: 0px;
    }
    .x-tab-strip-active, .x-tab-strip-text {
        font-weight: normal !important;
        font-size: 14px !important;
        font-family: arial !important;
    }
    .x-tab-strip-over {
        color: white !important;
    }
    .x-tab-right, .x-tab-left, .x-tab-strip-inner {
        background-image: url(images/xd-tabs-sprite.gif) !important;
    }
</style>

<cflayout type="tab">
    <cflayoutarea title="Mouse">
        Mickey Mouse
    </cflayoutarea>
    <cflayoutarea title="Duck">
        Donald Duck
    </cflayoutarea>
</cflayout>

Any clues appreciated

A: CF9 uses ExtJS 3.x while Cf8 uses ExtJS 2.x

How to use:

*

*Click Ext Theme Builder.

*Select Template (blue or gray) in the top toolbar (i recommend - gray)

*Select Base Color, Header Color, Background color, Border color, Header
  Font, Font, Window transparency,
  Toolset (Default, Vista,
  TargetProcess, Graphite)  and ExtJS
  version. Unselected Border color will
  be assigned automatically according to
  base color

*Click Apply

*Enter Theme name

*Click Download Theme. It will be xtheme-Theme name.zip file

http://extbuilder.dynalias.com/springapp/mainpage.htm

A: Use:
.x-tab-panel-header .x-tab-strip-over span {
    color: white;
}
.x-tab-panel-header .x-tab-strip-over.x-tab-strip-active span {
    color: red;
}

There's a lot going on in there, so I just tested until I found something that worked.


text:
Q: Keyboard shortcut for Force Quitting the current application? Instead of pressing Command + Option + Esc to bring up the Force Quit menu, is there a way that I can force quit the application that I'm currently using directly?

A: Found it – the keyboard shortcut I was looking for was Command + Option + Shift + Esc. This will quit the frozen app as long as it's in focus.

A: Well, the Force Quit dialog opens with the currently running application already selected. So the shortcut is kind of Cmd-Opt-EscReturn (which IMHO is good enough for all practical purposes).


text:
Q: using enum inside a switch Can we use enum inside a switch?
public enum Color {
  RED,BLUE,YELLOW

}

 public class Use {
  Color c = Color.BLUE;

  public void test(){
      switch(c){
      case Color.BLUE:

      }
  }
}

I am getting some error in this.
The enum constant Color.BLUE reference cannot be qualified in a case label  Use.java        line 7  Java Problem

A: Write it like this:
public void test(){
  switch(c) {
  case BLUE:

  }
}

The enum label MUST NOT be qualified when used as a case label.  The grammar at JLS 14.11 says this:
SwitchLabel:
    case ConstantExpression :
    case EnumConstantName :
    default :

EnumConstantName:
    Identifier

Note that a simple identifier is require, not an identifier qualified by the enum name.
(I don't know why they designed the syntax like that.  Possibility it was to avoid some ambiguity in the grammar.  But either way, that's the way it is.)

A: case COLOR.BLUE:

    }

In the above code instead of COLOR.BLUE only write BLUE

E.G.
import java.awt.Color;

class ColorEnum {

    enum Color{BLUE,RED,YELLOW};

    public static void main(String[] args) {
        Color c = Color.BLUE;
        switch(c) {
            case BLUE:
                System.out.println("Blue!");
                break;
            case RED:
                System.out.println("Red!");
                break;
            case YELLOW:
                System.out.println("Yellow!");
                break;
            default:
                System.out.println("Logic error!");
        }
    }
}

A: Why use a switch at all? Rather just let the enum hold the Color information itself (encapsulate it) and thereby do all the dirty work. The advantage to this, is if you change your enum, you don't have to root through all code that uses it, changing all switch statements.  For instance:
import java.awt.Color;

public enum MyColor {
   RED("Red", Color.red), BLUE("Blue", Color.blue),
   YELLOW("Yellow", Color.yellow);

   private String text;
   private Color color;
   private MyColor(String text,Color color) {
      this.text = text;
      this.color = color;
   }

   public String getText() {
      return text;
   }

   public Color getColor() {
      return color;
   }

   @Override
   public String toString() {
      return text;
   }
}

and an example of how this can be used is as follows:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
class MyColorTest extends JPanel {
   private static final Dimension PREF_SIZE = new Dimension(400, 300);

   public MyColorTest() {
      for (final MyColor myColor : MyColor.values()) {
         add(new JButton(new AbstractAction(myColor.getText()) {
            @Override
            public void actionPerformed(ActionEvent arg0) {
               MyColorTest.this.setBackground(myColor.getColor());
            }
         }));

      }
   }

   @Override
   public Dimension getPreferredSize() {
      return PREF_SIZE;
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("MyColorTest");
      frame.getContentPane().add(new MyColorTest());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }

}

A: Yes, you can use enums in switch statements, but make sure not to use FQCN (fully-Qualified Class Name) in case labels.

Following is extracted from "enum constant reference cannot be qualified in a case label of switch statement"
In Short
When a Java switch statement uses an enum parameter; qualified names of the enum values should not be used in case labels, but only the unqualified names; then switch statement will consider all the labels are referring to the enum type that is used as the parameter.
Why only unqualified values?
If qualified references were allowed for case labels; there would be no means to restrict the enum type used in the labels to be same as the parameter type of switch statement.
public enum Status {
    REGISTERED,
    TERMINATED
}

public class TestStatus {
    public static String getMessage(Status status) {
        String message;
        switch (status) {
            // case Status.REGISTERED: // line 1
            case REGISTERED: // line 2
                message = "Welcome";
                break;
            default:
                message = "Good bye";
                break;
        }
    return message;
}

A: enum MyEnum{
    A,B,C

    MyEnum(){
        switch(this){
            case A:
                 //....
                 break;
            case B:
                 //....
                 break;
            case C:
                 //....
                 break;
        }
    }
}


text:
Q: How to use staticLib in my own staticLib? i try to create my own Library to use it in other projects in C/C++. my static library use the library xercesc. Eclipse try to compile the xercesc included lib with gcc and not g++. If i try to compile my code i got the following error:
    Info: Internal Builder is used for build
g++ "-IC:\\00_Projects\\Ladeplanberechnung\\LadeplanLib\\lib\\include" -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\viterbi\\ViterbiAlgorithm.o" "..\\src\\viterbi\\ViterbiAlgorithm.cpp"
In file included from ..\src\viterbi\LocalSuitability.h:11:0,
                 from ..\src\viterbi\ViterbiAlgorithm.h:8,
                 from ..\src\viterbi\ViterbiAlgorithm.cpp:8:
gcc "-IC:\\00_Projects\\Ladeplanberechnung\\LadeplanLib\\lib\\include" -O0 -g3 -Wall -c -fmessage-length=0 -o "lib\\include\\xercesc\\util\\RefArrayVectorOf.o" "..\\lib\\include\\xercesc\\util\\RefArrayVectorOf.c"
    ..\lib\include\xercesc\util\RefArrayVectorOf.c:25:1: error: unknown type name 'XERCES_CPP_NAMESPACE_BEGIN'
     XERCES_CPP_NAMESPACE_BEGIN
     ^~~~~~~~~~~~~~~~~~~~~~~~~~
    ..\lib\include\xercesc\util\RefArrayVectorOf.c:30:10: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
     template <class TElem>
              ^
    ..\lib\include\xercesc\util\RefArrayVectorOf.c:39:10: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
     template <class TElem> RefArrayVectorOf<TElem>::~RefArrayVectorOf()
              ^
    ..\lib\include\xercesc\util\RefArrayVectorOf.c:49:10: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
     template <class TElem> void
              ^
    ..\lib\include\xercesc\util\RefArrayVectorOf.c:61:10: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
     template <class TElem> void RefArrayVectorOf<TElem>::removeAllElements()
              ^
    ..\lib\include\xercesc\util\RefArrayVectorOf.c:74:10: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
     template <class TElem> void RefArrayVectorOf<TElem>::
              ^
    ..\lib\include\xercesc\util\RefArrayVectorOf.c:102:10: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
     template <class TElem> void RefArrayVectorOf<TElem>::removeLastElement()
              ^
    ..\lib\include\xercesc\util\RefArrayVectorOf.c:112:10: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
     template <class TElem> void RefArrayVectorOf<TElem>::cleanup()
              ^
    ..\lib\include\xercesc\util\RefArrayVectorOf.c:122:1: error: expected '=', ',', ';', 'asm' or '__attribute__' at end of input
     XERCES_CPP_NAMESPACE_END
     ^~~~~~~~~~~~~~~~~~~~~~~~

Why eclipse try to compile the xercesc?
Can i force eclipse to compile the project with g++.

A: You need to explicitly tell gcc that your source code is C++, as it will assume a file ending in .c is written in C. Add -x c++ to the command and it should work:
gcc "-IC:\\00_Projects\\Ladeplanberechnung\\LadeplanLib\\lib\\include" -O0 -g3 -Wall -c -fmessage-length=0 -x c++ -o "lib\\include\\xercesc\\util\\RefArrayVectorOf.o" "..\\lib\\include\\xercesc\\util\\RefArrayVectorOf.c"


text:
Q: How to access a field from a class? How can I access 'i' variable of AA class inside meth3()? I tried calling super.i but its just calling i variable of BB class.
public class SuperTest {

    public static void main(String[] args) {
        CC cc = new CC();
        cc.meth3();
    }
}

class AA {
    int i=10; // **I mean this variable to access somehow**
}

class BB extends AA{
    int i=20;

    void meth2(){
        System.out.println(super.i);
    }
}

class CC extends BB{
    int i=30;

    void meth3(){
        System.out.println(super.i);
    }
}

A: You can cast this to an AA to read the i from AA:
class CC extends BB {
    int i = 30;
    void meth3() {
        System.out.println(((AA) this).i);
    }
}

prints

10

A: public class Test {

    public static void main(String[] args) {

        CC cc = new CC();
        cc.meth3();

    }
}

class AA {

    int i = 10; // **I mean this variable to access somehow**
}

class BB extends AA {

    int j = 20;

}

class CC extends BB {

    int k = 30;

    void meth3() {
        System.out.println(i);
        System.out.println(j);
        System.out.println(k);

    }
}

Output
10
20
30

A: When a class extends another class, it inherits all non-private variables from the original class.
So, let's rewrite the BB class to be as the compiler might see it (I'm going to write pseudo code to illustrate a point):
class BB extends AA{

int i = 10;//inherited from AA

int i = 20;

}

Now normally, if we wrote a class with two variables that both share the same name (i in this case) we would get a compilation error. But in the case of an extending class, any variable that shares the same name as a variable inherited from the original class is overwritten. The original i from class AA gets overwritten by the i from Class BB. This is known as name shadowing or name hiding. See this more in depth explanation.
If you want to access the AA i variable from BB or from CC instances, you need to cast the object you are using to class AA.
Here is the test class you provided, rewritten to access the AA i variable as you asked:
public class Test {

    public static void main(String[] args) {

        CC cc = new CC();
        AA aa = (AA) cc;//cast the CC class instance to an AA instance

        aa.i;//equals 10
        cc.i;//equals 30

    }
}

A: You should learn about class object's between references.
anyway
Try this code
public class SuperTest {

    public static void main(String[] args) {

        CC cc = new CC();
        cc.meth3();

AA aa = new AA();
System.out.println(aa.getI());

    }

}

class AA {
    int i=10; // **I mean this variable to access somehow**
public int getI() {
   return this.i;
}

public void setI(int i) {
   this.i = i ;
}
}

class BB extends AA{
    int i=20;

    void meth2(){
        System.out.println(super.i);

    }
public int getI() {
   return this.i;
}

public void setI(int i) {
   this.i = i ;
}
}

class CC extends BB{
    int i=30;

    void meth3(){
        System.out.println(super.i);

    }

public int getI() {
   return this.i;
}

public void setI(int i) {
   this.i = i ;
}
}

A: The super keyword allows you to access the variables of immediate super class... to access the 'i' value of AA class you need to call meth2() in CC class... which will print the desired vaue...


text:
Q: java.sql.SQLException: TNS:listener does not currently know of SID given in connect descriptor I have read the articles Oracle 11g Express error: ORA-12505, TNS: listener does not currently know of SID given in connect descriptor and ORA-12505, TNS:listener does not currently know of SID given in connect descriptor? , but it did not help. Below is the code, I am using to connect with my D.B using Hibernate.

        IVAADMIN
    <property name="connection.password">-----</property>

    <property name="connection.url">jdbc:oracle:thin:@GCU13282.austin.hpicorp.net:1526:IVAHPIP</property>

    <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>

    <property name="myeclipse.connection.profile">ivaitaly_oracle_thin_driver</property>

    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

    <property name="hibernate.show_sql">true</property>

    <property name="query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>

I am not able to connect with the database with the credentials provided. But I am able to connect with the DB in sqldeveloper. The following exception occurs when I try to UP my application. But, earlier I was using different credentials for connecting to the OTHER D.B and it was working FINE.
NOTE: I have OracleXETNSListener and OracleserviceXE in running mode.
I am getting following exception.
Caused by: java.sql.SQLException: Listener refused the connection with the following error:
 TNS:listener does not currently know of SID given in connect descriptor
 The Connection descriptor used by the client was:
 GCU13282.austin.hpicorp.net:1526:IVAHPIP

A: I have replaced the following line of code
jdbc:oracle:thin:@//GCU13282.austin.hpicorp.net:1526/IVAHPIP just added two forward slash in front of host name and one forward slash ahead of the service name and its working FINE now.


text:
Q: is there a syntax to call named overload operator functions directly Trying to invert a map and the following approach works fine:
  var x = { 'dart' : 'fun', 'dentist' : 'painful', };
  var xInv = x.keys.fold({}, (prev, elm) { prev[x[elm]] = elm; return prev; });

Is there a syntax to call 'operator[]=( , )' directly so you could also use cascades? Something like these which do not work:
  var xInv = x.keys.fold({}, (prev, elm) => prev..'operator[]='(x[k], k));
  var xInv = x.keys.fold({}, (prev, elm) => prev..operator[]=(x[k], k));

A: This is not what you want?
Map<String,String> xInv2 = x.keys.fold({},
    (Map<String,String> prev, String elm) => prev..[x[elm]] = elm);

Creates the same result as your first example with the return statement.
(You don't have to add to add the type annotations though. It's just easier for me to grasp the intention of the code)


text:
Q: About noise in shaders
When I use    return fract(sin(dot(uv,vec2(18.13,98.16)))*19978.13); to create random.
Why is there such a clear boundary?

A: Assuming that the uv (vec2) values are continuous, I would guess that this is caused by the fract function. What it does is t-floor(t), but the floor function is not continuous. That in turn makes the fract a not continuous function too.
This kind of function seems to be discussed here.
The Perlin noise is a common source of pseudo randomness.


text:
Q: Using javadoc for Python documentation I am currently beginning with Python and I have a strong PHP background and in PHP I have took the habit of using javadoc as a documentation template.
I was wondering if javadoc has its place as docstring documentation in Python. What are the established conventions and/or official guildelines here?
E.g. is something like this too elaborate to fit in the Python mindset or should I try to be as concise as possible?
"""
replaces template place holder with values

@param string timestamp     formatted date to display
@param string priority      priority number
@param string priority_name priority name
@param string message       message to display

@return string formatted string
"""

And if I am a bit too exhaustive should I go with something like this instead (where most of the documentation doesn't get printed through the __doc__ method)?
# replaces template place holder with values
#
# @param string timestamp     formatted date to display
# @param string priority      priority number
# @param string priority_name priority name
# @param string message       message to display
#
# @return string formatted string

def format(self, timestamp = '', priority = '', priority_name = '', message = ''):
    """
    replaces template place holder with values
    """
    values = {'%timestamp%' : timestamp,
              '%priorityName%' : priority_name,
              '%priority%' : priority,
              '%message%' : message}

    return self.__pattern.format(**values)

A: Follow Google Python Style Guide. Note that Sphinx can also parse this format using the Napolean extension, which will come packaged with Sphinx 1.3 (this is also compatible with PEP257):
def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Args:
        arg1 (int): Description of arg1
        arg2 (str): Description of arg2

    Returns:
        bool: Description of return value

    """
    return True

Example taken from the Napolean documentation linked above.
A comprehensive example on all types of docstrings here.

A: The standard for python documentation strings is described in Python Enhancement Proposal 257.
The appropriate comment for your method would be something like
def format(...):
    """Return timestamp string with place holders replaced with values.

    Keyword arguments:
    timestamp     -- the format string (default '')
    priority      -- priority number (default '')
    priority_name -- priority name (default '')
    message       -- message to display (default '')
    """

A: Have a look at the reStructuredText (also known as "reST") format, which is a plaintext/docstring markup format, and probably the most popular in the Python world. And you should certainly look at Sphinx, a tool to generate documentation from reStructuredText (used for eg. the Python documentation itself). Sphinx includes the possibility to extract documentation from the docstrings in your code (see sphinx.ext.autodoc), and recognizes reST field lists following certain conventions. This has probably become (or is becoming) the most popular way to do it.
Your example could look as follows:
"""Replace template placeholder with values.

:param timestamp: formatted date to display
:param priority: priority number
:param priority_name: priority name
:param message: message to display
:returns: formatted string
"""

Or extended with type information:
"""Replace template placeholder with values.

:param timestamp: formatted date to display
:type timestamp: str or unicode
:param priority: priority number
:type priority: str or unicode
:param priority_name: priority name
:type priority_name: str or unicode
:param message: message to display
:type message: str or unicode
:returns: formatted string
:rtype: str or unicode
"""

A: Take a look at Documenting Python, a page "aimed at authors and potential authors of documentation for Python."
In short, reStructuredText is what's used for documenting Python itself. The developer's guide contains a reST primer, style guide, and general advice for writing good documentation.


text:
Q: How to prove terence tao proposition 9.3.9 Proposition 9.3.9.  Let $X$ be a subset of $\mathbb{R}$, let $f : X → R$  be a function, let $E$ be a subset of $X$, let $x_0$ be an adherent point of $E$, and let $L$ be a real number. Then the following two statements are logically equivalent:
(a) $f$ converges to $L$ at $x_0$ in $E$. (i.e $\forall \varepsilon > 0 \exists \delta > 0 s.t \forall x \in E $ and $|x_{0}-x|\leq \delta , |f(x)-L|\leq \varepsilon$)
(b) For every sequence $(a_{n})_{n=0}^{\infty}$ which consists entirely of elements of $E$ and converges to $x_0$, the sequence $(f(a_{n}))_{n=0}^{\infty}$ converges to $L$.
I am having difficulty proving (b) implies (a).
Thanks in advance.

A: Suppose $f(x) \not \to L $ when $x \to x_{0}$
Then there exists a $\varepsilon >0$ such that for every $\delta > 0$ there exists some $y \in E$ such that $|y- x_{0}| < \delta$ and $|f(y) - L| \geq \varepsilon$
If we take for each $n \in \mathbb{N}$, $\delta_{n} = \frac{1}{n} $, then we have that for every $n \in \mathbb{N}$ there exists $y_{n} \in E$ such that $|y_{n} - x_{0}| < \delta_{n} = \frac{1}{n}$ and $|f(y_{n}) - L| \geq \varepsilon$ for all $n \in \mathbb{N}$
But $|y_{n} - x_{0}| < \frac{1}{n} \implies |y_{n} - x_{0}| \to 0$ thus $y_{n} \to x_{0}$
But by hypotesis we have that $f(y_{n}) \to L$, then is a contradiction.


text:
Q: Search a type assigned to a 'var' in Visual Studio This is probably a wish, more than a question:
In  some part of the code I have used a function like this:
var myProperty = typeof(T).GetProperty(titulo);

I'd like to seach in Visual Studio any usage of the type 'PropertyInfo' (that is the internal type that takes var in this example).

A: It sounds like you are asking for a feature where Visual Studio will show you all occurrences of var which are inferred to be a specific type.  Unfortunately, this feature does not exist in Visual Studio.
Can you explain what you would do with this feature?  Perhaps there's a different way to get to a solution.


text:
Q: Access JNI Object to Java layer as reference pointer I'm writing an application where I have lot to do with JNI call and every-time I have to perform getter() call to access variable values. Instead is it possible to access Object reference of JNI object on Java Layer so can get updated variable value just by variable name (like obj.name instead obj.getName()).
I have check with this and this, but not getting way how to covert address to Object at java layer.
EDIT
I wanted to access Obj this way at Java layer from JNI.
private native CustomObj getCPPCustomObjectPointer();

Any suggestion here.

A:
Is it possible to access Object reference of JNI object on Java Layer?

Yes, you can. However you cannot use it for accessing its properties. You are only able to hold its address as a long value.
If you would like to do so, you should create your C++ objects in heap memory and return their addresses as long numbers.
MyClass *obj = new MyClass();
return (long) obj;

In Java side you can save that address as a long number wherever you want. Since objects have been created in heap memory, they will remain valid between JNI calls.
Also, you have to pass them to later JNI calls as a long number and then you should cast them to MyClass * in your C++ side.
MyClass *obj = (MyClass *)thatLongNumber;
obj->someProperty; // Access its properties and methods via -> operator

A: You want to retain a reference to a C++ object from your Java side? you can't.
Those implementations (C/Java) for representing and accessing objects/primitives are completely different.
That's why there's so much mambo jambo functions when you you cast from one data type to another.


text:
Q: Wrong Output: Wrapped Matrix Wrong Trying to get the matrices to wrap around itself using modulus.
def neighbors(inputArray, row, col):
    count = 0
    for x, y in ((row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1), (row - 1, col - 1), (row - 1, col + 1), (row + 1, col - 1), (row + 1, col + 1)):
        if not (0 <= x < len(inputArray) and 0 <= y < len(inputArray[x])):
            continue
        if inputArray[x][y] == "O":
            count += 1
    return count

Thank you!

A: '%' is the modulo operator in python. See the reference here.
For your code, the fix would be to remove the first if that is checking if the (x, y) is valid and just do
 if inputArray[x % len(inputArray)][y % len(inputArray[0])]:
     count += 1


text:
Q: Which is better, less crosstalk or less skew? I'm designing a board that has a LVDS 2.5V interface with 30 lanes clocked at 600MHz and DDR.  This is going from one chip to another chip which could be placed right next to it, there are no other placement constraints.  The interface spec is 300ps maximum skew.
If the two chips are placed as close as possible, the trace lengths are between 10mm and 20mm and the delays on the different lanes are matched to 60ps.
To get a better match, I think I need to add around an extra 30mm or more space between the chips.  The problem is that the lanes run quite close together; to meander them some sideways space has to be opened up first (which lengthens the outermost traces) and then the inner (shorter) traces can meander.  The traces would then be matched to something like 50mm +- 2mm.
Is it worth adding the extra 30mm and meanders to get a perfect timing match, or should I keep it simple and just use the short direct connections and accept 60ps skew?
I am mostly concerned that longer traces would allow more crosstalk, and also the trace impedances / manufacturing tolerances of the board become more important.  Also, doing meanders takes a bunch of time.
UPDATE There is also 50ps skew (known) due to package delays, and up to 50ps skew from the logic of the sender chip.  So the trace skew budget is only 200ps, accounting for all other sources I know of.

A: The period of 600 MHz is 1667 ps, so 60 ps skew is very small and will not be a problem. There is no need to length match beyond this.


text:
Q: Perl is there any way to determine whether a text string contains binary data Hi currently I'm on a project that needs to read some strings from a text file and fill these strings into an XML file. But in this file there are some lines containing binary data. Is there a way that I could check whether the string contains binary data?

A: In most cases the following regular expression may be adequate:
m{
    [^          # Consider the match a success if each of the following meta-characters do not match
        \w          # Match word
        \d          # Match digit
        \s          # Match whitespace
        [:punct:]   # Match punctuation
    ]
}x

In essence, the text must contain at least a (binary) character that does not match:

*

*\w - word

*\d - digit

*\s - space

*[[:punct:]] - punctuation

A: Perl has file tests operators for this: -T and -B. Note, however, that simply because a string is limited to a certain set of characters doesn't mean it's what we think text is. It still might be binary data to whatever generated it.


text:
Q: "Could not create SSL/TLS secure channel" Error while trying to add Https Service from Visual Studio I am trying to add Service Https Service Reference to Visual Studio.
The https://thelinkiamtrying.com/Service.svc link opens in browser without problem. But when I try to add it through Visual studio interface, (Add Service Reference) I get the following error:
"There was an error downloading 'https://thelinkiamtrying.com/Service.svc/databin/ListData.svc/$metadata'.
The request was aborted: Could not create SSL/TLS secure channel.
Metadata contains a reference that cannot be resolved: 'https://thelinkiamtrying.com/Service.svc'.
Could not establish secure channel for SSL/TLS with authority 'thelinkiamtrying.com'.
The request was aborted: Could not create SSL/TLS secure channel.
If the service is defined in the current solution, try building the solution and adding the service reference again.
What should I do to add this Service?
If you just show me that how can I call it without using the interface and from codebehind, that would help too.

A: I had the same problem and resolved this by using another version of Visual Studio. VS 2012 did not let me add service reference with the exact same error message, but VS 2015 added it with no errors. Then I was able to save the project and open it again in VS 2012.


text:
Q: Individualize MarkerSize for each point in series based on axis values c# I have a mschart (System.Windows.Forms.DataVisualization.Charting.Chart) control added to a windows form that I have configured to be a point chart (not fast point). I already know how to individualize the marker size of each point in a series via:
MyChart.Series[0].Points[0].MarkerSize = K;

But I have been unable to find out what this value is actually based on as it doesn't seem to be linear. What I would like to do, is to have some way of computing an effective marker size that would be a radius or diameter in relation to the x or y axis.
In other words, supposing I have a scatter chart whose x and y axis values go from -100 to 100 (say, in "meters") each and I want to add a circular point that will take up a radius of 5 meters on that scale, how would I go about doing this? For example that same point would appear visually smaller if I changed the scale to be -200 to 200. I have searched everywhere and could not find a definite answer.
Thanks in advance!

A: The marker size is in pixels. You can try this code (untested!):
static int CalcualteMarkerPixelSize(double diameterOnXAxis, Chart chart)
{
    double innerWidthScale = chart.ChartAreas[0].AxisX.Maximum - chart.ChartAreas[0].AxisX.Minimum;
    float innerWidthPct = chart.ChartAreas[0].InnerPlotPosition.Width / 100;
    float innerWidthPixels = chart.Width*innerWidthPct;
    return (int) (diameterOnXAxis/innerWidthScale*innerWidthPixels);
}


text:
Q: Pointer casting problem with struct array member I've run across this source in a legacy code base and I don't really know why exactly it behaves the way it does.
In the following code, the pData struct member either contains the data or a pointer to the real data in shared memory. The message is sent using IPC (msgsnd() and msgrcv()). Using the pointer casts (that are currently commented out), it fails using GCC 4.4.1 on an ARM target, the member uLen gets modified. When using memcpy() and everything works as expected. I can't really see what is wrong with the pointer casting. What is wrong here?
typedef struct {
    long mtype;
    unsigned short uRespQueue;
    unsigned short uID;
    unsigned short uLen;
    unsigned char pData[8000];
} message_t;

// changing the pointer in the struct
{
    unsigned char *pData = <some_pointer>;
#if 0
    *((unsigned int *)pMessage->pData) = (unsigned int)pData;
#else
    memcpy(pMessage->pData, &pData, sizeof(unsigned int));
#endif
}

// getting the pointer out
{
#if 0
    unsigned char *pData; (unsigned char *)(*((unsigned int *)pMessage->pData));
#else
    unsigned char *pData;
    memcpy(&pData, pMessage->pData, sizeof(int));
#endif
}

A: I suspect it's an alignment problem and either GCC or the processor is trying to compensate.  The structure is defined as:
typedef struct {
    long mtype;
    unsigned short uRespQueue;
    unsigned short uID;
    unsigned short uLen;
    unsigned char pData[8000];
} message_t;

Assuming normal alignment restrictions and a 32-bit processor, the offsets of each field are:
mtype         0   (alignment 4)
uRespQueue    4   (alignment 2)
uID           6   (alignment 2)
uLen          8   (alignment 2)
pData         10  (alignment 1)

On all but the most recent versions of the ARM processor, memory access must be aligned on the ARM processor and with the casting:
*((unsigned int *)pMessage->pData) = (unsigned int)pData;

you are attempting to write a 32-bit value on a misaligned address.  To correct the alignment, the address appears to have truncated the LSB's of the address to have the proper alignment.  Doing so happened to overlap with the uLen field causing the problem.
To be able to handle this correctly, you need to make sure that you write the value to a properly aligned address.  Either offset the pointer to align it or make sure pData is aligned to be able to handle 32-bit data.  I would redefine the structure to align the pData member for 32-bit access.
typedef struct {
    long mtype;
    unsigned short uRespQueue;
    unsigned short uID;
    unsigned short uLen;
    union { /* this will add 2-bytes of padding */
        unsigned char *pData;
        unsigned char  rgData[8000];
    };
} message_t;

The structure should still occupy the same amount of bytes since it has a 4-byte alignment due to the mtype field.
Then you should be able to access the pointer:
unsigned char *pData = ...;
/* setting the pointer */
pMessage->pData = pData;

/* getting the pointer */
pData = pMessage->pData;

A: That is a very nasty thing to do (the thing that's compiled out). You're trying basically to hack the code, and instead of using the data copy in the message (in the provided 8000 bytes for it), you try to put a pointer, and pass it through IPC.
The main issue is sharing memory between processes. Who knows what happens to that pointer after you send it? Who knows what happens to the data it points to? That's a very bad habbit to send out a pointer to data that is not under your control (i.e.: not protected/properly shared).
Another thing that might happen, and is probably what you're actually talking about, is the alignment. The array is of char's, the previous member in the struct is short, the compiler might attempt packing them. Recasting char[] to int * means that you take memory area and represent it as something else, without telling the compiler. You're stomping over the uLen by the cast.
memcopy is the proper way to do it.

A: The point here is the code "int header = (((int)(txUserPtr) - 4))"
Illustration of UserTypes  and struct pointer casting is great of help!
typedef union UserTypes
{
    SAUser           AUser;
    BUser            BUser;
    SCUser           CUser;
    SDUser           DUser;
} UserTypes;

typedef struct AUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } AUser;
typedef struct AUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } AUser;

typedef struct BUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } BUser;

typedef struct CUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } CUser;

typedef struct DUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } DUser;

//this is the function I want to test

void Fun(UserTypes * txUserPtr)
{

   int header = (*((int*)(txUserPtr) - 4));

   //the problem is here
   //how should i set incoming pointer "txUserPtr" so that
   //Fun() would skip following lines.
   // I don't want to execute error()

        if((header & 0xFF000000) != (int)0xAA000000)
        {
            error("sth error\n");
        }
   /*the following is the rest */
}


text:
Q: Pixel coordinates in Instance segmentation(YOLOv7) I would like to use instance.ipynb in YOLOv7(https://github.com/WongKinYiu/yolov7).
Is there any way to save segmentation area to a TXT file or CSV file?
I would like to get all the pixel coordinates (integers) of segmentation area, but I don't know how to do it.
Thank you in advance for your help.
import matplotlib.pyplot as plt
import torch
import cv2
import yaml
from torchvision import transforms
import numpy as np

from utils.datasets import letterbox
from utils.general import non_max_suppression_mask_conf

from detectron2.modeling.poolers import ROIPooler
from detectron2.structures import Boxes
from detectron2.utils.memory import retry_if_cuda_oom
from detectron2.layers import paste_masks_in_image
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
with open('data/hyp.scratch.mask.yaml') as f:
    hyp = yaml.load(f, Loader=yaml.FullLoader)
weigths = torch.load('yolov7-mask.pt')
model = weigths['model']
model = model.half().to(device)
_ = model.eval()
image = cv2.imread('./horses.jpg')  # 504x378 image
image = letterbox(image, 640, stride=64, auto=True)[0]
image_ = image.copy()
image = transforms.ToTensor()(image)
image = torch.tensor(np.array([image.numpy()]))
image = image.to(device)
image = image.half()

output = model(image)
inf_out, train_out, attn, mask_iou, bases, sem_output = output['test'], output['bbox_and_cls'], output['attn'], output['mask_iou'], output['bases'], output['sem']
bases = torch.cat([bases, sem_output], dim=1)
nb, _, height, width = image.shape
names = model.names
pooler_scale = model.pooler_scale
pooler = ROIPooler(output_size=hyp['mask_resolution'], scales=(pooler_scale,), sampling_ratio=1, pooler_type='ROIAlignV2', canonical_level=2)
output, output_mask, output_mask_score, output_ac, output_ab = non_max_suppression_mask_conf(inf_out, attn, bases, pooler, hyp, conf_thres=0.25, iou_thres=0.65, merge=False, mask_iou=None)
pred, pred_masks = output[0], output_mask[0]
base = bases[0]
bboxes = Boxes(pred[:, :4])
original_pred_masks = pred_masks.view(-1, hyp['mask_resolution'], hyp['mask_resolution'])
pred_masks = retry_if_cuda_oom(paste_masks_in_image)( original_pred_masks, bboxes, (height, width), threshold=0.5)
pred_masks_np = pred_masks.detach().cpu().numpy()
pred_cls = pred[:, 5].detach().cpu().numpy()
pred_conf = pred[:, 4].detach().cpu().numpy()
nimg = image[0].permute(1, 2, 0) * 255
nimg = nimg.cpu().numpy().astype(np.uint8)
nimg = cv2.cvtColor(nimg, cv2.COLOR_RGB2BGR)
nbboxes = bboxes.tensor.detach().cpu().numpy().astype(np.int)
pnimg = nimg.copy()
for one_mask, bbox, cls, conf in zip(pred_masks_np, nbboxes, pred_cls, pred_conf):
    if conf < 0.25:
        continue
    color = [np.random.randint(255), np.random.randint(255), np.random.randint(255)]

    pnimg[one_mask] = pnimg[one_mask] * 0.5 + np.array(color, dtype=np.uint8) * 0.5
    pnimg = cv2.rectangle(pnimg, (bbox[0], bbox[1]), (bbox[2], bbox[3]), color, 2)
    #label = '%s %.3f' % (names[int(cls)], conf)
    #t_size = cv2.getTextSize(label, 0, fontScale=0.5, thickness=1)[0]
    #c2 = bbox[0] + t_size[0], bbox[1] - t_size[1] - 3
    #pnimg = cv2.rectangle(pnimg, (bbox[0], bbox[1]), c2, color, -1, cv2.LINE_AA)  # filled
    #pnimg = cv2.putText(pnimg, label, (bbox[0], bbox[1] - 2), 0, 0.5, [255, 255, 255], thickness=1, lineType=cv2.LINE_AA)

# coco example
%matplotlib inline
plt.figure(figsize=(8,8))
plt.axis('off')
plt.imshow(pnimg)
plt.show()

A: You can use --save-txt to get all the regions of the segmented area while running from the command prompt. It will create a label file for that segmented image.
enter image description here


text:
Q: Determine the probability, Such that array A is sorted after applying exactly $N$ swap operations on array $A.$ You have an array $A$ of size $6$, which is a permutation of numbers $1 \dots 6$. Apply exactly $N$ operations on this array $A$.
In one operation:

*

*You choose two distinct numbers in array $A$ randomly and swap them.

Determine the probability, such that array $A$ is sorted after applying exactly $N$ described operations on array $A$.
Examples

*

*$N = 0$
$A = \{ 1, 2, 3, 4, 5, 6 \}$
After $0$ operations the array is sorted, hence the probability is $1$.

*$N = 1$
$A = \{ 2, 1, 3. 4, 5, 6 \}$
There are $15$ possible operations that can be applied on array $A$, out of which only $1$ operation (swap 1 and 2) yields a sorted array. Hence the required probability is $1 / 15$.

*$N = 5$
$A = \{ 1, 5, 4, 2, 3, 6 \}$
There are 759375 possible sets of 5 operations that can be applied on array A, out of which only 2848 sets of operations yield a sorted array. Hence the required probability is $2848 / 759375$.

My starting approach
The way I am approaching the solution is as follow
I think there is some kind of maths behind it because there are only 10 possible configurations of Array,
following numbers are the number of misplaced numbers

*

*0+2

*3+0

*4+0

*0+4

*2+2

*5+0

*3+2

*6+0

*0+6

*4+2

The right values indicate the number of numbers that have a pair that brings both numbers to their correct position after just one swap for example 2 1 3 4 5 6, here 1 and 2 can be swapped and after just one swap 1 and 2 will be at their correct positions and the array will become 1 2 3 4 5 6
The left values are the opposite of right values for example 2 3 1 4 5 6, here 1 2 3 belongs to the left numbers,
All of those 10 possible cases will have the same answers for each value for N, no matter which numbers are at wrong positions. for example Array 2 1 3 4 5 6 is going to have the same answer for all possible values of N as an array 1 2 4 3 5 6 because both arrays belong to 1st possibility which is 0+2 out of those 10 possible cases.
For example
$A = 2 1 3 4 5 6$
Answers for the given array is follow
$n = 1$ then $1/15$
$n = 3$ then $51/3375$
$n = 5$ then $4821/759375$
$n = 7$ then $679910/170859375$
for $n = 2, 4, 6, 8$ answer is $0$.
The total possible set of operations are $15^n$

A: This was a programming problem asked on HackerEarth. I will address it as a programming problem rather than a Mathematical one.
We have to write code that runs for the given input in under $1$ second.

You are given a permutation of $6$ elements and an integer $N$. Give the probability that the permutation will be sorted after exactly $N$ swaps.
$$1 \le N \le 100$$
If the probability is $\frac{P}{Q}$, where $P, Q$ are integers in the reduced form, print $P \cdot Q^{-1} \pmod {10^9 + 7}$

The general rule of thumb in any programming problem is that the computer can perform $10^7$ instructions per second and the time limit is usually $1$ second. Hence, any code we write must be able to obtain the answer in fewer than $10^7$ computer instructions.

Recurrence
Let $P(A, i)$ be the probability of sorting an array $A$ in exactly $i$ moves.
Let $A'$ be an array that we can obtain from $A$ in exactly one swap. In any array $A$, we can make $\binom{6}{2} = 15$ swaps.
$$P(A, i) = \frac{1}{\binom{6}{2}}\sum P(A', i - 1)$$

Explanation of the Recurrence
We know that the probability of an event is the  size of the the event set divided by the size of the total space set.
In order to know the probability of sorting an array $A$ in $i$ moves, we need to know the probability of sorting $A'$ in $i - 1$ moves, and then divide by the number of different arrays we can get in $1$ move.
For example, from ${1, 2, 3}$, we can transition to $3$ different arrays with swaps.

*

*$\{1, 2, 3\} \to \{2, 1, 3\}$

*$\{1, 2, 3\} \to \{3, 2, 1\}$

*$\{1, 2, 3\} \to \{2, 1, 3\}$
In order to know the probability of sorting $\{1, 2, 3\}$ in $x$ moves, we need to add the probability of sorting these $3$ arrays in $x - 1$ moves and divide by $3$
The probabability of sorting an array $\{1, 2, 3\}$ in $2$ moves is $$P(\{1, 2, 3\}, 2) = \frac{1}{3} \cdot \big( P(\{1, 3, 2\}, 1) + P(\{2, 1, 3\}, 1) + P(\{3, 2, 1\}, 1) \big)$$

Space and Time Complexity
Let us now try to estimate the time and space complexity.
How many states does this DP have ?
We have $6! = 720$ different arrays and $$N = 100$$ moves.
So, we will have $720 \times 100$ different states.
How many transitions are there in each state ?
Each state has $\binom{6}{2} = 15$ transitions.
The total number of steps is roughly $720 \times 100 \times 15 \approx 10^7$

C++ Code
Here is a function which computes the probability of sorting an array with $N$ random swaps.
For convenience, I have stored the array as a string.
I used Fermat's Little Theorem to compute the modular inverse of the denominator. $$x^{m - 1} = 1 \pmod m \implies x \cdot x^{m - 2} = 1 \pmod m$$
#include<bits/stdc++.h>
using namespace std;

const int MOD = 1e9 + 7, NO_OF_ELEMENTS = 6;
map <pair <string, int>, long long> probability;

long long power_mod(long long x, long long p, long long m)
{
    long long answer = 1;

    while(p > 0)
    {
        if(p%2 == 1)
        {
            answer = (answer*x)%m;
        }

        x = (x*x)%m;
        p = p >> 1;
    }

    return answer;
}

long long inverse(long long x, long long m)
{
    return power_mod(x, m - 2, m);
}

int is_sorted(string S)
{
    for(int i = 0; i + 1 < NO_OF_ELEMENTS; i++)
    {
        if(S[i] > S[i + 1])
        {
            return false;
        }
    }

    return true;
}

long long get_probability(string S, int no_of_moves)
{
    pair <string, int> current_state = make_pair(S, no_of_moves);
    if(probability.find(current_state) != probability.end())
    {
        return probability[current_state];
    }

    if(no_of_moves == 0)
    {
        probability[current_state] = (is_sorted(S) ? 1 : 0);
        return probability[current_state];
    }

    long long numerator = 0, new_arrays = 0;
    for(int i = 0; i < NO_OF_ELEMENTS; i++)
    {
        for(int j = i + 1; j < NO_OF_ELEMENTS; j++)
        {
            string new_S = S;
            swap(new_S[i], new_S[j]);

            numerator += get_probability(new_S, no_of_moves - 1);
            new_arrays++;
        }
    }

    probability[current_state] = numerator*inverse(new_arrays, MOD);
    probability[current_state] %= MOD;

    return probability[current_state];
}

void solve()
{
    int no_of_moves;
    cin >> no_of_moves;

    vector <int> A(NO_OF_ELEMENTS);
    for(int i = 0; i < NO_OF_ELEMENTS; i++)
    {
        cin >> A[i];
    }

    string S;
    for(int i = 0; i < NO_OF_ELEMENTS; i++)
    {
        S += A[i];
    }

    cout << get_probability(S, no_of_moves) << "\n";
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);

    int no_of_test_cases;
    cin >> no_of_test_cases;

    while(no_of_test_cases--)
        solve();

    return 0;
}


text:
Q: This is not a norm! Define $\,\nu (T) = \max\limits_{1\leqslant k\leqslant n}ks_k(T)$, where $(s_k)$ are the singular values of the matrix $T\in M_n$.
I'd like to show that $\nu$ it is not a norm.
I am trying to find a counterexample, but it doesn't work.

A: Consider $A=\big(\begin{smallmatrix}0&h\\1&0\end{smallmatrix}\big)$, having singular values $\big\{|h|,1\big\}$.
What are the singular values of $A+A^T$?
Can you arrange for $h$ such that subadditivity does not hold?
I.e. $\,\nu (A+A^T)\not\leq\nu(A) + \nu(A^T)$

A: You could take two non-commuting nilpotent matrices : their singular values are zero but because of the non-commutativity, the kernel of the sum might be chosen trivial.

A: Let's call your supposed norm $\nu$.
We want the triangle inequality to fail. Since $s_1(T)$ gives the operator norm, you are looking for a matrix $T$ such that $2s_2(T)>s_1(T)$. For instance
$$
T=\begin{bmatrix} 4&0\\0&4\end{bmatrix},
$$
where $\nu(T)=2s_2(T)=8$. We may write $T$ as the sum of two matrices:
$$
T=\begin{bmatrix} 3&0\\0&2\end{bmatrix}+\begin{bmatrix} 1&0\\0&2\end{bmatrix}.
$$
If we call $T_1,T_2$ the two matrices above, we have
$$
\nu(T)=8>4+2=\nu(T_1)+\nu(T_2).
$$


text:
Q: SQL table design for ISCO / International Standard Classification of Occupations I am trying to figure out what is the best way to insert International Standard Classification of Occupations into MySQL.
Here is detailed info about categories:
http://www.ilo.org/wcmsp5/groups/public/---dgreports/---dcomm/---publ/documents/publication/wcms_172572.pdf
Also I found a github project:
https://github.com/patriciomacadden/isco/blob/master/db/schema.rb
It seems to use separate tables per different levels of groups.
My current opinion is to make a single table and store some duplicate data since the data wont change often and amount of the data is less than thousand rows. For example:
'l1','l2','l3','l4' are 'TINYINT' and 'level','name' are VARCHAR. So 'level' is the primary key

l1  |l2  |l3  |l4  |level|name
----|----|----|----|-----|--------
5   |null|null|null|5    |Services and Sales Workers
5   |1   |null|null|51   |Personal Services Workers
5   |1   |1   |null|511  |Travel Attendants, Conductors Guides
5   |1   |1   |1   |5111 |Travel Attendants and Travel Stewards
5   |1   |1   |2   |5112 |Transport Conductors
5   |1   |1   |3   |5113 |Travel Guides

The 'level' field is varchar because I may need to get all rows including the top category.

WHERE level LIKE '511%'

I am not sure if it is better to have 'level' as int but perhaps varchar has better characteristics also when sorting this specific data.
I am not sure if I need the l1,l2,l3,l4 separately but with so few rows, it does not really hurt perhaps to have some redundancy.
So, the question is, do you see any obvious errors in my design? Would you be able to improve on this?
I am not sure if I need to beware of more fields because I did not finish reading that ISCO pdf yet...
Thanks

A: I would do

*

*level VARCHAR(4) CHARACTER SET ascii.  (A glance at the PDF seems to say that 4 is sufficient, but increase the "4" if necessary.)  VARCHAR will sort 'correctly', INT will not.

*SUBSTR(level, 3, 1) to get the equivalent of l3, if you need to display such.

*The SUBSTR will give you an empty string instead of NULL; you can use IF(,) or CASE... to render it whatever way you like.

A: You don't need both l1/l2/l3/l4 and level: these are completely redundant. Storing the same data in two different ways just creates the possibility that somewhere along the line a mistake will make them inconsistent, and then you get weird results. A query that use l1/2/3/4 finds different records than a query that uses level, and users are baffled why their results don't make sense. Like, if the data entry screen uses level and you have code to break it into l1/2/3/4, a user runs a query that under the table uses l1/2/3/4 and it finds zero matching records. Then he looks at the screen and the record is right there! Or worse, totals don't add up, etc.
It's hard to say which of the two to prefer. Most queries are probably easier to write with the single field: select blah blah where level='512', or select blah blah were level like '51%', rather then select blah blah where l1=5 and l2=1 and l3=2 and l4 is null, etc. Oh, and testing lower levels without referencing higher levels is probably meaningless. That is, when would you ever say select blah blah where l2=4 but not test l1?
Level should surely be a string and not an integer. You want '51' to sort before '512', not after. You would never do arithmetic on these, right? What would it mean to say chemist.level + teacher.level, or clerk.level * 3?


text:
Q: Intersection of quadrics Having two quadratic surfaces in the form of implicit equations, what is the simplest way to decide whether they intersect or not? Finding the intersection itself is not necessary.

A: This question is not totally precise, but I'll try to piece together an answer. First, you should decide whether or not your quadrics are projective. Also, you should be asking which field you are working over. For example
$$
\textbf{Proj}\left( \frac{\mathbb{R}[x,y,z,w]}{x^2 + y^2 + z^2 + w^2} \right)
$$
has no solutions, hence it's just the empty variety which cannot intersect any other quadrics in $\mathbb{P}^3(\mathbb{R})$. If you look in the characteristic $p$ setting, you may be able to construct a pair of quadrics which do not intersect (this could be an interesting problem to construct a pair).
If you are working over $\mathbb{C}$, you should expect an intersection. Consider the case of two quadric surfaces intersecting in $\mathbb{P}^3(\mathbb{C})$, presented as
$$
\textbf{Proj}\left( \frac{\mathbb{C}[x,y,z,w]}{(f(x,y,z,w),g(x,y,z,w))} \right)
$$
if we intersect with a hyperplane, for example $w=0$, we get the intersection of conics
$$
\textbf{Proj}\left( \frac{\mathbb{C}[x,y,z]}{(f(x,y,z,0),g(x,y,z,0))} \right)
$$
which intersects at four points (including multiplicity) by Bezout's theorem. So in this case you are forced to have intersections of your quadrics.


text:
Q: Getting and setting values to an array with Overloading the subscript operator "[ ]" won't work After really hard search for answers...
I tried fo(u)r hours to get and set values to an array with Overloading the subscript operator "[ ]" but can't figure out why it won't work.
What I'm tring to do here is to set someType value to an array member (On Main "darr1[i] = i*10.0" for example) with overloading the [] and with overloading the = and to get someType value from an array member  (On Main "<< darr1[i] << endl" for example) but can't figure out why just the overloading of: "Type & operator [] (int index)" is invoking.
My program doesn't get to the '=' overloading or to the second '[]' overloading at all..
here is my program (sorry for the long one):
#include <iostream>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

class  AO1Array
{

private:
int _size;

protected:
int top;
int *B;
int *C;

AO1Array(int n);
~AO1Array();
bool isRealValue(int index)
{
    if ((0 <= B[index] && B[index] < top) && (index == C[B[index]]))
        return true;
    return false;
};
};

AO1Array::AO1Array(int n)
{
_size = n;
top = 0;
B = new int[n];
C = new int[n];
}

AO1Array::~AO1Array()
{
delete[] B;
B = NULL;

delete[] C;
C = NULL;
}

template<class Type>
class GenericO1Array : AO1Array
{

public:
GenericO1Array(int size, Type initVal) : AO1Array(size)
{
        _initVal = initVal;
        Len = size;
        A = new Type[size];

}

~GenericO1Array()
{
        delete[] A;
        A = NULL;
}
int Length() { return Len; }
Type & operator [](int index) const
{
    if (AO1Array::isRealValue(index))
        return A[index];
    return _initVal;

}
Type & operator [] (int index)
{
    if (AO1Array::isRealValue(index))
        realValue = true;
    else
        realValue = false;
    return A[index];
}
Type operator =(Type value)
{
    if (realValue)
        A[lastIndex] = _initVal;
    else
    {
        AO1Array::C[top] = lastIndex;
        AO1Array::B[lastIndex] = AO1Array::top++;
        A[index] = value;
    }

    return *this;

}

private:
int Len;
int lastIndex;
bool realValue;
Type _initVal;
Type *A;
};

int main()
{
int n = 20;
GenericO1Array<double> darr1(n, 1.1);
GenericO1Array<long> iarr1(n, 2);
int i;
cout << "\nLength.darr1 = " << darr1.Length() << endl;
cout << "\nLength.iarr1 = " << iarr1.Length() << endl;

for (i = 0; i < n; i += 2)
{
    darr1[i] = i*10.0;
    iarr1[i] = i * 100;
} // for

cout << "\ndarr1 = " << endl;
for (i = 0; i < n; i++)
    cout << "darr1[" << i << "] = " << darr1[i] << endl;

cout << "\niarr1 = " << endl;
for (i = 0; i < n; i++)
    cout << "iarr1[" << i << "] = " << iarr1[i] << endl;
 } // main

A:
My program doesn't get to the '=' overloading

You are overloading the = assignment operator of Generic01Array itself, but nothing in your code is actually assigning values to your darr1 or iarr1 variables directly (there are no darr1 = ... or iarr = ... statements).  That is why your = operator is not being invoked.
If you want something to happen when the user assigns a value to an element of your array, you need to create a proxy class and overload its = assignment operator, then have your [] operator return an instance of that proxy:
template<class Type>
class GenericO1Array : AO1Array
{
public:
    class Proxy;
    friend Proxy;

    class Proxy
    {
    private:
      Generic01Array& _arr;
      int _index;
    public:
        Proxy(Generic01Array &arr, int index) : _arr(arr), _index(index) {}

        operator Type() const
        {
            if (_arr.isRealValue(index))
                _arr.realValue = true;
            else
                _arr.realValue = false;

            return _arr.A[_index];
        }

        Proxy& operator=(const Type &value)
        {
            if (_arr.realValue)
                _arr.A[_arr.lastindex] = _arr._initVal;
            else
            {
                _arr.C[_arr.top] = _arr.lastIndex;
                _arr.B[_arr.lastIndex] = _arr.top++;
                _arr.A[_index] = value;
            }

            return *this;
        }
    };

    ...

    Proxy operator [] (int index)
    {
        return Proxy(*this, index);
    }

    ...
};

or to the second '[]' overloading at all..

You have two overloads of the [] operator, one that is const and the other is not.  The const version of [] is breaking the const-ness of the operator by returning a non-const reference to the array's internal data.  It should be returning a non-reference const value instead:
const Type operator [](int index) const

The non-const version of the [] operator can return a reference:
Type& operator [](int index)

You are not calling the [] operator on any const instances of your Generic01Array class, so only the non-const version of your [] operator should be getting invoked.


text:
Q: Python pandas DataFrame selection rows and columns based on specific condition I have the following:
  cl1 cl2 cl3 .... cln
0  aaa bbb ccc .... nnn
1  bbb aaa ccc .... nnn
2  xxx xxx xxx .... xxx

Need to select rows, which columns' value(any of them).lower() == 'aaa'
So it is 0 and 1 rows and output shall be:
   cl1 cl2 cl3 .... cln
0  aaa bbb ccc .... nnn
1  bbb aaa ccc .... nnn

I tried many ways, but all of them requires columns names to be specified, but in my case I have no idea about columns names.
So basically something similar would work if I know column names:
df.loc[~df['something1'].str.lower().str.strip().isin(['something2'])]

A: IIUC you can use:
df[df.eq('aaa').any(axis=1)]

   cl1  cl2  cl3  cln
0  aaa  bbb  ccc  nnn
1  bbb  aaa  ccc  nnn

If lower() has to be taken to consideration:
df[df.apply(lambda x: x.str.lower()).eq('aaa').any(1)] #thanks Chris

Or:
df[df.applymap(str.lower).eq('aaa').any(axis=1)]

The second one is faster and the firstone can handle NaNs.


text:
Q: oauth2 implicit flow lacks consent screen I am playing around with oauth2 using auth0.  I that I am able to send simulate the implicit flow using a REST client.  My problem is that I am able to get the user details without a consent screen being popped up.  The flow is as follows
1. I send the username, password, and client Id.
2. Get the access token
3. Send the request asking for user information using the access token in step 2.  Here I get the response back with the user details, however there is no consent screen, popping up to the user to grant access.  Istn't this like a flaw?


text:
Q: Can you add partitions to a table in hsqldb? I've been searching around and haven't seen anything about creating a new or altering an existing table to add a partition by a column for hsqldb.  Is it even possible?
When I run my environment locally, I'm able to add a partition to a table using mysql. Unfortunately, my code fails when adding a partition in my test environment which runs on hsqldb.  I also see 0 information about partitioning for hsqldb.
Sample:
CREATE TABLE t1 ( id INT, year_col INT ) PARTITION BY RANGE (year_col) ( PARTITION p0 VALUES LESS THAN (1991), PARTITION p1 VALUES LESS THAN (1995), PARTITION p2 VALUES LESS THAN (1999) )

ALTER TABLE MY_TEST_TABLE ADD PARTITION (PARTITION PARTITION_1 VALUES LESS THAN (5000))

A: It appears that HSQLDB does not support partitioning as others have mentioned and there being no documentation of partitioning.


text:
Q: FreeBSD Installation I have followed all the installation steps, installation is done but when I reboot it's not loading the host that I have created FreeBSD.local. It's loading by default root host.

A: Configuration of the hostname is done by changing /etc/rc.conf.local.  A description of this file and an example of it that actually sets the name of the host is found in in section 12.4.1. Managing System-Specific Configuration of the FreeBSD Handbook:

hostname="node1.example.org"

See also the rc.conf(5) manual on FreeBSD which further explains the /etc/rc.conf.local file and the hostname variable therein.

A: In addition to the time-honored method of editing /etc/rc.conf or /etc/rc.conf.local, recent versions of FreeBSD offer the sysrc utility to streamline workflows that require tweaks to the rc.conf subsystem.
For example, if the hostname you want to use is FreeBSD.local then as root, the command:
sysrc hostname=FreeBSD.local

will do that.  That hostname will be set upon the next reboot.
If you would like the hostname setting to take effect immediately, then you should additionally issue the following command, again as root:
hostname FreeBSD.local


text:
Q: tcpdump suppress console output in script & write to file In a bash script I need to run a tcpdump command and save the output to a file however when I do that via > /tmp/test.txt i still get the following output in the console:
tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 1500 bytes
1 packet captured
1 packet received by filter
0 packets dropped by kernel

However I do wnat the script to wait for the command to complete before continuing.
is it possible to supress this output?

A: The output you're seeing is written to stderr, not stdout, so you can redirect it to /dev/null if you don't want to see it.  For example:
 tcpdump -nn -v -i eth0 -s 1500 -c 1 'ether proto 0x88cc' > /tmp/test.txt 2> /dev/null


text:
Q: Remote desktop to a host I only know the mac address of I want to use Windows Remote Desktop to connect to a PC on my local network; I actually connect to a router which forwards to the PC.
Unfortunately I don't know the IP address of the router: my DHCP has no option to force IP addresses. I can look up the IP with eg arp -a, but I would like to have this automated (so my wife can use it...). Is this possible?
More info on setup:

*

*My pc: 192.168.123.5

*My router: 192.168.123.10 (for instance, but it changes) / 10.10.1.1

*PC I want to connect to : 10.10.1.2

I would like to have some alias that always points at the 192.168.123.x IP that my router gets.

A: It really sounds like you're trying to come up with ways, however painful, to cope with problems caused by a misconfigured router.
Most people run into problems like this because they added a second router to their network to provide connectivity to devices in another part of the house, but they didn't configure the extra router correctly for that role. When putting in a second router like that, you need to configure it to simply be a transparent bridge between the existing LAN and the wireless clients. Unfortunately, a lot of folks don't know how to do this or don't take the time to find out, so they leave it set up as a full NAT gateway router as if it was at the head of the network. This setup causes your home network to be split into two separate LANs and makes it tricky for devices on one side of the extra router to reach devices on the other side of the extra router.
In 99.99% of home networks, the only correct place for a NAT gateway router is at the head of the network (integrated into the same box as the broadband modem, or as the only device connected to the LAN port of the "modem-only" broadband modem). On any other routers you add to your network, you should disable NAT service and DHCP service. If you secondary router doesn't give you an option to disable these features, you can set the DHCP IP address lease pool to zero length, and then be sure to connect a LAN port (not the WAN port) of the secondary router to a LAN port of the primary router.
If it turns out that you're one of the 0.001% that has a truly good reason to be doing double-NAT (running a NAT gateway service on more than one router on your network), then this won't be the right Answer for you. But I still wanted to post this Answer for the 99.99% of people that might find this page when their real problem is that they shouldn't be running double NAT.


text:
Q: Laurent Series of $f(z) = \frac{(z+1)^2}{z(z^3+1)}$ about $z = 0$? This is supposed to be a non-calculator question, so I managed to get this far;

*

*$ z^3 + 1 = (z + 1)(z^2 - 1 +1)$ , by polynomial division.

*Therefore, $ f(z) = \frac{z+1}{z(z^2-z+1)} = (1 + \frac{1}{z})(z^2-z+1)^{-1}$
Now at this stage, my thinking is that I need to expand the second term into partial fractions. But it gets terribly messy. My other mode of thought is to just do this...

*

*$ \frac{1}{z^3+1} = \sum(-1)^{n}(z)^{3n}$
And to continue simply on from there. But I am unsure which way is the right way?

A: You have$$\frac1{1+z^3}=1-z^3+z^6-z^9+\cdots$$if $|z|<1$. So,$$\frac z{1+z^3}=z-z^4+z^7-z^{10}+\cdots$$(again, if $|z|<1$) and therefore$$\frac{z+1}{z^3+1}=1+z-z^3-z^4+z^6+z^7-\cdots$$It follows from this that\begin{align}\frac{(z+1)^2}{z^3+1}&=\frac{z+1}{z^3+1}(z+1)\\&=(1+z-z^3-z^4+z^6+z^7-\cdots)(1+z)\\&=(1+z-z^3-z^4+z^6+z^7-\cdots)+(z+z^2-z^4-z^5+z^7+z^8-\cdots)\\&=1+2 z+z^2-z^3-2 z^4-z^5+z^6+2z^7+\\&\qquad+z^8-z^9-2
z^{10}-z^{11}+z^{12}+2 z^{13}+\cdots\end{align}So, the Laurent series that you are after is$$\frac1z+2+z-z^2-2z^3-z^4+z^5+2z^6+z^7-z^8-2z^9-z^{10}+z^{11}+2z^{12}+\cdots$$


text:
Q: Unable to get data at first click in android webview with server communication I am calling this method from JavaScript.
For the first time, it is giving null. But from the second time onwards, the data is coming.
Please help me.
@SuppressLint("JavascriptInterface")
public String loadClickedData() {

    pDialog = ProgressDialog.show(this, "dialog title",
            "dialog message", true);
    new HttpAsyncTaskClickedData()
            .execute("http://192.168.0.9/btrepo/btrepo/android_api.php");
    return bdb.getmPosIdData();
}

Here we are getting data through AsyncTask in Android:
private class HttpAsyncTaskClickedData extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("tag", "get_pos_details"));
        nameValuePairs.add(new BasicNameValuePair("pos_id", posId));
        return GET(urls[0], nameValuePairs);
    }

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        // Toast.makeText(getApplicationContext(), result+" in post ",
        // Toast.LENGTH_LONG).show();
        pDialog.dismiss();
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
                .show();
        bdb.setmPosIdData(result);

    }
}

This method is for getting data from the server:
public static String GET(String url, List<NameValuePair> pair) {
    InputStream inputStream = null;
    String result = "";
    try {

        // create HttpClient
        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(pair));

        HttpResponse httpResponse = httpClient.execute(httpPost);

        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();
        is = inputStream;
        // convert inputstream to string
        if (inputStream != null) {
            // jObj = convertIsToJson(inputStream);
            result = convertIsToJson(inputStream) + " ";
            // jSonStr = result;
        } else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
}

I am getting data from the server in json string format.
It is displaying attributes with null value like {pos["posid":null, "storeName":null]} etc..

A: In the following function
public String loadClickedData() {

    pDialog = ProgressDialog.show(this, "dialog title",
            "dialog message", true);
    new HttpAsyncTaskClickedData()
            .execute("http://192.168.0.9/btrepo/btrepo/android_api.php");
    return bdb.getmPosIdData();
}

You execute your HttpAsyncTaskClickedData(), and return bdb.getmPosIdData() immediately. (Which will always be an issue for the 1st time)
The result of the AsyncTask is only available in onPostExecute, where you call bdb.setmPosIdData(result);.
@Override
protected void onPostExecute(String result) {
    // ...
    bdb.setmPosIdData(result); // result is only stored in bdb here!
}

The HttpAsyncTaskClickedData runs in the background, and possibly takes some time.
That is why your first call is always unable to get data, as you returned bdb.getmPosIdData() immediately after executing your AsyncTask.

A: private class HttpAsyncTaskClickedData extends
            AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs
                    .add(new BasicNameValuePair("tag", "get_pos_details"));
            nameValuePairs.add(new BasicNameValuePair("pos_id", posId));
            return GET(urls[0], nameValuePairs);
        }

        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            // Toast.makeText(getApplicationContext(), result+" in post ",
            // Toast.LENGTH_LONG).show();
            data = result;
            pDialog.dismiss();
            bdb.setmPosIdData(result);

        }

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
            pDialog = ProgressDialog.show(MainActivity.this, "dialog title",
                    "dialog message", true);
        }
         @SuppressLint("JavascriptInterface")
         public String loadData() {
         Toast.makeText(getApplicationContext(), data+ " hi ",
         Toast.LENGTH_LONG).show();
         return data;
        }
    }

and calling loadData() method from javascript.

A: This function is for get data by using post url in javascript
 function jsonPost(){
    var http = new XMLHttpRequest();
    var url = "http://192.168.0.9/btrepo/btrepo/android_api.php";
var params = "tag=fav_stores&mobile=984989874";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
  alert("hello "+http.send(params));

    }


text:
Q: PL/SQL Mutating Trigger - alternative ideas? The code below is meant to trigger when a new record is inserted and is meant to change the new record's field but I get a mutating error when trying to insert. What can I do to fix this?
CREATE OR REPLACE TRIGGER trig_auto_rating_desc
AFTER INSERT ON reviews
FOR EACH ROW

DECLARE
    vn_rating NUMBER(1);
    vc_rating_description reviews.rating_description%TYPE := '';

BEGIN
    vn_rating := :NEW.overall_rating;
    CASE vn_rating
        WHEN 1 THEN vc_rating_description := 'VERY POOR';
        WHEN 2 THEN vc_rating_description := 'POOR';
        WHEN 3 THEN vc_rating_description :='OKAY';
        WHEN 4 THEN vc_rating_description := 'GOOD';
        WHEN 5 THEN vc_rating_description := 'VERY GOOD';
        ELSE dbms_output.put_line('NO SUCH REVIEW');
    END CASE;

    dbms_output.put_line(vn_rating || ' = ' || vc_rating_description);
    UPDATE reviews SET rating_description = vc_rating_description WHERE review_id = :NEW.review_id;

END trig_auto_rating_desc;
/

A: A mutating table occurs when a statement causes a trigger to fire and that trigger references the table that caused the trigger. The best way to avoid such problems is to not use triggers or you may try below:

*

*Changed the trigger to an after trigger.

*Changed it from a row level trigger to a statement level trigger.

*Convert to a Compound Trigger.

*Made the trigger autonomous with a commit in it.

A: You don't need to do an update within the trigger if you are modifying the values on a row by row basis.
Just run your case then
CREATE OR REPLACE TRIGGER trig_auto_rating_desc
BEFORE INSERT
ON REVIEWS
REFERENCING NEW AS New OLD AS Old
FOR EACH ROW

DECLARE
    vn_rating NUMBER(1);
    vc_rating_description reviews.rating_description%TYPE := '';

BEGIN
    vn_rating := :NEW.overall_rating;
    CASE vn_rating
        WHEN 1 THEN vc_rating_description := 'VERY POOR';
        WHEN 2 THEN vc_rating_description := 'POOR';
        WHEN 3 THEN vc_rating_description :='OKAY';
        WHEN 4 THEN vc_rating_description := 'GOOD';
        WHEN 5 THEN vc_rating_description := 'VERY GOOD';
        ELSE vc_rating_description := 'Invalid value';
        --you will never see dbms_output from a trigger
        --ELSE dbms_output.put_line('NO SUCH REVIEW');
    END CASE;
    :new.rating_description := vc_rating_description;

END trig_auto_rating_desc;


text:
Q: How to use a angular variable as a parameter in JavaScript function I'm trying to use an angular variable as a JavaScript parameters like this:
 <li ng-repeat="link in Links">
    <button data-icon="gear" data-role="button" data-iconpos="right" type="button" id="bitrate_btn_{{ link.Code }}" class="bitrate_btn btn" onClick="play_live_ind({{link.Code}});">
        {{ link.Title }} ( {{ link.Bitrate }} Kbps )
    </button>
 </li>

As you can see I'm calling a method called play_live_ind like this:
play_live_ind({{link.Code}});

It's not working, as the page loads it exactly prints
play_live_ind({{link.Code}});
How can I pass the value of link to this JavaScript function?
This is a jw-player function that I can't rewrite it in angular because it has many function call on itself. So I need to call this function in javascript
So I just need a solution to pass the angular variable value to the Javascript function

A: Use ng-click instead of onClick, and define play_live_ind in your $scope.
//html
ng-click="play_live_ind(link.Code)";

//js
$scope.play_live_ind = function(inputs) {
                          // function body
                       }


text:
Q: R - importing a file using read.xlsx2 appends a 0 the end of certain cells When I read in an .xlsx file with a cell format of 0.00#, the resulting value that is imported is 0.00#0 (eg, if I read in an excel file with one cell with a value of "0.006", the corresponding data frame is a one cell value of "0.0060", formatted as a factor). I need to keep this as a factor.
Everything else I've tried does not have this problem. 0.111 for eg does not get read in as 0.1110, 0.1 is not read in as 0.10, etc.
It does not appear to be a "hidden" 0 in Excel, or anything to do with formatting in Excel, but I could be wrong.

A: num <- c("0.0040", "0.0130", "1.200", "0.001")
num2 <- c("0.0060", "0.1020", "0.0080", "0.0090")
df <- data.frame(x = as.factor(num), y = as.factor(num2))
df
       x      y
1 0.0040 0.0060
2 0.0130 0.1020
3  1.200 0.0080
4  0.001 0.0090

nozeroes <- function(df) {
  erased <- Map(function(x) gsub('0+$', '', x), df)
  as.data.frame(erased)
}
nozeroes(df)
      x     y
1 0.004 0.006
2 0.013 0.102
3   1.2 0.008
4 0.001 0.009

Update
Since you now asked for a different number format:
#new data
num <- c("0.0040", "0.0130", "1.200", "0.001", "10")
num2 <- c("0.0060", "0.1020", "0.0080", "0.0090", "10")
df2 <- data.frame(x = as.factor(num), y = as.factor(num2))

nozeroes2 <- function(df) {
  erased <- Map(function(x) gsub('(^0.*)0+$', '\\1', x), df)
  as.data.frame(erased)
}
nozeroes2(df2)
      x     y
1 0.004 0.006
2 0.013 0.102
3 1.200 0.008
4 0.001 0.009
5    10    10

In the future, be advised that you will get the help that you ask for and not wider case solutions that are not mentioned.


text:
Q: Android Studio 3.1.1 not working fine Recently I have installed latest android studio 3.1.1 and created new Kotlin demo project but its not working fine. When I open it some aapt2.exe command window open. Please check below screenshot.

Also when I close android studio its hang and not close. I have to force close it via Task Manager.
I have also try it with java code but nothing is worked.

A: *

*Uninstall Android studio ->

*Delete .android folder ->

*Clear temp files ->

*fix registry error using CCleaner or as you prefer ->

*Restart system ->

*Reinstall ->

*Restart system.

That worked and working fine for me now.
Update :  Check whether SDK and android studio version are same. In case of mismatch it may not work.


text:
Q: How to update data for all users with a button on rails? I have my index view with some code :
So i have my User model. Each user has a column "readyy".
If its = 0, so I display "Ready", = 1 "not ready", =2 "Unconfirmed"
Each user can edit its own state, and admins can edit all users state one by one.
But how can I display a button (only for admin with my "current_user.admin?" method) that set the readyy cell to 2 (to set all users "unconfirmed") for all users ? Like, all in the same time.
NowI have to click one by one to set the readyy state to 2, it's not convenient.
Here is my view erb :
<% @user.each do |u| %>

<div class="<% if u.readyy == 2 %>unconfirmed <% end %> <% if u.readyy == 1 %>ready<% end %> <% if u.readyy == 0 %> not_ready<% end %>">

<%= u.name %>

<% if current_user %>
<% if current_user.id == u.id || current_user.admin? %>

<%= form_with(model: u) do |form| %>

<%= form.submit 'UPDATE STATE' %>

<% if current_user.admin? %>

<%= form.select :readyy, @readyyy # @readyyy = {  unconfirmed: 2, ready: 1, not_ready: 0 } %>

<% else %>

<%= form.select :readyy, @readyy #@readyy = {  ready: 1, not_ready: 0 } %>

<%end %>

<%end %>
<%end %>
<%end %>
<%end %>

A: I would suggest that you look at the aasm gem for state management: https://github.com/aasm/aasm. This should work :
markup:
<%= button_to "Unconfirm users", unconfirm_all_users, method: :patch %>

routes:
resources :users do
  patch :unconfirm_all, on: :collection
end

controller:
class UsersController < ApplicationController
  def unconfirm_all
    User.update_all(ready: 2)
    redirect_to users_path
  end
end


text:
Q: How to stop macOS updates from taking over the rEFInd boot manager? I have rEFInd installed on the EFI partition of my 2015 MacBook Air. Every time I update macOS, it ends up taking over the bootloader and resetting it to using the macOS operating system. Afterwards, if I hold the option key while booting up my mac, there is no boot option for rEFInd that I can select. The only way I can bring rEFInd back is to boot up into recovery mode, manually mount my system partition with Disk Utility (as it is encrypted using FileVault), then open Terminal and reinstall rEFInd. It's quite a hassle.
Is there any better way to handle macOS updates?
I have read the section of the rEFInd manual named "Recovering from a Coup Using MacOS" but I didn't find any information in there that was pertinent to my situation. Note that I cannot disable System Integrity Protection (which one of the solutions there requires) as I need to keep it enabled for the software development I do on this system.
Below is the output from the command diskutil list disk0.
/dev/disk0 (internal, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *121.3 GB   disk0
   1:                        EFI EFI                     209.7 MB   disk0s1
   2:                 Apple_APFS Container disk1         121.1 GB   disk0s2

I have Windows, Linux, and macOS 10.15 beta installed to an external drive, so my MacBook's internal drive just has macOS.

A: By default, rEFInd is installed in the EFI partition. Another option is to install rEFInd in a new small "Mac OS Extended (Journaled)" volume. This will allow rEFInd to appear in the Startup Manager.
Below are the steps. The commands need to be entered into a Terminal application window.

*

*Create the new volume. The diskutil command, shrinks the APFS container (121100M, i.e. 121.1 GB) by 300 MB (120800M) and creates the new 300 MB "Mac OS Extended (Journaled)" volume labeled "Macintosh HD via rEFInd".
sudo diskutil ap resizeContainer disk1 120800M JHFS+ "rEFInd" 0

After the command completes, restart the Mac.

Note:  If you get an error message which includes the phrase "perhaps caused by APFS Snapshot usage by Time Machine", then see Neil's own answer to the question: Can't resize APFS Container: Not enough free space in Container due to APFS limits or tidemarks.

*Download the rEFInd Boot Manager software from this SourceForge web site. Enter the following commands to install the software to the "Macintosh HD via rEFInd" volume.
cd ~/Downloads/refind-bin-0.11.4
./refind-install --ownhfs /dev/disk0s3

Note: The error message Could not set boot device property: 0xe00002bc was expected and can be ignored.

*(Optional) Use the command below to navigate to the folder containing the refind.conf file.
cd "/Volumes/rEFInd/System/Library/CoreServices"

Add write permissions to the CoreServices folder and the refind.conf file.
sudo  chmod  a+w  .  refind.conf

*Restart the Mac and immediately hold down the option key until the Startup Manager icons appears. Next, hold down the control key and select to boot from the rEFInd volume.


text:
Q: List of Students Click and Redirect to page React I've a list of students as a navbar (it's not meant to be a navbar, just  a list), and want to click on a student link, and be redirected to the student page only, with no list of students visible.
Click on student => Redirected to Pupil.jsx with student's name, and no list of students showing. Same if it were a list of blogs e.g. click on blog => Redirected to Blog.jsx
I've tried with const history = useHistory() and ``history.push(/pupil/${student}}`. All it did was change the URL, but not redirect nor render the Pupil.jsx page.
I'd be grateful for any help.
What I have is
Home
Contact

Students
 o Levi
 o Mikasa
 o Eren

 This is Pupil Page
 Student: Eren

What I'd like is:
Home
Contact

This is Pupil Page
Student: Eren

My JSX files: StudentRoom, Home/Contact, Navbar, Pupil
StudentRoom.jsx
import React from "react";
import Pupil from "./Pupil";
import {Link, Switch, Route, BrowserRouter as Router, Redirect} from "react-router-dom";

const StudentRoom = props => {

    const students = ["eren", "levi", "mikasa", "armin", "erwin"];

    const studentPage = (student) => {

        console.log(student);
        console.log("Student page");
        setStudentName(student);

    }

    return (

            <Router>

            {students.map((student, i) => (

                    <React.Fragment key={i}>

                <Link to={`/pupil/${student}`} onClick={() => studentPage(student)}>

{student}

                </Link>
                </React.Fragment>

                )
              )}

                {students.map((student, i) => (

                    <React.Fragment key={i}>
                    <Redirect to={`/pupil/${student}`}/>
                    <Switch>
                    <Route exact path={`/pupil/${student}`}>
                        <Pupil name={student}/>
                    </Route>
                </Switch>
                        </React.Fragment>
                    )

                  )}
            </Router>

    );

};

export default StudentRoom;

Pupil.jsx
import React from "react";

const Pupil = (props) => {
    return (

Pupil page

Student: {props.name}

    );
};
export default Pupil;

Navbar.jsx
import React from "react";
import {Link, Switch, Route, BrowserRouter as Router} from "react-router-dom";
import Home from "../pages/Home";
import Contact from "../pages/Contact";
import StudentRoom from "../pages/StudentRoom";
import Pupil from "../pages/Pupil";

function Navbar(){

    return (

     <Router>

        <Link to="/">

Home

        </Link>

        <Link to="/contact">

Contact

        </Link>

          <Link to="/students">

Students

        </Link>

        <Switch>
            <Route exact path ="/" component={Home}/>
            <Route exact path ="/contact" component={Contact}/>

             <Route exact path ="/students" component={StudentRoom}/>
            <Route path="/pupil" component={Pupil}/>
        </Switch>
        </Router>

    );
};

export default Navbar;

Home.jsx and Contact.jsx are basically the same.
import React from "react";
const Home = props => {

    return (

This is the Home page

    );
};
export default Home;

A: Please do modify your StudentRoom.jsx and Pupil.jsx like this
StudentRoom.jsx
import React, { useState } from "react";
import Pupil from "./Pupil.jsx";
import {
  Link,
  Switch,
  Route,
  BrowserRouter as Router,
  Redirect,
} from "react-router-dom";

const StudentRoom = (props) => {
  const students = ["eren", "levi", "mikasa", "armin", "erwin"];

  const [student, setStudent] = useState(null);

  const studentPage = (student) => {
    console.log("Student page", student);
    setStudent(student);
  };

  return (

        <Router>
          {student ? (
            <Link to={`/`} onClick={() => setStudent(null)}> Go back </Link>
          ) : (
            students.map((student, i) => (
              <Link
                key={i}
                to={`/pupil/${student}`}
                onClick={() => studentPage(student)}
              >

{student}

              </Link>
            ))
          )}

          <Switch>
            <Route path={`/pupil/:name`} component={Pupil} />
          </Switch>
        </Router>

  );
};

export default StudentRoom;

Pupil.jsx
import React from "react";
import { useParams } from "react-router-dom";

const Pupil = (props) => {
  const { name } = useParams();
  return (

Pupil page

Student: {name}

  );
};
export default Pupil;


text:
Q: How can I calculate how many events are on a column for a calendar? I have x events with hour_start and hour_end. How can I find out which events intersect?

A: Two events a and b overlap if:

*

*a.hour_start is between b.hour_start and b.hour_end
and/or

*

*a.hour_end is between b.hour_start and b.hour_end


text:
Q: How to disable plane detection. Swift + ARKit I've seen plenty of tutorials and suggestions on plane detection but I haven't seen any on how to disable once enabled plane detection. I want to disable plane detection and detected planes after I put my nodes on them

A: At any point, you can reconfigure the ARKit Session. So, in swift,  you can do:
let configuration = ARWorldTrackingConfiguration();
//...any other configurations
configuration.planeDetection = [] //empty array (as opposed to .horizontal .vertical)
sceneview.session.run(configuration)

There's a good example of this running within the context of an app here where you can turn on/off Plane detection in the UI