text:
Q: bash mv command in script to rename a file but I got an error I have a problem with my script. I want to rename a file but I have an error
mv: cannot stat '/home/lidian/Video/dvd.iso': No such file or directory

Here is my script:
DESTINATION="/home/lidian/Video/dvd.iso"
DESTINATIONFINAL="/home/lidian/Video/"
read -p "what is the name of ISO ? " REP

mv -t "${DESTINATION}" ${DESTINATIONFINAL}"$REP.iso"

A: There is a syntax error in bash. Try splitting the first line as follows:
DESTINATION="/home/lidian/Video/dvd.iso"
DESTINATIONFINAL="/home/lidian/Video/"
read -p "what is the name of ISO ? " REP

mv -t "$DESTINATION" "$DESTINATIONFINAL$REP.iso"

I also removed redundant brackets and moved quotes.

A: The problem is probably you're using ~ tilde in the input. Tilde expansion does not expand/happen inside quotes regardless if it is single or double. Well you do a test on the user input and see if the input is indeed valid.


text:
Q: General question about quotient rings I hope to better understand the notion of a quotient ring through this example:
I am given $R=\mathbb{Z}[i]=\{a+bi:a,b\in \mathbb{Z}\}$ and $M=\{a+bi: 3|a,3|b\}$. I have already shown that $M$ is a maximal ideal of $R$, but I am also asked to show that $R/M$ is a field with $9$ elements. I understand that $R/M$ is the set of cosets of $M$ in $R$, but for rings I am confused as to what these look like. For instance, do I look at $k+M$ or $kM$ for $k\in R$? How am I to show that there are $9$ cosets?
$\mathbf{Note:}$ If you can clarify what $R/M$ looks like for me, I think I would be able to find the answer on my own.

A: This used to confuse me as well. Generally, the line of thinking that helps me is that two cosets $k$ and $k^{'}$ are equivalent mod $M$ if and only if $k-k^{'}$ is an element of $M$. In your example that means two cosets $\overline{a+bi}$, $\overline{c+di}$ are equivalent if and only if $3 \mid a-c$ and $3 \mid b-d$. Think about which kinds of elements satisfy this. You should be able to think of 9 natural coset representatives.

A: $M$ is $(3)$, the principal ideal generated by $3$ in $\mathbb{Z}[i]$.  Can you think of a good set of representatives for all the cosets of $(3)$?  What values of $a$ and $b$ might you pick for $(a + bi) + (3)$?

A: Hint: You could write out the multiplication table, but there's an easier argument: What happens when you mod out by a maximal ideal?
Quotient rings are made up of additive cosets, i.e. the elements of your quotient ring $R/M$ look like $k+M$ with $k\in R$.
Here are a few cosets, all distinct from eachother: $M$, $1+M$, $1+i+M$. I also claim that $2+M=5+3i+M=2+6i+M$ (why?). Hopefully this is enough for you to see what's going on. Feel free to comment if you still have questions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: a tag href data with newlines I am using angularjs and am trying to create a system of downloading a vcard created in javascript. In order for the vcard to work on mobile, the data needs to be downloaded through an a tag. The problem is everytime I set the href="data:text/vcard, "+ string it saves the vCard but removes the newlines. vCards only work with newlines
Is there any way to keep the newline characters while saving data?
$scope.saveVcard = function(){
    var user = $scope.member;
    var out_string = 'BEGIN:VCARD\nVERSION:2.1\n\rN:' + user.last_name + ';' + user.first_name + ';;;\n\r'; //name
    out_string += 'FN:' + user.first_name + ' ' + user.last_name + '\n\r';//FN
    if (user.phone){
    out_string += 'TEL;CELL:' + user.phone + '\n\r';} //Phone
    if (user.email){
    out_string += 'EMAIL;PREF;INTERNET:' + user.email + '\n\r';}//Email
    if (user.prof_pic){
    out_string += 'PHOTO;PNG:'+user.prof_pic + '\n\r';}//picture
    out_string += 'END:VCARD';
           var a         = document.createElement('a');
           a.href        = 'data:text/vcard,' + out_string;
           a.target      = '_blank';
           a.download    = 'contact.vcf';
           console.log(a.href);
           document.body.appendChild(a);
           a.click();
           document.body.removeChild(a);

A: Aha, I figured it out, simply use the function encodeURIComponent().
var a = document.createElement('a');
       a.href        = 'data:text/vcard,' + encodeURIComponent(out_string);
       a.target      = '_blank';
       a.download    = 'contact.vcf';
       console.log(a.href);
       document.body.appendChild(a);
       a.click();
       document.body.removeChild(a);


text:
Q: How to make color as alpha (remove a color) in SFML? I have a texture in the sprite and I want to make background invisible (white color).
sf::Texture texBohatera;
texBohatera.loadFromFile("bohater.png");

sf::Sprite bohater;
bohater.setTexture(texBohatera);

A: Something like this should work.
sf::Image image;
image.LoadFromFile("bohater.png");
image.CreateMaskFromColor(sf::Color::White);

sf::Texture texBohatera;
texBohatera.LoadFromImage(image);

sf::Sprite bohater;
bohater.SetTexture(texture);

(Disclaimer, I didn't test it because I don't want to install SFML)

A: you could
window.clear(sf::Color::White);
or find a program that allows you to draw png files like piskel.
you can either import the file and erase the areas you want transparent.
 or draw your own sprite.


text:
Q: ngx-translate: translations are not shown on reload In my webapp, I use ngx-translate module for localization. It works ok for html strings which I translate using pipes. I am having problems with strings translated in my ts components. Strings get translate but if I reload page they are empty strings, if I go to other page inside my app and come back they are again normal. I have method defined:
public getTranslation(key: string){
    let str="";
    this.translate.get(key).subscribe(value => {str = value});
    return str;
}

So when I define variables I use:
variable: string = this.getTranslation("key-in-my-json-file")

my configuration in app.module, loader:
export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

and in imports:
TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useFactory: (createTranslateLoader),
    deps: [HttpClient]
  }
})

my versions in package.json:
"@ngx-translate/core": "^8.0.0",
"@ngx-translate/http-loader": "^1.0.2",
"typescript": "2.5.2"

and angular version 4.3.6

A: Try using localStorage. For example, I use it in a function when changing the language:
public changeLanguage(lang) {
  this.languageActive = lang;
  this.translateService.use(lang);
  localStorage.setItem("language", this.languageActive);
}

A: Surround the line with minimal timeout it will work then.
setTimeout(()=> {
          variable: string = this.getTranslation("key-in-my-json-file");
}, 500);


text:
Q: How to Loop Through Table Rows, Return and Remove NULL Values? I have a table like this:
 t=table(1 1 as x, 2 NULL as y)

I want to iterate over rows and return a vector that does not contain NULL. Taking the table above as example, I want to get [1,1] and [2]. How can I do?

A: Convert the t table to a matrix, transpose the matrix, and then loop through columns.
loop(x->x[x.isValid()], t.matrix().transpose())

After running the above code on this table, the result is returned as follows.
offset  0   1
0   [1,2]   [1]


text:
Q: how to calculate percentile of each 15 rows in python I have 810 rows in my data frame about vehicle speed and I was trying to calculate the 85th percentile speed for each 15 rows. Here what I did so far:
count = 0
stat1 = []
for i, row in df.iterrows():
    if count == 10:
        stat1 = df.dbl_v.quantile(0.85)
        count = 0
    else:
        count += 1

how can I store and see the 85th percentile speed? It's supposed to be there are 54 of 85th percentile speed.
Thankyou

