问:
Find k'th smallest value in binary tree in C
I have been trying to follow algorithm provided here to find k'th smallest value in the binary tree. However, I'm not clear about searching the right subtree (is this the error in my code?).

For example, for the following tree: 9, 3, 6, 5, 8, 13, 14.

```<code>   9
  / \
 /   \
3    13
 \     \
  6    14
 / \
5   8
</code>```

The output I get is:

```<code>k = 0, returned 3
k = 1, returned 6     // should return 5
k = 2, returned -1    // should return 6
k = 3, returned -1    // should return 8
k = 4, returned 9
k = 5, returned -1    // should return 13
k = 6, returned -1    // should return 14
</code>```

In another example - 4, 3, 2, 5, 6 - the output is also partially correct and fails to locate all nodes in the right subtree.

```<code>    4
   / \
  3   5
 /     \
2       6

k = 0, returned 2
k = 1, returned 3
k = 2, returned 4
k = 3, returned -1    // should return 5
k = 4, returned -1    // should return 6
</code>```

Can someone please explain how to locate k'th smallest value in the right subtrees?

My code:

```<code>int length(Tree t) {
    if (t == NULL) {
        return 0;
    } else {
        return 1 + length(t->left) + length(t->right);
    }
}

int findSmallest(Tree t, int k) {

    if (t == NULL) {
        return -1;
    }

    if (k == length(t->left)) {
        return t->value;
    }

    if (k < length(t->left)) {
        return findSmallest(t->left, k);
    }

    if (k > length(t->left)) {
        return findSmallest(t->right, (k - length(t->left)));
    }

    return 0;

}
</code>```

答:
For short, we can get correct result by replacing single line in the function findSmallest

original code :

return findSmallest(t->right, (k - length(t->left)));
```
</li>
<li>corrected code :
<pre class="lang-c prettyprint-override"><code>return findSmallest(t->right, (k - length(t->left) - 1));
</code>```

In each round of findSmallest, the parameter k represents the remaining number of how many smaller nodes to be found.

The reason we put (k - length(t->left) - 1) here is because we have already found length(t->left) smaller nodes inside the sub-tree of t->left, and another one smaller node which is t itself. We need to find the rest number of smaller nodes inside the tree whose root node is t->right.

Note that the function length(t) returns the number of nodes inside the tree whose root node is t. It doesn't care if the value of the sub node is less than the value of root node or not.

The following describes what's behind it step by step :

Declare the data structure Tree
Since the question doesn't provide the whole code, I assume the data structure is like:

struct tree;
typedef struct tree {
    struct tree *left;
    struct tree *right;
    int value;
} Tree;
```
<p>Each node contains its value, and the pointers to its children.<br />
The left child is smaller than parent.<br />
The right child is larger than parent.</p>
</li>
<li><p>Create the tree structure<br />
For the simplicity, I just write a messy ugly function in order to insert new node into the binary tree.</p>
<pre class="lang-c prettyprint-override"><code>void addnode(Tree *parent, int value)
{
    Tree *node = malloc(sizeof(*node));

    node->left = NULL;
    node->right = NULL;
    node->value = value;

/* Recursive check until the new node can be the direct child of the parent node */
check:
    if (value < parent->value) { /* new node belongs to left sub-tree */
        if (parent->left) { /* sub-tree is not null, so dig into it */
            parent = parent->left;
            goto check;
        }
        parent->left = node;
    } else {
        if (parent->right) { /* sub-tree is not null, so dig into it */
            parent = parent->right;
            goto check;
        }
        parent->right = node;
    }
}
</code>```

Note that:

Any child node whose value is smaller than root node will locate in the left sub-tree of the root node.

Any child node whose value is larger than root node will locate in the right sub-tree of the root node.
In the main function, we just declare a root node, and add the other nodes in order :

int main()
{
    Tree root = {
        .left = NULL,
        .right = NULL,
        .value = 9,
    };

    addnode(&root, 3);
    addnode(&root, 6);
    addnode(&root, 5);
    addnode(&root, 8);
    addnode(&root, 13);
    addnode(&root, 14);
/* ... */
    return 0;
}
```
</li>
<li><p>Provide the <code>findSmallest</code> function<br />
Its subroutine, the <code>length</code> function, returns <strong>the number of nodes (including root node itself) belong to the specified tree</strong></p>
<pre class="lang-c prettyprint-override"><code>int length(Tree *t) {
    if (t == NULL) {
        return 0;
    } else {
        return 1 + length(t->left) + length(t->right);
    }
}
</code>```

Here, the parameter t is corrected to pointer type, so we can use -> to access member through pointer

And the final part, findSmallest function :

int findSmallest(Tree *t, int k) {
    if (t == NULL) { /* this case should not happen */
        return -1;
    }

    if (k == length(t->left)) {
        return t->value;
    }

    if (k < length(t->left)) {
        return findSmallest(t->left, k);
    }

    if (k > length(t->left)) {
        return findSmallest(t->right, (k - length(t->left) - 1));
    }

    return 0;
}
```
<p>The parameter <code>t</code> is also corrected to pointer type.<br />
<code>length(t->left)</code> represents the number of nodes whose <code>value</code> is less than <code>t->value</code>, because :</p>
<ul>
<li>The function <code>length(root)</code> returns the number of nodes in the whole tree whose root node is <code>root</code>.</li>
<li>In the tree of this question, all left sub(child) nodes are smaller than the root node.</li>
<li>In the tree of this question, all right sub(child) nodes are larger than the root node.</li>
</ul>
<p><strong>So, if <code>length(t->left)</code> is <code>0</code>, <code>t</code> is the smallest node inside the tree whose root node is <code>t</code>.</strong></p>
<p>The test function call is :</p>
<pre class="lang-c prettyprint-override"><code>int main() {
/* ... */
    for (int k = 0; k < 6; k++) {
        int ret = findSmallest(&root, k);
        printf("k = %d, returned %d\n", k, ret);
    }
    return 0;
}
</code>```
```<code>k = 0, returned 3
k = 1, returned 5
k = 2, returned 6
k = 3, returned 8
k = 4, returned 9
k = 5, returned 13
</code>```

Body:
I have been trying to follow algorithm provided here to find k'th smallest value in the binary tree. However, I'm not clear about searching the right subtree (is this the error in my code?).

For example, for the following tree: 9, 3, 6, 5, 8, 13, 14.

   9
  / \
 /   \
3    13
 \     \
  6    14
 / \
5   8

The output I get is:

k = 0, returned 3
k = 1, returned 6     // should return 5
k = 2, returned -1    // should return 6
k = 3, returned -1    // should return 8
k = 4, returned 9
k = 5, returned -1    // should return 13
k = 6, returned -1    // should return 14

In another example - 4, 3, 2, 5, 6 - the output is also partially correct and fails to locate all nodes in the right subtree.

    4
   / \
  3   5
 /     \
2       6

k = 0, returned 2
k = 1, returned 3
k = 2, returned 4
k = 3, returned -1    // should return 5
k = 4, returned -1    // should return 6

Can someone please explain how to locate k'th smallest value in the right subtrees?

My code:

int length(Tree t) {
    if (t == NULL) {
        return 0;
    } else {
        return 1 + length(t->left) + length(t->right);
    }
}

int findSmallest(Tree t, int k) {

    if (t == NULL) {
        return -1;
    }

    if (k == length(t->left)) {
        return t->value;
    }

    if (k < length(t->left)) {
        return findSmallest(t->left, k);
    }

    if (k > length(t->left)) {
        return findSmallest(t->right, (k - length(t->left)));
    }

    return 0;

}

Body:
For short, we can get correct result by replacing single line in the function findSmallest

original code :

return findSmallest(t->right, (k - length(t->left)));

corrected code :

return findSmallest(t->right, (k - length(t->left) - 1));

In each round of findSmallest, the parameter k represents the remaining number of how many smaller nodes to be found.

The reason we put (k - length(t->left) - 1) here is because we have already found length(t->left) smaller nodes inside the sub-tree of t->left, and another one smaller node which is t itself. We need to find the rest number of smaller nodes inside the tree whose root node is t->right.

Note that the function length(t) returns the number of nodes inside the tree whose root node is t. It doesn't care if the value of the sub node is less than the value of root node or not.

The following describes what's behind it step by step :

Declare the data structure Tree
Since the question doesn't provide the whole code, I assume the data structure is like:

struct tree;
typedef struct tree {
    struct tree *left;
    struct tree *right;
    int value;
} Tree;

Each node contains its value, and the pointers to its children.

The left child is smaller than parent.

The right child is larger than parent.

Create the tree structure

For the simplicity, I just write a messy ugly function in order to insert new node into the binary tree.

void addnode(Tree *parent, int value)
{
    Tree *node = malloc(sizeof(*node));

    node->left = NULL;
    node->right = NULL;
    node->value = value;

/* Recursive check until the new node can be the direct child of the parent node */
check:
    if (value < parent->value) { /* new node belongs to left sub-tree */
        if (parent->left) { /* sub-tree is not null, so dig into it */
            parent = parent->left;
            goto check;
        }
        parent->left = node;
    } else {
        if (parent->right) { /* sub-tree is not null, so dig into it */
            parent = parent->right;
            goto check;
        }
        parent->right = node;
    }
}

Note that:

Any child node whose value is smaller than root node will locate in the left sub-tree of the root node.

Any child node whose value is larger than root node will locate in the right sub-tree of the root node.
In the main function, we just declare a root node, and add the other nodes in order :

int main()
{
    Tree root = {
        .left = NULL,
        .right = NULL,
        .value = 9,
    };

    addnode(&root, 3);
    addnode(&root, 6);
    addnode(&root, 5);
    addnode(&root, 8);
    addnode(&root, 13);
    addnode(&root, 14);
/* ... */
    return 0;
}

Provide the findSmallest function

Its subroutine, the length function, returns the number of nodes (including root node itself) belong to the specified tree

int length(Tree *t) {
    if (t == NULL) {
        return 0;
    } else {
        return 1 + length(t->left) + length(t->right);
    }
}

Here, the parameter t is corrected to pointer type, so we can use -> to access member through pointer

And the final part, findSmallest function :

int findSmallest(Tree *t, int k) {
    if (t == NULL) { /* this case should not happen */
        return -1;
    }

    if (k == length(t->left)) {
        return t->value;
    }

    if (k < length(t->left)) {
        return findSmallest(t->left, k);
    }

    if (k > length(t->left)) {
        return findSmallest(t->right, (k - length(t->left) - 1));
    }

    return 0;
}

The parameter t is also corrected to pointer type.

length(t->left) represents the number of nodes whose value is less than t->value, because :

The function length(root) returns the number of nodes in the whole tree whose root node is root.

In the tree of this question, all left sub(child) nodes are smaller than the root node.

In the tree of this question, all right sub(child) nodes are larger than the root node.

So, if length(t->left) is 0, t is the smallest node inside the tree whose root node is t.

The test function call is :

int main() {
/* ... */
    for (int k = 0; k < 6; k++) {
        int ret = findSmallest(&root, k);
        printf("k = %d, returned %d\n", k, ret);
    }
    return 0;
}

