Ordinal numbers addition property: $b<c$ implies $b+a \le c+a$

Question: I'm having trouble proving the following property of ordinal numbers.
If $a, b, c$ are ordinal numbers such that $b \lt c$, then $b+a \le c+a$.
I first started by assuming $g$ as an order isomorphism from a well-ordered set $B$ to $C_q$, which is a proper segment of $C$, such that $ord(B)=b$ and $ord(C)=c$.
However, I don't know how to extend this situation to get the desired result. Any help?
Comment: How did you define ordinal addition?  Are you allowed to use transfinite induction?
Comment: This is how the book defined ordinal sum. Let $a$ and $b$ be ordinal numbers. The ordinal sum of $a$ and $b$, denoted by $a+b$, is the ordinal number ord($A \cup B, \le*$), where $(A, \le)$ and $(B, \le')$ are disjoint well-ordered sets such that ord($A, \le$)=$a$ and ord($B, \le'$)=$b$. And yes transfinite induction has been introduced.
Answer: Proceed as follows. All sets are well orders.
1) If $f: D\rightarrow D$ is order preserving, ($x<y \rightarrow f(x) <f(y)$) then $x\leq f(x)$
2) If $f: D\rightarrow E$ is order preserving, then $ord(D) \leq ord(E)$.
(Hint: use trichotomy and 1) to show you cannot order preservingly map a set into an initial segment of itself.)
(I take your definition as $ord(D) \leq ord(E)$ means that $D$ is isomorphic to an initial segment of $E$.)
3)Now show your statement by finding an order preserving
$f:B+A \rightarrow C+A$ by maping $B$ to $C$ as you have done, then using the identity on $A$.
Comment: Is the definition of order preserving here, a strictly increasing function? Because one of the references I'm looking at defined order preserving function as $(x \le y \to f(x) \le f(y))$ and with this version of the definition, I can't prove 1). Moreover, can you help me with the proof of 2)? I'm having trouble proving this part since here $E$ may not be a subset of $D$ so I don't know how to use 1).
Answer: I use that $a \le b$ for order types iff there is a strict order-preserving function from a set with order type $a$ to one with order type $b$.
As $a < b$ in particular $a \le b$, so there is a (strict) order preserving $f: a \rightarrow b$ (so for all $x,y \in a: a < b \rightarrow f(a) < f(b)$, where $<$ denotes the order on both $a$ and $b$. Assume that $a$ and $b$ are represented by disjoint well-ordered sets here (and $c$ is disjoint from both of them; such can always be arranged, of course). So $a + c$ is represented by the union of $a$ and $c$ in the sum order, and $b + c$ also by the union in the sum order.
Define $f': a \cup c \rightarrow b \cup c$ by $f'(x) = f(x)$ if $x \in a$, $f(x) = x$ for $x \in c$.
Claim: $x < y$ ($x,y \in a \cup c$) implies $f'(x) < f'(y)$: if $x,y$ are both in $a$ this follows from the property of $f$, if $x,y$ are both in $c$, this is clear as $f'$ is the identity on $c$, and if $x \in a$, $y \in c$ (the other way round cannot be, by the definition of the sum order: everything in $a$ is strictly before $c$), $f(x') \in b$, and $f'(y) = y \in c$, so again the definition on the sum order on $b \cup c$ says that $f'(x) < f'(y)$.
This implies that $a + c \le b + c$.
Comment: @MartinSleziak I see; if there is an order embedding from a well-ordered set into a well-ordered set, we can find one to an initial segment as well, as the answer said. I was thinking about general order types, for which my notion was meant; there two order types can be $\le$ than each other, while not being isomorphic, like the order types of $\mathbb{R}$ and $[0,1]$. For well-ordered types we do get a proper order this way, as noted. My proof works for all order types, not just well-orders.
Comment: I see that you're using the fact that a≤b  for order types iff there is a strict order-preserving function from a set with order type a  to one with order type b . However, the definition I got from the book I'm looking at is a≤b iff there is an order isomorphism from a set with order type $a$ to a segment of a set with order type $b$. I'm having trouble proving that the definition you used is equivalent to this. Can you prove this part for me?
Comment: It's not, I think. So this answer wouldn't work for you, I'm afraid.
Comment: @user135204 The two definitions are equivalent. See the second part of Rene Schipperus' answer or this separate post: http://math.stackexchange.com/questions/9483/order-isomorphic-with-a-subset-iff-order-isomorphic-with-an-initial-segment


Scrape / extract data from hidden divs in scrapy

Question: Hi I am trying to scrape a website where there is an input text. Whenever, I click on the input text there are dropdown suggestions for the value of the input text. It is not on select tag.
The value of those suggestion is inside a div tag elements. There were almost 200 divs/suggestions of it.
What I did is scrape from it using scrapy using xpath / css selectors. I found out that these 200 divs are actually hidden when I view the code using "View page source" instead of "Inspect elements".
Please help. Thank you
Answer: These elements are generated on the fly by some dropdown library, so you have to investigate the website source code and/or the HTTP requests it's making. All the data you are looking for should be there (most likely in JSON format), not in the HTML itself.
For example, if you are using Chrome:

Press F12 to open devtools while you are on the website
Press F5 to reload the page
Navigate to Network or Source tab
Try to locate the data (CTRL+F would be really helpful here)


x2go login terminated immediately for one user only

Question: I was trying to use my x2go client on a pc to login into a ubuntu desktop.
After login, the session was terminated immediately. I have access to two other accounts and they both login find. Putty ssh of the problematic account and all other accounts worked fine as well.
Here is the .Xsession-error output:
<code>      GNU nano 4.8                                                                                .xsession-errors.old                                                                                Modified
dbus-update-activation-environment: setting DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1001/bus
dbus-update-activation-environment: setting DISPLAY=:0
dbus-update-activation-environment: setting XAUTHORITY=/mnt/md0/brandi/.Xauthority
dbus-update-activation-environment: setting GTK_MODULES=gail:atk-bridge
dbus-update-activation-environment: setting QT_ACCESSIBILITY=1
dbus-update-activation-environment: setting SHELL=/bin/bash
dbus-update-activation-environment: setting QT_ACCESSIBILITY=1
dbus-update-activation-environment: setting XDG_CONFIG_DIRS=/etc/xdg/xdg-xubuntu:/etc/xdg
dbus-update-activation-environment: setting XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0
dbus-update-activation-environment: setting CLUTTER_BACKEND=x11
dbus-update-activation-environment: setting LANGUAGE=en_US
dbus-update-activation-environment: setting MESA_LOADER_DRIVER_OVERRIDE=i965
dbus-update-activation-environment: setting DESKTOP_SESSION=xubuntu
dbus-update-activation-environment: setting GTK_MODULES=gail:atk-bridge
dbus-update-activation-environment: setting PWD=/mnt/md0/brandi
dbus-update-activation-environment: setting XDG_SESSION_DESKTOP=xubuntu
dbus-update-activation-environment: setting LOGNAME=brandi
dbus-update-activation-environment: setting QT_QPA_PLATFORMTHEME=gtk2
dbus-update-activation-environment: setting XDG_SESSION_TYPE=x11
dbus-update-activation-environment: setting GPG_AGENT_INFO=/run/user/1001/gnupg/S.gpg-agent:0:1
dbus-update-activation-environment: setting XAUTHORITY=/mnt/md0/brandi/.Xauthority
dbus-update-activation-environment: setting XDG_GREETER_DATA_DIR=/var/lib/lightdm-data/brandi
dbus-update-activation-environment: setting GDM_LANG=en_US
dbus-update-activation-environment: setting HOME=/mnt/md0/brandi
dbus-update-activation-environment: setting IM_CONFIG_PHASE=1
dbus-update-activation-environment: setting LANG=en_US.UTF-8
dbus-update-activation-environment: setting XDG_CURRENT_DESKTOP=XFCE
dbus-update-activation-environment: setting XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0
dbus-update-activation-environment: setting XDG_SESSION_CLASS=user
dbus-update-activation-environment: setting GTK_OVERLAY_SCROLLING=0
dbus-update-activation-environment: setting USER=brandi
dbus-update-activation-environment: setting DISPLAY=:0
dbus-update-activation-environment: setting SHLVL=1
dbus-update-activation-environment: setting XDG_RUNTIME_DIR=/run/user/1001
dbus-update-activation-environment: setting XDG_DATA_DIRS=/usr/share/xfce4:/usr/share/xubuntu:/usr/local/share:/usr/share:/var/lib/snapd/desktop
dbus-update-activation-environment: setting PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
dbus-update-activation-environment: setting GDMSESSION=xubuntu
dbus-update-activation-environment: setting DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1001/bus
dbus-update-activation-environment: setting _=/usr/bin/dbus-update-activation-environment
/usr/bin/iceauth:  creating new authority file /run/user/1001/ICEauthority
libGL error: failed to create dri screen
libGL error: failed to load driver: i965
libGL error: failed to create dri screen
libGL error: failed to load driver: i965

(xfwm4:2662): xfwm4-WARNING **: 15:06:43.920: Unsupported GL renderer (llvmpipe (LLVM 12.0.0, 256 bits)).
** (wrapper-2.0:2791): WARNING **: 15:06:44.327: No outputs have backlight property
(wrapper-2.0:2791): Gtk-WARNING **: 15:06:44.368: Negative content width -3 (allocation 1, extents 2x2) while allocating gadget (node button, owner PowerManagerButton)
(wrapper-2.0:2793): Gtk-WARNING **: 15:06:44.370: Negative content width -3 (allocation 1, extents 2x2) while allocating gadget (node button, owner PulseaudioButton)
(wrapper-2.0:2786): Gtk-WARNING **: 15:06:44.394: Theme parsing error: <data>:1:46: The style property GtkWidget:focus-padding is deprecated and shouldn't be used anymore. It will be removed in a future version
(wrapper-2.0:2786): Gtk-WARNING **: 15:06:44.394: Theme parsing error: <data>:1:78: The style property GtkWidget:focus-line-width is deprecated and shouldn't be used anymore. It will be removed in a future version
(wrapper-2.0:2786): Gtk-WARNING **: 15:06:44.394: Theme parsing error: <data>:1:108: The style property GtkButton:default-border is deprecated and shouldn't be used anymore. It will be removed in a future version
(wrapper-2.0:2786): Gtk-WARNING **: 15:06:44.394: Theme parsing error: <data>:1:136: The style property GtkButton:inner-border is deprecated and shouldn't be used anymore. It will be removed in a future version
Tracker-Message: 15:06:44.397: Set scheduler policy to SCHED_IDLE
Tracker-Message: 15:06:44.397: Setting priority nice level to 19

(polkit-gnome-authentication-agent-1:2866): GLib-CRITICAL **: 15:06:44.415: g_variant_new_string: assertion 'string != NULL' failed
(polkit-gnome-authentication-agent-1:2866): polkit-gnome-1-WARNING **: 15:06:44.416: Failed to register client: GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.SessionManager was not provided by any .service files
Tracker-Message: 15:06:44.439: Set scheduler policy to SCHED_IDLE
Tracker-Message: 15:06:44.439: Setting priority nice level to 19