A: We can create groups every 15 lines using the remainder of the division by 15
grouper = df.groupby(df.index // 15)

To create a new DF by applying .quantile to multiple columns, we can do this:
df_new = grouper.agg(
               quantile85 = ('dbl_v', lambda x: x.quantile(0.85))
              ,quantile20 = ('other_column', lambda x: x.quantile(0.20))
              ,mean_dbl_v = ('dbl_v', 'mean')
              ,sum_col3 = ('name_column3', 'sum')
               #and so on...
           )


text:
Q: Como guardar todas las filas que genera mi formulario en mysql +php + javascript Tengo el siguiente código:

<form action="guardar_bandas.php" id="" method="post">

        Nombre: <input id="nomb" name="nomb[]" style="margin:10px" type="text">

        Categoria:<input id="cat"  name="cat[]" style="margin:4px" type="text">

        Precio: <input id="precio" name="precio[]" style="margin:20px" type="text">

        Stock: <input id="stock"   name="stock[]" style="margin:25px" type="text">

                    Nombre
                    Categoria
                    Precio
                    Stock

<input class="md-trigger boton" data-modal="fodors" type="submit" value="Enviar" id="btn_inicia"/>

 </form>

<button id="btn_guardar" onclick="guardar()">Guardar</button>

Luego sigue el procesar que seria el archivo: guardar_bandas en donde tengo uso un for para que recorra el arreglo pero al momento de guardar los registros, solo inserta el ultimo registro.
el código funciona de la siguiente manera:
lleno los datos de cada input luego presiono el botón guardar y mediante javascript trae allí mismo una fila con la información, para luego presionar el botón enviar que esta dentro del form y que me guarde toda la información de cada fila que se cree.
Saludos.

A: El motivo por el que siempre te guarda el ultimo registro es porque los registros introducidos anteriormente no están en una etiqueta input valida que pueda enviarse al darle click al botón de Enviar del formulario, para ello tu codigo que inserta las nuevas filas de la tabla debería verse mas o menos así:


text:
Q: Visualizing ViT Attention maps after fine tuning on medical dataset I have imported the Vit-b32 model and fine-tuned it to perform classification task on echo images. Now I want to visualize the attention maps so that I can know on which part of the image the model is focusing for doing the classification task. But I am unable to do it and I am getting an error when I am trying to visualize the attention maps after fine-tuning the model.
Below is the code:
!pip install --quiet vit-keras
from vit_keras import vit
vit_model = vit.vit_b32(
        image_size = IMAGE_SIZE,
        activation = 'softmax',
        pretrained = True,
        include_top = False,
        pretrained_top = False,
        classes = 3)

When I try yo visualize the attention map without any finetuning then it is working without any error:
from vit_keras import visualize

    x = test_gen.next()
    image = x[0]

    attention_map = visualize.attention_map(model = vit_model, image = image)

    # Plot results
    fig, (ax1, ax2) = plt.subplots(ncols = 2)
    ax1.axis('off')
    ax2.axis('off')
    ax1.set_title('Original')
    ax2.set_title('Attention Map')
    _ = ax1.imshow(image)
    _ = ax2.imshow(attention_map)

Now in the below code I have added some classification layers to the model and fine-tuned it:
model = tf.keras.Sequential([
        vit_model,
        tf.keras.layers.Flatten(),
        tf.keras.layers.BatchNormalization(),
        tf.keras.layers.Dense(11, activation = tfa.activations.gelu),
        tf.keras.layers.BatchNormalization(),
        tf.keras.layers.Dense(3, 'softmax')
    ],
    name = 'vision_transformer')

model.summary()

Below is the output of the above cell:
> Model: "vision_transformer"
> _________________________________________________________________ Layer (type)                 Output Shape              Param #
> ================================================================= vit-b32 (Functional)         (None, 768)               87455232
> _________________________________________________________________ flatten_1 (Flatten)          (None, 768)               0
> _________________________________________________________________ batch_normalization_2 (Batch (None, 768)               3072
> _________________________________________________________________ dense_2 (Dense)              (None, 11)                8459
> _________________________________________________________________ batch_normalization_3 (Batch (None, 11)                44
> _________________________________________________________________ dense_3 (Dense)              (None, 3)                 36
> ================================================================= Total params: 87,466,843 Trainable params: 87,465,285 Non-trainable
> params: 1,558
> _________________________________________________________________

Now I have trained the model on my own medical dataset:
learning_rate = 1e-4

optimizer = tfa.optimizers.RectifiedAdam(learning_rate = learning_rate)

model.compile(optimizer = optimizer,
              loss = tf.keras.losses.CategoricalCrossentropy(label_smoothing = 0.2),
              metrics = ['accuracy'])

STEP_SIZE_TRAIN = train_gen.n // train_gen.batch_size
STEP_SIZE_VALID = valid_gen.n // valid_gen.batch_size

reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor = 'val_accuracy',
                                                 factor = 0.2,
                                                 patience = 2,
                                                 verbose = 1,
                                                 min_delta = 1e-4,
                                                 min_lr = 1e-6,
                                                 mode = 'max')

earlystopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_accuracy',
                                                 min_delta = 1e-4,
                                                 patience = 5,
                                                 mode = 'max',
                                                 restore_best_weights = True,
                                                 verbose = 1)

checkpointer = tf.keras.callbacks.ModelCheckpoint(filepath = './model.hdf5',
                                                  monitor = 'val_accuracy',
                                                  verbose = 1,
                                                  save_best_only = True,
                                                  save_weights_only = True,
                                                  mode = 'max')

callbacks = [earlystopping, reduce_lr, checkpointer]

model.fit(x = train_gen,
          steps_per_epoch = STEP_SIZE_TRAIN,
          validation_data = valid_gen,
          validation_steps = STEP_SIZE_VALID,
          epochs = EPOCHS,
          callbacks = callbacks)

model.save('model.h5', save_weights_only = True)

After training when I am trying to visualize the attention map of the model, it is showing error:
from vit_keras import visualize

x = test_gen.next()
image = x[0]

attention_map = visualize.attention_map(model = model, image = image)

# Plot results
fig, (ax1, ax2) = plt.subplots(ncols = 2)
ax1.axis('off')
ax2.axis('off')
ax1.set_title('Original')
ax2.set_title('Attention Map')
_ = ax1.imshow(image)
_ = ax2.imshow(attention_map)

Below is the following error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-f208f2d2b771> in <module>
      4 image = x[0]
      5
----> 6 attention_map = visualize.attention_map(model = model, image = image)
      7
      8 # Plot results

/opt/conda/lib/python3.7/site-packages/vit_keras/visualize.py in attention_map(model, image)
     14     """
     15     size = model.input_shape[1]
---> 16     grid_size = int(np.sqrt(model.layers[5].output_shape[0][-2] - 1))
     17
     18     # Prepare the input

TypeError: 'NoneType' object is not subscriptable

Please suggest some way to rectify the above error and visualize the attention maps of the fine-tuned model

A: You can visualize attention maps by doing the following.
attention_map = visualize.attention_map(model=model.layers[0], image=image)

Since attention_map assumes a ViT model as the model argument, you need to specify the first element of the fine-tuned model defined as tf.keras.Sequential.

A: I have a solution working.
I have the path to the image in a string, open it with OpenCv library, and I previosly load a ViT model fine tunned.
I think you only need to use the method get_layer, and select your Vit, as you use it entirely in your sequential model, it works as a layer.
path='/content/drive/MyDrive/TFM/Harvard_procesado/ISIC_0025612.jpg'
img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
res = cv2.resize(img, dsize=(224,224), interpolation=cv2.INTER_CUBIC)

attention_map1 = visualize.attention_map(model = vit_model_t.get_layer('vit_model'), image = res)

fig = plt.figure(figsize=(20,20))
ax = plt.subplot(1, 2, 1)
ax.axis('off')
ax.set_title('Original')
_ = ax.imshow(res)

ax = plt.subplot(1, 2, 2)
ax.axis('off')
ax.set_title('Attention Map')
_ = ax.imshow(attention_map1)


text:
Q: Datediff without weekends/holidays with info coming from 2 different tables The scenario is: I have a workflow in which an object passes through multiple stages until it's closed (end of process). In this case, I have a table with the unique Id of this object, the day it arrived in a given stage, and the day it left this same stage. The calculation of "total days in stage X" must NOT consider weekends and holidays (which is an info that comes from a different calendar table).

Id
first time at stage
last time at stage

01
2021-09-02
2021-09-09

So in between those dates, we have a weekend and 2 holidays here in my country, which means the proper time in stage would be 3.
In paralel, I created a table with the dates of all weekends and holidays of the year (it's just one column "date"), with the intention of basically counting the days in this table that would be in between "first time at stage" and "last time at stage", in order to subtract it from the final datediff.
So I have:
SELECT DISTINCT
    id,
    first_time_stage,
    last_time_stage,
    DATE_DIFF(last_time_stage,first_time_stage,DAY) - COALESCE(
            (SELECT COUNT(1)
             FROM base_holidays_and_weekends c
                LEFT JOIN base_stage_periods p ON c.date = p.first_time_at_steage AND c.date = p.last_time_stage
                WHERE date BETWEEN first_time_stage AND last_time_stage), 0) AS time_spent_in_stage

Where am I getting it wrong? I assume the issue is having 2 different tables, or in the JOIN... :(
Thank you for any inputs!


text:
Q: Questions concerning the Integration of Integer Tetration I've been interested in finding the antiderivative of integer tetration, a function defined as iterative exponentiation. Integer tetration is written as $^n$$x$ where $^1$$x =x$, $^2$$x =x^x$, $^3$$x =$ $x^{\scriptscriptstyle x^{x}}$ and so forth where $n=1,2,3\ldots$ (Further info can be found on Wikipedia. One solution to the problem is found on the MathWorld page (see equation #10), but the given solution is difficult to evaluate; accordingly, I am searching for an simpler representation than the result given. (Note that my questions are located at the bottom of this post, and number theorists are encouraged to skip to that point... everything leading up to the questions is background and context.)
Using Wolfram Alpha I found the Puiseux series of $x^x$ to be the following:$$1+ x\log(x)+\frac{1}{2}x^2\log^2(x) + \frac{1}{6}x^3\log^3(x)\ldots$$ $$ = \sum_{n=0}^{\infty} \frac{x^n \log^n(x)}{n!} \qquad 1.$$
As such, the antiderivative can be found simply by integrating the series:
$$\int x^xdx = \int \bigg(\sum_{n=0}^{\infty} \frac{x^n \log^n(x)}{n!}\bigg)dx = \sum_{n=0}^{\infty}\bigg(\frac{1}{n!}\int x^n \log^n(x)dx\bigg)$$
We then note the following: (again, pulled from Wolfram Alpha)
$$\int x^n \log^n(x)dx = \frac{\Gamma(n+1,-(n+1)\log(x))(-n-1)^{-n} }{(n+1)} \qquad 2. $$
All that is left is to substitute in Equation 2 and convert the denominator the gamma function.
$$\sum_{n=0}^{\infty}\bigg(\frac{1}{n!}\int x^n \log^n(x)dx\bigg) = \sum_{n=0}^{\infty}\bigg(\frac{\Gamma(n+1,-(n+1)\log(x))(-n-1)^{-n} }{\Gamma(n+2)}\bigg)$$
This solution can be checked by substituting in x=1, yielding the Sophomore's Dream:
$$ \sum_{n=0}^{\infty}\bigg(\frac{\Gamma(n+1,-(n+1)\log(1))(-n-1)^{-n} }{\Gamma(n+2)}\bigg) = \sum_{n=0}^{\infty}\bigg(\frac{\Gamma(n+1,0)(-n-1)^{-n} }{\Gamma(n+2)}\bigg)$$
$$= \sum_{n=0}^{\infty}\bigg(\frac{\Gamma(n+1)(-n-1)^{-n} }{\Gamma(n+2)}\bigg) = \sum_{n=0}^{\infty}\bigg((-1)^n(n+1)^{n+1}\bigg)$$
$$= 1-\frac{1}{4}+\frac{1}{27}-\frac{1}{64}\,\ldots \, = -\sum_{n=1}^{\infty}(-n)^{-n} = \int_{0}^{1}x^xdx$$
Further, any other definite integral of $x^x$ can be calculated the same way. (Note that $F'(x)$ is $x^x$)
$$\int_{0}^{r}x^xdx = F(r) - \lim_{a\to 0}F(a)$$
$$= F(r) - \sum_{n=0}^{\infty}\lim_{a\to 0}\bigg(\frac{\Gamma(n+1,-(n+1)\log(a))(-n-1)^{-n} }{\Gamma(n+2)}\bigg) = F(r)$$
No standard Puiseux series can be found for $^n$$x$ when $n>2$, although Wolfram Alpha tells me that "Generalized Puiseux series" exists for these functions. For $^3$$x$ the series is as such:
$$x + x^2\log^2(x) + \frac{1}{2}x^3\log^3(x)[1+\log(x)] + \frac{1}{6}x^4\log^4(x)[1+3\log(x)+\log^2(x)]\ldots$$
Notice that this series closely resembles Equation 1, except for the additional powers of $\log(x)$. If we temporarily exclude the coefficients on these additional terms we find that the $n^{th}$ term of the series is multiplied by $\sum_{n=0}^{n-2}\log^n(x)$ (except for the first term). As a result, we can represent the series as follow, where the additional coefficients are represented as $C_{kn}$
$$\sum_{n=2}^{\infty}\bigg[\frac{x^n\log^n(x)}{\Gamma(n)}\sum_{k=0}^{n-2}\bigg(C_{kn}\log^k(x)\bigg)\bigg] = \sum_{n=2}^{\infty}\sum_{k=0}^{n-2}\bigg(\frac{C_{kn}\log^{k+n}(x)x^n}{\Gamma(n)}\bigg)  \qquad 3. $$
Listing the coefficients generated, we get $[1],[1,1],[1,3,1],[1,7,6,1]\ldots$
A quick search on the OEIS revealed that these are in fact the Stirling numbers of the second kind, written as $S_n^k$ or $S(n,k)$. Substituting this into the series representation above, we get the following series for $^3$$x$:
$$x + \sum_{n=2}^{\infty}\sum_{k=0}^{n-2}\bigg(\frac{S_{n-1}^{k+1}\log^{k+n}(x)x^n}{\Gamma(n)}\bigg) = x + \sum_{n=0}^{\infty}\sum_{k=0}^{n}\bigg(\frac{S_{n+1}^{k+1}\log^{k+n+2}(x)x^{n+2}}{\Gamma(n+2)}\bigg)$$
Going through a similar process to the one outlined for $x^x$, $\int$ $^3$$xdx$ can be shown to be the following equation:
$$\frac{x^2}{2} + \sum_{n=0}^{\infty}\sum_{k=0}^{n}\bigg(\frac{\Gamma[n+3+k,-(n+3)\log(x)]S_{n+1}^{k+1}}{\Gamma(n+2)(-(n+3))^{n+3+k}}\bigg)$$
Likewise, we find that
$$\int_{0}^{r} {^3x}dx = \frac{r^2}{2} + \sum_{n=0}^{\infty}\sum_{k=0}^{n}\bigg(\frac{\Gamma[n+3+k,-(n+3)\log(r)]S_{n+1}^{k+1}}{\Gamma(n+2)(-(n+3))^{n+3+k}}\bigg)$$
The hard part is when we get to the generalized Puiseux series for $^4x$, which is:
$$1+x\log(x)+\frac{1}{2}x^2\log^2(x)[1+2\log(x)]+\frac{1}{6}x^3 \log^3(x) [1+9 \log(x)+3\log^2(x)]+\ldots$$
$$***$$
Here is where the real questions start. This series has the first few powers of $x\log(x)$ as $x^x$, namely $1+x\log(x)$. I wonder if this is related to the fact that the function $y = (x^x)^y$ is the same as $y = (^{2n}x)^y$? Equivalently, $y=x^y$ is the same as $y = (^{2n-1}x)^y$. We can see this same symmetry in that for all $^{2n-1}x$ I checked (up to $^7x$) the first two terms are $x+x^2\log^2(x)$, while for all $^{2n}x$ I checked the first two terms are $1+x\log(x)$. Thus, my first question is somewhat broad... Is there any simple explanation for this symmetry?
My next question concerns the series for $^4x$. We can represent this in a very similar form to Equation 1, except for the additional powers of $\log(x)$, reminiscent of the additions to Equation 1. Thus, we get the form
$$\sum_{n=0}^{\infty} \bigg[\frac{x^n \log^n(x)}{n!}\sum_{k=0}^{n-1}\bigg(C_{kn}\log^k(x)\bigg)\bigg] = 1 + \sum_{n=1}^{\infty} \bigg[\frac{x^n \log^n(x)}{n!}\sum_{k=0}^{n-1}\bigg(C_{kn}\log^k(x)\bigg)\bigg]$$
$$= 1 + \sum_{n=1}^{\infty}\sum_{k=0}^{n-1}\bigg(\frac{x^n \log^{n+k}(x)C_{kn}}{n!}\bigg) = 1 + \sum_{n=0}^{\infty}\sum_{k=0}^{n}\bigg(\frac{x^{n+1} \log^{n+1+k}(x)C_{kn}}{\Gamma(n+2)}\bigg)$$
Having already worked with $^2x$ and $^3x$ integrating this series would not be difficult, but I can't figure out what the constants are. Thus, my main question is:
What is the pattern for the numbers $[1,2],[1,9,3],[1,28,36,4],[1,75,245,110,5],[1,186,1290,1410,300,6]...$ where each number is some $C_{kn}$?
I have noticed that the first member of each set is 1, and the second term in each set is $nS_n^2$ (where the first set is n=2, the second is n=3, and so forth and $S_n^k$ are the Stirling numbers of the second kind). The nth set also contains n members (using the definition of n above), and the final member of each set is n. Other than these observations, I can't find a way to represent these numbers.
My final question is "How do we calculate a generalized Puiseux series, specifically for $^nx$ where $n>2$? I feel that if I had more knowledge on how these series are calculated I could gain insight into my other questions, but I cannot find much literature on finding generalized Puiseux series, let alone literature elementary enough for me to understand and apply to tetration.
(Note: If I should split this post into three seperate posts for each question I can, but I included them all here to avoid posting excessively. If I should edit my tags to reach a wider audience I will do so, although I am not sure what specific fields of mathematics my questions fall under)


text:
Q: Flux Quantization in a Compact $U(1)$ Gauge Theory in 2+1D I was reading through the Gauge Theory section on Xiaogang Wen's textbook on Quantum Field Theory of Many Body Systems.
In this chapter, he talks about a compact $U(1)$ gauge theory in $2+1 D$, where the Lagrangian is given as
$$L = \frac{1}{2g^2}(e^2-b^2) \,, \ e_i = \partial_0 a_i - \partial_i a_0 \,, \ b_0 = \partial_1 a_2 - \partial_2 a_1 $$
He says around Eq. 6.3.6 that in order for the gauge field $a_i$ to be gauge equivalent under the periodic boundary conditions, $x_1 \rightarrow x_1 + L_1$, and $x_2 \rightarrow x_2 + L_2$, the total flux has to be quantized as $\int d^2 x \ b = \frac{2\pi N}{q}$. He later also says that in order to prove this, one needs to make use of the expansion,
$$a_i = X_i(t)/L_i + b_0 x_1 \delta_{i,2} + \sum_k i c_k(t) \epsilon_{ij} k_j e^{i k \cdot x} $$
I am not sure how you can prove the flux quantization with the above equation - for one, the charge isn't defined at all in the Lagrangian or in the above expansion, and it only comes in once we introduce the Wegner-Wilson loop amplitude of $O(C) = e^{i q \oint_C d x^\mu a_\mu} $.
Anyone know how to do this?


text:
Q: Webpack library function is not a function As the title says, i'm getting an error in the browser Uncaught TypeError: MYLIB.init is not a function.
webpack.config.js:
As you can see i have set the library and libraryTarget, which is usually the problem with this.
module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'mylib.min.js',
    path: path.resolve(__dirname, 'dist'),
    library: 'MYLIB',
    libraryTarget: 'var'
  },
  devServer: {
    contentBase: './dist/demo',
    https: {
      key: fs.readFileSync(__dirname + '/certs/key.pem'),
      cert: fs.readFileSync(__dirname + '/certs/cert.pem'),
    }
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        options: {
          presets: [
            '@babel/preset-env',
            {
              "plugins": ['@babel/plugin-proposal-class-properties'],
            }
          ]
        }
      },
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
  resolve: {
    extensions: ['*', '.js']
  },
};

index.js:
Here i'm exporting correctly the init function.
'use strict';

export function init(provider, options){
  alert('init!');
}

index.html:
The path to the js file is correct and is found by the browser.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Lib Demo</title>

  <script src="../mylib.min.js"></script>
</head>
<body>
  <script>
    MYLIB.init('bla', {});
  </script>
</body>
</html>

package.json:
...
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode=production",
    "watch": "webpack --watch",
    "start": "webpack serve --open --host 0.0.0.0"
  },
  "devDependencies": {
    "@babel/core": "^7.13.8",
    "@babel/plugin-proposal-class-properties": "^7.13.0",
    "@babel/preset-env": "^7.13.9",
    "babel-loader": "^8.2.2",
    "css-loader": "^5.1.1",
    "style-loader": "^2.0.0",
    "webpack": "^5.24.2",
    "webpack-cli": "^4.5.0",
    "webpack-dev-server": "^3.11.2"
  }

npm run build runs successfully: webpack 5.24.2 compiled successfully
then npm run start, it opens the browser and i get that error Uncaught TypeError: MYLIB.init is not a function.. What am i doing wrong? i have a similar setup that works perfectly fine with older package versions so i'm guessing something changed with webpack and i don't know what.

A: Your webpack configuration is wrong where you are using babel-loader(plugins will not be inside presets).
Correct:
{
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "babel-loader",
                options: {
                    presets: [
                        '@babel/preset-env'
                    ],
                    "plugins": ['@babel/plugin-proposal-class-properties'], //<--Notice here
                }
},

Secondly:
Change the version of webpack dev server as stated here to "^4.0.0-beta.0"
and More Detail on this is here at github page.
Final Configuration, I checked with:
const path = require('path');

module.exports = {
    entry: {
        mylib: ['./src/index.js']
    },
    output: {
        filename: 'mylib.min.js',
        path: path.resolve(__dirname, 'dist'),
        library: 'MYLIB',
        libraryTarget: 'var'
    },
    devServer: {
        static: path.join(__dirname, 'public'),
        hot: true,
        port: 3000
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "babel-loader",
                options: {
                    presets: [
                        '@babel/preset-env'
                    ],
                    "plugins": [
                        '@babel/plugin-proposal-class-properties'
                    ],
                }
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
        ],
    },
    resolve: {
        extensions: ['*', '.js']
    },
};

Package Json:
    "main": "dist/mylib.min.js",
    "description": "Light Weight Next Generation MAP-Renderer",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack --mode=production",
        "watch": "webpack --watch",
        "start": "webpack serve --mode development --config webpack.config.js"
    },
"devDependencies": {
        "@babel/core": "^7.13.8",
        "@babel/plugin-proposal-class-properties": "^7.13.0",
        "@babel/preset-env": "^7.13.9",
        "babel-loader": "^8.2.2",
        "css-loader": "^5.1.1",
        "style-loader": "^2.0.0",
        "webpack": "^5.24.2",
        "webpack-cli": "^4.5.0",
        "webpack-dev-server": "^4.0.0-beta.0"
    },

Screenshot:

Thanks!


text:
Q: Two variables referencing the same collection I have the following fragments of code (suppose x is of type Integer[]):
Collection<Integer> col1 = new TreeSet<Integer>(Arrays.asList(x));
Collection<Integer> col2 = new TreeSet<Integer>(Arrays.asList(x));

After the second line, is it true that col1 and col2 reference the same collection?

A: No. The two variables refer to two different TreeSet instances that happen to contain the same elements. Each constructor call (new TreeSet<Integer>) produces a different instance of TreeSet.
In order for both variables to refer to the same instance, you'll need to assign one to the other :
Collection<Integer> col1 = new TreeSet<Integer>(Arrays.asList(x));
Collection<Integer> col2 = col1;

A: That depends on what you mean with "same".
col1 and col2 will refer to two different TreeSet objects, since separate objects are created in the two different uses of the new operator. If you add or remove elements to or from one of them that will not affect the other. In that sense they are definitely different.
But they represent the same collection of elements. In Java comparisons with the equals method are very common and important, and the two different TreeSet objects will be considered equal by that method. So in some sense they are kind of the same (at least until one of them is modified).
The first sense of the word "same" is the usual one in the context of Java programming. The second sense is very important too, but that is usually called "equality".

A: NO
Every time you create an object using the new keyword, a new object with a new identity will  be created. For example,
Collection<Integer> list = Arrays.asList(1,2,3);
Collection<Integer> list2 = Arrays.asList(1,2,3);
TreeSet<Integer> set = new TreeSet<>(list);
TreeSet<Integer> set2 = new TreeSet<>(list2);

System.out.println(set==set2); // false, reference equality
System.out.println(set.equals(set2)); // true, value equality

A: Just extending Eran's post
Integer[] x = {1,2,3,4,5,6};

    Collection<Integer> col1 = new TreeSet<Integer>(Arrays.asList(x));
    Collection<Integer> col2 = col1;

In the above code col2 refers col1 TreeSet<Integer> object
So in this case if you try to change any one object the other will change as well
col1.add(7);
System.out.println(col2.toString());

In the above code, 7 is added to col1 object, but it is also appears to be added to  col2 as col2 refers to col1 and col2 yields output as
[1, 2, 3, 4, 5, 6, 7]

Same goes for below code
col2.add(8);
System.out.println(col1.toString());

Output
[1, 2, 3, 4, 5, 6, 7, 8]

A: They will refer to the same collection of objects but in actual are different objects.
Please try this test class:
public class Test {
public static void main(String[] args) {
  Integer[] arr=new Integer[]{12,10};
  System.out.println(Arrays.asList(arr).hashCode());
  Collection<Integer> col1 = new TreeSet<Integer>(Arrays.asList(arr));
  Collection<Integer> col2 = new TreeSet<Integer>(Arrays.asList(arr));
  System.out.println(col1.hashCode()+":"+col2.hashCode());
  System.out.println(col1.equals(col2));

System.out.println(col1==col2);//false
    }
}


text:
Q: How to add all cookies from previous cURL to next cURL I have a PHP file that sends a cURL request to a web page, gets some cookies that should be set, and then sets the cookies in order to perform the next cURL request:
<?php
$ch = curl_init('https://www.roblox.com/newLogin');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    username => "EncodedLua",
    password => "", // Hidden
    submitLogin => "Log In"
));

curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
$roblosecuritykey = "";

foreach($matches[1] as $item) {
    parse_str($item, $cookie);
    $cookies = array_merge($cookies, $cookie);

    // Set all of the returned cookies
}

curl_close($ch);

$ch2 = curl_init('https://www.roblox.com/groups/api/change-member-rank');
curl_setopt($ch2, CURLOPT_POSTFIELDS, array(
    groupId => 2902455,
    newRoleSetId => 19777964,
    targetUserId => 55203439
));
curl_setopt($ch2, CURLOPT_HEADER, 1);
$result2 = curl_exec($ch2);

curl_close($ch2);
?>

I'm just not sure how to separate all of the cookies and then get the names and values by themselves. How would I do this?

A: Just put those cookies in the cookie jar:
<?php
$ch = curl_init('https://www.roblox.com/newLogin');
curl_setopt($ch, CURLOPT_COOKIEJAR, "/home/me/mycookies");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    username => "EncodedLua",
    password => "", // Hidden
    submitLogin => "Log In"
));


text:
Q: Linux (Ubuntu 12.04) getting horrible multithreaded performance? I have a multithreaded file converter that I'm working on. On Windows, it puts each file that's being converted in its own thread and uses 100% CPU (on all cores) all the time. It's awesome! On Ubuntu, I get 100% on the first core and ~10% on all the rest. The performance is poor and disappointing.
I'm using Threads, all within a SwingWorker so I don't freeze the GUI. I use thread.join on all threads so I perform a certain task when all threads are complete. I have not changed the code between OS's. Is there a feasible way to fix this?

A: It was very dumb and I don't quite understand why, but shortly after I posted this, I transferred all of my files to my Ubuntu partition, and it's just as fast (if not faster) than the Windows one. Not sure why moving files would make it go faster? Perhaps my real issue was that since they were on different file systems, my bottleneck was I/O. Converting just one file from the NTFS partition took 3x longer than if I moved it to the ext4 partition. (And Yes, these are all on the same SSD)


text:
Q: Multiple row insertion in MySQL DB from Dependency Dropdown I'm trying to insert all selected users from dependency dropdown for the admin user but something I am doing wrong here.

Below is my table structure: Table_Name: docrole

I need data to be inserted as follows:

Here is my code
Controller
public function DocumentRoleStore(Request $request)
    {
        $DocRoleModel = new Docrole;
        $DocRoleModel->deptid = $request->roledepartment;
        $DocRoleModel->accessto = $request->roleuser;
        $DocRoleModel->uploadby = $request->roleassignuser;
        $DocRoleModel->save();

        $rolesassign[] = $request->roleassignuser;
        foreach($rolesassign as $key=>$name)
        {
             Docrole::insert($key);
        }

return redirect()->back()->with('status','Role added successfully');

blade view

        <form action="/document-role-data" method="post">
            @csrf

                    <select class="form-select form-control" name="roleuser">
                        <option selected>Select User</option>
                        @foreach ($usersdata as $item)
                            <option value="{{$item->username}}">{{$item->username}}</option>
                        @endforeach
                    </select>

                    <select class="form-select form-control" name="roledepartment" id="Role-Department">

                        <option selected>Select Department</option>
                        <option value="1">All Departments</option>
                        @foreach ($departmentDatas as $item)
                            <option value="{{$item->deptid}}">{{$item->deptname}}</option>
                        @endforeach
                    </select>

                    <select class="form-select form-control" id="employeelist" required multiple name="roleassignuser[]">
                        <option  selected="false">Select User</option>
                    </select>

                    <button type="submit" class="btn btn-primary float-right mt-4">Submit</button>

        </form>

A: I believe your DocumentRoleStore() function should be like...
public function DocumentRoleStore(Request $request)
{
    foreach($request->roleassignuser as $roleUser) {
        Docrole::create([
            'deptid' => $request->roledepartmen,
            'accessto' => $request->roleuser,
            'uploadby' => $roleUser
        ]);
    }

    return redirect()->back()->with('status','Role added successfully');
}

Here I have used Create() method of Model class, which is requires mass assignment enabled in model. To enable mass assignment you can add following code to your Docrole class.
protected $fillable = ['deptid', 'accessto', 'uploadby'];


text:
Q: Error Importing Plotly Widgets? Very strange error here that I haven't seen anywhere else, I am trying to import Plotly widgets and keep coming up with this error.
from plotly.widgets import *

IPython.utils.traitlets has moved to a top-level traitlets package.

<IPython.core.display.Javascript object>
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    from plotly.widgets import *
  File "/Users/Clinder/Downloads/task/lib/python2.7/site-packages/plotly/widgets/__init__.py", line 3, in <module>
    from plotly.widgets.graph_widget import GraphWidget
  File "/Users/Clinder/Downloads/task/lib/python2.7/site-packages/plotly/widgets/graph_widget.py", line 31, in <module>
    class GraphWidget(widgets.DOMWidget):
  File "/Users/Clinder/Downloads/task/lib/python2.7/site-packages/IPython/utils/shimmodule.py", line 92, in __getattr__
    raise AttributeError(key)
AttributeError: DOMWidget

Does anyone have any ideas? I have looked through the files but cannot seem to find the issue as well as reinstalling this package.

A: plotly.widgets expects iPython and Jupyter notebook to be installed, see this related bug report. Try installing jupyter (pip3 install jupyter) and the import should work.


text:
Q: IBM Queue Message Transmission understanding I am confused with the usage of Local vs Remote Queue. Let me put a scenario :
I have an Application 1 that sends message (Msg1) to IBM MQ that stores the message in the Queue 1 which resides in QMGR which is then consumed by Application 2.
At this is stage is it necessary for me to implement a Remote Queue or a Local Queue. If I use a Local Queue for the this then where would I be using Remote Queue.
I believe this a basic question but I just trying to get a better understanding of IBM MQ. Please help me with your suggestions.
Thanks

A: If you are just using MQ so that one application can store messages on a queue for another application to retrieve, all within a single queue manager then a local queue suffices. Within MQ messages always reside on local queues (normal or transmission queues), and the other definitions just help route traffic.
An example of when you would use a remote queue is when you wish to split the applications apart, so the putter application puts to one queue manager on one machine, and the consumer/getter application lives on another queue manager potentially on another machine. In this scenario the putter can address a remote queue, but the messages really end up on a transmission queue - then a channel retrieves the messages from the transmission queue, flows it over the channel to the other queue manager and puts to the 'local' queue on the destination queue manager which the consumer is reading from.
Using a remote queue for example, it is possible to split apart the producer and the consumer without needing them to change the queue name they get from - Imagine they both the producer and consumer read from queue MYQUEUE. You could then move the consumer to one queue manager (QM1) with a remote queue called MYQUEUE whose real (remote) name is MYQUEUE on another queue manager (QM2). On queue manager 2, you would then have a local queue definition called MYQUEUE. The producer still opens and writes to MYQUEUE and doesnt know its messages will be routed, and the consumer still reads from MYQUEUE and retrieves the messages.


text:
Q: В чём разница между new mysqli и mysqli_connect? В чём разница между new mysqli() и mysqli_connect()?

A: new mysqli() - это объекто-ориентированный стиль, mysqli_connect() - процедурный.
В конечном итоге делают они одно и тоже - создают "соединение" с бд.
Если вы пишите приложение на функциях и преимущественно без ООП - то используйте процедурный стиль, если с ООП -  то объектный, чтобы не нарушать стиль.


text:
Q: Importing .obj files leads to different vertex orders when switching from Blender 2.92 to Blender 3.1 I am a very happy Blender user. My latest project runs in Blender 2.92 and everything is working great. When I tried the new Blender release 3.1, I noticed that some of my scripts are no longer working.
I tracked down the issue to the import of .obj files. To be precise, the vertex order of an imported .obj mesh differs depending on the Blender version. For reference, an .obj file is imported using the following line in both Blender 2.92 and 3:
bpy.ops.import_scene.obj(filepath=fname, split_mode="OFF")

I also manually imported the meshes in both Blender 2.92 and 3.1 for comparison (File -> Import -> OBJ and toggled "Keep Vert Order"). The same effect occurs and the vertex order is different.
I could not find anything regarding this topic in the Blender changelogs. Is this behaviour intended? I am rather lost at the moment and would appreciate any available insight.


text:
Q: Dropdowns are not working using react-draft-wysiwyg in React JS I tried to use react-draft-wysiwyg using the docs
Some icons are displayed but not working : block type, font, font size,pickerColor (the dropdowns are not working). For example, the font size is set to 16 by defauft, but I can't change it...
import { Editor } from "react-draft-wysiwyg";
import { EditorState } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

const TabContent = ({ name, typeProof }) => {
  const [text, setText] = useState(
  () => EditorState.createEmpty(),);

  return (
    <>
      <SafeAreaView>
        <Editor
          editorState={text}
          onEditorStateChange={setText}
          wrapperClassName="wrapperClassName"
          editorClassName="editorClassName"
          toolbarClassName="toolbarClassName"
          placeholder="Enter your text here:"
          style={{
           //some styles
          }}
          toolbar={{
            options: ['inline', 'blockType', 'fontSize', 'fontFamily', 'list', 'textAlign', 'colorPicker', 'embedded', 'remove', 'history'],
            inline: { inDropdown: true },
            blockType: { inDropdown: true },
            fontSize: { inDropdown: true },
            fontFamily: { inDropdown: true },
            list: { inDropdown: true },
            textAlign: { inDropdown: true },
            colorPicker: { inDropdown: true },
            embedded: { inDropdown: true },
            remove: { inDropdown: true },
            history: { inDropdown: true },
         }}
        />
      </SafeAreaView>
    </>
  );
};

export default function Tabs({ data }) {
  return (
    <TabsComponent forceRenderTabPanel>
      <TabList>
        {data.map(({ name }, i) => (
          <Tab key={name}>Question {i + 1}</Tab>
        ))}
      </TabList>
      {data.map(({ name, typeProof }) => (
        <TabPanel key={name}>
          <TabContent {...{ name, typeProof }} />
        </TabPanel>
      ))}
    </TabsComponent>
  );
}

A: Well that's weird, I have no explanation for that but I've changed only in index.js:
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

by :
import "./index.css";
import App from "./App";
import React from "react";
import ReactDOM from "react-dom";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

Is there an explanation ? I would be glad to understand that...

A: Try to replace your codes by this example SandboxExample
I think your Sandbox dependency configuration is not good also I have found something like this , what I did , I have create a new Sandbox add dependencies react-draft-wysiwyg and draft-js , import Editor and use it in the App component like you used on your files , and everything is worked , try to clear your app , read this npx Create React APP
 My Sandbox example this is my Sandbox example with functional components
Hope it will be helpful for you

A: also note that react strict mode causes this "dropdown options not showing" error :
https://github.com/jpuri/react-draft-wysiwyg/issues/1291#issuecomment-1203348769


text:
Q: Error "found unreadable content" when open excel file written by .to_excel() I'm practicing web scraping, and try to get some info of cars.
I want one of my dataframe columns be a hyperlink to the model image, and I succeeded in creating the formula and saving it to dataframe
For example:
print(suvs['images'][0])
=HYPERLINK("https://www.cstatic-images.com/car-pictures/main/USD00AUS052A021001.png"; "Audi Q3")

print(suvs['images'][3])
=HYPERLINK("https://www.cstatic-images.com/car-pictures/main/USD00AUS011B021001.png"; "Audi Q7")

, but when opening the file (I'm using Excel 2010), it throws me that error "Excel found unreadable content...", and if I responded with Yes, it deletes the column contents.
Here is log:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><logFileName>error040320_03.xml</logFileName><summary>Errors were detected in file 'D:\Users\Tamer\PycharmProjects\Udemy\suvs.xlsx'</summary><removedRecords summary="Following is a list of removed records:"><removedRecord>Removed Records: Formula from /xl/worksheets/sheet1.xml part</removedRecord></removedRecords></recoveryLog>

I tried to copy and paste the link generated by the code into the file, and it works very well.
So what is the problem?
Thank you
Here's the code:
import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup

try:
    HEADERS = {"Accept-Language": "en-US,en;q=0.5"}
    URL = 'https://www.cars.com/research/audi/'

    images = []
    models = []
    model_years = []
    msrp_ranges = []
    consumer_ratings = []
    combined_mpgs = []
    body_styles = []

    page = requests.get(URL, headers=HEADERS)
    data = BeautifulSoup(page.text, 'html.parser')
    cards = data.find_all('div', class_='card make-model-card suvs')

    for card in cards:
        model = card.p.text
        models.append(model)

        image = card.img['data-image-src']
        # Creating hyperlinks to save it in suvs.xlsx file
        hyperlink = f'=HYPERLINK("{image}"; "{model}")'
        print(hyperlink)
        images.append(hyperlink)
        # images.append(image)

        # Get 'More Details' page URL
        details_url = 'https://www.cars.com' + card.div.a.attrs['href']
        details_page = requests.get(details_url, headers=HEADERS)
        details_data = BeautifulSoup(details_page.text, 'html.parser')
        details = details_data.find_all('div', class_='expanded-list-contents')

        model_year = details_data.h3.text
        model_years.append(model_year)

        if details_data.find('li', class_='expanded-list-item'):
            msrp_range = details_data.find('li', class_='expanded-list-item').text.replace('MSRP Range\n', '').strip()
        else:
            msrp_range = ''

        if details_data.find('td', class_='expanded-list-item'):
            msrp_range = details_data.find('li', class_='expanded-list-item').text.replace('MSRP Range\n', '').strip()
        else:
            msrp_range = ''

        msrp_ranges.append(msrp_range)

        if details_data.find('div', class_='star-rating__consumer-review'):
            consumer_rating = details_data.find('div', class_='star-rating__consumer-review').text.replace('\n', '').strip()
            consumer_rating = consumer_rating[:5] + ' ' + consumer_rating[-15:]
        else:
            consumer_rating = 'Not rated yet'

        consumer_ratings.append(consumer_rating)

    # Creating dataframe "homes"
    suvs = pd.DataFrame({
        'images': images,
        'models': models,
        'year': model_years,
        'msrp_ranges': msrp_ranges,
        'consumer_ratings': consumer_ratings,
        #     'combined_mpgs': combined_mpgs,
        #     'body_styles': body_styles
    })

    file_name = 'suvs.xlsx'
    suvs.to_excel(file_name, index=False)  # index=False to avoid creating index column

    # to see where you're missing data and how much data is missing
    print(suvs.isnull().sum())

except requests.exceptions.ConnectionError:
    print("Couldn't connect to the requested page!\n"
          'Please, check your internet connection.')

except PermissionError:
    print(f'The {file_name} file is opened.\n'
          'Please, close it, and run the script again.')


text:
Q: Quotient rules and fractions! I'm doing a problem in my textbook that I have the answer too thanks to it being an odd problem in the back. The problem is that I can't get to the answer of this problem.
Problem by the way is shown to be "Differentiate: (1 / y^2 - 3 / y^4)(y + 5y^3)".
The answer in the book happens to be: "5 + 14/ y^2 + 9/Y^4".
What I've tried thus far is use (fg)' = fg' + gf'
With F being the first parenthesis and G being the second parentheses respectably.
But doing so gets me (y^2 - 3)(5y^2 + 1) / y^3 + (y^2 - 3)(5y^2 + 1). I stop at this point because I know theirs no way to get the answer from here.
Can someone point me to the right way?Also how can I make fractions like others are doing on this site? I can't find the button on here..
$\frac{1}{y^2}$

A: You can expand what you have to give:
$$\left(\frac{1}{y^2}-\frac{3}{y^4}\right)\left(y+5y^3\right)=5y-14y^{-1}-3y^{-3}$$
Therefore, the derivative will be given by:
$$\frac{d}{dy} (5y-14y^{-1}-3y^{-3})=5\cdot\frac{d}{dy}(y)-14\cdot\frac{d}{dy}(y^{-1})-3\cdot\frac{d}{dy}(y^{-3})$$
Now, use the fact that $\frac{d}{dy}(y^n)=ny^{n-1}$.

Alternatively, you can use the product rule or the quotient rule, as you have mentioned. I personally prefer to expand it in this case.
I see that you asked how to format questions using LaTeX. Here is a nice guide showing how to use the formatting.

A: So, you are taking the derivative with respect to y. What you have to do is to first expand your expression by multiplying it out. You will get
$\frac{1+5y^2}{y}-\frac{3+15y^2}{y^3}$ after some simplification.
Then you simply take the derivative using the quotient rule: $\frac{f'g-fg'}{g^2}$ and you'll have it!


text:
Q: Route an Istio Virtual Service based off the user claim in a JWT Istio can route traffic based off headers and such.  There are great examples of how to do this in the Istio docs.
Istio can also validate your JWT.  The Istio docs also cover that.
But I can't seem to find a way to get my JWT Validated, then use the user claim found in the JWT Json to route traffic.  The example I linked to just expects the user to be plain text in a header.
How can an Istio Virtual Service be setup to route based on a claim in a JWT (preferably one it validated).

A: You can implement this using the Istio authorization policy. I did something similar with Keycloak and Kong to restrict user traffic at API gateway level if claim or roles were not there.
Here is one nice example of JWT auth with istio:
apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
 name: backend
 namespace: default
spec:
  selector:
    matchLabels:
      app: backend
  jwtRules:
  - issuer: "${KEYCLOAK_URL}/auth/realms/istio"
    jwksUri: "${KEYCLOAK_URL}/auth/realms/istio/protocol/openid-connect/certs"
---
# To allow only requests with a valid token, create an authorization policy
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
 name: backend
 namespace: default
spec:
 selector:
   matchLabels:
     app: backend
 action: ALLOW
 rules:
 - from:
   when:
    - key: request.auth.claims[preferred_username]
      values: ["testuser"]

Example link : https://istio.io/latest/docs/tasks/security/authorization/authz-jwt/
Another nice example with OIDC : https://www.jetstack.io/blog/istio-oidc
RBAC and group list checks : https://istio.io/v1.4/docs/tasks/security/authorization/rbac-groups/


text:
Q: Detecting flight info via NSDataDetector's NSTextCheckingTypeTransitInformation is not ever matching anything Has anyone had any luck using NSDataDetector on iOS to match flight information?  It looks really amazingly powerful, except I can't get it to work at all.
Here's what I'm trying:
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)NSTextCheckingTypeTransitInformation error:&error];

[detector enumerateMatchesInString:string
                           options:0
                             range:NSMakeRange(0, [string length])
                        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

                            NSLog(@"Detected: %@, %@", result, [result URL]);
}

I'm trying this on a variety of strings, including the body of every calendar entry I could find in my calendar that had flight info in it.
Examples:

*

*"UA460 SFO to YVR [Flight] 6/12/2013 United Airlines(UA) #460 dep SFO 7:57pm PDT arr YVR 10:14pm PDT;  Ticket #0162360127882, Ticket #0162360127883; conf #K5XBXY; Note:, Seats:---/30A , Seats:---/30B
"

*"Pick up Laura at Airport  UA 1255"

*"Lufthansa 1128 Business (C) | Seat 07F Frankfurt Barcelona 2 h 0 m 679miles
FRA 1:15pm BCN 3:15pm , Arrives on Fri Oct/5/2012
Lufthansa 1128
Business (C) | Seat 07F | Confirm or change seats with the airline*"

But none of these match.  If I change data detector types to include NSTextCheckingTypePhoneNumber or NSTextCheckingTypeLink, those match great. But I can't get flight data.
Any one have any luck with this?

A: Flight numbers are detected on OS X, but not on iOS. Please file a bug with Apple to either get the documentation updated, or to get support for this on iOS.

A:     NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)NSTextCheckingTypeTransitInformation error:nil];
    NSString *result = @"Pick up Laura at Airport UA 1255";
    [detector enumerateMatchesInString:result options:0 range:NSMakeRange(0, [result length]) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
        NSLog(@"%@ %@",result, [result components]);
    }];

2016-05-20 11:49:29.912 detectTest[20894:4085484] <NSTransitInformationCheckingResult: 0x7fcc92019f30>{25, 7} {
    Flight = 1255;
}

the only difference is flight info stored in [result components] rather than [result URL]


text:
Q: $X_n\Rightarrow X$, $Y_n\Rightarrow Y$ and $X_n$ & $Y_n$ are independent implies $X$ & $Y$ are independent? Suppose $X_n$ and $Y_n$ are independent for all $n\geq 1$, and
$$X_n\Rightarrow X$$
and
$$Y_n\Rightarrow Y$$
as $n\to\infty$, where "$\Rightarrow$" means the convergence in distribution.
Is that right: $X$ and $Y$ are independent? How to prove?
Thank you!


text:
Q: Create a table from a table with same row values on 1 or more columns and a third column with new logic I have a table like this -

Host_ID
PCI_ID
Class_ID
Device_Name

230
04:00.0
512
Cisco VIC

230
03:00.0
512
Cisco VIC

230
04:01.0
512
Cisco VIC

230
ff:00.0
1040
CPU Xeon

451
04:00.0
512
Cisco VIC

451
03:00.0
512
Cisco VIC

451
ef:00.0
1040
CPU Xeon

671
03:01.0
512
Cisco VIC

671
02:00.0
512
Cisco VIC

671
ff:00.0
1040
CPU Xeon

I want to have a table like below which will have rows where CLASS_ID=514 and is sorted by HOST_ID,PCI_ID and will have a third column called 'Name' which will have integer appended to text 'vmnic' for each row with same HOST_ID (vmnic0,vmnic1,vmnic2 etc)

Host_ID
PCI_ID
Name

230
04:00.0
vmnic0

230
03:00.0
vmnic1

230
04:01.0
vmnic2

451
04:00.0
vmnic0

451
03:00.0
vmnic1

671
03:01.0
vmnic0

671
02:00.0
vmnic1

I currently have something like this to start with -
SELECT
     HOST_ID as ID
    ,PCI_ID as PCIe_Address
    ,'vmnic'+ <LOGIC for appending INT> as Name
FROM VPX_HOST_PCI_DEVICE
WHERE CLASS_ID=512
ORDER BY HOST_ID,PCI_ID

Can anyone help me with the sql server code for LOGIC for appending INT?

A: You can use ROW_NUMBER to get the correct number to append. You need to CONVERT it to VARCHAR to avoid conversion error
SELECT
    HOST_ID AS ID,
    PCI_ID AS PCIe_Address,
    'vmnic' +
        CONVERT(VARCHAR(10), ROW_NUMBER() OVER (PARTITION BY HOST_ID ORDER BY PCI_ID DESC) - 1) AS Name
FROM VPX_HOST_PCI_DEVICE
WHERE
    CLASS_ID = 512
ORDER BY
    HOST_ID, PCI_ID


text:
Q: JSP MYSQL Hide Same Number and show letter I am a newbie still learning jsp and mysql.
I have a database with following table fields:
id   no letter content
1    1         book
2    2         pen
3    3  a      apple
4    3  b      mango
5    3  c      banana
6    4         car

I need somebody help me, how can I do a query in jsp with mysql so the result will be like this?
 No   Content
1.    book
2.    pen
3. a  apple
   b  mango
   c  banana
4.    car


text:
Q: Update stored procedure in edmx file I have updated stored procedure by deleting column and added where clause. The stored procedure already added in the edmx file. Now I want to update those changes in edmx file. I tried by deleting stored procedure and update model from database. How do I update edmx file with updated stored procedure?

A: Forgot to delete from the Complex Types. After deleting from it, it worked.


text:
Q: .DS_Store file in os.walk() I am trying to write a code which renames files in directory's folder and subfolders. However while reading the filenames using os.walk I always encounter the .DS_Store file (system generated file in MacOS). Any solutions to get past this?
I am using os.walk() in this manner:
    for path, subdirs, files in os.walk(folder_path):
        # scroll_count = 1
        # panel_count = 1
        files.sort()

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 11, in replace
FileNotFoundError: [Errno 2] No such file or directory: '.DS_Store'


text:
Q: How to center align the section navigation bar in the headline I have a section navigation bar in my headline, and I want it to show the sections center aligned. Although, the section navigation bar is right aligned, I tried to position it in the center by setting the position manually using the following code:
\setbeamertemplate{headline}{%
\leavevmode%
  \hbox{%
    \begin{beamercolorbox}[wd=\paperwidth,ht=12.5ex]{section in head/foot}%
      \insertsectionnavigation{0.5\paperwidth}
    \end{beamercolorbox}%
  }
}

With the above definition of the headline, here is the snap of one of the frames:

How can I get the text (the sections) in the section navigation bar center aligned?

A: I added two \hfill around \usebeamertemplate{section in head/foot} to make them centred.
\documentclass{beamer}

\usetheme{Berlin}

\setbeamertemplate{headline}{%
    \leavevmode%
    \hbox{%
        \begin{beamercolorbox}[wd=\paperwidth,ht=12.5ex]{section in head/foot}%
            \insertsectionnavigation{\paperwidth}
        \end{beamercolorbox}%
    }
}

\makeatletter
\def\insertsectionnavigation#1{%
    \hbox to #1{%
        \vbox{{\usebeamerfont{section in head/foot}\usebeamercolor[fg]{section in head/foot}%
                \vskip0.5625ex%
                \def\slideentry##1##2##3##4##5##6{}%
                \def\sectionentry##1##2##3##4##5{%
                    \ifnum##5=\c@part%
                    \def\insertsectionhead{##2}%
                    \def\insertsectionheadnumber{##1}%
                    \def\insertpartheadnumber{##5}%
                    \setbox\beamer@tempbox=\hbox{%
                        \hyperlink{Navigation##3}{\hbox to #1{%
                                \hskip0.3cm%
                                \ifnum\c@section=##1%
                                {\hfill\usebeamertemplate{section in head/foot}\hfill}%
                                \else%
                                {\hfill\usebeamertemplate{section in head/foot shaded}\hfill}%
                                \fi\hskip0.3cm}}}%
                    \ht\beamer@tempbox=1.6875ex\dp\beamer@tempbox=0.75ex%
                    \box\beamer@tempbox\fi}%
                \dohead\vskip0.5625ex}}\hfil}}
\makeatother

\begin{document}

\section{loooooooooooooong}
\frame{as}

\section{er}
\frame{sd}

\end{document}


text:
Q: Range of the coefficient of quadratic equation The problem is stated below

Find the range of $\alpha$ such that $1-x-\alpha x^2$ has roots greater than $1$ or less than $-1$ (i.e if $\mu_1$ and $\mu_2$ are the roots of $1-x-\alpha x^2$, we require $|\mu_1|, |\mu_2|>1$).

Solution:
Transform the above question into the following. We require the roots of the quadratic equaion $\frac{1}{x^2}-\frac{1}{x}-\alpha$ have absolute value smaller than 1. Its roots are given by $$\mu_1=\frac{1+\sqrt{1+4\alpha}}{2}, \mu_2=\frac{1-\sqrt{1+4\alpha}}{2}$$
Case 1: If $1+4\alpha > 0$, then $|\mu_1|<1$ implies $\alpha <0$.
Case 2: If $1+4\alpha < 0$, then $|\mu_1|<1$ is equivalent to $(\frac{1}{2})^2-(\frac{\sqrt{1+4\alpha}}{2})^2<1$ which implies $\alpha > -1$.
Thus the solution is given by $-1<\alpha<0$.
My Questions:

*

*In the solution given, only the absolute value of $\mu_1$ is taken into consideration. Why?

*Also, I don't understand how $(\frac{1}{2})^2-(\frac{\sqrt{1+4\alpha}}{2})^2<1$ is come from. I know that when $1+4\alpha < 0$, the roots would become complex number. Yet, I still can't come up with the expression above.

A: For the first question:
Case 1. if $\alpha < 0$ then $0<\mu_2<1/2$ because the second root is 1/2 * (1 - something positive less than 1), so the second root is automatically less than 1
Case 2. You have complex roots, the absolute value (magnitude) of the roots is the same, so if $|\mu_1|<1$ then $|\mu_2|=|\mu_1|<1$
I would also add that Case 1 should be $1+4\alpha \ge 0$, so that $\alpha=-1/4$ is included in one of the cases :)
The rest has been already answered by divx

A:

*

*In the solution given, only the absolute value of $μ_1$ is taken into consideration. Why?

Because, as noted just above that: "We require the roots ... have absolute value smaller than 1".

*Also, I don't understand how $(\frac{1}{2})^2-(\frac{\sqrt{1+4\alpha}}{2})^2<1$ is come from. I know that when $1+4\alpha < 0$, the roots would become complex number.

When $1+4 \alpha \lt 0$ let $\beta = -(1+4 \alpha) \gt 0$, so that $\sqrt{\beta}= i\, \sqrt{1+4 \alpha}$. Then the roots can be written as $\mu_{1,2} = \frac{1}{2} \pm i \frac{\sqrt\beta}{2}$ and $|\mu_{1,2}|^2 = \left(\frac{1}{2}\right)^2+\left(\frac{\sqrt{\beta}}{2}\right)^2 = \left(\frac{1}{2}\right)^2+\left(\frac{i \; \sqrt{1 + 4 \alpha}}{2}\right)^2 = \left(\frac{1}{2}\right)^2-\left(\frac{\sqrt{1 + 4 \alpha}}{2}\right)^2$.

[ EDIT ]    To answer the question from the comment, in Case 1:

$$\mu_1=\frac{1}{2} + \frac{\sqrt{1+4\alpha}}{2} \lt 1 \iff \frac{\sqrt{1+4\alpha}}{2} \lt \frac{1}{2} \iff \sqrt{1+4\alpha} \lt 1 \iff \alpha \lt 0$$


text:
Q: Scroll page on page load if at top of page I would like to do something if the page is detected to be at the very top of the page otherwise don't do it. I'm guessing I need to use and if statement somehow but I'm just not sure how to do this.
For example, I want the page to scroll to 125 pixels if the page is at the very top otherwise don't scroll to that position.
$('html, body').animate({scrollTop:125}, 4000);

A: Use this on load:
function checkTop(){
    if ($(window).scrollTop() == 0) {
        $(window).animate({scrollTop:125}, 4000);
    }
}

checkTop();

$(window).scroll(function(){
    checkTop();
})


text:
Q: Swift version dropdown doesn't have latest version My Swift version on my mac:
$ swiftc -version
Apple Swift version 5.3.2 (swiftlang-1200.0.45 clang-1200.0.32.28)
Target: x86_64-apple-darwin19.6.0

However, when I try to change my project's Swift version to 5.3, there's no dropdown option for it:

Xcode version is 12.3


text:
Q: Cache maintained by caller app or by provider app in microservices inter-app communication? Suppose there are app1 and app2 in a microservices.
app2 needs to call app1's RESTful APIs.
Cache is needed since the call will be frequent. So after a successful RESTful call, there will be cache available for app2.
My question is who maintains the cache, app1 or app2?
Any comparison between the two? Is there industry best practices?
In addition, are there any differences if there's a app3 also needs to call the app1's APIs?

A: If there is only one requester (one instance) that uses app1, then it doesn't really matter where the caching is done. As soon as a second requester comes into the picture (either a new app or a second instance), it will be most efficient to have the cache either in app1 or in a separate caching server in front of app1, because

*

*only a single copy of the response needs to be cached, rather than a copy in each requester

*when two different requesters ask for the same data, the second one can be served the cached copy. That would not be possible if the cache was on the requester side.

As I mentioned above, the caching doesn't even have to be within the code of app1, but a dedicated caching server could be used. Then app2 and app3 would send their requests for app1 to the caching server. If the server has a recent-enough response in their cache, then that response will be returned and otherwise the request is forwarded to app1 and the response from app1 is added to the cache. If the microservices use HTTP or HTTPS to communicate with each other, then you can use an off-the-shelf caching server.
If you use caching outside app1, then you have to determine for how long it is acceptable, in the worst case, that the cache serves old information while new information has just become available in app1. If the data at an endpoint can change without a write action occurring that is seen by the cache implementation, then you must put some time limit on how long the cache may regard the information as recent enough to serve it from the cache. In addition to this time limit, caching servers will also mark information as obsolete when they see a request to the same endpoint that has the semantics of (potentially) changing the data at that endpoint.

A: As a rule of thumb, a cache maintained and running close to the client/caller side scales much better for read-heavy service, while a cache maintained and running close to the server/callee side is easier to maintain for frequently updated data. In many scenarios, you may need both types of caches.
Broadly speaking, there are three types of cache invalidation strategy: expiry, token check (e.g. ETag), and push invalidation. Push invalidation is best for fast invalidation, but also the most resource intensive as both sides have to maintain an open connection at all time. Expiry is simple and scales very well, but quick invalidation is tricky.
In most cases, the server should be in control of caching, even when using a client-side cache. This can be done by the server advising the clients how and what can be cached and what invalidation mechanism to use explicitly on each request and response. In HTTP, this is usually done by using the Expires and Cache Control header (and a couple other headers to specify the exact caching semantic) or the ETag/If-Match/If-None-Match headers or by invitation to use web socket. HTTP provides a very rich vocabularies for the server to describe the caching requirements of a resource to the clients and any intermediary servers. As the other answer mentioned, if you use HTTP, you'll benefit from the widespread support of off the shelf caching components.
Another option is for the server to document how long the client are allowed to cache and how they invalidate and all clients just have to assume that, this may be ok if you control all endpoints and can co-ordinate a cache invalidation. But in very large networks with a diverse types of clients and intermediaries, this may be tricky to do correctly, so you may want to consider negotiating caching explicitly anyway. The benefit of implicit caching is that your communication protocol is cleaner, as it doesn't need to waste bytes negotiating caches; if your microservice network exchanges large number of small packets, where these negotiation overhead are problematic, implicitly negotiated caching may be the only sensible way to go.


text:
Q: This inspection warns about local variables before assignment when I use a function to remove certain substrings I have a dataframe that looks like this:
             State                                         RegionName
0  Alabama[edit]\n                    Auburn (Auburn University)[1]\n
1  Alabama[edit]\n           Florence (University of North Alabama)\n
2  Alabama[edit]\n  Jacksonville (Jacksonville State University)[2]\n
3  Alabama[edit]\n       Livingston (University of West Alabama)[2]\n
4  Alabama[edit]\n         Montevallo (University of Montevallo)[2]\n

I am trying to use a function to remove the '(' and '[' but it gives me the following error:
This inspection warns about local variables before assignment

This is the code and the function that I am using:
towns_df = pd.DataFrame(university_towns, columns=['State', 'RegionName'])

# print(towns_df.head())

towns_df = towns_df.applymap(get_citystate(university_towns))

def get_citystate(item):
    if ' (' in item:
        return item[:item.find(' (')]
    elif '[' in item:
        return item[:item.find('[')]
    else:
        return item

The error is where I call the get_citystate function. university_towns is the list where it contains (state, city).
expected output
   State      RegionName
0  Alabama        Auburn
1  Alabama      Florence
2  Alabama  Jacksonville
3  Alabama    Livingston
4  Alabama    Montevallo

A: The function should be created before you call it.
def get_citystate(item):
    if ' (' in item:
        return item[:item.find(' (')]
    elif '[' in item:
        return item[:item.find('[')]
    else:
        return item

towns_df = towns_df.applymap(get_citystate)
print(towns_df.head())

And with everything else working, this is the end result:
     State    RegionName
0  Alabama        Auburn
1  Alabama      Florence
2  Alabama  Jacksonville
3  Alabama    Livingston
4  Alabama    Montevallo

A: From MachineX: Data Cleaning with NumPy and Pandas

*

*towns_df = towns_df.applymap(get_citystate(university_towns)) has been incorrectly implemented.

*

*towns_df is the dataframe with State and RegionName

*.applymap is updating towns_df, using the function get_citystate.

*university_towns does not belong in the parenthesis

import pandas as pd

# given
data = {'State': ['Alabama[edit]\\n', 'Alabama[edit]\\n', 'Alabama[edit]\\n', 'Alabama[edit]\\n', 'Alabama[edit]\\n'],
        'RegionName': ['Auburn (Auburn University)[1]\\n', 'Florence (University of North Alabama)\\n', 'Jacksonville (Jacksonville State University)[2]\\n', 'Livingston (University of West Alabama)[2]\\n', 'Montevallo (University of Montevallo)[2]\\n']}

df = pd.DataFrame(data)

# display df
             State                                         RegionName
0  Alabama[edit]\n                    Auburn (Auburn University)[1]\n
1  Alabama[edit]\n           Florence (University of North Alabama)\n
2  Alabama[edit]\n  Jacksonville (Jacksonville State University)[2]\n
3  Alabama[edit]\n       Livingston (University of West Alabama)[2]\n
4  Alabama[edit]\n         Montevallo (University of Montevallo)[2]\n

# function
def get_citystate(item):
    if ' (' in item:
        return item[:item.find(' (')]
    elif '[' in item:
        return item[:item.find('[')]
    else:
        return item

# call function
df = df.applymap(get_citystate)

# display updated df
     State    RegionName
0  Alabama        Auburn
1  Alabama      Florence
2  Alabama  Jacksonville
3  Alabama    Livingston
4  Alabama    Montevallo

Additional note:

*

*The following line of code by cs95 does the same thing as def get_citystate
df = df[['State', 'RegionName']].apply(lambda col: col.str.replace(r'([\[(].*?[\]\)])\s*\\n?', '').str.strip())


text:
Q: Apache2 (reverse proxy) + Django + Gunicorn I have a problem with my Apache2 web server as reverse proxy server. The simplified server setup with my domain "example.com" looks like this:

If clients now go to the page https://example.com/guacamole, then the Apache2 web server should forward the requests to the Tomcat server (https://127.0.0.1:8080/guacamole). This part works.
If clients go to https://example.com/mydjangoproject, then the Apache2 web server should forward requests to the web server using Gunicorn and the Django project (https://192.168.30.5:8000). However, this configuration works only partially. The page https://example.com/mydjangoproject shows the main page of the Django project, but when calling the admin page https://example.com/mydjangoproject/admin the django application gives the error that the page http://192.168.30.5:8000//admin does not exist. It seems like the sub-URL "/mydjangoproject/" is removed when calling the admin page. What could that be?
This is my configuration:
<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerAdmin admin@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem

    JKMount /* ajp13_worker

    SSLProxyEngine on
    SSLProxyVerify none
    SSLProxyCheckPeerCN off
    SSLProxyCheckPeerName off
    ProxyPreserveHost On

    ProxyPass /static/ !
    ProxyPass /mydjangoproject https://192.168.30.5:8000/
    ProxyPassReverse /mydjangoproject https://192.168.30.5:8000/
</VirtualHost>
</IfModule>

Thanks for your help!
Edit:
When i try to enter the admin-page via https://example.com/mydjangoproject/admin then this error occurs:

A: You'll likely need to alter your ProxyPass and ProxyPassReverse directives to get this to work.
You should try replacing these lines:
ProxyPass /static/ !
ProxyPass /mydjangoproject https://192.168.30.5:8000/
ProxyPassReverse /mydjangoproject https://192.168.30.5:8000/

With e.g.:
# "Convenience" URL
ProxyPass /mydjangoproject https://192.168.30.5:8000
ProxyPassReverse /mydjangoproject https://192.168.30.5:8000

# --- The lines below are what actually allow access to /admin ---

# Proxy /admin for login
ProxyPass /admin http://192.168.30.5:8000/admin
ProxyPassReverse /admin http://192.168.30.5:8000/admin

# Proxy /static for CSS, etc.
ProxyPass /static http://192.168.30.5:8000/static
ProxyPassReverse /static http://192.168.30.5:8000/static

You should then be able to use e.g. https://example.com/admin to access your Django /admin page and get the correct login dialog:
ex. Django Admin Login

When I try to enter the admin page via https://example.com/mydjangoproject/admin an error occurs.

You should be able to add the following lines (in addition to those recommended above) to get this to (kind of) work:
ProxyPass /mydjangoproject/admin http://192.168.30.5:8000
ProxyPassReverse /mydjangoproject/admin http://192.168.30.5:8000

Note that Django seems to redirect ex. https://example.com/mydjangoproject/admin to ex. https://example.com/admin automatically, which breaks things unless you already have ex. ProxyPass /admin http://192.168.30.5:8000/admin as an existing entry (included above).


text:
Q: What do gunslingers do with their hands? In movies and games with cowboys when they are in a duel their fingers are almost about to get their guns, but then their fingers just start wiggling.

IN this specific motion what are gunslingers doing with their hands, especially their fingers? Is there a specific word that describes this motion?

A: You could say the gunslinger had his...

fingers/hands twitching over his guns (+more results for singular gun)

twitch - to move jerkily or spasmodically (thefreedictionary.com)

A: I don't know of a formal term for this, but many seem to use hovering in situations like these.
For example:

with his hands hovering only inches over his gun grips (here)

and:

Duke takes his stance, hand hovering over the Colt (here)

and:

Their hands hover over their holsters. (here)

and:

She flexed her fingers, an old-style gunslinger hovering her hand over her holster (here)

and specifically in reference to a video game:

keep your hand hovering over your holster (here)

Hover, of course, doesn't capture the finger wiggle. But the finger wiggle might be so ingrained in the public consciousness that just using hover will suggest it to those familiar with the imagery.
I was also thinking fingering might work, but it suggests actually touching the gun and it is often used in conjunction with nervously, as in "He was nervously fingering the gun in his holster".
Another option is flutter, which has the same benefits as hover, while also suggesting movement.
A final option is to describe the fingers as undulating over the holstered gun, where undulating means "move with a smooth wavelike motion" (Google).


text:
Q: How to trim the end of horizontal lines in a table with vertical lines? How to obtain something like this ?

The only way that I have found for trimming horizontal lines in a table is using booktabs.
The problem with booktabs is that it doesn't manage vertical lines well.
I tried this code:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{xcolor}
\usepackage{colortbl}
\usepackage{booktabs}

\begin{document}

\arrayrulecolor{gray}
\begin{tabular}{!{\color{gray}\vline}ll!{\color{gray}\vline}}
  a & b \\
  c & d \\
  \cmidrule(rl){1-2}
  e & f
\end{tabular}

\end{document}

But what I get the following output, which is not what I am looking for:

A:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{xcolor}
\usepackage{colortbl}

\begin{document}

\arrayrulecolor{red}
\begin{tabular}{|ll|}
  a & b \\
  c & d \\
\multispan{2}{\color{red}\vline\hspace*{.5em}\leaders \hrule height\arrayrulewidth\hskip\fill\hspace*{.5em}\vline}\\
  e & f
\end{tabular}

\end{document}

A: Here's a way using scalerel's \stretchleftright macro:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{xcolor}
\usepackage{booktabs}
\usepackage{colortbl}
\usepackage{scalerel}
\begin{document}
\arrayrulecolor{gray}
\stretchleftright{\color{gray}|}{%
\begin{tabular}{ll}
  a & b \\
  c & d \\
  \cmidrule(rl){1-2}
  e & f
\end{tabular}%
}{\color{gray}|}
\end{document}

A: With {NiceTabular} of nicematrix, you have directly the expected output because, in that environment, the vertical rules are never broken.
\documentclass{article}
\usepackage{xcolor}
\usepackage{nicematrix}
\usepackage{booktabs}

\begin{document}

\begin{NiceTabular}{|ll|}[rules/color=gray]
  a & b \\
  c & d \\
  \cmidrule(rl){1-2}
  e & f
\end{NiceTabular}

\end{document}

A: I will give an alternative solution with tblr environment of tabularray package.
Note that you need to put trim option lr inside the square brackets.
\documentclass{article}

\usepackage{xcolor}
\usepackage{tabularray}
\UseTblrLibrary{booktabs}

\begin{document}

\begin{tblr}{|[gray]ll|[gray]}
  a & b \\
  c & d \\
  \cmidrule[gray,lr]{1-2}
  e & f
\end{tblr}

\end{document}


text:
Q: How to display and style elements depending on their value (Angular 4+)? I would like to create a conditional template that will display a different content depending on the referenced-value of a {{status}}.
I have a table and the status column, I need the text color to change depending if it's "Active" or "Deactivated".
It doesn't seem to work, how can I make it work with Angular 4+?
HTML:
<ng-container matColumnDef="status">
      STATUS
       {{status}}
</ng-container>

CSS:
.status[matCellDef="ACTIVE"] {
        color : green
}

A: You can use ngStyle like this
<ng-container matColumnDef="status">
  STATUS
   {{status}}
</ng-container>

A: just use ngClass
like
<ng-container matColumnDef="status">
      STATUS
       {{status}}
</ng-container>


text:
Q: Don't stop me from creating a similar tag when the tag is new / renaming new tags Somebody on Arqade just created a [windows8] tag. Unfortunately this isn't consistent the other Windows tag, such as [windows-xp] and [windows-7], so I tried renaming it to [windows-8]. Unfortunately the system picked this up and helpfully pointed out that the [windows8] tag already exists - yes, I know that, that's what I'm trying to fix! Now the only way to fix the inconsistent tagging is to remove the tag then wait 24 hours before it is purged from the system and create the new tag again.
Can the system be a bit smarter about the edge cases? There are a few ways to avoid this - disable this feature for when the tag only has a few questions for one will work. Or just add a "are you really very sure you want to do this?" button somewhere where I can click.

A: It seems that for now, the only way to fix these corner cases are to ping or flag for a moderator to come in and fix the posts.

You can also @ a moderator on the question; moderators always get inbox notifications even if they haven't participated in the comments on the post. – casperOne♦


text:
Q: Converting Integer into list of digits without 'mod' and 'div' I currently have the Haskell function below which converts an integer into a list of digits taken from the original integer. My question is thus: Is there a way to do this without using mod and div? For example, if I wanted to do the same thing with a string I could create a function utilising other functions such as head and tail etc.
I struggled with this problem for a while before finally come to SO and finding the answer in another post. What got me asking this question is the fact that I would have never thought of using mod and div myself!
toDigits :: Integer -> [Integer]
toDigits n
 | n < 1 = []
 | otherwise = toDigits (n `div` 10) ++ [n `mod` 10]

A: You mentioned that you could do the same thing on strings with list operations. Indeed, that would be another way. You could convert the integer to a string and then convert each character to an integer:
import Data.Char (digitToInt)

toDigits :: Int -> [Int]
toDigits = map digitToInt . show

Here I used Int rather than Integer, but you can use Integer if you really want with a little more trouble:
toDigits :: Integer -> [Integer]
toDigits = map (fromIntegral . digitToInt) . show

A: @icktoofay's answer uses show, a generic way to convert some value to a String (in other words, get its string representation). A value should be of a type that is an instance of a typeclass Show. For example, Int is an instance of Show (enter :i Int in ghci and seek for a string instance Show Int -- Defined in `GHC.Show'). But a function isn't an instance of Show, so let f n = n in f will throw an error, because how would you convert a function to a string? (See also: If functions as instances of the Show typeclass). Anyway, using show function is idiomatic, so you can stick to it.
There is however a way to extract a digit from a number using logarithms, powers and integer divisions. Remember that you can remove digits from the left by finding a remainder, and remove digits from the right by integer division. In both cases, the right operand is some power of 10. For example:
*Main> 123 `mod` 10
3
*Main> 123 `div` 100
1

But how do you know, which power of 10 you should use to divide by? By finding a logarithm base 10: #digits of N = log10N + 1, e.g. log1012345 = 4. Unfortunately you can't use logBase, because it uses floating point arithmetic, which is inaccurate. For example:
*Main> logBase 10 1000
2.9999999999999996

You can use custom function iLogBase for integers—copy the code from the link into your source code. This way to find a first digit of a number I use the following code:
firstDigit :: (Integral a) => a -> a
firstDigit n = n `div` (10^log)
  where log = fst $ iLogBase 10 n

Creating a more general function of finding an arbitrary digit of a number and converting a number into a list of digits is left to you as an exercise :).
Also, the code in your question is inefficient. List concatenation (++) operation has the complexity of O(n), that is, every time you want to append an element to and end of list, it has to add the left list to the right list one by one, until you have a resulting list. Check out the source for (++), basically [1,2,3] ++ [4] becomes 1 : 2 : 3 : [4], which is terribly inefficient, as it takes 3 cons (:) operations just to add a list. And as you append numbers to the end multiple times, it has to repeat the same process each time, therefore overall complexity of your function is O(n^2).
On the other hand (:) is instant, that is, has complexity of O(1). No matter how long is your list, prepending an element to the beginning is cheap. So instead of adding an element to the end, I would recommend, adding it to the beginning and an the end simply reversing the list once (for information, Lisp people call this push/nreverse idiom):
reverse $ (n `mod` 10) : toDigits (n `div` 10)


text:
Q: VMware Horizon 7 Administrator Console web-UI will not load, page is blank When I try to open "Horizon 7 Administrator" (URL is https://View-Connection-Server.Corp.local/admin/#) Chrome opens to a blank page. I am trying from the Horizon Connection Server itself, so this is not a firewall issue (plus the Windows Firewall is off as of now). I am thinking this is an SSL cert issue, but am not sure how to troubleshoot it or fix it.

*

*Host OS is Windows Server 2016

*Horizon 7 Connection Server version is 7.6.0

Here are some log snippets from C:\ProgramData\VMware\VDM\logs:
2020-01-19T12:54:50.490-07:00 WARN  (10EC-11F4) <Thread-2> [bp] Item enqueued on "Outbound JMS Forwarder" but there are no workers available to process it. Busy workers = 0, queue length = 8677
2020-01-19T12:54:54.394-07:00 ERROR (10EC-13A0) <SwiftMQ-ConnectorPool-1> [JMSTunnelSSLSocketFactory] Certificate thumbprint verification failed, no matching thumbprint. Presented identity: router/view
2020-01-19T12:54:54.394-07:00 ERROR (10EC-13A0) <SwiftMQ-ConnectorPool-1> [JMSTunnelSSLSocketFactory] General error occurred: Unexpected certificate: router/view
2020-01-19T12:54:54.427-07:00 ERROR (10EC-13B8) <SwiftMQ-ConnectorPool-3> [JMSTunnelSSLSocketFactory] Certificate thumbprint verification failed, no matching thumbprint. Presented identity: router/view
2020-01-19T12:54:54.427-07:00 ERROR (10EC-13B8) <SwiftMQ-ConnectorPool-3> [JMSTunnelSSLSocketFactory] General error occurred: Unexpected certificate: router/view
2020-01-19T12:54:54.722-07:00 ERROR (10EC-13BC) <SwiftMQ-ConnectorPool-4> [JMSTunnelSSLSocketFactory] Certificate thumbprint verification failed, no matching thumbprint. Presented identity: router/view
2020-01-19T12:54:54.722-07:00 ERROR (10EC-13BC) <SwiftMQ-ConnectorPool-4> [JMSTunnelSSLSocketFactory] General error occurred: Unexpected certificate: router/view
2020-01-19T12:54:54.751-07:00 ERROR (10EC-13A0) <SwiftMQ-ConnectorPool-1> [JMSTunnelSSLSocketFactory] Certificate thumbprint verification failed, no matching thumbprint. Presented identity: router/view
2020-01-19T12:54:54.751-07:00 ERROR (10EC-13A0) <SwiftMQ-ConnectorPool-1> [JMSTunnelSSLSocketFactory] General error occurred: Unexpected certificate: router/view
2020-01-19T12:54:55.471-07:00 ERROR (10EC-13E8) <SwiftMQ-ConnectorPool-7> [JMSTunnelSSLSocketFactory] Certificate thumbprint verification failed, no matching thumbprint. Presented identity: router/view
2020-01-19T12:54:55.471-07:00 ERROR (10EC-13E8) <SwiftMQ-ConnectorPool-7> [JMSTunnelSSLSocketFactory] General error occurred: Unexpected certificate: router/view
2020-01-19T12:54:59.456-07:00 ERROR (10EC-13C4) <SwiftMQ-ConnectorPool-5> [JMSTunnelSSLSocketFactory] Certificate thumbprint verification failed, no matching thumbprint. Presented identity: router/view
2020-01-19T12:54:59.456-07:00 ERROR (10EC-13C4) <SwiftMQ-ConnectorPool-5> [JMSTunnelSSLSocketFactory] General error occurred: Unexpected certificate: router/view
2020-01-19T12:54:59.508-07:00 ERROR (10EC-13A0) <SwiftMQ-ConnectorPool-1> [JMSTunnelSSLSocketFactory] Certificate thumbprint verification failed, no matching thumbprint. Presented identity: router/view
2020-01-19T12:54:59.508-07:00 ERROR (10EC-13A0) <SwiftMQ-ConnectorPool-1> [JMSTunnelSSLSocketFactory] General error occurred: Unexpected certificate: router/view
2020-01-19T12:54:59.772-07:00 ERROR (10EC-13B4) <SwiftMQ-ConnectorPool-2> [JMSTunnelSSLSocketFactory] Certificate thumbprint verification failed, no matching thumbprint. Presented identity: router/view
2020-01-19T12:54:59.772-07:00 ERROR (10EC-13B4) <SwiftMQ-ConnectorPool-2> [JMSTunnelSSLSocketFactory] General error occurred: Unexpected certificate: router/view
2020-01-19T12:54:59.810-07:00 ERROR (10EC-13C4) <SwiftMQ-ConnectorPool-5> [JMSTunnelSSLSocketFactory] Certificate thumbprint verification failed, no matching thumbprint. Presented identity: router/view
2020-01-19T12:54:59.810-07:00 ERROR (10EC-13C4) <SwiftMQ-ConnectorPool-5> [JMSTunnelSSLSocketFactory] General error occurred: Unexpected certificate: router/view
2020-01-19T12:55:00.453-07:00 WARN  (10EC-11F4) <Thread-2> [bp] Item enqueued on "Outbound JMS Forwarder" but there are no workers available to process it. Busy workers = 0, queue length = 8678
2020-01-19T12:55:00.590-07:00 ERROR (10EC-13BC) <SwiftMQ-ConnectorPool-4> [JMSTunnelSSLSocketFactory] Certificate thumbprint verification failed, no matching thumbprint. Presented identity: router/view
2020-01-19T12:55:00.590-07:00 ERROR (10EC-13BC) <SwiftMQ-ConnectorPool-4> [JMSTunnelSSLSocketFactory] General error occurred: Unexpected certificate: router/view

A: What happened is that the thumbprint for the JMS router's certificate on the Connection Server should've been registered in the secure gateway's config files on the same CS, but the certificates had expired.
I simply uninstalled and reinstalled VMware Horizon 7 Connection Server and boom, problem solved.
EDIT: After uninstalling the Horizon CS, you also must remove the AD LDS role from the Windows Server: first via Add/Remove, then via Server Manager. DO NOT ADD IT BACK MANUALLY! The Horizon Connection Server installs this!


text:
Q: Is it possible so send just a part of an object by angular resource? I have a resource where the get is receiving an object like {metadata : {}, data : {}}. But when I save, I just want to send the data and not metadata.
    .factory("$profile", function($resource) {
        return $resource("service/profile/:profileid");
    })
    .controller('ProfileController', function($scope, $routeParams, $profile) {
        $scope.profile = new $profile();
        $scope.doSave = function() {

            // need to send profile.data only               << ----------

            $scope.profile.$save($routeParams, function(data) {
                console.log("saved profile");
            });
        }

What I have done right now is the following:
    .controller('ProfileController', function($scope, $routeParams, $profile) {
        $scope.profile = new $profile();
        $scope.doSave = function() {

            $scope.profile.data.$save = $scope.profile.$save;

            $scope.profile.data.$save($routeParams, function(data) {
                console.log("saved profile");
            });
        }

This works but I am sure there is a much cleaner way to do what I need to do. Ideally I would tell the resource to look for a data property on "save".

A: Yes, you can do that. The properties you need are 'transformResponse' (on GET) and 'transformRequest' (on Post).
.factory("$profile", function($resource) {
  return $resource("service/profile/:profileid",
    {},
    {
      get: {
        method: 'GET',
        transformResponse: function(response, headers){
          return response.data;
        }
      },
      post: {
        method: 'POST',
        transformRequest: function (request, headers) {
            var result = request.data; // << This line might not be exactly what you need.
            return result;
        }
      }
    });
})

I actually suspect that the transformRequest part isn't needed at all (but you did ask for it).
$scope.profile.$save($routeParams, function(data) {
  console.log("saved profile");
});


text:
Q: Maximo BMXAA4114E - An illegal access exception occurred I want to display a workorder with WONUM by using a request query using enterpirse maximo enterprise service. I am using SoapIU to call request with maxadmin user with all security access enabled. For external system I am using predefined EXTSYS1. I keep getting error "BMXAA4114E- An illegal access exception occurred" only with this database. I changed users enabled all security access, changed external systems and made a new object structure.
SoapIU code:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:max="http://www.ibm.com/maximo">
   <soapenv:Header/>
   <soapenv:Body>
      <max:QueryMXTWORKORDERCUSTOM  rsStart="0">
         <max:MXTWORKORDERCUSTOMQuery operandMode="AND">
            <!--Optional:-->
            <max:WORKORDER>
               <max:WONUM>1022</max:WONUM>
            </max:WORKORDER>
         </max:MXTWORKORDERCUSTOMQuery>
      </max:QueryMXTWORKORDERCUSTOM>
   </soapenv:Body>
</soapenv:Envelope>

Return code:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Server</faultcode>
         <faultstring>BMXAA4114E - An illegal access exception occurred. The associated message indicates where the exception occurred.</faultstring>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>