k = 0, returned 3
k = 1, returned 5
k = 2, returned 6
k = 3, returned 8
k = 4, returned 9
k = 5, returned 13


来源: stackexchange

问:
Android authentication to google accounts passed on to Google App Engine
Before I dig into the details of implementing this particular design, I wanted some advice/validation on whether I was approaching it correctly. I have a beginners knowledge of Android, advanced beginner in Python, GAE, and OpenId.

Environment

Android application

Web Services built in Python on Google App Engine

User(s) with Google Account

Scenario

I want to enable sign-in capabilities in my Android application without writing my own authentication system in GAE. Within the app, the user should be able to play as a guest without the ability to save high scores. If a user would like to have his high scores saved, he would authenticate against his Google account on the Android device. At the end of the game, the authenticated users high score would be saved (associated with his Google Account) via the game's web services on Google App Engine. The user should also be able to sign-out and hand the device to a friend who could also log in, play a game, and save her high scores associated with her Google account.

Design

In the Android application, use OpenId for authentication whenever the user wishes to sign-in (using something along the lines of what Nick has posted here.

Grab the OpenId token from the cookie that is returned and associate it with the current user.

Make a web service call to the GAE services adding the token as a cookie and including the high score

The web service would authenticate that the token is valid

The web service would determine the unique Google accounts id associated with the token (don't know how to do this, but assuming there should be a means to do this) and lookup that unique id against a cross reference table to find the users in-game id (which was previously created during account setup)

Save the high score associated with the in-game id.

Allow logout so another user can login to the game with their Google Account and repeat above process

Thank you for your help

答: I would look at Google's OpenID instead of OAuth. OpenID is the protocol for a federated login. See Google's information on OpenID. </p>

ContentLicense: CC BY-SA 3.0


问:
how can I create a table in Vertica with receiving time?
I get weather telemetries from Kafka and insert it to Vertica.
I want to add to the vertica table a 'receive_time' type timestamp column and 'receive_date' type date column that indicate the exact time a telemetry was been inserted to the table.

this is my creation statement for example:

```<code>CREATE TABLE my_scheme.weather
(
    location_id int NOT NULL,
    humidity float,
    current_temp float,
    wind_speed float,
    wind_direction varchar(100),
    feels_like float,
    latitude float,
    longitude float,
    current_condition varchar(100)
);
</code>```

how to add 'receive_time' and 'receive_date' columns that get the time from the Vertica? it is even possible?

答:
You can use DEFAULT expression to set the default value of a column as sysdate.

```<code>CREATE TABLE my_scheme.weather
(
    location_id int NOT NULL,
    humidity float,
    current_temp float,
    wind_speed float,
    wind_direction varchar(100),
    feels_like float,
    latitude float,
    longitude float,
    current_condition varchar(100),
    receive_datetime TIMESTAMP DEFAULT sysdate
);
</code>```

For further read:
https://forum.vertica.com/discussion/240077/default-a-column-s-value

ContentLicense: CC BY-SA 4.0

Body:
I get weather telemetries from Kafka and insert it to Vertica.
I want to add to the vertica table a 'receive_time' type timestamp column and 'receive_date' type date column that indicate the exact time a telemetry was been inserted to the table.

this is my creation statement for example:

CREATE TABLE my_scheme.weather
(
    location_id int NOT NULL,
    humidity float,
    current_temp float,
    wind_speed float,
    wind_direction varchar(100),
    feels_like float,
    latitude float,
    longitude float,
    current_condition varchar(100)
);

how to add 'receive_time' and 'receive_date' columns that get the time from the Vertica? it is even possible?

Body:
You can use DEFAULT expression to set the default value of a column as sysdate.

CREATE TABLE my_scheme.weather
(
    location_id int NOT NULL,
    humidity float,
    current_temp float,
    wind_speed float,
    wind_direction varchar(100),
    feels_like float,
    latitude float,
    longitude float,
    current_condition varchar(100),
    receive_datetime TIMESTAMP DEFAULT sysdate
);

For further read:
https://forum.vertica.com/discussion/240077/default-a-column-s-value


问:
Multiple definition error of StringCchPrintfW when cross-compling with MinGW on Alpine linux
I'm cross-compiling opencascade on Alpine linux for windows with MinGW and run into a multiple definition linking error of StringCchPrintfW. I have managed to cross-compile and link this successfully without errors with Ubuntu linux, however I'm not sure how to debug this on Alpine, any ideas would be appreciated? The output is as follows:

```<code>Compiling test.exe

x86_64-w64-mingw32-g++ -O2 obj/geom_util.o-mingw obj/main.o-mingw
obj/util.o-mingw obj/error.o-mingw obj/geom.o-mingw obj/mesh.o-mingw
obj/shapemap.o-mingw obj/export.o-mingw obj/import.o-mingw
obj/gobj.o-mingw -L/usr/local/lib/opencascade-mingw -lTKSTEP
-lTKSTEP209 -lTKSTEPAttr -lTKSTEPBase -lTKIGES -lTKSTL -lTKXSBase
-lTKMesh -lTKOffset -lTKFillet -lTKBool -lTKBO -lTKShHealing -lTKPrim
-lTKTopAlgo -lTKGeomAlgo -lTKBRep -lTKGeomBase -lTKG3d -lTKG2d
-lTKMath -lTKernel -o test.exe -s -lws2_32 -lpsapi -static -lpthread

/usr/lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld:
/usr/lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingwex.a(lib64_libmingwex_a-strsafe.o):strsafe.c:(.text+0xbe3):
multiple definition of `StringCchPrintfW';
/usr/local/lib/opencascade-mingw/libTKernel.a(OSD_FileNode.cxx.o):OSD_FileNode.c:(.text$StringCchPrintfW[StringCchPrintfW]+0x0):
first defined here

collect2: error: ld returned 1 exit status
make: *** [Makefile:146: test.exe] Error 1
</code>```

答:
As the error says: StringCchPrintfW is defined in -lmingwex and then redefined in OSD_FileNode.c.

You should check why that is and see if you can remove the defenition from OSD_FileNode.c.

Or maybe you can get away with ignoring this using linker flag -Wl,-allow-multiple-definition to allow the build to continue.

Body:
I'm cross-compiling opencascade on Alpine linux for windows with MinGW and run into a multiple definition linking error of StringCchPrintfW. I have managed to cross-compile and link this successfully without errors with Ubuntu linux, however I'm not sure how to debug this on Alpine, any ideas would be appreciated? The output is as follows:

Compiling test.exe

x86_64-w64-mingw32-g++ -O2 obj/geom_util.o-mingw obj/main.o-mingw
obj/util.o-mingw obj/error.o-mingw obj/geom.o-mingw obj/mesh.o-mingw
obj/shapemap.o-mingw obj/export.o-mingw obj/import.o-mingw
obj/gobj.o-mingw -L/usr/local/lib/opencascade-mingw -lTKSTEP
-lTKSTEP209 -lTKSTEPAttr -lTKSTEPBase -lTKIGES -lTKSTL -lTKXSBase
-lTKMesh -lTKOffset -lTKFillet -lTKBool -lTKBO -lTKShHealing -lTKPrim
-lTKTopAlgo -lTKGeomAlgo -lTKBRep -lTKGeomBase -lTKG3d -lTKG2d
-lTKMath -lTKernel -o test.exe -s -lws2_32 -lpsapi -static -lpthread

/usr/lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld:
/usr/lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingwex.a(lib64_libmingwex_a-strsafe.o):strsafe.c:(.text+0xbe3):
multiple definition of `StringCchPrintfW';
/usr/local/lib/opencascade-mingw/libTKernel.a(OSD_FileNode.cxx.o):OSD_FileNode.c:(.text$StringCchPrintfW[StringCchPrintfW]+0x0):
first defined here

collect2: error: ld returned 1 exit status
make: *** [Makefile:146: test.exe] Error 1


问:
Permission denied: '/tmp/.tensorboard-info/pid-31318.info' when trying to access the tensorboard file after running tensorboard
After running my code which works totally fine, I run tensorboard via terminal with the command 'tensorboard --logdir /work/tensorboard_logs/GLN' I get this error :
PermissionError: [Error 13] Permission denied: '/tmp/.tensorboard-info/pid-31452.info'
I run the command whoami and I actually am the same user.
I checked here https://github.com/tensorflow/models/issues/2641 and tried some of the proposed solutions but still doesn't work for me.
PS: I am using jupyter notebook (my own environment) on the server of my school with my account</p>

答:
I also had the same issue.

This issue occurs because you do not have a permission to access /tmp/.tensorboard-info/ directory which already exists, but tensorboard want to access it.

Therefore,

The first solution is chaining the default temp path environmental variable ($TMPDIR) as commented above.

If you do not want to change $TMPDIR, the second one is to get the permission. If you can get superuser authority, then just give 777 permission.

```<code>sudo chmod 777 /tmp/.tensorboard-info
</code>```

If you do not get superuser authority, then change tensorboard code.
In tensorboard-installed directory (probably [PYTHON_INSTALLED_DIR]/lib/python3.7/site-packages/tensorboard )

Please edit ".tensorboard-info" to ".tensorboard-info_custom" in  _get_info_dir() function in manager.py

```<code>def _get_info_dir():
  """Get path to directory in which to store info files.

  The directory returned by this function is "owned" by this module. If
  the contents of the directory are modified other than via the public
  functions of this module, subsequent behavior is undefined.

  The directory will be created if it does not exist.
  """
  # Change this part  .tensorboard-info->.tensorboard-info_custom
  path = os.path.join(tempfile.gettempdir(), ".tensorboard-info_custom")
  try:
    os.makedirs(path)
  except OSError as e:
    if e.errno == errno.EEXIST and os.path.isdir(path):
      pass
    else:
      raise
  else:
    os.chmod(path, 0o777)
  return path

</code>```

Body:
I also had the same issue.

This issue occurs because you do not have a permission to access /tmp/.tensorboard-info/ directory which already exists, but tensorboard want to access it.

Therefore,

The first solution is chaining the default temp path environmental variable ($TMPDIR) as commented above.

If you do not want to change $TMPDIR, the second one is to get the permission. If you can get superuser authority, then just give 777 permission.

sudo chmod 777 /tmp/.tensorboard-info

If you do not get superuser authority, then change tensorboard code.
In tensorboard-installed directory (probably [PYTHON_INSTALLED_DIR]/lib/python3.7/site-packages/tensorboard )

Please edit ".tensorboard-info" to ".tensorboard-info_custom" in  _get_info_dir() function in manager.py

def _get_info_dir():
  """Get path to directory in which to store info files.

  The directory returned by this function is "owned" by this module. If
  the contents of the directory are modified other than via the public
  functions of this module, subsequent behavior is undefined.

  The directory will be created if it does not exist.
  """
  # Change this part  .tensorboard-info->.tensorboard-info_custom
  path = os.path.join(tempfile.gettempdir(), ".tensorboard-info_custom")
  try:
    os.makedirs(path)
  except OSError as e:
    if e.errno == errno.EEXIST and os.path.isdir(path):
      pass
    else:
      raise
  else:
    os.chmod(path, 0o777)
  return path


问:
Image Replacement Script (jQuery)
I'm building an employee bios page where the client wants selected thumbnails to display in color at full opacity and all others at lower opacity in black and white. Which wouldn't be hard - the trouble is, every thumbnail has to have a color state and a black and white state. So my next thought was to swap out the black and white image (which would be resting within the div with a color background image) on mouseover.

```<code>$('.thumbnail').mouseenter(function(){
    var current = $(this); // cache thing
    var thishtml = current.html(); // get contents of thing
    current.html('').mouseleave(function(){ //empty the thing
        current.html(thishtml); //put the variable back in the thing
        });
});
</code>```

My HTML would be as follows:

```<code><div class = "thumbnail" style = "background-image: url(color.jpg);">
<img src="blackandwhite.jpg" />
</div>
</code>```

Obviously, since I'm asking the question, my idea didn't work. The mouseover removes the innerHTML, and the variable is converted successfully, but it doesn't get inserted into the DIV again. What am I missing?

答:
Instead of swapping HTML use css.

CSS:

```<code>.hidden {
     visibility:hidden
}
</code>```

JS:

```<code>$(".thumbnail").hover(
  function () {
    $(this).find('img').addClass('hidden')
  },
  function () {
    $(this).find('img').removeClass('hidden')
  }
);
</code>```

Title: Image Replacement Script (jQuery)

Body:
I'm building an employee bios page where the client wants selected thumbnails to display in color at full opacity and all others at lower opacity in black and white. Which wouldn't be hard - the trouble is, every thumbnail has to have a color state and a black and white state. So my next thought was to swap out the black and white image (which would be resting within the div with a color background image) on mouseover.

$('.thumbnail').mouseenter(function(){
    var current = $(this); // cache thing
    var thishtml = current.html(); // get contents of thing
    current.html('').mouseleave(function(){ //empty the thing
        current.html(thishtml); //put the variable back in the thing
        });
});

My HTML would be as follows:

Obviously, since I'm asking the question, my idea didn't work. The mouseover removes the innerHTML, and the variable is converted successfully, but it doesn't get inserted into the DIV again. What am I missing?

Body:
Instead of swapping HTML use css.

CSS:

.hidden {
     visibility:hidden
}

JS:

$(".thumbnail").hover(
  function () {
    $(this).find('img').addClass('hidden')
  },
  function () {
    $(this).find('img').removeClass('hidden')
  }
);


问:
Asking for input again with do while loop in c
I am trying to have the user type in a number between 1 and 8 to print out stuff on screen (height), if the number is lower than 1 or higher than 8 I would like for the program to prompt again for an input instead of it quitting out and say "invalid". I know I have to set it up with do on top and when on the bottom in C, my question is how would I go about it when I have 2 possible outcomes, i.e. too low or too high?</p>
```<code>do {
    int height = get_int(Height: ");
    if (height < 1)
        ~ ~printf("invalid");
    else if (height > 8)
        ~ ~printf("invalid");
} when(???????)

printf("valid")
</code>```

答:
A simple way of checking if the user has made an invalid choice would be to use a simple Boolean variable and set it to "false" when an invalid choice is made.

I have modified your own example code to include what I mean here:

```<code>bool valid = true;
do {
  valid = true; //reset valid to true at the beginning of the loop, otherwise it will remain false when the loop runs again
  int height = get_int("Height: ");
  if (height < 1)
    valid = false; //set valid to false when an invalid choice is made
  else if (height > 8)
    valid = false; //set valid to false when an invalid choice is made
} while (!valid) //if valid is not true ( or ==false), repeat. If valid is true or not equal to false, don't repeat and continue to the print statement below.

print("valid");
</code>```

Please note that I used the same get_int function you provided in your post. I am not aware of this function. For ways of reading integers (for example scanf) see other answers in this thread.

Body:
I am trying to have the user type in a number between 1 and 8 to print out stuff on screen (height), if the number is lower than 1 or higher than 8 I would like for the program to prompt again for an input instead of it quitting out and say "invalid". I know I have to set it up with do on top and when on the bottom in C, my question is how would I go about it when I have 2 possible outcomes, i.e. too low or too high?

do {
    int height = get_int(Height: ");
    if (height < 1)
        ~ ~printf("invalid");
    else if (height > 8)
        ~ ~printf("invalid");
} when(???????)

printf("valid")

Body:
A simple way of checking if the user has made an invalid choice would be to use a simple Boolean variable and set it to "false" when an invalid choice is made.

I have modified your own example code to include what I mean here:

bool valid = true;
do {
  valid = true; //reset valid to true at the beginning of the loop, otherwise it will remain false when the loop runs again
  int height = get_int("Height: ");
  if (height < 1)
    valid = false; //set valid to false when an invalid choice is made
  else if (height > 8)
    valid = false; //set valid to false when an invalid choice is made
} while (!valid) //if valid is not true ( or ==false), repeat. If valid is true or not equal to false, don't repeat and continue to the print statement below.

print("valid");

Please note that I used the same get_int function you provided in your post. I am not aware of this function. For ways of reading integers (for example scanf) see other answers in this thread.


问:
.NET Framework. How to get the text value from invisible column of datagridview?
My issue is very simple and it would be easy if I write my program on ASP.NET. But I apply .NET Framework 4.8 and I have no idea how to get the value from that datagridview if the column is hidden.

```<code>for (int i2 = 0; i2 < RowsAmount; i2++)
        {
            int er = Convert.ToInt32(dataGridView1.Rows[i2].Cells["id_contact"].Value.ToString());
            MessageBox.Show($"{er}");
            // to do smth with that value.
        }
</code>```

The column named as id_contact is hidden as you can guess. What should I do if the error is "object reference does not point to an instance of an object "?

答:
Recommend adding columns to your DataGridView, set DataPropertyName to the source whatever that may be (perhaps a DataTable or List). Set Visible property to false for in your case id_contact.

Setup a BindingList, BindingSource to your data source where the BindingSource becomes the data source of the DataGridView. To get an the invisible column access via the BindingList indexed by the BindingSource Position property.

Here the first column IdColumn (defined in the DataGridView designer) is hidden.

```<code>namespace DataGridViewSamples
{
    public partial class SampleForm : Form
    {
        public SampleForm() { InitializeComponent(); }
        private readonly BindingSource _bindingSource = new BindingSource();
        private BindingList<Item> _bindingList;

        private void SampleForm_Load(object sender, EventArgs e)
        {
            List<Item> items = new List<Item>()
            {
                new Item(){ Id = 1, Process = false, Product = "Phone 2"},
                new Item(){ Id = 2, Process = true, Product = "Phone 3"},
                new Item(){ Id = 3, Process = false, Product = "Phone 4"},,
            };

            _bindingList = new BindingList<Item>(items);
            _bindingSource.DataSource = _bindingList;
            dataGridView1.DataSource = _bindingSource;
        }
        private void CurrentIdButton_Click(object sender, EventArgs e)
        {
            if (_bindingSource.Current != null)
            {
                MessageBox.Show($"{_bindingList[_bindingSource.Position].Id}");
            }
        }
    }
    public class Item
    {
        public int Id { get; set; }
        public bool Process { get; set; }
        public string Product { get; set; }
    }
}
</code>```

Body:
My issue is very simple and it would be easy if I write my program on ASP.NET. But I apply .NET Framework 4.8 and I have no idea how to get the value from that datagridview if the column is hidden.

for (int i2 = 0; i2 < RowsAmount; i2++)
        {
            int er = Convert.ToInt32(dataGridView1.Rows[i2].Cells["id_contact"].Value.ToString());
            MessageBox.Show($"{er}");
            // to do smth with that value.
        }

The column named as id_contact is hidden as you can guess. What should I do if the error is "object reference does not point to an instance of an object "?

Body:
Recommend adding columns to your DataGridView, set DataPropertyName to the source whatever that may be (perhaps a DataTable or List). Set Visible property to false for in your case id_contact.

Setup a BindingList, BindingSource to your data source where the BindingSource becomes the data source of the DataGridView. To get an the invisible column access via the BindingList indexed by the BindingSource Position property.

Here the first column IdColumn (defined in the DataGridView designer) is hidden.

namespace DataGridViewSamples
{
    public partial class SampleForm : Form
    {
        public SampleForm() { InitializeComponent(); }
        private readonly BindingSource _bindingSource = new BindingSource();
        private BindingList<Item> _bindingList;

        private void SampleForm_Load(object sender, EventArgs e)
        {
            List<Item> items = new List<Item>()
            {
                new Item(){ Id = 1, Process = false, Product = "Phone 2"},
                new Item(){ Id = 2, Process = true, Product = "Phone 3"},
                new Item(){ Id = 3, Process = false, Product = "Phone 4"},,
            };

            _bindingList = new BindingList<Item>(items);
            _bindingSource.DataSource = _bindingList;
            dataGridView1.DataSource = _bindingSource;
        }
        private void CurrentIdButton_Click(object sender, EventArgs e)
        {
            if (_bindingSource.Current != null)
            {
                MessageBox.Show($"{_bindingList[_bindingSource.Position].Id}");
            }
        }
    }
    public class Item
    {
        public int Id { get; set; }
        public bool Process { get; set; }
        public string Product { get; set; }
    }
}


问:
React Native - updating UI when in a loop using functional component
I am developing a React Native app and I have a process whereby I want to put a progress center or progress bar in the UI as it runs.

I found this code in SO but I'm not sure how to implement in my functional component.

Could please give me an example of how to call ProgressBar from my func component and how to increase progress value.?

Thanks in advance.

```<code>const ProgressBar = (props)=>{

    const [value] = useState(new Animated.Value(props.value))

    useEffect(()=>{
        Animated.timing(value, {
            toValue: props.value,
            duration: 100,
        }).start()
    }, [props.value])

    const width = value.interpolate({
        inputRange: [0, 100],
        outputRange: ['0%', '100%'],
    })

    return (
        <View style={{
            width: '100%',
            height: '100%',
            flexDirection: 'row',
            backgroundColor: 'white',
        }}>
            <Animated.View style={{
                width: width,
                height: '100%',
                backgroundColor: 'green',
            }}></Animated.View>
        </View>
    )
}
</code>```

答:
Check a fully working example with progress value change.

import * as React from "react";
import { useEffect, useState } from "react";
import { Text, View, StyleSheet, Animated } from "react-native";
import Slider from "@react-native-community/slider";
import Constants from "expo-constants";

const ProgressBar = (props) => {
  const [value] = useState(new Animated.Value(props.value));

  useEffect(() => {
    Animated.timing(value, {
      toValue: props.value,
      duration: 100,
    }).start();
  }, [props.value]);

  const width = value.interpolate({
    inputRange: [0, 100],
    outputRange: ["0%", "100%"],
  });

  return (
    <View
      style={{
        width: "100%",
        height: "100%",
        flexDirection: "row",
        backgroundColor: "white",
      }}
    >
      <Animated.View
        style={{
          width: width,
          height: "100%",
          backgroundColor: "green",
        }}
      ></Animated.View>
    </View>
  );
};

export default function App() {
  const [progress, setProgress] = useState(10);

  return (
    <View style={styles.container}>
      <View style={{ paddingVertical: 20 }}>
        <Text> Change slider value to see progress bar follow </Text>{" "}
      </View>
      <View style={{ height: 20 }}>
        {" "}
        <ProgressBar value={progress} />{" "}
      </View>

      <View style={{ paddingVertical: 20 }}>
        <Slider
          minimumValue={0}
          maximumValue={100}
          onValueChange={setProgress}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingTop: Constants.statusBarHeight,
    backgroundColor: "#ecf0f1",
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: "bold",
    textAlign: "center",
  },
});
```
<p>Expo snack - https://snack.expo.dev/@emmbyiringiro/30efea</p>
``````

Body:
I am developing a React Native app and I have a process whereby I want to put a progress center or progress bar in the UI as it runs.

I found this code in SO but I'm not sure how to implement in my functional component.

Could please give me an example of how to call ProgressBar from my func component and how to increase progress value.?

Thanks in advance.

const ProgressBar = (props)=>{

    const [value] = useState(new Animated.Value(props.value))

    useEffect(()=>{
        Animated.timing(value, {
            toValue: props.value,
            duration: 100,
        }).start()
    }, [props.value])

    const width = value.interpolate({
        inputRange: [0, 100],
        outputRange: ['0%', '100%'],
    })

    return (
        <View style={{
            width: '100%',
            height: '100%',
            flexDirection: 'row',
            backgroundColor: 'white',
        }}>
            <Animated.View style={{
                width: width,
                height: '100%',
                backgroundColor: 'green',
            }}></Animated.View>
        </View>
    )
}

Body:
Check a fully working example with progress value change.

import * as React from "react";
import { useEffect, useState } from "react";
import { Text, View, StyleSheet, Animated } from "react-native";
import Slider from "@react-native-community/slider";
import Constants from "expo-constants";

const ProgressBar = (props) => {
  const [value] = useState(new Animated.Value(props.value));

  useEffect(() => {
    Animated.timing(value, {
      toValue: props.value,
      duration: 100,
    }).start();
  }, [props.value]);

  const width = value.interpolate({
    inputRange: [0, 100],
    outputRange: ["0%", "100%"],
  });

  return (
    <View
      style={{
        width: "100%",
        height: "100%",
        flexDirection: "row",
        backgroundColor: "white",
      }}
    >
      <Animated.View
        style={{
          width: width,
          height: "100%",
          backgroundColor: "green",
        }}
      ></Animated.View>
    </View>
  );
};

export default function App() {
  const [progress, setProgress] = useState(10);

  return (
    <View style={styles.container}>
      <View style={{ paddingVertical: 20 }}>
        <Text> Change slider value to see progress bar follow </Text>{" "}
      </View>
      <View style={{ height: 20 }}>
        {" "}
        <ProgressBar value={progress} />{" "}
      </View>

      <View style={{ paddingVertical: 20 }}>
        <Slider
          minimumValue={0}
          maximumValue={100}
          onValueChange={setProgress}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingTop: Constants.statusBarHeight,
    backgroundColor: "#ecf0f1",
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: "bold",
    textAlign: "center",
  },
});

Expo snack - https://snack.expo.dev/@emmbyiringiro/30efea


问:
How to add a condition to a for loop in Kotlin?
I know that in Java, it is possible to do the following:

```<code>boolean condition = true;

for(int i=0; i<array.length && condition; i++){

}
</code>```

If the condition is false, the for loop stops,
but, how to do the same in Kotlin?

答:
```<code>fun checkCondition(){
  val condition=true
  outerloop@for(i in array.indices) {
    if(array[i]!=condition){
      condition=false
      break@outerloop
    }
  }
  return condition
}
</code>```

Body:
I know that in Java, it is possible to do the following:

boolean condition = true;

for(int i=0; i<array.length && condition; i++){

}

If the condition is false, the for loop stops,
but, how to do the same in Kotlin?


问:
Calculate the transpose of a list python without using numpy
How to calculate the transpose of this without using numpy:</p>
```<code>t = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code>```

Body:
How to calculate the transpose of this without using numpy:

t = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Body:
Just do:

t = list(zip(*t))

Output:

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]


问:
Angular.js: TrackBy doesn't prevent full *ngFor-generated list refresh
I have code, which prints words of a simple sentence in an ul-list, so that you can remove any of the items and then insert it back:

  arr = ['hi', 'i', 'am', 'an' ,'item', 'too'].map(function (word) {
    return {value: word}
  });
  trackByFn (item : any) {
    return item.value;
  }

  removed   : any = null;
  removed_i : any = null;
  removeItem (i : number) {
    this.removed_i = i;
    this.removed = this.arr.splice(i, 1);
  }
  insert () {
    this.arr.splice(this.removed_i, 0, this.removed);
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
    <li *ngFor="let item of arr; let i = index; trackBy: trackByFn">
      {{item.value}}
      <button *ngIf="!removed" (click)="removeItem(i)">Remove</button>
    </li>
</ul>
<button *ngIf="removed" (click)="insert()">Insert</button></code>```

It resulted in 2 issues:

I tried to do it with trackBy feature. My trackByFn returns item.value as an "id" but still when list is re-rendered after invoking insert(...), there are always several li-s updated (checked via Browser Console)!

Moreover, the inserted item does not contain {{item.value}}, which is interpolated into it!

Please, can somebody explains what's going on?

UPDATE

I have changed trackBy-function and added a button with full_refresh() reaction.

<button (click)="full_refresh()">Random refresh</button>```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>full_refresh () {
    var prevSource = this.source, prevLength = prevSource.length;
    var source = this.source = new Array(prevLength);
    for (let i = 0; i < prevLength; i++)
      source[i] = {value: prevSource[i].value + prevSource[i].value};
  }

  trackBy (i : number, word : any) {
    return i; // UPDATE 3: corrected according to Siddhant's note
  }</code>```

So, now I have changed the trackBy-function (now it returns index with purpose) and added a full refresh button, each of which replaces both old array and array objects with entirely new ones. So, new array objects have nothing to do with the old ones, so == should return false. Then Angular is supposed to check trackBy-function, right? And trackBy-function returns array index, so each new object should be recognized as "identical" to the corresponding old object in array, right? But still I get complete refresh of the elements! And also, an error pops up in console:

Can't bind to 'ngForNgTrackBy' since it isn't a known property of 'li'.

UPDATE 2:

Just found out that function trackBy isn't called at all. When I add console.log(...) into it nothing gets logged when I commit full_refresh, which changes source, which is then printed as a list via ngFor.

Moreover, when I change function name like this (please, see ngTrackBy: trackByByeByeBye in the end of the ngFor statement), app gets compiled but in the console there appears the error: Can't bind to 'ngForNgTrackBy' since it isn't a known property of 'li'.

    {{word.value}}
    <button (click)="remove(i)">Remove</button>

```

ANSWER

Please, see the last comment to Saddhant's reply! It is there! :) Above you see the code, which's already been corrected! Enjoy your day! :)

答:
The reason {{item.value}} doesn't print the value after insert is because the value inserted is an array and not an object containing value property.

// splice returns an array of deleted elements
this.removed = this.arr.splice(i, 1);
// this.removed would be [{value: 'deletedValue'}]

// You can use this.removed[0] when inserting
this.arr1.splice(this.removed_i, 0, this.removed[0]);
// In case if this.removed contains multiple elements, you can use spread operator as ...this.removed
```
<p>In your example, using <code>trackBy</code> doesn't really help in any way and is not required as you are mutating the same array and playing around with same object references. Since object references within the array remain same, Angular automatically would be able to handle unnecessary re-creation of DOM nodes.</p>
<p>Also <code>trackByFn</code> written in your case won't work as expected, because the 1st argument passed to <code>trackByFn</code> is the index.</p>
<p>The proper way to write the function would be:</p>
<pre class="lang-ts prettyprint-override"><code>trackByFn (index: number, item : any) {
  return item.value;
}
</code>```

Edit: For the new issue added to the post

Since you are now creating a new array with new references, using trackBy will make sense in this scenario.

To your point of why the elements are getting refreshed?
You are using word.value within trackByFn and since you have changed the value within the new object, Angular will consider it as a new record and re-create the element.

// The 'value' which is being used in trackByFn is now changed
{value: prevSource[i].value + prevSource[i].value}
```

Body:
I have code, which prints words of a simple sentence in an ul-list, so that you can remove any of the items and then insert it back:

  arr = ['hi', 'i', 'am', 'an' ,'item', 'too'].map(function (word) {
    return {value: word}
  });
  trackByFn (item : any) {
    return item.value;
  }

  removed   : any = null;
  removed_i : any = null;
  removeItem (i : number) {
    this.removed_i = i;
    this.removed = this.arr.splice(i, 1);
  }
  insert () {
    this.arr.splice(this.removed_i, 0, this.removed);
  }

      {{item.value}}
      <button *ngIf="!removed" (click)="removeItem(i)">Remove</button>

<button *ngIf="removed" (click)="insert()">Insert</button>

It resulted in 2 issues:

I tried to do it with trackBy feature. My trackByFn returns item.value as an "id" but still when list is re-rendered after invoking insert(...), there are always several li-s updated (checked via Browser Console)!

Moreover, the inserted item does not contain {{item.value}}, which is interpolated into it!

Please, can somebody explains what's going on?

UPDATE

I have changed trackBy-function and added a button with full_refresh() reaction.

<button (click)="full_refresh()">Random refresh</button>

full_refresh () {
    var prevSource = this.source, prevLength = prevSource.length;
    var source = this.source = new Array(prevLength);
    for (let i = 0; i < prevLength; i++)
      source[i] = {value: prevSource[i].value + prevSource[i].value};
  }

  trackBy (i : number, word : any) {
    return i; // UPDATE 3: corrected according to Siddhant's note
  }

So, now I have changed the trackBy-function (now it returns index with purpose) and added a full refresh button, each of which replaces both old array and array objects with entirely new ones. So, new array objects have nothing to do with the old ones, so == should return false. Then Angular is supposed to check trackBy-function, right? And trackBy-function returns array index, so each new object should be recognized as "identical" to the corresponding old object in array, right? But still I get complete refresh of the elements! And also, an error pops up in console:

Can't bind to 'ngForNgTrackBy' since it isn't a known property of 'li'.

UPDATE 2:

Just found out that function trackBy isn't called at all. When I add console.log(...) into it nothing gets logged when I commit full_refresh, which changes source, which is then printed as a list via ngFor.

Moreover, when I change function name like this (please, see ngTrackBy: trackByByeByeBye in the end of the ngFor statement), app gets compiled but in the console there appears the error: Can't bind to 'ngForNgTrackBy' since it isn't a known property of 'li'.

    {{word.value}}
    <button (click)="remove(i)">Remove</button>

ANSWER

Please, see the last comment to Saddhant's reply! It is there! :) Above you see the code, which's already been corrected! Enjoy your day! :)

Body:
The reason {{item.value}} doesn't print the value after insert is because the value inserted is an array and not an object containing value property.

// splice returns an array of deleted elements
this.removed = this.arr.splice(i, 1);
// this.removed would be [{value: 'deletedValue'}]

// You can use this.removed[0] when inserting
this.arr1.splice(this.removed_i, 0, this.removed[0]);
// In case if this.removed contains multiple elements, you can use spread operator as ...this.removed

In your example, using trackBy doesn't really help in any way and is not required as you are mutating the same array and playing around with same object references. Since object references within the array remain same, Angular automatically would be able to handle unnecessary re-creation of DOM nodes.

Also trackByFn written in your case won't work as expected, because the 1st argument passed to trackByFn is the index.

The proper way to write the function would be:

trackByFn (index: number, item : any) {
  return item.value;
}

Edit: For the new issue added to the post

Since you are now creating a new array with new references, using trackBy will make sense in this scenario.

To your point of why the elements are getting refreshed?
You are using word.value within trackByFn and since you have changed the value within the new object, Angular will consider it as a new record and re-create the element.

// The 'value' which is being used in trackByFn is now changed
{value: prevSource[i].value + prevSource[i].value}


问:
favicon.ico not working on chrome, firefox. working on a few pages in IE
i have a favicon.ico in my webroot folder according to this piece of code

```<code><link rel="icon" href="<?php echo $this->webroot;?>favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="<?php echo $this->webroot;?>favicon.ico" type="image/x-icon" />
</code>```

and i use this in my header to make it appear on all the pages.

```<code><?php echo $html->meta('icon', 'favicon.ico'); ?>
</code>```

The site am working on is -----> this.

What can possibly be wrong ?
It works in 3 pages on IE. On firefox and chrome, it works only for homepage, not others.

Please let me know what i should do.

答:
If you tried everything above and it still doesn’t work in IE, check your IIS settings if you are using a Windows Server.
Make sure that the  HTTP Headers > “Enable content expiration” setting, IS NOT SET to “Expire immediately” </p>

ContentLicense: CC BY-SA 2.5

Body:
i have a favicon.ico in my webroot folder according to this piece of code

<link rel="icon" href="<?php echo $this->webroot;?>favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="<?php echo $this->webroot;?>favicon.ico" type="image/x-icon" />

and i use this in my header to make it appear on all the pages.

<?php echo $html->meta('icon', 'favicon.ico'); ?>

The site am working on is -----> this.

What can possibly be wrong ?
It works in 3 pages on IE. On firefox and chrome, it works only for homepage, not others.

Please let me know what i should do.


问:
Yarn requires Node.js 4.0 or higher to be installed. - Symfony - Docker - Yarn
I'm trying to install yarn in my symfony project, but did not succeed yet.

I installed nodejs and all needed requirements on windows. When I type node -v or yarn -v inside a windows cmd, it displays versions for the respective tools as expected.

But in my symfony project inside the container, it seems like the node and yarn commands can't be found.

Here is a screentshot of my Directory

When I type yarn -v or yarn install it gives the following error:

Yarn requires Node.js 4.0 or higher to be installed.

I don't know how to fix this error. Can someone point me in the right direction?

答:
Yarn requires Node.js 4.0 or higher to be installed.

Currently working on Windows 8.1 and first had this issue recently when working with Gatsby and also with Rails, this issue persisted even though everything was up to date, what worked for both instances was running the CMD Line in the project directory as Administrator, then running yarn commands.

Seems to only work in the CMD Line, this was just a hunch and it worked.

Sure there is a reference but couldn't find it in the Documentation to prove the above, if anyone in future comes across the Docs, kindly link it to this post.


问:
Top-level await and Import in Typescript
I'm studying Typescript and running into a problem. I want to use the import and top-level await but currently, I can only use one at a time.

Here is my config in tsconfig.json which allows me to use import

```<code>"target": "ESNext",
"module": "ESNext"
</code>```

And this one allows me to use top-level await:

```<code>"module":"commonjs"
</code>```

I added

```<code>"type":"module"
</code>```

to my package.json

Is there any way that I can take advantage of both features? Many thanks.

I'm using Nodejs 16 and Typescript 4.5.5

答:
Yes, you can use both. Here's info to help you reproduce a successful test:

Node.js (LTS) version:

```<code>$ node --version
v16.14.0
</code>```

./package.json:

{
  "name": "so-71099311",
  "version": "0.1.0",
  "private": true,
  "description": "",
  "type": "module",
  "scripts": {
    "compile": "tsc",
    "start": "npm run compile && node dist/main.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@types/node": "^17.0.17",
    "typescript": "^4.5.5"
  }
}

```
<hr />
<p><code>./tsconfig.json</code>:</p>
<pre class="lang-json prettyprint-override"><code>{
  "compilerOptions": {
    "esModuleInterop": true,
    "exactOptionalPropertyTypes": true,
    "isolatedModules": true,
    "lib": [
      "esnext"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noUncheckedIndexedAccess": true,
    "outDir": "dist",
    "strict": true,
    "target": "esnext",
    "useUnknownInCatchVariables": true
  },
  "include": [
    "./src/**/*"
  ]
}

</code>```

./src/module.ts:

export function greet (name = 'world'): void {
  console.log(`Hello ${name}`);
}

```
<hr />
<p><code>./src/main.ts</code>:</p>
<pre class="lang-ts prettyprint-override"><code>import {greet} from './module.js';

const name = await Promise.resolve('Nguyen');
greet(name);

</code>```

In your console:

```<code>$ cd /path/to/the/directory/where/you/created/these/files
$ npm install
$ npm run start
</code>```
```<code>> so-71099311@0.1.0 start
> npm run compile && node dist/main.js

> so-71099311@0.1.0 compile
> tsc

Hello Nguyen
</code>```

Body:
I'm studying Typescript and running into a problem. I want to use the import and top-level await but currently, I can only use one at a time.

Here is my config in tsconfig.json which allows me to use import

"target": "ESNext",
"module": "ESNext"

And this one allows me to use top-level await:

"module":"commonjs"

I added

"type":"module"

to my package.json

Is there any way that I can take advantage of both features? Many thanks.

I'm using Nodejs 16 and Typescript 4.5.5

Body:
Yes, you can use both. Here's info to help you reproduce a successful test:

Node.js (LTS) version:

$ node --version
v16.14.0

./package.json:

{
  "name": "so-71099311",
  "version": "0.1.0",
  "private": true,
  "description": "",
  "type": "module",
  "scripts": {
    "compile": "tsc",
    "start": "npm run compile && node dist/main.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@types/node": "^17.0.17",
    "typescript": "^4.5.5"
  }
}

./tsconfig.json:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "exactOptionalPropertyTypes": true,
    "isolatedModules": true,
    "lib": [
      "esnext"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noUncheckedIndexedAccess": true,
    "outDir": "dist",
    "strict": true,
    "target": "esnext",
    "useUnknownInCatchVariables": true
  },
  "include": [
    "./src/**/*"
  ]
}