(wrapper-2.0:2785): GLib-GIO-CRITICAL **: 15:06:44.441: g_file_new_for_path: assertion 'path != NULL' failed
(wrapper-2.0:2785): GLib-GIO-CRITICAL **: 15:06:44.441: g_file_monitor_file: assertion 'G_IS_FILE (file)' failed
(wrapper-2.0:2785): GLib-GObject-WARNING **: 15:06:44.441: invalid (NULL) pointer instance
(wrapper-2.0:2785): GLib-GObject-CRITICAL **: 15:06:44.441: g_signal_connect_data: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed
(wrapper-2.0:2785): Gtk-WARNING **: 15:06:44.441: Attempting to add a widget with type GtkToggleButton to a container of type XfcePanelPlugin, but the widget is already inside a container of type XfcePanelPlugin, please remove the widget from its existing container first.
(wrapper-2.0:2786): Gtk-WARNING **: 15:06:44.457: Theme parsing error: <data>:1:46: The style property GtkWidget:focus-padding is deprecated and shouldn't be used anymore. It will be removed in a future version
(wrapper-2.0:2786): Gtk-WARNING **: 15:06:44.457: Theme parsing error: <data>:1:78: The style property GtkWidget:focus-line-width is deprecated and shouldn't be used anymore. It will be removed in a future version
(wrapper-2.0:2786): Gtk-WARNING **: 15:06:44.457: Theme parsing error: <data>:1:108: The style property GtkButton:default-border is deprecated and shouldn't be used anymore. It will be removed in a future version
(wrapper-2.0:2786): Gtk-WARNING **: 15:06:44.457: Theme parsing error: <data>:1:136: The style property GtkButton:inner-border is deprecated and shouldn't be used anymore. It will be removed in a future version
(tracker-miner-fs:2862): Tracker-CRITICAL **: 15:06:44.471: Could not request DBus name 'org.freedesktop.Tracker1.Miner.Files': D-Bus service name:'org.freedesktop.Tracker1.Miner.Files' is already taken, perhaps the application is already running?
</code>
Thanks for your help in advance!
Comment: Please edit and format the pasted output as `code` using the {_} icon above the edit window.
Answer: Turns out it is the .bashrc paths that got messed up after switching from anaconda3 to miniconda. Once the paths are corrected, the user login issue was resolved.


CryptoJS AES decrypt Hex String?

Question: This is sort of a part two to the question Trying to print hex string with CryptoJS
Basically, I have a function that uses CryptoJS to encrypt a message and spit out the cypher text as a hex string.
function EncryptAES(text, key) {
  var encrypted = CryptoJS.AES.encrypt(text, key);
  return encrypted.ciphertext.toString()
}

I want to write a function DecryptAES that takes the hex string, key, and salt (which I apparently need) and returns the original plaintext. The problem is I can't figure out how to get the hex string back into a form that CryptoJS.AES.decrypt will accept, and I can't find anywhere in the documentation where it actually explains how to do it. Maybe I overlooked something. Please help.
Answer: CryptoJS uses the WordArray data type internally and provides encoders for conversion. If you want to convert a hex encoded string into a WordArray, this is possible with the Hex encoder as follows:
CryptoJS.enc.Hex.parse(<your hex encoded string>)

or the other way around
<your WordArray>.toString(CryptoJS.enc.Hex)

or for short
<your WordArray>.toString()

Moreover, CryptoJS.AES.encrypt() returns a CipherParams object that encapsulates ciphertext and salt, among other things. This CipherParams object is to be passed to CryptoJS.AES.decrypt() for decryption.
With this, what you want can be implemented as follows:

function EncryptAES(text, key) {
    var encrypted = CryptoJS.AES.encrypt(text, key);
    return {ciphertext: encrypted.ciphertext.toString(), salt: encrypted.salt.toString()}
}

function DecryptAES(ciphertext, salt, key){
    var decrypted = CryptoJS.AES.decrypt({ciphertext:CryptoJS.enc.Hex.parse(ciphertext), salt:CryptoJS.enc.Hex.parse(salt)}, key);
    return decrypted;
}

var {ciphertext, salt} = EncryptAES('The quick brown fox jumps over the lazy dog', 'my passphrase');
console.log('Ciphertext (hex): ', ciphertext);
console.log('Salt (hex): ', salt);

var decrypted = DecryptAES(ciphertext, salt, 'my passphrase');
console.log('Decrypted: ', decrypted.toString(CryptoJS.enc.Utf8));

However, there is an easier way to handle salt and ciphertext. For a CipherParams object, .toString() returns the data in the Base64 encoded OpenSSL format consisting of the hex encoding of Salted__ followed by the 8 bytes salt and the actual ciphertext. CryptoJS.AES.decrypt() implicitly converts such a Base64 string into a CipherParams object:

var encrypted = CryptoJS.AES.encrypt('The quick brown fox jumps over the lazy dog', 'my passphrase').toString();
console.log("Salt, ciphertext (OpenSSL format, Base64): ", encrypted);

var decrypted = CryptoJS.AES.decrypt(encrypted, 'my passphrase');
console.log("Decrypted: ", decrypted.toString(CryptoJS.enc.Utf8));

Answer: CryptoJS expects a certain format for its encrypted data. If you're supplying only the hexadecimal string of the ciphertext, you'll need to reconstruct this formatted data when decrypting. Here's an example:
function EncryptAES(text, key) {
  var encrypted = CryptoJS.AES.encrypt(text, key);
  return encrypted.toString();  // this will be a string includes salt, iv and ciphertext
}

function DecryptAES(ciphertext, key) {
  var decrypted = CryptoJS.AES.decrypt(ciphertext, key);
  return decrypted.toString(CryptoJS.enc.Utf8); // decode to original text
}

In the EncryptAES function, by calling encrypted.toString(), it will generate a string which includes salt, iv, and ciphertext. When we decrypt it, we don't need to handle salt and iv separately.
However, if you are only dealing with the ciphertext (hexadecimal string), you can decrypt it using:
function DecryptFromHex(ciphertextHex, key, iv) {
  var cipherParams = CryptoJS.lib.CipherParams.create({
    ciphertext: CryptoJS.enc.Hex.parse(ciphertextHex)
  });
  var decrypted = CryptoJS.AES.decrypt(cipherParams, CryptoJS.enc.Utf8.parse(key), { iv: CryptoJS.enc.Utf8.parse(iv) });
  return decrypted.toString(CryptoJS.enc.Utf8);
}

DecryptFromHex takes the hexadecimal ciphertext string, parses it back into a format that CryptoJS can understand, and then decrypts it. Note that the key and the iv are also parsed from UTF8 to the WordArray format that CryptoJS uses.
Ensure the key and iv you use for the decryption match those used for encryption.
Comment: This answer looks like ChatGPT

CryptoJS AES decrypt Hex String?


Sum elements along a line of numpy array