./src/module.ts:

export function greet (name = 'world'): void {
  console.log(`Hello ${name}`);
}

./src/main.ts:

import {greet} from './module.js';

const name = await Promise.resolve('Nguyen');
greet(name);

In your console:

$ cd /path/to/the/directory/where/you/created/these/files
$ npm install
$ npm run start

> so-71099311@0.1.0 start
> npm run compile && node dist/main.js

> so-71099311@0.1.0 compile
> tsc

Hello Nguyen


问:
Showing particular row data as column
My table is as follows:

Date
Code
Price
MA5
MA20

2022-01-01
APPLE
1000
1080
1090

2022-01-02
APPLE
1100
1084
1100

2022-01-03
APPLE
1200
1090
1100

2022-01-01
MICROSOFT
7
9
10

2022-01-02
MICROSOFT
7.5
8
9.5

2022-01-03
MICROSOFT
8
8.5
9

...
...
...
...
...

2022-01-01
NASDAQ
14400
15600
16700

2022-01-02
NASDAQ
14500
15200
16100

2022-01-03
NASDAQ
14600
15000
16000

I'm currently saving NASDAQ values and stock data on the same table using MariaDB.

However, I want to show NASDAQ's MA values as new column fields into rest of the field, as NASDAQ_MA5, NASDAQ_MA20.

My question is, how do I select nasdaq's MA5 and MA20 values and put it as the values according to the matching dates? My desired output is as follows:

Date
Code
Price
MA5
MA20
NASDAQ_MA5
NASDAQ_MA20

2022-01-01
APPLE
1000
1080
1090
15600
16700

2022-01-02
APPLE
1100
1084
1100
15200
16100

2022-01-03
APPLE
1200
1090
1100
15000
16000

2022-01-01
MICROSOFT
7
9
10
15600
16700

2022-01-02
MICROSOFT
7.5
8
9.5
15200
16100

2022-01-03
MICROSOFT
8
8.5
9
15000
16000

I've been trying the following:

```<code>        SELECT *,
        (PARTITION BY DATE, case when (code='NASDAQ') then MA5 else NULL end) as 'NASDAQ_MA5',
        (PARTITION BY DATE, case when (code='NASDAQ') then MA20 else NULL end) as 'NASDAQ_MA20'
        FROM TABLE
</code>```

Your help will be very appreciated.

答:
You can do a self join on date column and separating the data by CODE = 'NASDAQ'. Here is a way of doing this:</p>
```<code>select a.*, b.ma5 as NASDAQ_MA5, b.ma20 as NASDAQ_MA20 from table1 a
left outer join (select date, ma5,ma20 from table1 where code = 'NASDAQ') b
on a.date = b.date where a.code <> 'NASDAQ'
</code>```