Question: I have a big matrix of shape (977,699). I would like to compute the sum of the elements along a line that starts approximately from the center of the matrix. The angle of the line should vary from 0 to 180 degrees (with respect to another line that passes from the center of the matrix) with steps of 20 degrees. For each step I want to have the sum of the elements, thus the output should be a numpy array of 10 elements. How could I do that in numpy?
I think I have found the way of doing what I want but I still need help. Here there is an example:
data = array([[  0.,   3.,   0.,   2.,   0.,   0.,   0.,   0.,   0.,   3.],
              [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
              [  0.,   0.,   0.,   0.,  18.,  15.,  25.,   0.,   0.,   0.],
              [  0.,   0.,   0.,  23.,  19.,  20.,  20.,   0.,   0.,   0.],
              [  0.,   0.,  20.,  22.,  26.,  23.,  18.,   0.,   0.,   0.],
              [  0.,   0.,   0.,  23.,  16.,  20.,  13.,   0.,   0.,   0.],
              [  0.,   0.,   0.,   0.,  18.,  20.,  18.,   0.,   0.,   0.],
              [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
              [  0.,   4.,   0.,   0.,   3.,   0.,   0.,   3.,   0.,   0.]])

def index_coords(data, origin=None):
    """Creates x & y coords for the indicies in a numpy array "data".
    "origin" defaults to the center of the image. Specify origin=(0,0)
    to set the origin to the lower left corner of the image."""
    ny, nx = data.shape
    if origin is None:
       origin_x, origin_y = nx // 2, ny // 2
    else:
        origin_x, origin_y = origin
    x, y = np.meshgrid(np.arange(nx), np.arange(ny))
    x -= origin_x
    y -= origin_y
    return x, y

def cart2polar(x, y):
    """Transform carthesian to polar coordinates"""
    r = np.sqrt(x**2 + y**2)
    theta = np.arctan2(y, x)
    return r, theta

a,b = index_coords(data,origin=(4,4))
r,theta = cart2polar(b,a)

degree = theta*(180.0/np.pi) # degrees
d = degree.astype(np.int) # from float to integer (degrees at all pixels)

d = array([[-135, -143, -153, -165,  180,  165,  153,  143,  135,  128],
           [-126, -135, -146, -161,  180,  161,  146,  135,  126,  120],
           [-116, -123, -135, -153,  180,  153,  135,  123,  116,  111],
           [-104, -108, -116, -135,  180,  135,  116,  108,  104,  101],
           [ -90,  -90,  -90,  -90,    0,   90,   90,   90,   90,   90],
           [ -75,  -71,  -63,  -45,    0,   45,   63,   71,   75,   78],
           [ -63,  -56,  -45,  -26,    0,   26,   45,   56,   63,   68],
           [ -53,  -45,  -33,  -18,    0,   18,   33,   45,   53,   59],
           [ -45,  -36,  -26,  -14,    0,   14,   26,   36,   45,   51]])

Once I have "d array", I want to sum all the elements of "data array" which are located at the same degrees with respect to the origin, i.e. along 180, along 165, along 161 and so on till zero degrees. The output should be an array containing degree and the sum of element for that degree, i.e. out = array ([[180,sum along 180],[165, sum along 165],...[0, sum along 0]]). Could you help me with that? Thank you
Comment: It's not entirely clear what you want: what is a "line" in a matrix, especially one that varies? It appears you want to apply geometry to the notion of a matrix. Perhaps a little sketch can help. Also: what have you so far tried yourself?
Comment: Have a look at the example I've just edited, I hope it is more clear..
Answer: Maybe the radon transform contains the projection you are looking for or possibly is what you are describing. An example with code for the transform along with some reconstruction methods can be found in the scikit-image documentation here
Try copying and pasting this:
import numpy as np
from skimage.transform import radon

image = np.zeros([100, 100])
image[25:75, 25:50] = np.arange(25)[np.newaxis, :]

angles = np.linspace(0., 180., 10)

# If the important part of the image is confined
# to a circle in the middle use circle=True
transformed = radon(image, theta=angles)

import matplotlib.pyplot as plt
plt.matshow(image)
plt.matshow(transformed.T)
plt.show()

The transformed matrix contains one column per angle and all projection lines in the direction encoded this angle over the whole image. If your image is circular, it is useful to specify circle=True so that it does not project the borders.
Comment: Unfortunately I am having trouble to install the skimage package and I cannot try out your example. I edit the new code, can you please look at that? Thanks
Comment: OK, could you just take a quick look at the wikipedia entry for radon transform to see if this is actually what you want?
Comment: OK, from what you describe, your problem is a sort of subproblem of the radon transform. What is necessary, if you want to do this by hand, is to smooth the lines slightly, otherwise you will probably miss many relevant pixels.
Comment: Could you please give me an example?
Comment: you need to build a set of matrices that represent the rays along which you want to look. Since the radon transform does something like this, you can go and take the relevant part of their code without installing skimage (but it would be better to just install it). You would need to apply the transformation 4x separately on each quarter of the image


Why does OCTGN keep asking me to update? I already have the new version!

Question: OCTGN keeps asking me to update even though I've already updated to the latest version.
Answer: This most likely happens because your shortcut points to an old version of OCTGN. Early this month, the OCTGN development group released an update that moved the current version of OCTGN to My Documents\Octgn\OCTGN\OCTGN.exe or Documents\OCTGN\OCTGN\OCTGN.exe. Your shortcut needs to point there. To fix it, right-click on it, select properties, and enter the first location (Windows XP) or the second (Windows Vista, Windows 7, and Windows 8, I assume) in the target field. Then click okay.


Failure to use ml5.js image classification model-Error: Based on the provided shape, [1,64,64,4], the tensor should have 16384 values but has 20155392

Question: I trained an image classification neural network model written in ml5.js. When I try to use the model files in a p5.js web editor, I get an error 'Based on the provided shape, [1,64,64,4], the tensor should have 16384 values but has 20155392'.
The code is in this p5 sketch - https://editor.p5js.org/konstantina1/sketches/85Ny1SC2J (clicking on the arrow in the top right corner will show the files).
When I run a local server on a web page with the same structure, I see 'model ready!' (a confirmation that the model has loaded) and that's it.
I read a lot of comments that the bin file may be corrupt - I saved the model myself producing the bin file so it should be ok.
As suggested here by the author of very similar code, https://www.youtube.com/watch?v=3MqJzMvHE3E, adding pixelDensity(1) in setup() doesn't help.
I am new to machine learning, could someone please help? Thank you in advance.
Answer: The model was trained with images 64x64 px so the input test image must be the same size.
1944 (original image width) * 2592 (original image height) * 4 (number of channels) = 20155392. The tensor should have 64 (image width) * 64 (image height) * 4 (number of channels) = 16387 values. This is what the error refers to.

The copy() method used originally didn't resize the input image properly.
The correct way to resize the image is inputImage.resize(IMAGE_WIDTH, IMAGE_HEIGHT).
Working sketch: https://editor.p5js.org/konstantina1/sketches/85Ny1SC2J
Answer: A version of the sketch with image file upload: https://editor.p5js.org/konstantina1/sketches/qMNkkkbIm


any $\lambda-$pure morphism in a $\lambda$-accessible category is a monomorphism

Question: I'm trying to understand the proof of the proposition 2.29 in the book
Locally presentable and accessible categories which is also given in the snippet below.
I've got stuck in the -2nd paragraph there: the existence of $h$ is unclear to me. Can someone kindly help me to understand how existence of $\bar{v}$ helps us with existence of $h$ having the property  $$h\cdot (\bar{f}\cdot p')=h\cdot(\bar{f}\cdot q')$$?
Comment: Ah, I see. The old question https://math.stackexchange.com/questions/3020241/lambda-accessible-categories-unclear-proof was on the same topic but different.
Answer: I'll be a bit pedantic to make sure there are no misunderstanding, but the idea is supersimple. Denote by
$$F : (\mathbf{Pres}_{\lambda}\mathcal{K} \downarrow B) \to \mathbf{Pres}_{\lambda}\mathcal{K} \qquad F(B', v: B' \to B)=B'$$ the canonical diagram of $B$, since $\mathcal{K}$ is $\lambda$-accessible, $(\mathbf{Pres}_{\lambda}\mathcal{K} \downarrow B)$ is $\lambda$-filtered.
Now since $K$ is $\lambda$-presentable you have
$$\mathcal{K}(K, B) \cong \varinjlim \mathcal{K}(K, F) = \varinjlim_{v: B' \to B} \mathcal{K} (K, B').$$
At this point notice that the equality $\bar{v} \cdot (\bar{f} \cdot p')= \bar{v} \cdot (\bar{f} \cdot q')$ is telling you (in force of the above) that that $\bar{f} \cdot p' \in \mathcal{K} (K, \bar{B})$ and $\bar{f} \cdot q' \in \mathcal{K} (K, \bar{B})$ have the same image in the colimit, i.e., recalling how ($\lambda$-)filtered colimits are computed in $\mathbf{Set}$,that there has to be an object $(B', v: B' \to B)$ and a map $h : (\bar{B}, \bar{v}) \to (B', v)$ in the domain $\mathbf{Pres}_{\lambda}\mathcal{K} \downarrow B$ of the canonical diagram $F$ such that the map $$(\mathcal{K}(K,F))(h)= h \cdot - : \mathcal{K}(K, \bar{B}) \to \mathcal{K}(K,B')$$ sends $\bar{f} \cdot p'$ and $\bar{g} \cdot q$ to the same element, i.e. s.t. $h \cdot (\bar{f} \cdot p') = h \cdot ( \bar{f} \cdot q')$.
Comment: Good answer, thank you.
Answer: The map $f\cdot p = f\cdot q: K\to B$ factors in two ways through
the object $\bar{B}$ in the canonical diagram of $B$:
(a) via $\bar{f}\cdot p': K\to \bar{B}$
(b) via $\bar{f}\cdot q': K\to \bar{B}$.
Therefore there exists some object $B'$ at some "later stage", i.e. connected
through some $h: \bar{B} \to B'$ in the canonical diagram of $B$, through
which both maps extend to a common factorization. This is how the $h$
comes into this.
In Definition 1.1 of the book, this is the explicit description of the
essential uniqueness of the factorizations (phrased there for the finite
case and directed diagrams)
The $h$ equalizes $\bar{f}\cdot p'$ and $\bar{f}\cdot q'$.
Comment: I have an idea what is $\bar{v}$ good for $h$ here, but I'd prefer to hear it from you, Marc.
Comment: There is nothing special about $\bar{v}$. Once the two maps factor through it, there is a common factorization of them through some $v$.
Comment: Is this the same as saying that $\bar{f}\cdot p'$ has the same codomain as $\bar{f}\cdot q'$ in the filtered canonical diagram ?
Comment: I do not have time now, we can continue  via e-mail


Does PyOpenSSL verify_certificate() do signature verification

Question: I use PyOpenSSL verify_certificate() to verify certificate chains. My code seems to work. But I was wondering if the function also checks the signatures along the certificate chain. Lets assume we have the chain ca_cert -> i_ca_cert -> s_cert. Thus ca_cert signed i_ca_cert and i_ca_cert signed s_cert. Does verify_certificate() check whether the signer's (RSA) key was used to sign the certificate and whether the signature is correct, for every certificate along the chain?
Comment: Related... OpenSSL 1.0.2 and earlier *does not* perform hostname matching. OpenSSL 1.1.0 *does* perform hostname matching. Also see [SSL/TLS Client | Verification](https://wiki.openssl.org/index.php/SSL/TLS_Client#Verification) on the OpenSSL wiki.
Comment: When in doubt, I always check https://www.openssl.org/docs/man1.0.2/man1/verify.html
Answer:
But I was wondering if the function also checks the signatures along the certificate chain

Of course it does. Otherwise what is the purpose of chain verification? From the OpenSSL documentation (man 1ssl verify on linux):

The final operation is to check the validity of the certificate chain. The validity period is checked against the current system time and the notBefore and notAfter dates in the certificate. The certificate signatures are also checked at this point.


$X^A \equiv B \pmod{2K + 1}$

Question: I recently found this problem which asks you to find an algorithm to find all $X$ such that $X^A \equiv B \pmod{2K + 1}$.
Is there something special about the modulus being odd that allows us to solve it?
Comment: Exhaustive search will solve $x^a\equiv b\pmod c$ whether $c$ is even or odd, so you can always solve it (at least, in theory).
Comment: Dear @Gerry: By "you can always solve it", I guess you mean: "you can always decide if it is soluble, and solve it if it is". Don't you?
Comment: @Pierre, yes, that would have been a better way to say it.
Comment: The range is quite large $(2K \leq 10^9)$. Exhaustive search can't solve $1000$ cases in $2$s I think. Does this problem have anything to do with _primitive roots_ or _discrete logarithm_?
Answer: The author of the problem once wrote an article about baby-step-giant-step algorithm (but in Chinese).
The baby-step giant-step is a meet-in-the-middle algorithm computing the discrete logarithm.
I think this article may help you.
http://en.wikipedia.org/wiki/Baby-step_giant-step

$X^A \equiv B \pmod{2K + 1}$


iOS 14 Change kind of a widget that is already in production

Question: I have a static widget as below and deployed to production.
<code>struct ABCWidget: Widget {
    let kind: String = "xyzWidget"
    var body: some WidgetConfiguration {
           StaticConfiguration(kind: kind,
}
</code>
Now I want to change the kind to "abcWidget" but when I do it, on the upgrade I see a black box for the installed widget. Is there any way to do this change without impacting existing customers.
Thanks!
Comment: There might be other folks who have a better idea about how to do it in Swift than me. But that seems like a basic versioning problem.  And versioning is a pain. If you want to change a software interface, and you already have people depending on the old interface... you have to have 2 versions. Old version, and new version. Once your logs show people have upgraded off the version that used old version then you can retire old version.  Unfortunately... changing to lowercase is your new version.
Comment: I want to change the let kind: String = "xyzWidget" to "abcWidget". Not the ABCWidget struct.
Comment: Doh. Misread it.
Answer: No, there's no way to "upgrade" your existing users to a bee widget or widget configuration.
That said, the "kind" string isn't visible to your users so it doesn't matter what it is. Just leave the old string.
Comment: It's not visible.. but I want to add some generic method for usage of every widget, so I have to do it.. Thanks!


Listen close event of iexplorer in my application

Question: I am writing a win32 application by C++, and I want it to do something when all iexplorer.exe were closed.
I know that SetWindowsHook() may be useful in my case.
But if I have no idea about the process or thread ID of IE, because every time open IE would get a different thread ID.
If I do not use timer to check the process list to get the ID of iexplorer, does there have another approach to listen close event of IE in my win32 application?
Answer: The object for IE is called InternetExplorer. TheShellWindows object is a collection of InternetExplorer objects. But here it gets complicated. Not all InternetExplorer objects are what you would call an IE window. Some of them are "Windows Explorer" windows. See About the Browser (Internet Explorer).
The following is a managed C++ console program that lists the existing windows and sets a count of the number of existing windows. Then it uses WindowRegistered and WindowRevoked events to monitor creation and closing of windows. Those event are not documented very well. The sample below uses the Document member of each InternetExplorer object to determine if the window has HTML. However see the comment in c# - Distinguishing IE windows from other windows when using SHDocVw; it is possible for a IE window to not have HTML in it.
Note that the following sample is using an AutoResetEvent to keep the program going since it is a console program.
The following is the header:
<code>#pragma once

#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <ShlObj.h>
#include <comdef.h>
#include <vcclr.h>
</code>
The following is the program:
<code>#include "stdafx.h"
using namespace System;
using namespace System::Threading;

static int Browsers = 0;
static gcroot<AutoResetEvent^> Event;

bool IsBrowser(SHDocVw::InternetExplorer ^ ie)
{
    MSHTML::IHTMLDocument2^ Document;
    try { Document = (MSHTML::IHTMLDocument2^)ie->Document; }
    catch (Exception^ ex)
    {
        return false;
    }
    return Document != nullptr;
}

 static void WindowRegistered(int lCookie) {
    ++Browsers;
    Console::WriteLine("WindowRegistered");
}

static void WindowRevoked(int lCookie) {
    --Browsers;
    Console::WriteLine("WindowRevoked");
    if (Browsers <= 0)
        Event->Set();
}

int main(array<System::String ^> ^args)
{
    SHDocVw::ShellWindows^ swList = gcnew SHDocVw::ShellWindowsClass();
    Console::WriteLine(L"{0} instances", swList->Count);
    for each (SHDocVw::InternetExplorer ^ ie in swList) {
        Console::WriteLine(ie->LocationURL);
        if (IsBrowser(ie)) {
            Console::WriteLine("HTML document");
            ++Browsers;
        }
        else
            Console::WriteLine("Not HTML");
        }
    if (Browsers == 0)
    {
        Console::WriteLine("No browsers");
        return 0;
    }
    Event = gcnew AutoResetEvent(false);
    swList->WindowRegistered += gcnew SHDocVw::DShellWindowsEvents_WindowRegisteredEventHandler(WindowRegistered);
    swList->WindowRevoked += gcnew SHDocVw::DShellWindowsEvents_WindowRevokedEventHandler(WindowRevoked);
    Event->WaitOne();
    Console::WriteLine("No more browsers");
    return 0;
}
</code>
Now I just realized that there is a problem with the way this works. The WindowRegistered and WindowRevoked handlers are incrementing the Browsers count even if the window is not an IE window. I don't know how to determine what window that the cookie passed to WindowRegistered and WindowRevoked represents. A few years ago I spent a couple of days or more tryinig to figure that out. So what you should do is to somehow re-list all the windows after each WindowRegistered and WindowRevoked event.
You need to add references for "Microsoft Internet Controls" (SHDocVw.dll) and "Microsoft HTML Object Library" (mshtml.dll) to the project. They are COM objects that should be in your "C:\Windows\System32" directory.


Are smoke/CO detectors required to be interconnected with wire?

Question: I am planning on hardwiring 6 combination smoke/CO detectors on various levels of the house (2nd flr, 1st flr, basement) using 12/2 wire branching off from permitted sources (standalone 20a outlets).
Per IRC 314.3 and 314.4 I understand what the detector locations need to be and that they need to be interconnected, in order that they all sound an alarm when one of them does.
Kidde sells a great combo detector which communicates with its siblings via RF, thereby fulfilling the "sound one - sound all" requirement.  I am planning on using this type of detector for all 6 of mine.
I have searched high and low to find anything in the code (IRC 2015, NEC 2017, NFPA 72) that requires the smoke detectors to be HARD-WIRE INTERCONNECTED, instead of wirelessly interconnected, and found nothing.
Question: Can anyone point to a code section applicable to residential family housing where a hard wire interconnectivity requirement may exist?
The inspector mentioned he thinks detectors must not only be hard wired for power (which i will do) but also interconnectivity.
It would be a lot of extra work and intra-drywall fishing, let alone buying the 14/3 or 12/3 wire to do that, literally costing more and being more time consuming without any gain in safety, so i want to make sure i'm on solid footing if i have to defend my choice.
Comment: R314.5 seems pretty clear that wireless interconnection is permitted: *"Physical interconnection of smoke alarms shall not be required where listed wireless alarms are installed and all alarms sound upon activation of one alarm."*
Comment: My local IRC 2015 code version omits that wording as section 314.5 looks like this - https://up.codes/viewer/connecticut/irc-2015/chapter/3/building-planning#R314.5 -  but it also doesn't specifically state a wired requirement. Aside from some very unusual electromagnetic interference messing with the RF signal between the detectors (like running the microwave with the door open), i really don't see a downside, but i welcome any input that i may be blind to due to my potential confirmation bias.
Answer: There is not such a section, because there is no such requirement
The requirements for interconnect are designed intentionally to be technology-agnostic; as long as UL has put its stamp of approval on the system as part of the listing process, and it works in the field, you're good to go under the current model Codes.
Comment: That's what I thought, I just needed some confirmation I wasn't missing anything, much appreciated, ThreePhaseEel!  I have another question related to detector placement if you don't mind giving it a shot - https://diy.stackexchange.com/questions/229649/smoke-co-detector-location-within-a-bedroom


Dota 2 Workshop Content downloading, DLC unticked

Question: Okay, so basically everytime I restart steam or go into this one specific steam account, it always starts to download Workshop Content. DLC unticked, files deleted. As you can see in the image below, my internet speed is slow, so sometimes I have to wait 30 minutes till I can play without lag, it allows me to start dota and play it, but it keeps downloading. If I pause the download it instsantly unpauses it and keeps downloading the update. It has been happening for about 6 months now or more, before the update was only 30 mb big, now it's 120.
https://i.stack.imgur.com/VLMUF.jpg
Comment: Not all that great of a question, but I'll give it a shot.  Do you have any items in the inventory/any mods installed?
Comment: nothing installed on that steam acc, and computer has been reinstalled like 4 or 5 times since this started happening.
Comment: No items in the account's inventory? Items being in the inventory can cause downloads like these, especially if you have them equipped and they're updated.
Comment: Usually that's caused by workshop subscriptions. Please check the Dota2 workshop for active subscriptions.
Answer: The two things I know of that download as Dota 2 Workshop Content are Custom Games and guides. Guides are usually just a few kilobytes though, so I assume you are subscribed to Custom Games. A major update to one of these can be large.
To remove a custom game that you've installed, go to the Arcade tab, then the Library sub-tab:

Then click each game and the uninstall button. This will make them unavailable to play, but will prevent downloading these large updates for them that is causing you problems.


Where can I get this type of 'wood paneling'/'siding'/(name?)

Question: Sorry about my ignorance here but I don't know what to call this stuff.  I have a few wood (Pretty sure it's wood) boards that have falling off the side of the area that supports my deck.  Questions:

What are these boards called?
Is it possible to order it anywhere so I can replace it?

We also have some fascia(?) or molding that has come off (looks like the previous owner installed the gutters poorly.  So not sure I can get this fascia board at the same place? THANKS!
Comment: could be Hardieplank
Comment: @Jasen I am almost positive you are right on the siding. Trim by roof and gutter likely original wood.
Answer: Generically, that's called "Ship Lap" siding. What it is made of is another aspect; it could be wood such as cedar or redwood, it could be pressboard, it could be vinyl or even aluminum made to look like wood. You should be able to tell if it's vinyl or metal by tapping on it. If it's pressboard, you would be able, if you look long enough, to see repeating grain patterns, something that never happens with real wood.
That fascia / molding and the roof joint needs some professional attention in my opinion. That's a tough spot for a typical DYI project and getting it wrong can leave you with some serious water damage.
Comment: Just "lap siding". Shiplap has a rabbet on the edges so every board lays flat rather than sitting at a slight angle like the pictured lap siding.
Comment: You guys are the best.  The previous owner(s?) have been known to frequent the local Home Depot and get absolutely everything there.  I think there's a very good chance this is the one:  https://www.homedepot.com/p/James-Hardie-HardiePlank-HZ10-5-16-in-x-8-25-in-x-144-in-Fiber-Cement-Select-Cedarmill-Lap-Siding-215518/100064049


md-autocomplete dropdown overlaps the input when using md-floating-label

Question:
When adding md-floating-label to angular material's md-autocomplete
The dropdown suggestion items are overlapping the input area of the autocomplete.
Note: all css used are default
Comment: Can you create a snippet or bin for this? It will be easier for us to understand the problem and help you.
Answer: As a last resort I needed to add a custom CSS
.md-autocomplete-suggestions-container{
    margin-top: 2em;
    width:auto;
}

Comment: For rapid resolution, thanks! But the autocomplete without md-floating-label  show this margin gap...
Answer: Don't put floating in input, but put it in common parent element/div of input and drop down.


How to give subfield to a field of a document in couch db using java program?

Question: I want to insert data in document in the following format:
<code>_id:"c0b3457b1d6e5f8431d62a31fd00073c"
Name:"priya"
Education:
       10th:"68.9%"
       12th:"62.83%"
       graduation:"69.73%
       post-graduation:"71.55%"
</code>
i want this format through programming . new to couchdb.
Answer: Try it...
<code>Session studentDbSession = new Session("localhost",5984);

           Database studentCouchDb = studentDbSession.getDatabase("student");

           Document newdoc = new Document();

           HashMap<String , String> properties = new HashMap<String,String>();

           newdoc.setId("c0b3457b1d6e5f8431d62a31fd00073c");

           newdoc.put("Name", "Priya");

           properties.put("10th", "69.9");

           properties.put("12th", "62.83");

           properties.put("Graduation", "69.73");

           properties.put("Post_Graduation", "71.55");

           newdoc.put("Education", properties);

           studentCouchDb.saveDocument(newdoc);
</code>


Congruence $320 \equiv 1 (\text{mod }x)$

Question: I have the following congruence $320 \equiv 1 (\text{mod }x)$
And the question is : find all the modulos $x$ that make this congruence true.
Comment: $x$ has to divide $319$
Comment: ho thanks ! it was easy
Comment: @GregoryGrant not only has, but it is also sufficient for $x$ to divide $319$. i.e. $x$ satisfies the conditions iff $x$ divides $319$.
Answer: Well basically the definition of $$a \equiv b (\text{mod }n)$$ is that n should divide $(a-b)$ So according to your question $x$ should divide $320-1$ that is $319$. It would be $11$ and $29$
Since you want all the $x$'s then it would be $11$, $29$ and $319$
Comment: and 319 too....
Comment: Yes I saw that thanks@HonzaBrabec
Comment: And $1$. And, if you allow negative moduli (some people do), four more.
Comment: @AndréNicolas 320 mod 1 is 0.
Comment: @HonzaBrabec 0 is congruent to 1 (mod 1).
Comment: @wythagoras Thanks :)
Comment: I dont know.... i just provided few answers @AndréNicolas i dont want to tell all answers
Comment: Yes i know 1 will be there@AndréNicolas
Answer: $320 \equiv 1 (\text{mod }x)  \rightarrow 320-1 \equiv 0 (\text{mod }x) \rightarrow 319 \equiv 0 (\text{mod }x) \rightarrow x=11$ or $29$, since that only works for the divisors.
Answer: $320 \equiv 1 \pmod{x} \implies x \mid 320 -1 =319$ and hence there exists an integer $k$ such that $$xk = 319$$
Now should find all pairs $x,k$ that when you multiply them together you get $319$
$1 \times 319$
$29 \times 11$
$-1 \times -319$
$-29 \times -11$
any one of these 8 numbers can work for $x$
Basically you get the prime factorization for $319$ and then you add to your list the negatives of these numbers plus the number itself plus 1, that will give you a complete list for the divisors of $319$ or generally any number.


JavaScript: Print character with number of uninterrupted occurrences for each sequence of characters

Question: This is not a duplicate of Counting the occurrences / frequency of array elements
There are differences.
I've got an array with chars:
const data = ['a', 'a', 'b', 'x', 'x', 'x', 'a'];

I need to count each sequence of characters and print character with number of uninterrupted occurrences like this (each line should log after program finds uninterrupted occurrences:
a: 2
b: 1
x: 3
a: 1

I thought to use 'while' but I'm stuck a little bit on this logic.
const countSeq = (arr) => {

  while (arr.length > 0) {

    // logic there

    console.log(/*char: count number*/);

    if (arr.length === 0) break;

  }

}

Sorry for bothering, I'm just learning. Thanks in advance!
Comment: @a1tern4tive that was not my intent - i genuinely want to help if you have something specific about where you get stuck. you'll learn best if you push yourself
Answer:

const data = ['a', 'a', 'b', 'x', 'x', 'x', 'a'];

const result = data.reduce((acc, val) => {
    const prevSeq = acc[acc.length - 1];

    if (!prevSeq || prevSeq.key !== val) {
        acc.push({ key: val, count: 1 });
    } else {
        prevSeq.count++;
    }

    return acc;
}, []);

console.log(result);
Comment: @Andreas He can ask a question in a comment. His answer is not valid JS, on this he may also ask a question.
Comment: @Andreas *are better* I'm not saying that my answer is good, but I don't see the answers anymore at all, if you open the topic deeper, I'll delete my answer
Comment: The output of your answer does not match the expected output


Why don't I have permission to use WorldEdit?

Question: I'm trying to install WorldEdit, and I've done the following:

Gotten the craftbukkit JAR,
run it, stopped it,
replaced world with my save from single,
run again, stopped again,
copied WorldEdit.jar into plugins,
tried //hpos1 and other WorldEdit commands.

I get the following error:

You don't have permission to do this

What causes this? (I'm on a Mac, if that's a factor)
Comment: what are you using as permissions plugin / are you using a permissions plugin?
Comment: @alexanderpas i dont use any permissions plugin. Somehow i managed to get myself permitted with pure WorldEdit on an ooold software. Didnt know it changed... Which is the best permission plugin ?
Comment: Perhaps try oopping yourself, If you do not want to use a permissions plugin. Just type /op  in the console. This should work.
Answer: Due to the nature of worldedit, worldedit requires you to specify permissions, either the build in, or by using a permissions plugin
Worldedit uses the WEPIF (WorldEdit Permissions Interoperability Framework) to handle permissions.
If you're not using a permissions plugin, the easiest way is using Flat file permissions which allows you to simply give yourself all permissions by editing two files in the root of your server (same location as bukkit itself):
perms_groups.txt
admins:*

perms_users.txt
sk89q:admins:*

(replace sk89q with your username)
There's a list of permissions, on the Worldedit Wiki which can help you if you want to further specify permissions
Comment: I am sorry but that does not seem to work... Maybe im not in the group 'admins' ?

(Really, which perms plugin do you recommend? http://plugins.bukkit.org/#ti=permissions&ta=all&au=&subm=false&pno=0)
Comment: nevermind! works! perfect! Ive messed too much with worldedit's config.yml, sorry! Thanks!
Comment: @alexanderpas I'm doing it for him.
Comment: He can't upvote until he reaches 15 rep, remember? :)
Answer: I realize this is a very old thread but for those players who still need help I will offer my limited experience.
Recently the bukkit commands have changed to include minecraft commands that basically have the same permissions but are preceded with minecraft instead of bukkit. For example:
  - bukkit.command.op
becomes

minecraft.command.op

and so on.
I had the same problem described above and solved it by adding all the minecraft.commands to my perms. I use Groupmanager.
I found this information at:
http://wiki.bukkit.org/CraftBukkit_Commands
The new perms are listed under Mojang Permission on the spreadsheet.
I suspect bukkit is being phased out to be replaced by a Microsoft system under the heading of Mojang.
Regardless, I no longer get the dreaded fail message. :)
Answer: Man this took me so long to figure out. I'm using Paper minecraft server and what I needed to do was add this to my permissions.yml:
server.basics:
       description: Basic permissions for my server.
       default: true
       children:
              worldedit.*: true


React Native PanResponder onStartShouldSetPanResponder locationX varies by platform

Question: I'm new to RN gesture apis, so if any of this looks like a fundamentally incorrect approach, I would really appreciate the feedback as well as any suggestions on where to look instead. Thanks!
Goals

use the PanResponder api to handle tap only and swipe gestures
use onStartShouldSetPanResponder to handle tap only and pre-move swipe
guarantee that the event.nativeEvent handled by onStartShouldSetPanResponder has positioning information relative to the ListComponent, not a child of the list component.

The following code receives a different event.nativeEvent according to whether I am testing via expo's local web server and expo ios app. This seems reasonable, given how different the underlying infrastructures are.
My hunch is that on ios, the onStartShouldSetPanResponder handler is firing 'too late' (or too early?), that is, the gesture is being attributed to a child component, so the event bubbling up to this handler has positioning relative to the child component, not the list component in the render function below.
const panResponder = useRef(
  PanResponder.create({
    onStartShouldSetPanResponder: (event: GestureResponderEvent) => {
      console.log(event.nativeEvent.locationX)
      updateSelectionValue(event.nativeEvent.locationX) // does some math and conditionally updates local state
    },
    onStartShouldSetPanResponder: () => true,
    onPanResponderMove: handleSwipe,
  })
).current

return (
  <View onLayout={handleLayout} {...panResponder.panHandlers}>
    <ListComponent proportion={selectionValue} {...props} />
  </View>
)

Given that the list component is 300px wide, and there are 3 100px wide items in the list component, tapping approximately 5/6 of the width from left side of the list component yields a locationX of ~250/300 (correct) on web and 50/300 on ios.
List     [----------------300px----------------]
Children [---100px---][---100px---][---100px---]
Tapping Here ---------------------------^^

It seems that on ios, the event is positioned relative to the 3rd 100px wide child element.
Additional Context:
node --version
v15.12.0

"dependencies": {
  "expo": "~40.0.0",
  "expo-status-bar": "~1.0.3",
  "react": "16.13.1",
  "react-dom": "16.13.1",
  "react-native": "https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz",
  "react-native-web": "~0.13.12"
},

Answer: ended up setting a ref onLayout and ignoring event.nativeEvent in favor of gestureState.x0 and gestureState.moveX
let coords = useRef({ x: -1, y: -1 }).current

const handleLayout = useCallback((event: LayoutChangeEvent) => {
  const { x, y } = event.nativeEvent.layout
  coords = { x: Math.round(x), y: Math.round(y) }
}, [])
...
const panResponder = useRef(
 PanResponder.create({
   onStartShouldSetPanResponder: () => true,
   onPanResponderStart: (event, gestureState) =>
   updateSelectionValue(gestureState.x0 - coords.x),
   onPanResponderMove: (event, gestureState) =>
   updateSelectionValue(gestureState.moveX - coords.x),
  })
).current


How to remove 'www.' with awk in output file

Question: How can I remove all the 'www.' with awk in my output file.
e.g.: my output file has multiple sites like
abc.com
www.def.com
blabla.org
www.zxc.net

I would like to remove all the www. in my output file:
abc.com
def.com
blabla.org
zxc.net

Comment: Why "with awk"?
Comment: BTW, this is a subset of the space covered in [BashFAQ #21](http://mywiki.wooledge.org/BashFAQ/021)
Comment: Possible duplicate of [Remove unwanted character using awk](https://stackoverflow.com/questions/8008546/remove-unwanted-character-using-awk)
Comment: What would you want to happen if one of the lines in your output file was just `www.org` (one alias for the W3C home page)?
Answer: Probably better done in sed:
 sed -i 's/^www\.//g' outputFile

In awk:
 awk '{gsub(/^www\./,"",$0)}1' outputFile

Comment: get rid of the `g` from both commands. You can't remove from the front of a string more than once. You also don't need the `,$0` in the awk command as that's the default.
Comment: Probably better to use `sed -i 's/^www\.//g' outputFile` to avoid cases like `thisisawww.net`.
Comment: @Defenestrator Good idea. I've updated both `sed` and `awk` with the `^`
Answer: This is probably what you're looking for:
$ cat file
abc.com
www.def.com
blabla.org
www.zxc.net
www.org
www.acl.lanl.gov

$ sed -E 's/^www\.(([^.]+(\.|$)){2,})/\1/' file
abc.com
def.com
blabla.org
zxc.net
www.org
acl.lanl.gov

The above uses a sed that has -E for ERE support, e.g. GNU or OSX sed. Note the need for a more comprehensive input file to test if a proposed solution really works or not.


Computation of contour integral without winding numbers.

Question: I am trying to solve problem $3$ on page 108 in Ahlfors. The problem asks to compute $\int_{\left\vert z \right\vert = 2} \frac{dz}{z^2 - 1}$ so I am trying to do so without the use of winding numbers, which isn't introduced until later sections.
I first used partial fraction decomposition to write $\frac{1}{z^2 - 1}$ as $\frac{1}{2} \cdot (\frac{1}{z-1} - \frac{1}{z+1})$. From here, it's clear that the integral is $0$ if we resort to winding numbers. Since I was unable to compute the integral using elementary methods, I resorted to reading this solution. However, I don't understand how they changed the path of integration from $\left\vert z \right\vert = 2$ to $\left\vert z - 1 \right\vert = 1$ because when $z = -2$, $\left\vert z - 1 \right\vert = \left\vert -3 \right\vert = 3 \ne 1$.
Comment: So you aren't allowed to use the fact that $\oint_C 1/z\, dz = 2\pi i$ for any positively oriented Jordan curve about $0$? If not, why not just evaluate each integral directly, e.g. use substitution $z = 2e^{it}$ and so $\oint_{|z|=2} \frac{1}{z-1} dz  = 2i\int_0^{2\pi}\frac{e^{it}}{2e^{it}-1}\, dt = \left[i\log(2e^{it}-1)\right]_0^{2\pi} = 2\pi i.$ I don't know how to account for the manipulation used in the solutions with just the information you provided - it looks like the solutions are homework solutions? They are probably using extra information not yet introduced in Ahlfors.
Comment: I don't have the text. Can you use the Cauchy theorem?
Comment: @SeanRoberson Cauchy's integral formula and Cauchy's theorem haven't been introduced at this point. All we know is what a line integral is and that the integral of $\frac{1}{z-a}dz$ taken over a circle centered at $a$ is $2\pi i$
Comment: Ah I didn't think to use the derivative of log. Thank you!
Answer: You have
\begin{align}
\int_{\left\vert z \right\vert = 2} \frac{dz}{z^2 - 1}&=\frac12\int_0^{2\pi}\left(\frac{2ie^{it} }{2e^{it}-1}-\frac{2ie^{it} }{2e^{it}+1}\right)\,dt\\ \ \\
&=\frac12\left.\left(\log(2e^{it} -1)-\log(2e^{it}+1)\right)\right|_0^{2\pi}\\ \ \\
&=0-0=0
\end{align}
Answer: This is a fairly general argument you will probably find useful.
Note that the function $\frac{1}{z^2-1}$ is analytic everywhere except the points $1$ and $-1$. This means that we can move the contour so long as the singular points ($1$ and $-1$) remain inside the domain. We can deform the contour into an infinity-looking domain, where the touch point is the origin, and the center of the two circles located in the infinity are $1$ and $-1$. Because those are essentially two different circles, the integral around the contour is equal to the sum of the integrals around the two circles. These two circle's new contours are $|z-1| = 1$ and $|z+1| = 1$ (note they still intersect at the origin). Now, we can use the formula you know regarding $2 \pi i$, which would then yield the answer of $0$.
Comment: And this leads to the homotopic version of the Cauchy theorem.


How can I choose which chapter to play in Spartan Ops?

Question: I have completed chapter one with friends in a private match and I just finished playing chapter 2 online, but there does not seem to be an option to choose which chapter to play when online matchmaking.
I want to play chapter one online so I can get it on legendary and after that I want to go to chapter 3 but I only have the option to play chapter 2 online.
Can somebody tell me how I can choose or is there no option to choose?
Comment: Related, but not a dupe of: http://gaming.stackexchange.com/questions/92466/can-you-change-difficulty-on-spartan-ops-multiplayer
Answer: In "matchmaking" Spartan Ops (where you play with your Halo 4 party or with random strangers) the available ops and their difficulty is set by Microsoft/343 Industries and you may only select from ones that they have chosen for you.  The current rotation appears to change weekly.  To date, this has always been the "op released this week" when ops are being released, and it has varied in the off season.  (One week it was a grab bag, but now it seems to be one Episode per week, on Legendary)
In "private game" Spartan Ops (where you can either play solo or with a party of up to 4 friends), you can choose from any of the unlocked ops, and you can pick the difficulty level.
Answer: In "matchmaking" Spartan Ops (where you play with your Halo 4 party or with random strangers) the available ops and their difficulty is set by Microsoft/343 Industries and you may only select from ones that they have chosen for you. The current rotation appears to change weekly. To date, this has always been the "op released this week" when ops are being released, and it has varied in the off season. (One week it was a grab bag, but now it seems to be one Episode per week, on Legendary)
In "matchmaking" Spartan Ops (where you play with your Halo 4 party or with random strangers) the available ops and their difficulty is set by Microsoft/343 Industries and you may only select from ones that they have chosen for you. The current rotation appears to change weekly. To date, this has always been the "op released this week" when ops are being released, and it has varied in the off season. (One week it was a grab bag, but now it seems to be one Episode per week, on Legendary)


R: parallel makePSOCKcluster hangs

Question: I'm trying to connect to another computer via makePSOCKcluster:
library(parallel)
cl <- makePSOCKcluster('10.0.0.107')

Unfortunatelly it hangs. I have done passwordless login with the help of ssh-keygen and ssh command in the console works on both computers.
I have also tried:
cl <- makePSOCKcluster('10.0.0.107', outfile = '')

and got the following error:
starting worker pid=2937 on blabla:11225 at 17:41:20.364
Error in socketConnection(master, port = port, blocking = TRUE, open = "a+b",  :
  cannot open the connection
Calls: <Anonymous> ... doTryCatch -> recvData -> makeSOCKmaster -> socketConnection
In addition: Warning message:
In socketConnection(master, port = port, blocking = TRUE, open = "a+b",  :
  blabla:11225 cannot be opened
Execution halted

Then suggested by Steve Weston's answer I have tried the manual mode. I went step by step with debugging slaveRSOCK function. I got stuck on:
Error in socketConnection(master, port = port, blocking = TRUE, open = "a+b",  :
  cannot open the connection
In addition: Warning message:
In socketConnection(master, port = port, blocking = TRUE, open = "a+b",  :
  blabla:11225 cannot be opened

I have also tried to open any port using
sudo iptables -A INPUT -p tcp --dport 11000 -j ACCEPT
sudo iptables -A OUTPUT -p tcp --dport 11000 -j ACCEPT

and it's variations on both computers.
On both laptops I have the same version of R (R.3.2.2) and parallel package. One computer has Ubuntu 14.04 and the other - Kubuntu 14.04.
Please help.
Comment: Have you checked your router's configuration?
Comment: No, could you tell me what I should do?
Comment: You should take a look at your the device owner's manual for more info.
Answer:
Open a port on machine 1 for listening
sudo nc -l <portnumber> and leave the terminal open
From another terminal check if netstat -an |grep <portnumber> |grep LISTEN is showing the port as LISTENING
from machine 2 , run nc machine1 <portnumber> and see if u are able to connect and type something

If the above works fine , then your router setup is correct.
90% chance that the issue is due to router and firewall settings.

R: parallel makePSOCKcluster hangs


Can adding version tags be mandatory?

Question: I have seen a lot of questions lately that will have different answers, depending on whether the user is running Drupal 6 or Drupal 7.  Very often the first comment is "What version of Drupal?"
Is there a way to make adding 6, 7, or 8 be mandatory?
Comment: To clarify the Drupal version for which the OP is interested, it is not necessary to use a tag.
Comment: I think this needs to be revisited. I agree that there should be mandatory version numbers. Drupal 7 differs greatly from 6 and therefore the answers do as well. I find myself skipping over questions that do not clarify.
Comment: See: http://meta.drupal.stackexchange.com/questions/229/version-tags-considered-harmful and
http://meta.drupal.stackexchange.com/questions/2541/version-tags-the-sequel
Comment: I don't know why this question getting negative vote. I noticed this post too.
Comment: @Bala Voting on meta is different.  Instead of good/bad, it mans agree/disagree (see http://meta.stackoverflow.com/help/whats-meta).  Downvotes here think mandatory version tags are a bad idea.
Comment: I agree with kiamlaluno, every Drupal Answers user should clarify the Drupal version within the question text if necessary. Forcing to choose a version would be a bad idea (think about all the questions regarding drush which is independent from Drupal's core versioning system).
Answer: As far as I can see, on meta sites there are tags that are marked as mandatory, such as discussion; if the software they run is the same, then it should be possible to do the same on the main site.

The problem is that the version tags should not be mandatory, but used when strictly necessary. I should not use 6 because I am using Drupal 6, but because the question (and the answers) is only valid for Drupal 6. When somebody see the question, and see it's tagged 6, he could decide not to read the answers because he is interested in Drupal 7, but the answers could still be valid for Drupal 7. I could ask a question that doesn't depend from the Drupal version; if you force me to select a version tag, then I should use at least two. This would mean that, when Drupal 8 is out, somebody would read my question and, seeing it is tagged 6 7 could think it's a question for those Drupal versions, when it is not so.
It is not different from tagging a question c#-4.0 when I am asking the syntax to use for the "switch" statement, which was not introduced in C# 4.0. You could object that in Stack Overflow you could tag the question with "c#," but the equivalent tag in Drupal Answers would be "drupal" that you can consider an invisible tag always added to every question.
Comment: My counterargument would be that questions should be tagged with the version of Drupal that the user happens to be using, and be retagged with other versions if the question is generic.  Very often users don't know that some situations are version specific, but most of the users (at least the ones with retag permissions) do know.
Comment: The problem is at the moment, [tag:9] doesn't exist. What would happen when Drupal 9 is out? Would you add the tag to every question that is not specific for a Drupal version?
Answer: Some questions can be version independent. Well, most questions that does not depend on actual api should be version independent. And if question have different answers for different versions, nothing prevents posting them all.
Mechanism detecting phrases like "Drupal 7" in body or title and suggesting appropriate tags would be nice, but I think we may do it by hand easily enough.
Comment: Note: above answer was migrated here from much more recent question (closed as duplicate). It had a bit different feel in previous context, or so I think. I wouldn't post it here as kiamlaluno's one was sufficient and more comprehensive already.
Comment: I thought this was a good answer, and this is an important topic, so I decided that merging was better than simple close-as-duplicate.

Can adding version tags be mandatory?


ValueTuples lose their property names when serialized

Question: While trying to serialize a named value tuple to JSON string, it loses the names assigned to items
(string type, string text) myTypes = ("A", "I am an animal");
var cnvValue = JsonConvert.SerializeObject(myTypes);

I am expecting the serialized value as

{"type":"A","text":"I am an animal"}

but the actual results are

{"Item1":"A","Item2":"I am an animal"}

There are two things that i am interested to know

Why does it behave like that
How to get the expected output
Comment: FYI https://github.com/JamesNK/Newtonsoft.Json/issues/1505
Answer:
How to get the expected output

Something like this:
var myTypes = new{ type = "A", text = "I am an animal"};
var cnvValue = JsonConvert.SerializeObject(myTypes);

should work if you're looking for a similarly terse approach. Doesn't use ValueTuples (but anonymous types) under the hood though; this is my interpreting your question as "how can I produce this expected JSON without going to the full extent of declaring a class etc"
Comment: You interpreted it in the correct sense. I used ValueTuples to do exactly that.
Answer: The names are a compiler trick. If you look at the definition for ValueTuple you'll see that its field names are just Item1, Item2, etc.
Since JsonConvert.SerializeObject was compiled well before you assigned names that you could use during your compilation, it cannot recover the names.
Method parameters/return types are decorated with attributes that indicate the names to be used when a method's signature includes ValueTuples. This allows code authored later to "see" the names by the compiler playing tricks again, but that's the "wrong way around" to be of much use here.

How to get the expected output

Introduce an explicit type, if the names of the fields/properties are so important.
Comment: @AvnerShahar-Kashtan *Anonymous type* are not explicit anyway
Comment: I do not want to create an explicit type to use it only once. But still I want the names of items to appear in JSON string.
Comment: Important to note that the explicit type could be an *anonymous type*.
Comment: If you want the better names, you need to at least use an anonymous type, or a named type. `ValueTuple` will not help you, as you've seen.
Answer:
How to get the expected output

Use explicit custom type or anonymous class like in @Caius answer.
Or don't create special type for it at all (for anonymous type compiler generates class behind the scene for you) and use JObject to dynamically create json:
var myTypesJson = new JObject(
    new JProperty("type", "A"),
    new JProperty("text", "I am an animal")
);
var cnvValue = myTypesJson.ToString();

or use indexer and initialization syntax for it:
var createdJson = new JObject()
{
    ["type"] = "A",
    ["text"] = "I am an animal"
};
var cnvValue = createdJson.ToString();


How to slid left/right two divs using jquery?

Question: I am new to coding and I am trying to achieve the following using JQuery:
I have two Divs Where clicking on the first shows some content and clicking the second would hide the content of the first one and show its content instead (Toggling). What I want to do is that I want to keep the same functionality but I want the second Div to slide to the right when I click on the first Div and make a drawer shape and vice versa. I have attached images to it so it may explain more about my idea.
both of contents are hidden by default.
I can't seem to know how to join these two functionalities together
HTML
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Test</title>

    <link rel="stylesheet" href="style.css" />

Title one

          Lorem ipsum dolor sit amet consectetur, adipisicing elit. Inventore
          quidem ex tenetur ipsum dolore repudiandae molestiae mollitia! Dolore
          numquam.

Title two

          Lorem ipsum dolor sit amet consectetur, adipisicing elit. Inventore
          quidem ex tenetur ipsum dolore repudiandae molestiae mollitia! Dolore
          numquam.

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla voluptatem
      veritatis assumenda. Obcaecati veniam quo impedit tempora pariatur maiores
      ipsa voluptates commodi esse eveniet! Nihil corrupti illum at accusantium
      sit? Lorem ipsum dolor sit amet consectetur adipisicing elit. Ut veritatis
      et molestias? Reprehenderit distinctio sint provident ratione dolorem
      veritatis sapiente, fuga amet obcaecati. Laboriosam rerum consectetur nemo
      magnam saepe mollitia. Lorem ipsum dolor sit amet consectetur adipisicing
      elit. Excepturi sit perferendis earum debitis corrupti dolore commodi
      minima consectetur veniam itaque inventore et pariatur sapiente, maxime
      quis, in nulla, eos molestias! Lorem ipsum dolor sit amet consectetur,
      adipisicing elit. Quasi, incidunt repudiandae perferendis ea praesentium
      blanditiis, voluptate accusantium, repellat molestiae quisquam eveniet
      earum officia sed assumenda maxime officiis sequi laboriosam! Tempore.
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Alias modi hic
      officia iste optio in delectus veniam obcaecati reprehenderit, voluptate
      ipsum! Incidunt ducimus animi, id quae blanditiis provident dignissimos
      harum?

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla voluptatem
      veritatis assumenda. Obcaecati veniam quo impedit tempora pariatur maiores
      ipsa voluptates commodi esse eveniet! Nihil corrupti illum at accusantium
      sit? Lorem ipsum dolor sit amet consectetur adipisicing elit. Ut veritatis
      et molestias? Reprehenderit distinctio sint provident ratione dolorem
      veritatis sapiente, fuga amet obcaecati. Laboriosam rerum consectetur nemo
      magnam saepe mollitia. Lorem ipsum dolor sit amet consectetur adipisicing
      elit. Excepturi sit perferendis earum debitis corrupti dolore commodi
      minima consectetur veniam itaque inventore et pariatur sapiente, maxime
      quis, in nulla, eos molestias! Lorem ipsum dolor sit amet consectetur,
      adipisicing elit. Quasi, incidunt repudiandae perferendis ea praesentium
      blanditiis, voluptate accusantium, repellat molestiae quisquam eveniet
      earum officia sed assumenda maxime officiis sequi laboriosam! Tempore.
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Alias modi hic
      officia iste optio in delectus veniam obcaecati reprehenderit, voluptate
      ipsum! Incidunt ducimus animi, id quae blanditiis provident dignissimos
      harum?

CSS
body {
  display: inline-block;
  margin: 100px 100px 25px 100px;
  text-align: center;
}
#box-container {
  height: 300px;
  display: flex;
}
#div1 {
  background: linear-gradient(90deg, #f57350, #fa8282);
  width: 50%;
  height: 50%;
  cursor: pointer;
}

#div2 {
  background: linear-gradient(90deg, #a42e5a, #f57350);
  width: 50%;
  height: 50%;
  cursor: pointer;
}
#contentDiv1,
#contetnDiv2 {
  margin: 25px;
}

JQuery
jQuery(document).ready(function($){
    $('#contentDiv1').hide();
    $('#contentDiv2').hide();

    $('#div1').on('click', function(){
        $('#contentDiv1').slideToggle();
        $('#contentDiv2').hide();
    });

    $('#div2').on('click', function(){
        $('#contentDiv2').slideToggle();
        $('#contentDiv1').hide();
    });
});

attached image
Comment: Please add your HTML code as well.
Comment: We are going to need more information then this like some css, html, the rest of your functions etc what would be perfect is a live example of what you have at the moment!
Comment: I added both the html and css
Answer: It has more than one solution, and for me, this is my favorite method, I hope it helps you:

$('.tabs .tab').on('click', function () {
  if ($(this).hasClass('active')) {
    $(this).removeClass('active')
    .closest('.tabs').removeClass('active1 active2');
    $('.content').hide();
  } else {
    let i = $(this).index() + 1;
    $(this)
        .addClass('active')
        .siblings('.tab').removeClass('active')
        .closest('.tabs').removeClass('active1 active2')
        .addClass('active' + i);

    $('.content').hide();
    $('.content' + i).fadeIn();
  }
});
.tabs,
.tabs .tab,
.tabs .content {
    border: 1px solid #000;
    border-collapse: collapse;
    box-sizing: border-box;
}
.tabs {
    display: flex;
    flex-wrap: wrap;
    text-align: center;
    position: relative;
}
.tabs.active1 {
    padding-left: 0;
    padding-right: 65px;
}
.tabs.active2 {
    padding-left: 65px;
    padding-right: 0;
}
.tabs .tab {
    padding: 15px;
    cursor: pointer;
    min-width: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}
.tabs.active1 .tab,
.tabs.active2 .tab {
    min-width: 100%;
    width: 100%;
}
.tabs .content {
    padding: 15px;
    min-width: 100%;
    display: none;
}
.tabs.active1 .tab1:not(.active),
.tabs.active2 .tab1:not(.active){
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    min-width: 65px;
    width: 65px;
}
.tabs.active1 .tab2:not(.active),
.tabs.active2 .tab2:not(.active) {
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    min-width: 65px;
    width: 65px;
}

div1

div2

div content1

div content2

Comment: Thank you a lot.. this is a great solution.. How can I get to the normal position using close button for example? I mean if i click on a button  in the content body to close it and get the two divs on the same line?
Comment: It has a solution
I will immediately modify the code
Comment: You are a life saver! I can't thank you enough! I will try applying it to me code
Comment: Hello Emy, hope you are doing well. I was wondering if it's possible to reach you personally. I need your help on a website i am working on. thank you


AWS Cognito Admin GetUser with associated groups

Question: I am using aws cognito sdk with .net core 3.1 webapi. The issue is, I have to display users info as well as user groups. ListUserApi https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html doesn't return users group information. According to the docs I have to call other api ListUserInGroups (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsersInGroup.html) but as I need both information on single table. This call would be really expensive for me. Is there any other api which returns user's profile info as well as user group info. I tried to find one but couldn't
Also one other question do aws cognito api provied sorting functionality? Like sort by name of email? I can only see filtering option but not sorting.
Comment: I would suggest to use DynamoDB to store only the userData you want to display. You can call a Lambda-function every time you create a user, add user to group, delete user, etc. and handle the data for DynamoDB. There you can easily query, filter and sort your data for your needs.
Answer: No, there is no API to get list of users with group they are associated with.
If you only want group names associated with that user you try this workaround ,this will reduce some api calls :
Get All Groups using - ListGroups
now for each group call ListUsersInGroup,so you know group assigned with that list
var listUsersInGroupRequest = new ListUsersInGroupRequest
{
    UserPoolId = UserPoolId,
    GroupName = groupName
};

ListUsersInGroupResponse response = (await provider.ListUsersInGroupAsync(listUsersInGroupRequest));

var groupList = response?.Users.Select(x => new UserDTO()
{
    FirstName = x.Attributes.SingleOrDefault(x => x.Name == "given_name")?.Value,
    SurName = x.Attributes.SingleOrDefault(x => x.Name == "family_name")?.Value,
    Email = x.Attributes.SingleOrDefault(x => x.Name == "email")?.Value,
    Sub = x.Attributes.SingleOrDefault(x => x.Name == "sub")?.Value,
    Groups = groupName,
    UserName = x.Username
});

now you have different list of users for each group, so you can concat all list and use GroupBy by sub/username and aggregate string groups
allConcatedUserDTO.GroupBy(row => row.Sub)
    .Select(x => new UserDTO()
    {
        Sub = x.Key,
        UserName = x.FirstOrDefault()?.UserName ?? string.Empty,
        Email = x.FirstOrDefault()?.Email ?? string.Empty,
        FirstName = x.FirstOrDefault()?.FirstName ?? string.Empty,
        SurName = x.FirstOrDefault()?.SurName ?? string.Empty,
        Groups = string.Join(",", x.Select(y => y.Groups))
    }).ToList();

And ListUsers and ListUsersInGroup does not provide sorting functionality, but when you provide filter attribute in ListUsers request, result will be sorted by attribute name provided for filtering in ascending order.


How do I download other players' replays?

Question: It says that you can view replays that you've downloaded from other players, but so far, I can't find out where to go to download them. Is there a specific menu in which you can download replays from other players?
Any answers would be appreciated.
Answer: It seems you can download replays only from viewing the "Player License" of another player. You can get to that from various places, such as the "Soul Link" if they're marked as your rival, a multiplayer match while you're still connected and in the lobby with them, or your Battle Log in the Replay section of online multiplayer.
If you want to find the Player License of a friend that you haven't played against recently or registered as a rival, you can do that from the Leaderboards. Just switch the Filter a couple of times until it's only showing you and your friends list.
Once you're in the Player License, there should be an indicator telling you which button to press to download their replays. On Xbox 360 it's X, so I'm guessing it would be Square on PS3.


How to install HPLIP 3.20.3 or above in Ubuntu 20.04

Question: When trying to install HPLIP 3.20.5 or 3.20.9 it crashes due to dependency problem mainly because of pyqt5 and lot of other dependencies.
If I tried to install those dependencies manually some of them are not listed in Ubuntu repository. From where I will get those dependencies.
Thanks for any help...
Comment: What is your HP device model? What was wrong with simple `sudo apt-get install hplip-gui`?
Comment: Unable to communicate with device (code=12): hp:/usb/DeskJet_5820_series?serial=CN7CB5G2DC06BP
Comment: HP Deskjet Gt 5821 - It was working in 18.04
Answer: I have an HP DeskJet Ink Advantage 4535 All-In-One printer and the HPLIP version 3.21.2 works on my Ubuntu 20.04 LTS version. However, I must point out that the first installation of the HPLIP package (downloaded from the HPLIP website because the Ubuntu's package did not work) did not install properly. It failed to install my printer in wireless mode. But second time I went ahead and installed the printer in USB mode. It required a rebooting of the system. And currently it is working fine in USB mode and even the scanning function works smoothly. The GUI tray still poses problem.


Pushing dist subtree to GH-Pages

Question: I'm trying to automate my build chain to push my generated doc to github gh-pages.
Here's the workflow:
Jenkins checkout the remote sources to a local master branch.
It builds the project locally (generates binary to target/staging, e.g. mvn site site:staging).
Then I've a shell post step:
git push origin --delete gh-pages #removes the existing remote gh-pages branch
git checkout -b gh-pages # creates a local gh-page branch
git rm -rf . #untrack everything
git add target/staging #adds the generated doc to tracking
git commit -am "Added staging" commit changes
git subtree split --prefix target/staging -b gh-pages #subtree branch to gh-pages branch

So, I thought it was something like this, but a weird 'Branch 'gh-pages' is not an ancestor of commit ...' Hits me in the face...
Has anyone got the solution to be able to push this subtree in the remote github banch?
Thank you in advance
Disclaimer's, I tested github-site-plugin and scm-publisher but I've too many files in my site for these plugins...
Answer: Looks like you forgot to delete the local gh-pages branch:
$ git branch -D gh-pages

Answer: I found a nice shell on github that does this: https://github.com/X1011/git-directory-deploy
However, I'm always open for an inline answer :)

Pushing dist subtree to GH-Pages


Unable to instantiate RollingFileAppender

Question: I am trying to create a RollingFileAppender through java code.
The below code always throws a null pointer Exception for the line appender.start() stating RollingFileAppender 'null': No name provided. I am unable to set the name because the name is usually set by the RollingFileAppender plugin.
https://logging.apache.org/log4j/2.x/log4j-core/apidocs/src-html/org/apache/logging/log4j/core/appender/RollingFileAppender.html
Please advise how to instantiate the RollingFileAppender.
public static RollingFileAppender getAppender() {

        final TimeBasedTriggeringPolicy timeBasedPolicy = new TimeBasedTriggeringPolicy.Builder().withModulate(true).build();
        timeBasedPolicy.start();
        RollingFileAppender appender = new RollingFileAppender.Builder()
                     .withFileName("fileName")
                    .withFilePattern("pattern")
                    .withPolicy(timeBasedPolicy)
                    .build();
        appender.start();
        return appender;
}

Comment: What type of object is `loggerAppender` and where is it initialised in your code? Without knowing anything about what it is, presumably, you need to call a method of that object to make it aware of your RollingFileAppender.
Comment: @sorifiend - Apologies, actually it's appender. start. Edited the question now
Answer: package com.demo.example;

import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.appender.RollingFileAppender;
import org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExampleApplication {

  public static RollingFileAppender getAppender() {

    final TimeBasedTriggeringPolicy timeBasedPolicy = new TimeBasedTriggeringPolicy.Builder().withModulate(true).build();
    timeBasedPolicy.start();
    RollingFileAppender appender = new RollingFileAppender.Builder<>()
        .withFileName("fileName")
        .withFilePattern("pattern")
        .withPolicy(timeBasedPolicy)
        .setName("MyAppender")
        .build();
    appender.start();
    return appender;
  }

  public static void main(String[] args) {
    Appender app = ExampleApplication.getAppender();
  }
}

POM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.demo</groupId>
    <artifactId>example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>example</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.17.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.17.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>2.6.1</version>
        </dependency>
     </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Error
Exception in thread "main" java.lang.IllegalStateException: Pattern does not contain a date
    at org.apache.logging.log4j.core.appender.rolling.PatternProcessor.getNextTime(PatternProcessor.java:154)
    at org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy.initialize(TimeBasedTriggeringPolicy.java:117)
    at org.apache.logging.log4j.core.appender.rolling.RollingFileManager.initialize(RollingFileManager.java:170)
    at org.apache.logging.log4j.core.appender.RollingFileAppender$Builder.build(RollingFileAppender.java:153)
    at com.demo.example.ExampleApplication.getAppender(ExampleApplication.java:20)
    at com.demo.example.ExampleApplication.main(ExampleApplication.java:26)

Comment: The above setName cannot be done and it throws error
Comment: @Harish Please see the full code above . SetName is working fine.


Can I infer this about probability of drawing a queen or heart from deck of a cards (twice in a row) no replacements?

Question: So I know the probability of drawing a queen or a heart from a deck of cards is 4/13
Let A be the event a heart or queen is drawn on the first draw
Let B be the event a heart or queen is drawn on the second draw
If I were to draw twice from the deck, with no replacements would, could I assume that
P(A⋂B) + P(A⋂BC) = P(A) = 4/13
I found myself making this assumption and was like...wait...can I?
Comment: Well, the probality of doing $A$ will be whatever it is regardless of anything else in the world.  And the events of $B$ and the events of *not* $B$ are mutually exclusive and exhaustive so $P(A\cap B) + P(A\cap B^C)$ had *better* be equal to $P(A \cap (B\cup B^c)) = P(A\cap [anything]) = P(A)$.  If not our development of this mathematical model is not aligned with reality.  .... Now just how this model *does* align with reality...
Answer: Yes, that's correct, because $A\cap B$ and $A\cap\overline B$ are mutually exclusive, and their union is $A$.
Answer: Yes.  $P(A$ or $C)= P(A) + P(C) - P(A\cap C)$.
And as $A = A\cup (B\cap B^c) = (A\cap B) \cup (A\cap B^c)$ then
$P(A) = P(A\cap B) + P(A\cap B^c) - P([A\cap B] \cap [A\cap B^c])$
But as $B$ and $B^c$ are mutually exclusive $A\cap B$ and $A\cap B^c$ are mutually exclusive so $P([A\cap B] \cap [A\cap B^c]) = 0$.
Basically "the probability of $A$ is the probability of $A$ with something happening plus the probability of $A$ with that something not happening" and that really has to be true.


How to upload video to bunyy.net using API PHP

Question: I'm trying to upload video to my library on bunny cdn using API but I can't find how to upload it.
In their docs you I can't find how to upload the video only create a title for the video but no upload the video its self.
Here is the API request from the docs
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('PUT', 'https://video.bunnycdn.com/library/libraryId/videos/videoId', [
  'headers' => [
    'accept' => 'application/json',
  ],
]);

echo $response->getBody();

I have found here that you have to create a video first and this ok but the part of uploading the video content is not the same.
You can see they add a link to the docs but its not the same same as in the image as there is a upload video button in the image but in the docs there isn't.
Comment: Do you have the use the Stream API? On their site it looks like they have an official PHP library for their Edge Storage API: https://github.com/BunnyWay/BunnyCDN.PHP.Storage
Answer: The Bunny API is really poorly documented, I spent a lot of time figuring out how to make it work:
Let's move forward step by step.
First of all we must select the file to upload: below is the html code to do so:
index.html
<form id="uploadForm" enctype="multipart/form-data">
  <input type="file" name="videoFile" accept="video/*">
  <progress value="0" max="100" id="progressBar"></progress>
  <button type="button" onclick="uploadVideo()">Upload Video</button>
</form>

I also included a progress bar to visually display the upload progress.
As you can see there is an onclick action with a javascript function to handle the loading.
Also include jQuery to handle the upload

then the function
function uploadVideo() {
        const formData = new FormData(document.getElementById('uploadForm'));

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            xhr: function () {
                const xhr = new XMLHttpRequest();
                xhr.upload.addEventListener('progress', function (event) {
                    if (event.lengthComputable) {
                        const percent = (event.loaded / event.total) * 100;
                        $('#progressBar').val(percent);
                    }
                }, false);
                return xhr;
            },
            success: function (data) {
                alert('Video uploaded successfully!');
                $('#progressBar').val(0);
            },
            error: function () {
                alert('Error uploading video. Please try again.');
                $('#progressBar').val(0);
            }
        });
    }

upload.php
$apiKey = "your-library-api-key"; //the library apiKey
$libraryId = "the-library-id";
$file = $_FILES['videoFile']['tmp_name'];
$videoName = "the-name-of-the-video";

function upload_video($video_path, $auth_key, $library_id, $video_name) {
  $base_url = "https://video.bunnycdn.com/library/";

  // Initialize cURL session
  $ch = curl_init();

//first of all we have to create the video

  // Set cURL options
  curl_setopt($ch, CURLOPT_URL, $base_url . $library_id . "/videos");
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("title" => $video_name)));
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "AccessKey: " . $auth_key,
    "Content-Type: application/json"
  ));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // Execute cURL request
  $response = curl_exec($ch);

  // Close cURL session
  curl_close($ch);

  // Check if video create was successful
  //then begin the upload process
  if ($response !== false) {
    // Initialize cURL session
    $ch = curl_init();

    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $base_url . $library_id . "/videos/" . json_decode($response)->guid);
    curl_setopt($ch, CURLOPT_PUT, 1);
    curl_setopt($ch, CURLOPT_INFILE, fopen($video_path, "rb"));
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($video_path));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      "AccessKey: " . $auth_key
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Execute cURL request
    $response = curl_exec($ch);

    // Close cURL session
    curl_close($ch);

    // Check if upload was successful
    if ($response !== false) {
      return true;
    }
  }

  return false;
}

$response = upload_video($file, $apiKey, $libraryId, $videoName);
//get the bunny response
echo $response;

I hope I have been helpful.
However with this code I have some problems with files larger than 100Mb.
I'm still trying to figure out why.
Answer: Upload it as a raw file not an encoded one. This is from a laravel PHP and it worked for me. You can also test it in postman and set the Headers with the AccessKey and Go to Body and choose Binary and upload a video e.g mp4.
$fileData = file_get_contents($request->file('video')->getRealPath());

$uploadResponse = Http::withHeaders($uploadHeaders)
    ->withBody($fileData, 'application/json')
    ->put($apiEndpoint);

if ($uploadResponse->successful()) {
    return response($uploadResponse->body())->header('Content-Type',
    $uploadResponse->header('Content-Type'));
} else {
    return response()->json(['error' => 'File upload failed'], $uploadResponse->status());
}


Getting JSON from a URL

Question: I am attempting to get a JSON string and it keeps coming up NULL and I am not sure why. Can someone check to see if I got my code right?
<code>$url = "http:/engin.umich.edu/college/about/cal/event-calendar/futurejson";
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
     $feed = curl_exec($ch);
     curl_close($ch);

    $data = json_decode($feed,true);
</code>
Comment: You have a typo in the URL, it should begin `http://` -- you're missing one of the slashes. You also need to enable the `CURLOPT_FOLLOWLOCATION` option, because it returns a redirect.
Comment: Can you post the contents of `$feed` ?
Comment: Can you post the result of `curl_error($ch)`? You can put that after the line `$feed = curl_exec($ch);`. It will tell you if there were problems fetching the url.
Answer: <code> $url = "http://engin.umich.edu/college/about/cal/event-calendar/futurejson";
 // missing /  ^
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
 // It's returning a redirect to www.engin.umich.edu
 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
 $feed = curl_exec($ch);
 curl_close($ch);

 $data = json_decode($feed,true);
</code>
Comment: I wonder why is it that when I go to the page in a browser its pure JSON but your telling me its a redirect? That might explain why I am getting NULL - Syntax error, malformed JSON when I fixed the // issue.
Comment: Browsers follow redirects automatically. CURL requires you to set an option for this, otherwise it returns the redirect status and you have to follow it yourself if you want.
Comment: Thanks! Fixing the URL and then dumping the result and clicking on the redirect link finally showed me where the data actually lived.

Getting JSON from a URL


Ruby String: how to match a Regexp from a defined position

Question: I want to match a regexp from a ruby string only from a defined position. Matches before that position do not interest me. Moreover, I'd like \A to match this position.
I found this solution:
code[index..-1][/\A[a-z_][a-zA-Z0-9_]*/]

This match the regexp at position index in the string code. If the match is not exactly at position index, it return nil.
Is there a more elegant way to do this (I want to avoid to create the temporary string with the first slice)?
Thanks
Answer: You could use ^.{#{index}} inside the regular expression. Don't know if that's what you want, because I don't understand your question completely. Can you maybe add an example with the tested String? And have you heard of Rubular? Great way to test your regular expressions.
This is how you could do it if I understand your question correctly:
code.match(/^.{#{index}}your_regex_here/)

The index variable will be put inside your regular expression. When index = 4, it will check if there's 4 characters from the beginning. Then it will check your own regular expression and only return true if yours is valid as well. I hope it helps. Good luck.
EDIT
And if you want to get the matched value for your regular expression:
code.scan(/^.{#{index}}([a-z_][a-zA-Z0-9_]*)/).join

It puts the matched result (inside the brackets) in an Array and joins it into a String.
Comment: The only problem with this approach is that `your_regex_here` cannot use `\A` or `^`. Reasonable solution if Mildred doesn't need to anchor anything at the beginning (or if they can modify their regex appropriately) though.