Title: Showing particular row data as column

Body:
My table is as follows:

Date
Code
Price
MA5
MA20

2022-01-01
APPLE
1000
1080
1090

2022-01-02
APPLE
1100
1084
1100

2022-01-03
APPLE
1200
1090
1100

2022-01-01
MICROSOFT
7
9
10

2022-01-02
MICROSOFT
7.5
8
9.5

2022-01-03
MICROSOFT
8
8.5
9

...
...
...
...
...

2022-01-01
NASDAQ
14400
15600
16700

2022-01-02
NASDAQ
14500
15200
16100

2022-01-03
NASDAQ
14600
15000
16000

I'm currently saving NASDAQ values and stock data on the same table using MariaDB.

However, I want to show NASDAQ's MA values as new column fields into rest of the field, as NASDAQ_MA5, NASDAQ_MA20.

My question is, how do I select nasdaq's MA5 and MA20 values and put it as the values according to the matching dates? My desired output is as follows:

Date
Code
Price
MA5
MA20
NASDAQ_MA5
NASDAQ_MA20

2022-01-01
APPLE
1000
1080
1090
15600
16700

2022-01-02
APPLE
1100
1084
1100
15200
16100

2022-01-03
APPLE
1200
1090
1100
15000
16000

2022-01-01
MICROSOFT
7
9
10
15600
16700

2022-01-02
MICROSOFT
7.5
8
9.5
15200
16100

2022-01-03
MICROSOFT
8
8.5
9
15000
16000

I've been trying the following:

        SELECT *,
        (PARTITION BY DATE, case when (code='NASDAQ') then MA5 else NULL end) as 'NASDAQ_MA5',
        (PARTITION BY DATE, case when (code='NASDAQ') then MA20 else NULL end) as 'NASDAQ_MA20'
        FROM TABLE

Your help will be very appreciated.

Body:
You can do a self join on date column and separating the data by CODE = 'NASDAQ'. Here is a way of doing this:

select a.*, b.ma5 as NASDAQ_MA5, b.ma20 as NASDAQ_MA20 from table1 a
left outer join (select date, ma5,ma20 from table1 where code = 'NASDAQ') b
on a.date = b.date where a.code <> 'NASDAQ'


问:
Changing Data Class From Live Data
I have a BaseViewModel that basically has the function to get the user data like so:

```<code>abstract class BaseViewModel(
    private val repository: BaseRepository
) : ViewModel() {
    private var _userResponse: MutableLiveData<Resource<UserResponse>> = MutableLiveData()
    val userResponse: LiveData<Resource<UserResponse>> get() = _userResponse

    fun getUserData() = viewModelScope.launch {
        _userResponse.value = Resource.Loading
        _userResponse.value = repository.getLoggedInUserData()
    }
}
</code>```

In my Fragment, I access this data by just calling viewModel.getUserData(). This works. However, I'd like to now be able to edit the data. For example, the data class of UserResponse looks like this:

```<code>data class UserResponse(
    var id: Int,
    var username: String,
    var email: String
)
</code>```

In other fragments, I'd like to edit username and email for example. How do I do access the UserResponse object and edit it? Is this a good way of doing things? The getUserData should be accessed everywhere and that is why I'm including it in the abstract BaseViewModel. Whenever the UserResponse is null, I do the following check:

```<code>if (viewModel.userResponse.value == null) {
    viewModel.getUserData()
}
</code>```

答:
If you want to be able to edit the data in userResponse, really what you're talking about is changing the value it holds, right? The best way to do that is through the ViewModel itself:

```<code>abstract class BaseViewModel(
    private val repository: BaseRepository
) : ViewModel() {
    private var _userResponse: MutableLiveData<Resource<UserResponse>> = MutableLiveData()
    val userResponse: LiveData<Resource<UserResponse>> get() = _userResponse

    fun setUserResponse(response: UserResponse) {
        _userResponse.value = response
    }

    ...
}
</code>```

This has a few advantages - first, the view model is responsible for holding and managing the data, and provides an interface for reading, observing, and updating it. Rather than having lots of places where the data is manipulated, those places just call this one function instead. That makes it a lot easier to change things later, if you need to - the code that calls the function might not need to change at all!

This also means that you can expand the update logic more easily, since it's all centralised in the VM. Need to write the new value to a SavedStateHandle, so it's not lost if the app goes to the background? Just throw that in the update function. Maybe persist it to a database? Throw that in. None of the callers need to know what's happening in there

The other advantage is you're actually setting a new value on the LiveData, which means your update behaviour is consistent and predictable. If the user response changes (either a whole new one, or a change to the current one) then everything observeing that LiveData sees the update, and can decide what to do with it. It's less brittle than this idea that one change to the current response is "new" and another change is "an update" and observers will only care about one of those and don't need to be notified of the other. Consistency in how changes are handled will avoid bugs being introduced later, and just make it easier to reason about what's going on

There's nothing stopping you from updating the properties of the object held in userResponse, just like there's nothing stopping you from holding a List in a LiveData, and adding elements to that list. Everything with a reference to that object will see the new data, but only if they look at it. The point of LiveData and the observer pattern is to push updates to observers, so they can react to changes (like, say, updating text displayed in a UI). If you change one of the vars in that data class, how are you going to make sure everything that needs to see those changes definitely sees them? How can you ensure that will always happen, as the app gets developed, possibly by other people? The observer pattern is about simplifying that logic - update happens, observers are notified, the end

If you are going to do things this way, then I'd still recommend putting an update function in your VM, and let that update the vars. You get the same benefits - centralising the logic, enabling things like persistence if it ever becomes necessary, etc. It could be as simple as

```<code>    fun setUserResponse(response: UserResponse) {
        _userResponse.value?.run {
            id = response.id
            username = response.username
            email = response.email
        }
    }
</code>```

and if you do decide to go with the full observer pattern for all changes later, everything is already calling the function the right way, no need for changes there. Or you could just make separate updateEmail(email: String) etc functions, whatever you want to do. But putting all that logic in the VM is a good idea, it's kinda what it's there for

Oh and you access that object through userResponse.value if you want to poke at it - but like I said, better to do that inside a function in the VM, keep that implementation detail, null-safety etc in one place, so callers don't need to mess with it

Title: Changing Data Class From Live Data

Body:
I have a BaseViewModel that basically has the function to get the user data like so:

abstract class BaseViewModel(
    private val repository: BaseRepository
) : ViewModel() {
    private var _userResponse: MutableLiveData<Resource<UserResponse>> = MutableLiveData()
    val userResponse: LiveData<Resource<UserResponse>> get() = _userResponse

    fun getUserData() = viewModelScope.launch {
        _userResponse.value = Resource.Loading
        _userResponse.value = repository.getLoggedInUserData()
    }
}

In my Fragment, I access this data by just calling viewModel.getUserData(). This works. However, I'd like to now be able to edit the data. For example, the data class of UserResponse looks like this:

data class UserResponse(
    var id: Int,
    var username: String,
    var email: String
)

In other fragments, I'd like to edit username and email for example. How do I do access the UserResponse object and edit it? Is this a good way of doing things? The getUserData should be accessed everywhere and that is why I'm including it in the abstract BaseViewModel. Whenever the UserResponse is null, I do the following check:

if (viewModel.userResponse.value == null) {
    viewModel.getUserData()
}

Body:
If you want to be able to edit the data in userResponse, really what you're talking about is changing the value it holds, right? The best way to do that is through the ViewModel itself:

abstract class BaseViewModel(
    private val repository: BaseRepository
) : ViewModel() {
    private var _userResponse: MutableLiveData<Resource<UserResponse>> = MutableLiveData()
    val userResponse: LiveData<Resource<UserResponse>> get() = _userResponse

    fun setUserResponse(response: UserResponse) {
        _userResponse.value = response
    }

    ...
}

This has a few advantages - first, the view model is responsible for holding and managing the data, and provides an interface for reading, observing, and updating it. Rather than having lots of places where the data is manipulated, those places just call this one function instead. That makes it a lot easier to change things later, if you need to - the code that calls the function might not need to change at all!

This also means that you can expand the update logic more easily, since it's all centralised in the VM. Need to write the new value to a SavedStateHandle, so it's not lost if the app goes to the background? Just throw that in the update function. Maybe persist it to a database? Throw that in. None of the callers need to know what's happening in there

The other advantage is you're actually setting a new value on the LiveData, which means your update behaviour is consistent and predictable. If the user response changes (either a whole new one, or a change to the current one) then everything observeing that LiveData sees the update, and can decide what to do with it. It's less brittle than this idea that one change to the current response is "new" and another change is "an update" and observers will only care about one of those and don't need to be notified of the other. Consistency in how changes are handled will avoid bugs being introduced later, and just make it easier to reason about what's going on

There's nothing stopping you from updating the properties of the object held in userResponse, just like there's nothing stopping you from holding a List in a LiveData, and adding elements to that list. Everything with a reference to that object will see the new data, but only if they look at it. The point of LiveData and the observer pattern is to push updates to observers, so they can react to changes (like, say, updating text displayed in a UI). If you change one of the vars in that data class, how are you going to make sure everything that needs to see those changes definitely sees them? How can you ensure that will always happen, as the app gets developed, possibly by other people? The observer pattern is about simplifying that logic - update happens, observers are notified, the end

If you are going to do things this way, then I'd still recommend putting an update function in your VM, and let that update the vars. You get the same benefits - centralising the logic, enabling things like persistence if it ever becomes necessary, etc. It could be as simple as

    fun setUserResponse(response: UserResponse) {
        _userResponse.value?.run {
            id = response.id
            username = response.username
            email = response.email
        }
    }

and if you do decide to go with the full observer pattern for all changes later, everything is already calling the function the right way, no need for changes there. Or you could just make separate updateEmail(email: String) etc functions, whatever you want to do. But putting all that logic in the VM is a good idea, it's kinda what it's there for

Oh and you access that object through userResponse.value if you want to poke at it - but like I said, better to do that inside a function in the VM, keep that implementation detail, null-safety etc in one place, so callers don't need to mess with it


问:
.NET error handling
I have been writing .NET applications and have been impressed with the error handling included in the framework.

When catching an error that has been throw by the processes or somewhere in the code I like to include the message (ex.Message, which is usually pretty general) but also the stacktrace (ex.stacktrace) which helps to trace the problem back to a specific spot.

For a simple example let's say for instance that we are recording numbers to a log in a method:

```<code>public void ExampleMethod(int number){
    try{
        int num = number
        ...open connection to file
        ...write number to file
    }
    catch(Exception ex){
        .... deal with exception (ex.message,ex.stacktrace etc...)
    }
    finally{
    ...close file connection
    }
}
</code>```

Is there any way to see the method called (in this case ExampleMethod) with the specific number that was passed that potentially crashed the method call? I believe you could log this perhaps in the catch block but I am interested essentially in catching the method call and parameters that caused the system to throw the exception.

Any ideas?

答:
I suggest stuffing the parameter values into the exception's Data dictionary, e.g.

```<code>public void ExampleMethod(int number) {
try {
    int num = number
    ...open connection to file
    ...write number to file
}
catch(Exception ex) {
    ex.Data["number"] = number;
    //.... deal with exception (ex.message,ex.stacktrace etc...)
}
finally {
    //...close file connection
}
</code>```

Another advantage of this method is that you can stuff the parameters in the catch block, then re-throw the exception and log it somewhere else without losing the stack trace, e.g.

```<code>catch(Exception ex) {
    ex.Data["number"] = number;
    throw;
}
</code>```

Title: .NET error handling

Body:
I have been writing .NET applications and have been impressed with the error handling included in the framework.

When catching an error that has been throw by the processes or somewhere in the code I like to include the message (ex.Message, which is usually pretty general) but also the stacktrace (ex.stacktrace) which helps to trace the problem back to a specific spot.

For a simple example let's say for instance that we are recording numbers to a log in a method:

public void ExampleMethod(int number){
    try{
        int num = number
        ...open connection to file
        ...write number to file
    }
    catch(Exception ex){
        .... deal with exception (ex.message,ex.stacktrace etc...)
    }
    finally{
    ...close file connection
    }
}

Is there any way to see the method called (in this case ExampleMethod) with the specific number that was passed that potentially crashed the method call? I believe you could log this perhaps in the catch block but I am interested essentially in catching the method call and parameters that caused the system to throw the exception.

Any ideas?

Body:
I suggest stuffing the parameter values into the exception's Data dictionary, e.g.

public void ExampleMethod(int number) {
try {
    int num = number
    ...open connection to file
    ...write number to file
}
catch(Exception ex) {
    ex.Data["number"] = number;
    //.... deal with exception (ex.message,ex.stacktrace etc...)
}
finally {
    //...close file connection
}

Another advantage of this method is that you can stuff the parameters in the catch block, then re-throw the exception and log it somewhere else without losing the stack trace, e.g.

catch(Exception ex) {
    ex.Data["number"] = number;
    throw;
}


问:
PHP $_POST not working but $_GET works fine
I'm trying to build a simple login system using <form method="post">. Everything works fine on MAMP on my laptop but when I upload the script to the server (Windows) it doesn't work; it seems that the $_POST array is empty.

I commented out everything but the bare bones and it still doesn't work.

index.php:

```<code><form id="login-form" method="POST" action="_scripts/check_login.php">
Email Address
<input name="login-email" type="text" id="login-email">
Password
<input name="login-password" type="text" id="login-password">
<input type="submit" name="Submit" id="login-button" value="Login">
</form>
</code>```

_scripts/check_login.php: (I've removed everything except some var_dumps for debugging)

```<code>var_dump($_POST);

$loginEmail = trim($_POST['login-email']);
echo '<br>';
$loginPassword = ($_POST['login-password']);
var_dump($loginEmail);
echo '<br>';
var_dump($loginPassword);
</code>```

When I submit the form, no matter what I put in the text fields, I see this:

```<code>array(0) { }
string(0) ""
NULL
</code>```

If I change all the instances of "post" to "get" in the above two files, everything works fine. But I don't want to use get. ($_REQUEST doesn't work either if I submit the form using method="post").

NB this all works fine on localhost, but not on the server (which is running Windows.) So it would seem to be a problem with the server, but I have no idea what. You can see the PHPInfo here: http://brailleapps.org/phpinf0.php

Any ideas?

EDIT: Solved! See below.

答:
and another thing is if you have ever changed .htaccess to hide the format
Example .php or .html

action="filename.php" instead of this give action="filename"

your problem solved.

Body:
I'm trying to build a simple login system using <form method="post">. Everything works fine on MAMP on my laptop but when I upload the script to the server (Windows) it doesn't work; it seems that the $_POST array is empty.

I commented out everything but the bare bones and it still doesn't work.

index.php:

<form id="login-form" method="POST" action="_scripts/check_login.php">
Email Address
<input name="login-email" type="text" id="login-email">
Password
<input name="login-password" type="text" id="login-password">
<input type="submit" name="Submit" id="login-button" value="Login">
</form>

_scripts/check_login.php: (I've removed everything except some var_dumps for debugging)

var_dump($_POST);

$loginEmail = trim($_POST['login-email']);
echo '
';
$loginPassword = ($_POST['login-password']);
var_dump($loginEmail);
echo '
';
var_dump($loginPassword);

When I submit the form, no matter what I put in the text fields, I see this:

array(0) { }
string(0) ""
NULL

If I change all the instances of "post" to "get" in the above two files, everything works fine. But I don't want to use get. ($_REQUEST doesn't work either if I submit the form using method="post").

NB this all works fine on localhost, but not on the server (which is running Windows.) So it would seem to be a problem with the server, but I have no idea what. You can see the PHPInfo here: http://brailleapps.org/phpinf0.php

Any ideas?

EDIT: Solved! See below.


问:
How do I format tabular text in matplotlib plots?
In my code I have something like:

```<code>    import matplotlib.pyplot as plt

    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot()

    ...

    fmtstr = '{:<15}{:<15}{:<15}\n{:<15}{:<15}{:<15}\n{:<15}{:<15}{:<15}\n{:<15}{:<15}{:<15}'
    ntext = fmtstr.format('    ', 'tot', 'unique',
            'in  ', str(len(seqzs[fp])), str(len(seqzsSet[fp])),
            'std ', str(len(seqzs[std])), str(len(seqzsSet[std])),
            'shrd', '', str(len(dRTShrd)))

    ax.text(0.03, 0.8, ntext, transform=ax.transAxes)
    print(ntext)
    ...

    plt.savefig(os.path.join(outDir, oname))

</code>```

The formatted text ntext looks good when printed:

```<code>               tot            unique
in             6826           3837
std            24773          11376
shrd                          3220
</code>```

But not good in the plot:

How do I get it right in the plot? (The widths of the numbers change with every plot so I need a constant formatter)

答:
Use monospace font like this: (Thanks to @Aziz for suggesting.)

```<code>    import matplotlib.pyplot as plt

    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot()

    ...

    fmtstr = '{:<7}{:<8}{:<9}\n{:<7}{:<8}{:<9}\n{:<7}{:<8}{:<9}\n{:<7}{:<8}{:<9}'  # format string
    ntext = fmtstr.format('    ', 'tot', 'unique',
            'in  ', str(len(seqzs[fp])), str(len(seqzsSet[fp])),
            'std ', str(len(seqzs[std])), str(len(seqzsSet[std])),
            'shrd', '', str(len(dRTShrd)))
    ax.text(0.03, 0.8, ntext, transform=ax.transAxes, fontname = 'monospace')

    ...

    plt.savefig(os.path.join(outDir, oname))
</code>```

Body:
In my code I have something like:

    import matplotlib.pyplot as plt

    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot()

    ...

    fmtstr = '{:<15}{:<15}{:<15}\n{:<15}{:<15}{:<15}\n{:<15}{:<15}{:<15}\n{:<15}{:<15}{:<15}'
    ntext = fmtstr.format('    ', 'tot', 'unique',
            'in  ', str(len(seqzs[fp])), str(len(seqzsSet[fp])),
            'std ', str(len(seqzs[std])), str(len(seqzsSet[std])),
            'shrd', '', str(len(dRTShrd)))

    ax.text(0.03, 0.8, ntext, transform=ax.transAxes)
    print(ntext)
    ...

    plt.savefig(os.path.join(outDir, oname))

The formatted text ntext looks good when printed:

               tot            unique
in             6826           3837
std            24773          11376
shrd                          3220

But not good in the plot:

How do I get it right in the plot? (The widths of the numbers change with every plot so I need a constant formatter)

Body:
Use monospace font like this: (Thanks to @Aziz for suggesting.)

    import matplotlib.pyplot as plt

    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot()

    ...

    fmtstr = '{:<7}{:<8}{:<9}\n{:<7}{:<8}{:<9}\n{:<7}{:<8}{:<9}\n{:<7}{:<8}{:<9}'  # format string
    ntext = fmtstr.format('    ', 'tot', 'unique',
            'in  ', str(len(seqzs[fp])), str(len(seqzsSet[fp])),
            'std ', str(len(seqzs[std])), str(len(seqzsSet[std])),
            'shrd', '', str(len(dRTShrd)))
    ax.text(0.03, 0.8, ntext, transform=ax.transAxes, fontname = 'monospace')

    ...

    plt.savefig(os.path.join(outDir, oname))


问:
IntelliJ IDEA: install plugins from command line
Does IDEA provide a command line executable to edit some settings, install/uninstall plugins, etc without actually starting the IDE and clicking around?

For example, it is possible to install new plugins for Eclipse with:

```<code>eclipse -application org.eclipse.equinox.p2.director -noSplash -repository #{repo} -installIUs #{plugins}
</code>```

Any equivalent for IntelliJ?

答:
If you want to sync plugins for members, you can use Required Plugins:

An error will pop up if no plugin:

Body:
Does IDEA provide a command line executable to edit some settings, install/uninstall plugins, etc without actually starting the IDE and clicking around?

For example, it is possible to install new plugins for Eclipse with:

eclipse -application org.eclipse.equinox.p2.director -noSplash -repository #{repo} -installIUs #{plugins}

Any equivalent for IntelliJ?


问:
TextInput is returning undefined. How to convert undefined to String()?
I am making an OTP login with react native. the API is working fine and I have tested it on React.js. It works fine.
But I am getting errors while implementing it in React Native, TextField is returning undefined But I want a String.

This is the response from Backend:

```<code>Object {
  "hash": "ffe9c1edd9362ac06cc3049287cb60c07484c494c8b9e8305524f57a4efedefc.1644744727322",
  "number": "undefined",
  "otp": 438014,
}
</code>```

As you can see the number is undefined. How can I convert it to String?

This is my TextInput code:

```<code>import axios from "axios";
import React from "react";
import { Button, TextInput, View } from "react-native";

function NumberIn(props) {
  const { value, handleChange, hashHandleChange } = props;

  const Continue = (e) => {
    axios
      .post("http://172.20.10.4:9000/api/otp", {
        number: `${value.number}`,
      })
      .then((res) => {
        console.log(res.data);

        const hash = res.data.hash;
        hashHandleChange(hash);
      })
      .catch((err) => {
        console.log(err);
      });

    e.preventDefault();
    props.nextStep();
  };

  return (
    <View>
      <TextInput
        placeholder="enter Your Number"
        value={value.number}
        onChangeText={(text) => handleChange("number",text)}
      />
      <Button onPress={Continue} title="get otp"></Button>
    </View>
  );
}

export default NumberIn;

</code>```

And my SetForm function is :

```<code>import React, { useState } from "react";
import NumberIn from "./NumberIn";
import Otp from "./Otp";

function SetForm() {
  const [state, setState] = useState({
    number: "",
    hash: "",
    otp: "",
  });

  const [step, setStep] = useState(1);

  const handleChange = (input, inputText) => () => {
    setState({
      ...state,
      [input]: inputText,
    });
  };

  const hashHandleChange = (hash) => {
    setState({
      ...state,
      hash: hash,
    });
  };

  const nextStep = () => {
    setStep((prevStep) => prevStep + 1);
  };
  const prevStep = () => {
    setStep((prevStep) => prevStep - 1);
  };

  const { number, otp, hash } = state;
  const value = { number, hash, otp };
  switch (step) {
    case 1:
      return (
        <NumberIn
          nextStep={nextStep}
          hashHandleChange={hashHandleChange}
          handleChange={handleChange}
          value={value}
        />
      );
    case 2:
      return (
        <Otp
          nextStep={nextStep}
          prevStep={prevStep}
          handleChange={handleChange}
          value={value}
        />
      );
    default:
      return (
        <NumberIn
          nextStep={nextStep}
          hashHandleChange={hashHandleChange}
          handleChange={handleChange}
          value={value}
        />
      );
  }
}

export default SetForm;
</code>```

答:
Please change

```<code>  const handleChange = (input, inputText) => () => {
      setState({
        ...state,
        [input]: inputText,
      });
  };
</code>```

to

```<code>  const handleChange = (input, inputText) => {
      setState({
        ...state,
        [input]: inputText,
      });
  };
</code>```

Body:
I am making an OTP login with react native. the API is working fine and I have tested it on React.js. It works fine.
But I am getting errors while implementing it in React Native, TextField is returning undefined But I want a String.

This is the response from Backend:

Object {
  "hash": "ffe9c1edd9362ac06cc3049287cb60c07484c494c8b9e8305524f57a4efedefc.1644744727322",
  "number": "undefined",
  "otp": 438014,
}

As you can see the number is undefined. How can I convert it to String?

This is my TextInput code:

import axios from "axios";
import React from "react";
import { Button, TextInput, View } from "react-native";

function NumberIn(props) {
  const { value, handleChange, hashHandleChange } = props;

  const Continue = (e) => {
    axios
      .post("http://172.20.10.4:9000/api/otp", {
        number: `${value.number}`,
      })
      .then((res) => {
        console.log(res.data);

        const hash = res.data.hash;
        hashHandleChange(hash);
      })
      .catch((err) => {
        console.log(err);
      });

    e.preventDefault();
    props.nextStep();
  };

  return (
    <View>
      <TextInput
        placeholder="enter Your Number"
        value={value.number}
        onChangeText={(text) => handleChange("number",text)}
      />
      <Button onPress={Continue} title="get otp"></Button>
    </View>
  );
}

export default NumberIn;

And my SetForm function is :

import React, { useState } from "react";
import NumberIn from "./NumberIn";
import Otp from "./Otp";

function SetForm() {
  const [state, setState] = useState({
    number: "",
    hash: "",
    otp: "",
  });

  const [step, setStep] = useState(1);

  const handleChange = (input, inputText) => () => {
    setState({
      ...state,
      [input]: inputText,
    });
  };

  const hashHandleChange = (hash) => {
    setState({
      ...state,
      hash: hash,
    });
  };

  const nextStep = () => {
    setStep((prevStep) => prevStep + 1);
  };
  const prevStep = () => {
    setStep((prevStep) => prevStep - 1);
  };

  const { number, otp, hash } = state;
  const value = { number, hash, otp };
  switch (step) {
    case 1:
      return (
        <NumberIn
          nextStep={nextStep}
          hashHandleChange={hashHandleChange}
          handleChange={handleChange}
          value={value}
        />
      );
    case 2:
      return (
        <Otp
          nextStep={nextStep}
          prevStep={prevStep}
          handleChange={handleChange}
          value={value}
        />
      );
    default:
      return (
        <NumberIn
          nextStep={nextStep}
          hashHandleChange={hashHandleChange}
          handleChange={handleChange}
          value={value}
        />
      );
  }
}

export default SetForm;

Body:
Please change

  const handleChange = (input, inputText) => () => {
      setState({
        ...state,
        [input]: inputText,
      });
  };

to

  const handleChange = (input, inputText) => {
      setState({
        ...state,
        [input]: inputText,
      });
  };


问:
Is it OK to show localized pricing information in an ios app
I've read in a number of places (ie. http://iphoneincubator.com/blog/app-store/rejections) that you should not include price information in your app for either the "full version" or in app purchases.

The reasoning is generally that the apps are sold globally, and prices and currency vary by region.

I've used the localized currency value (I'm actually using MKStoreKit, it's great and you should try it), and I'm wondering if anyone has displayed localized price information in their app and had it pass app store submission?

I'd sure like to include the price in my promotional view for my IAP, but I don't want to be rejected for doing so.

答:
I have had no problems with apps that display the pricing information provided it's getting fetched on the fly from MKStoreKit. It's as much to do with local variations as global ones - Apple's restriction is designed to prevent situations arising where you might hard-code a pricing value into your app which subsequently goes out of date due to currency variations. For example, a month or so ago Apple re-calculated the pricing tiers for the Euro, Pound, and a few other currencies.

The best place to go for this information would be the Apple published guidelines, which have much improved: http://developer.apple.com/appstore/resources/approval/guidelines.html


问:
Python regex to find all strings that start with ' and end with '.tr ignoring leading and trailing whitespaces
I am struggling to get the correct regex for my script. I would like to find all Substrings in a file that start with a ' and end with '.tr. And save all these matches in a list.

This is what Ive got so far:

```<code>import glob
import pathlib
import re

libPathString = str(pathlib.Path.cwd().parent.resolve())

for path in glob.glob(libPathString + "/**", recursive=True):
    if(".dart" in path):
        with open(path, 'r+', encoding="utf-8") as file:
            data = [line.strip() for line in file.readlines()]
            data = ''.join(data)
            words = re.findall(r'\'.*\'.tr', data)
            print(words)
</code>```

The first problem is that words is not just the matching substring but the whole file until the substring.

Also it is giving me this file:

```<code>  child: Hero(
    tag: heroTag ?? '',  // <- because of this and the line below starts with `tr`
    transitionOnUserGestures: true,
    child: Material(
</code>```

But this should not match!

And then it is not finding this:

```<code>  AutoSizeText(
      'Das ist ein langer Text, der immer in einer Zeile ist.'
          .tr,
      style: AppTextStyles.montserratH4Regular,
</code>```

This one should match!

What am I missing here?

答:
You can use

words = re.findall(r"'[^'\\]*(?:\\.[^'\\]*)*'\s*\.tr\b", data)
```

See the Python demo. Details:

'[^'\\]*(?:\\.[^'\\]*)*' - ', zero or more chars other than ' and \, and then zero or more sequences of a \ followed with any single char and any zero or more chars other than ' and \ (this will match strings between ' chars with any escaped chars in between)

\s* - zero or more whitespaces (this will match any whitespace, including line breaks)

\.tr - .tr string (note the escaped . that now matches a litera dot)

\b - word boundary.

Body:
I am struggling to get the correct regex for my script. I would like to find all Substrings in a file that start with a ' and end with '.tr. And save all these matches in a list.

This is what Ive got so far:

import glob
import pathlib
import re

libPathString = str(pathlib.Path.cwd().parent.resolve())

for path in glob.glob(libPathString + "/**", recursive=True):
    if(".dart" in path):
        with open(path, 'r+', encoding="utf-8") as file:
            data = [line.strip() for line in file.readlines()]
            data = ''.join(data)
            words = re.findall(r'\'.*\'.tr', data)
            print(words)

The first problem is that words is not just the matching substring but the whole file until the substring.

Also it is giving me this file:

  child: Hero(
    tag: heroTag ?? '',  // <- because of this and the line below starts with `tr`
    transitionOnUserGestures: true,
    child: Material(

But this should not match!

And then it is not finding this:

  AutoSizeText(
      'Das ist ein langer Text, der immer in einer Zeile ist.'
          .tr,
      style: AppTextStyles.montserratH4Regular,

This one should match!

What am I missing here?

Body:
You can use

words = re.findall(r"'[^'\\]*(?:\\.[^'\\]*)*'\s*\.tr\b", data)

See the Python demo. Details:

'[^'\\]*(?:\\.[^'\\]*)*' - ', zero or more chars other than ' and \, and then zero or more sequences of a \ followed with any single char and any zero or more chars other than ' and \ (this will match strings between ' chars with any escaped chars in between)

\s* - zero or more whitespaces (this will match any whitespace, including line breaks)

\.tr - .tr string (note the escaped . that now matches a litera dot)

\b - word boundary.


问:
Update old data in oracle
hi I have old data and I want to recover them .Lets say I have the following tables .

Table1:

Company
FirstName

All
Beornræd

Table2:

CompanyNames

X

Y

Z

I want to map All to all values of the table of company such that I obtain the following result.

Table1: after update

Company
FirstName

X
Beornræd

Y
Beornræd

Z
Beornræd

I there a way to update them using a query and thanks in advance.

答:
Two simple steps (update (with a cross join) + delete) look the simplest to me - at least, with as many info and sample data you provided.

```<code>SQL> insert into table1 (company, firstname)
  2    select b.companynames, a.firstname
  3    from table1 a cross join table2 b;

3 rows created.

SQL> delete from table1 where company = 'All';

1 row deleted.
</code>```

Result:

```<code>SQL> select * from table1;

COM FIRSTNAME
--- ---------
X   Beornrad
Y   Beornrad
Z   Beornrad

SQL>
</code>```

Title: Update old data in oracle

Body:
Two simple steps (update (with a cross join) + delete) look the simplest to me - at least, with as many info and sample data you provided.

SQL> insert into table1 (company, firstname)
  2    select b.companynames, a.firstname
  3    from table1 a cross join table2 b;

3 rows created.

SQL> delete from table1 where company = 'All';

1 row deleted.

Result:

SQL> select * from table1;

COM FIRSTNAME
--- ---------
X   Beornrad
Y   Beornrad
Z   Beornrad

SQL>


问:
Execution failed for task ':app:compileJava' with ./gradlew run
When I try using "./gradlew run" on my gradle projects, I receive this error:

```<code>* What went wrong:
Execution failed for task ':app:compileJava'.
> java.lang.IllegalAccessError: class org.gradle.internal.compiler.java.ClassNameCollector (in unnamed module @0x1fa4cfc5) cannot access class com.sun.tools.javac.code.Symbol$TypeSymbol (in module jdk.compiler) because module jdk.compiler does not export com.sun.tools.javac.code to unnamed module @0x1fa4cfc5
</code>```

I have tried on multiple different projects and it still doesn't work. I believe it has something to do with gradle expecting a different version of Java, as I am using java 16 and when I check "gradle -v" it says "JVM: 15.0.2". I am not sure how to fix this or if this is even the problem. Any help would be greatly appreciated!

答:
I think the root cause of this issue is a mismatch between the Gradle version and the JDK version in use.  One should refer to the compatibility matrix.

For example, for a Java 17 runtime, one needs at least Gradle 7.3.

I hit the "IllegalAccessError" issue and in my case, it was solved by selecting "Specific Gradle version" 7.4 in Eclipse Gradle (Buildship) preferences.

Ensuring the correct match of JDK and Gradle version is environment-specific but I think once this is ascertained, the issue goes away.

Body:
When I try using "./gradlew run" on my gradle projects, I receive this error:

* What went wrong:
Execution failed for task ':app:compileJava'.
> java.lang.IllegalAccessError: class org.gradle.internal.compiler.java.ClassNameCollector (in unnamed module @0x1fa4cfc5) cannot access class com.sun.tools.javac.code.Symbol$TypeSymbol (in module jdk.compiler) because module jdk.compiler does not export com.sun.tools.javac.code to unnamed module @0x1fa4cfc5

I have tried on multiple different projects and it still doesn't work. I believe it has something to do with gradle expecting a different version of Java, as I am using java 16 and when I check "gradle -v" it says "JVM: 15.0.2". I am not sure how to fix this or if this is even the problem. Any help would be greatly appreciated!


问:
Operator in variable Swift
I am trying to make a function to see if all my textfields are filled in, I pass it an array, Let's say var array = ["1", "2", "3"]

And I want to check the if statement if array[0].isEmpty || array[1].isEmpty || array[2].isEmpty

But it has to be variable, so I thought about using a for loop and using the operator as a variable, that doesn't work, at least not how I am doing it, does anyone have an idea for this?

```<code>var op = false

    for field in array {
        op += field.isEmpty
        op += ||
    }

    if op {

    }
</code>```

Kind regards
Daan

答:
You could do the check as

```<code>array.first(where: \.isEmpty) != nil
</code>```

As suggested by @MartinR in the comments you can use contains instead which makes it a bit neater and with the same performance

```<code>array.contains(where: \.isEmpty)
</code>```

Title: Operator in variable Swift

Body:
I am trying to make a function to see if all my textfields are filled in, I pass it an array, Let's say var array = ["1", "2", "3"]

And I want to check the if statement if array[0].isEmpty || array[1].isEmpty || array[2].isEmpty

But it has to be variable, so I thought about using a for loop and using the operator as a variable, that doesn't work, at least not how I am doing it, does anyone have an idea for this?

var op = false

    for field in array {
        op += field.isEmpty
        op += ||
    }

    if op {

    }

Kind regards
Daan

Body:
You could do the check as

array.first(where: \.isEmpty) != nil

As suggested by @MartinR in the comments you can use contains instead which makes it a bit neater and with the same performance

array.contains(where: \.isEmpty)