$(this) selector working awry

Question: I'm using inview.js and knobs.js plugins to create a animated knob chart.
I'm using the following code to animate a knob:
jQuery('.knobchart').bind('inview', function (event, visible) {
if (visible == true) {
    jQuery(this).knob();
    jQuery({
        value: 0
    }).animate({
        value: jQuery(this).attr("rel")
    }, {
        duration: 5000,
        easing: 'swing',
        step: function () {
            jQuery(this).val(Math.ceil(this.value)).trigger('change');
        }
    })

} else {

$(this).val(0);

}
});

The markup for a knob looks like this :
<input data-readonly="true" class="knobchart" rel="999" value="0">

The problem is that specifying jQuery(this) selector in step function for the animation does nothing.
I tried changing it to '.knobchart' but then all the knobs get animated to same value.
EDIT: RESOLVED @Gaby 's method works brilliantly...
Comment: Why use alias 'jQuery' when you seem to use '$' too?
Comment: If you didn't get the answer then you shouldn't mark a post as answer. This let other users assume that you got the answer and they move to next post.
Comment: So, use your browser's debugging tools and find out what `this` is.
Comment: changing to '$' does nothing..
Comment: How do I find out what 'this' is
Comment: console.log($(this));
Comment: [Object, jquery: "1.9.1", constructor: function, init: function, selector: "", size: function…]
0: Object
value: 9
__proto__: Object
length: 1
__proto__: Object[0]
Comment: Console returns this ^^^^^^^^^^^^
Comment: try `console.log(this)` don't wrap it with jQuery
Comment: @TecHunter should i do this with Arun 's solution cos it works partially?
Comment: @ArunPJohny method works but still not rounding off.. Can sm1 help?
Comment: @Sid post from Gaby works for me : http://jsfiddle.net/techunter/2h8mF/6/
Answer: You should store this to a variable when you know where it points, and use that variable instead of this..
jQuery('.knobchart').bind('inview', function (event, visible) {
    var self = this; // <-- added this line, and using self from now on in this method
    if (visible == true) {
        jQuery(self).knob();
        jQuery({
            value: 0
        }).animate({
            value: jQuery(self).attr("rel")
        }, {
            duration: 5000,
            easing: 'swing',
            step: function () {
                jQuery(self).val(Math.ceil(this.value)).trigger('change');
            }
        });

    } else {
        $(self).val(0);
    }
});

This is needed because you do not animate an element but an object.
Demo at http://jsfiddle.net/2h8mF/1/
Comment: @user, did you replace all `this` with `self` ?
Comment: here is a demo http://jsfiddle.net/2h8mF/1 (*i commented out the .knob() as i do not have that plugin*). Also made a correction, inside the `val(..)` i had in error replace `this.value` which was correct..
Comment: Try it with more than 1 ``
Comment: @sid, i did what about it ?
Answer: Why arent you using $ but jQuery?
You could try to do this within an each loop, which might not be too perfomant:
$('.knobchart').each(function() {
    var el = $(this);
    el.bind('inview', function (event, visible) {
        if (visible == true) {
            el.knob();
            $({
                value: 0
            }).animate({
                value: el.attr("rel")
            }, {
                duration: 5000,
                easing: 'swing',
                step: function () {
                    el.val(Math.ceil(this.value)).trigger('change');
                }
            })

        } else {

            el.val(0);

        }
    });
});

One question though: what shall the lines
jQuery({
        value: 0
    }).animate({
        value: jQuery(this).attr("rel")
    }, {
        duration: 5000,
        easing: 'swing',
        step: function () {
            jQuery(this).val(Math.ceil(this.value)).trigger('change');
        }
    })

do? Looks wrong to me
Comment: well i get that, but the syntax is looking falsy to me. Are you sure those dont throw an error? Did the .each() function work?
Answer: There were two problems which I found.

jQuery({value: 0}).animate(...) is not a valid statement, you need to animate the current element that is this
Usage of this inside the step handler, you need to use $.proxy() to pass a custom context to the callback method

Code
jQuery('.knobchart').bind('inview', function (event, visible) {
    if (visible == true) {
        jQuery(this).knob();
        jQuery(this).animate({
            value: jQuery(this).attr("rel")
        }, {
            duration: 5000,
            easing: 'swing',
            step: $.proxy(function () {
                jQuery(this).val(Math.ceil(this.value)).trigger('change');
            },this)
        })
    } else {
        $(this).val(0);
    }
});

Comment: can somebody tell me y its not rounding off?
Comment: describe your solution a bit instead of just posting code please
Comment: @arun would u describe ur method?

$(this) selector working awry


Mark Beginning and End of Runs in R

Question: I have the following table and want to make a "Beginning" and "End" column with T/F values:

Trigger
Beginning
End

1
T
F

1
F
F

0
F
T

1
T
F

0
F
T

1
T
F

1
F
F

How can this be done in R?
Many thanks
Comment: Can you explain a bit more about what your expected output is?
Answer: Base:
df <- data.frame(Trigger = c(1, 1, 0, 1, 0, 1, 1))
df$Beginning <- df$Trigger & !c(0, df$Trigger[-nrow(df)])
df$End <- !df$Trigger & c(0, df$Trigger[-nrow(df)]

tidyverse:
mutate(
  df,
  Beginning = Trigger & !lag(Trigger, default = FALSE),
  End = !Trigger & lag(Trigger, default = TRUE)  # May want to use FALSE depending on use case.
)

Answer: Base R Solution:
# Import data: df => data.frame
df <- structure(list(Trigger = c(1L, 1L, 0L, 1L, 0L, 1L, 1L)),
                row.names = c(NA, 7L), class = "data.frame")

# Determine if an event has begun or ended: df => data.frame
df[,c("Beginning", "End")]  <- t(
  outer(
    c(1, -1),
    with(
      df,
      diff(
        c(
          0,
          Trigger
        )
      )
    ),
    `==`
  )
)

tidyverse():: solution:
library(tidyverse)
df %>%
  transmute(event_diff = c(if_else(first(Trigger) == 1, 1, 0), diff(Trigger))) %>%
  map2(., c(1, -1), `==`) %>%
  set_names(., c("Beginning", "End")) %>%
  bind_cols(Trigger = df$Trigger, .)

data.table():: solution:
library(data.table)
dt <- data.table(df)
dt[,trigger_diff := diff(c(0, Trigger)),]
dt[,c("Beginning", "End") := lapply(c(1, -1), function(x){trigger_diff == x}),]
dt[,trigger_diff := NULL, ]

Mark Beginning and End of Runs in R


something about the MVCObject in google map

Question: In google map's reference I found the MVCObject,it provide some cool function.
But I am really confused with this object,since I used to do the java web development,so say the MVC I will thought the Model-View-Controller layers.
But in the google map,I can not found anything which can match the three layers.
So I wonder what is the meaning of the MVCObject(how is it differ with the MVC in web development),and what is advantage?
Answer: http://code.google.com/apis/maps/articles/mvcfun.html
Google Maps Javascript API V3 has introduced the implementation of MVC objects that allow map objects to store state and update their presentation automatically
MVC is Model-View-Controller .....


How to compile Python from PHP?

Question: I am working on an Encryption Project and have used PyCrypto module in Python for all the Cryptographic algorithm.
When I connect PHP with MongoDB, at the user sign up I need to link each user with a specific public and private key, the code for RSA Key generation is in Python and I am using PHP to store all the user information in MongoDB.
How to call Python scripts and use the output in PHP without executing the script in shell first as it is a time taking process?
Is there any cross-compiler present for both PHP and Python so that I can execute on the same compiler ?
Comment: Please use the site-search before posting a question. We try to keep questions on topic and generalize individual problems. Thank you!
Answer: You could use exec (which eventually runs the script in the shell)
As described in the documentation the first argument to the method will be the command you want to run and the second one will be a reference which will hold the output
Comment: as mentioned I do not want to use shell for shell execution, that is a time taking task. Is there any other way to do it like using a cross compiler ? If yes please share the links.
Comment: Like anything that does soemthing, using exec (or for that matter inline code) is a *time taking task*. Unless you represent your metrics and requirements (quantified) so that it becomes clear what on any time taking task would be a no-go, it would be actually answerable if not exec is the solution.
Answer: There is no cross-compiler AFAIK. And for a non-toy project I would be very cautious of using something that promise to work both with PHP and Python. :)
To avoid creating a process everytime you want to run your Python script, you can implement server-client architecture using sockets to communicate between Python and PHP. Server being your crypto library in your case and client is your PHP script that queries the server.

Python sockets doc: https://docs.python.org/2/howto/sockets.html
PHP sockets doc: http://php.net/manual/en/book.sockets.php

It essentially means that your Python script is a long-running script (to avoid the cost of creating it again and again).

How to compile Python from PHP?


How to concatenate two CNN

Question: I have two CNN based on MobileNet
Code (is the same for first and second CNN):
img_height, img_width = 224, 224
num_classes = 30
input_shape = (img_height, img_width, 3)

epochs = 1

base_model_fingerprint = MobileNet(weights='imagenet', include_top=False, input_shape=input_shape)

x = base_model_fingerprint.output
x = GlobalAveragePooling2D()(x)
x = Dropout(0.5)(x)
output_fingerprint = Dense(num_classes, activation='softmax')(x)

model_fingerprint = Model(inputs=base_model_fingerprint.input, outputs=output_fingerprint)

for layer in model_fingerprint.layers:
    layer._name = 'fingerprint_' + layer.name

for layer in base_model_fingerprint.layers:
    layer.trainable = False

model_fingerprint.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

train_datagen_fingerprint = ImageDataGenerator(
        rescale=1./255,
        rotation_range=20,
        width_shift_range=0.2,
        height_shift_range=0.2,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

test_datagen_fingerprint = ImageDataGenerator(rescale=1. / 255)

train_generator_fingerprint = train_datagen_fingerprint.flow_from_directory(
        'C:/Users/giova/Desktop/CNN_FINGER_RESIZE/TRAIN',
        target_size=(img_height, img_width),
        batch_size=32,
        class_mode='categorical')

test_generator_fingerprint = test_datagen_fingerprint.flow_from_directory(
        'C:/Users/giova/Desktop/CNN_FINGER_RESIZE/TEST',
        target_size=(img_height, img_width),
        batch_size=32,
        class_mode='categorical')

reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, min_lr=0.0001)
early_stop = EarlyStopping(monitor='val_loss', patience=10)

history = model_fingerprint.fit(train_generator_fingerprint,
                                validation_data=test_generator_fingerprint,
                                epochs=epochs,
                                callbacks=[reduce_lr, early_stop])

test_loss, test_acc = model_fingerprint.evaluate(test_generator_fingerprint, verbose=2)
print('Test accuracy:', test_acc)

How can I create a third CNN for better accuracy?
I have tried to use model.save so I can use .h5 file but it doesn't work
the second CNN only changes the directory where it gets the input data from.
Update: I wrote this code but I can't solve the error:
import tensorflow as tf
from tensorflow.keras.models import Model, load_model

# Carica i modelli delle due CNN
model1 = load_model('pesi_fingerprint.h5')
model2 = load_model('pesi_palmprint.h5')

# Rimuove l'ultimo livello di ciascuna CNN
model1.layers.pop()
model2.layers.pop()

# Imposta i layer delle due CNN come non trainabili
for layer in model1.layers:
    layer.trainable = False
    layer._name = 'model1_' + layer.name
for layer in model2.layers:
    layer.trainable = False
    layer._name = 'model2_' + layer.name

# Crea il nuovo modello concatenando le feature maps
concatenated = tf.keras.layers.Concatenate()([model1.layers[-1].output, model2.layers[-1].output])

x = tf.keras.layers.Reshape((6, 5, 3))(concatenated) # aumenta le dimensioni
x = tf.keras.layers.Conv2D(16, kernel_size=(3, 3), activation='relu', input_shape=(6, 5, 3))(x) # utilizza un kernel di convoluzione 3x3
x = tf.keras.layers.MaxPooling2D(pool_size=(2,2))(x)
x = tf.keras.layers.Conv2D(8, kernel_size=(3,3), activation='relu', padding='same')(x)
x = tf.keras.layers.Conv2D(8, kernel_size=(3,3), activation='relu', padding='same')(x)
x = tf.keras.layers.MaxPooling2D(pool_size=(2,2))(x)
x = tf.keras.layers.MaxPooling2D(pool_size=(2,2))(x)
x = tf.keras.layers.Flatten()(x)
x = tf.keras.layers.Dense(128, activation='relu')(x)

output = tf.keras.layers.Dense(num_classes, activation='softmax')(x)

# Crea il modello finale
model = Model(inputs=[model1.input, model2.input], outputs=output)

# Compila il modello
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

# Stampa la struttura del modello
model.summary()

from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
    rescale=1./255, # normalizza i valori dei pixel tra 0 e 1
    rotation_range=20, # ruota le immagini in modo casuale
    width_shift_range=0.2, # sposta le immagini in orizzontale in modo casuale
    height_shift_range=0.2, # sposta le immagini in verticale in modo casuale
    shear_range=0.2, # applica la deformazione di taglio alle immagini
    zoom_range=0.2, # applica lo zoom alle immagini
    horizontal_flip=True, # inverte le immagini in orizzontale in modo casuale
    fill_mode='nearest',
    target_size = (224,224) # riempie i pixel mancanti con il valore più vicino
)

test_datagen = ImageDataGenerator(rescale=1./255,
                                  target_size=(224, 224))

# specifica il percorso della cartella che contiene i dati di training e di test
train_dir = 'C:\\Users\\giova\\Desktop\\MERGE CNN\\TRAIN'
test_dir = 'C:\\Users\\giova\\Desktop\\MERGE CNN\\TEST'

# imposta il numero di classi
num_classes = 30

# leggi i dati di training dalla cartella specificata
train_generator = train_datagen.flow_from_directory(
    train_dir,
    target_size=(224, 224),
    batch_size=32,
    class_mode='categorical'
)

# leggi i dati di test dalla cartella specificata
test_generator = test_datagen.flow_from_directory(
    test_dir,
    target_size=(224, 224),
    batch_size=32,
    class_mode='categorical'
)

# Addestramento del modello
# Addestramento del modello
model.fit(train_generator, epochs=10, validation_data=test_generator)

ERROR:
ValueError: Exception encountered when calling layer "reshape" (type Reshape).
total size of new array must be unchanged, input_shape = [60], output_shape = [6, 5, 3]
Call arguments received by layer "reshape" (type Reshape):
• inputs=tf.Tensor(shape=(None, 60), dtype=float32)
Answer: The output shape of your concatenated model is [60] but you're trying to reshape it to [6,5,3] which is not possible since it changes the total size of the array eg : 6x5x3 != 60, try reshaping it to  [6,5,2] instead.

How to concatenate two CNN


How do I know if this switch box has a neutral wire?

Question: This outlet is two rocker switches. Left controls my bathroom light (4), right controls my bathroom fan (3). I am trying to install a timer switch so the fan is only on for ~30 min at a time.
The instructions insist a neutral wire is connected to the switch.
My house was built in the late 60s. Many of the wires have paint on them which makes things difficult.
The wire nut under (1) contains wires which come from the wall and don't connect to the existing switches. They are an egg-cream color which I believe is white + age. All the other white looking wires are black wires that have paint on them. I think what's going on with the wire nut in 2 is that the hot line from the wall is joined with two other small wires, one for each switch.
My thought is that (1) is the neutral wire, and I should undo the existing wire nut, add an additional wire which will goto my new switch as a neutral, then wire nut them all together.
Is that correct? Is there anything else I can do to verify this? What's the risk if I'm wrong?
(note 3 is the actual timer switch, once I realized I didn't know what the neutral was I took the pictures and then put it back how it started)
(edit: additional note, this bathroom has a small room for shower/toilet, where this picture is, connected to the area with two sinks... basically the other side of the wall in the same position is a gfci outlet by the sink)
Comment: Welcome to Stack Exchange. There are tons of excellent questions with pictures on these very questions. Definitiely read up and get comfortable. We are talking about voltages that can kill, and you asked just the right questions to make it obvious you know enough to be dangerous but also dont want to be Darwin in the process!!! In the picture it appears you are using backstabs, (where the wire is pushed in vs. screwed down - please do not use these). Also, the white is PROBABLY Neutral (99.99% so), but, to help us answer, do you have a meter and know how to use it???
Comment: Here's a helpful one with lots of great advice, and pictures, and while it's a different application, there is much here that explains it all: https://diy.stackexchange.com/questions/155964/replacing-attic-light-switch-with-leviton-combo/156029#156029
Comment: I do have a multimeter, but I don't know how to use it other than using it to test the voltage coming out of an outlet. And yes, your comment is correct --- I kinda-sorta know how this works (based a lot on reading other posts), but I know that it's very dangerous. Probably the most important thing I wanted to get out of the post was how to test they are neutral and/or what would go wrong if they weren't.
Answer: Yes, #1  is your group of neutrals and you would need to pigtail into that connector with a piece #14. Naturally, you want to shut off the breaker before doing any work. You're going to have to be careful arranging the existing wires so you can get the new timer switch into the box, and even then, you might need to add a box extender.
Comment: I agree with Jack all those whites are the neutrals for the circuits.
Comment: Thanks. And I will shut off the breaker, of course. The breaker in my house wasn't labeled and seems kind of illogical (so the efforts to label it thus far hasn't gone that well since its not clearly like room by room) so this part always takes me like 4x the time to do any other work.
Comment: I held off on answering because A.) it is possible the whites are not neutral (like a hundredth of a %1 or less), but also 2.) because no grounds are seen in the picture, backstabs are used, and it looks like the insualtion on a white wire is bare and exposed as well as undetermined routing of black... (E.g., the switch on the right doesn't seem to be fed from #2, and it "should be")
Comment: @noybman  Grounding wasn't required when this wiring was done. Those are not back stabs but back clamps tightened by the side screws. There is a wire going from the switch to  #2. but we don't know the rotation of the switch.
Comment: @JACK ohh, if those are clamps then all good for sure. When did grounds get introduced as required? I thought NM form mid 1960's (like 1965) introduced ground wire?
Comment: @noybman  Grounds for outlets were required in 1962. They were not required for switches. There were two types of NM cable: with a ground wire and without a ground wire and you'd find both types in homes.
Comment: @noybman I can confirm that one wire from the cluster in #2 goes to the left switch, and another wire in that cluster goes to the right switch. Between the angle and the paint on the black wires and the mess it's very tough to tell. My guess from visual inspection of how it's configured, not testing the wires, is that #2 contains a wire from the wall joined with one wire for each switch (the hot wires) and then each switch has a wire that goes into the wall (for light and fan respectively). Then 1 contains wires which come from the wall and are all joined together.
Comment: Awesome, @JACK is spot on. Did you manage to solve it? If you still want to test the wire you can (with hot live), or use Ohms (circuit off). For Ohms breaker off, poke the meter lead into the white wire nut and check it to a known good ground. You'll read low ohms, ideally 0, but probably more like 20. If testing with hot live (use VAC), just be sure your connection from the meter to white is safe, nothing else is touching metal (including you), and then touch the other meter lead to a black-wire screw on a switch. try each wire for ~120VAC. Either test proves it if you have any doubt.
Comment: Yes. I originally was going to get a mechanical timer because it was cheaper but then the order didn't go through, so I went back and hooked this up. Couldn't figure out the testing w/ the multimeter with the breaker off and decided not to try and test with it on, so I just treated the bundle in 1 like it was neutral and it all worked great. Thanks again!
Answer: They also make timers that don't use neutral wires.  Same company, same shelf.
They wire up exactly like your old switch, and are guaranteed to work anywhere a plain switch works.
These have a dial you twist and set to the exact time you want, and a spring and clockwork mechanism makes them unwind. They come in any range from 5 minutes to 12 hours, with or without a "stay on indefinitely" position.   (At the lodge I use the ones without the "stay on" function, because the point is to stop people from leaving things turned on.)
Comment: Great alternative!
Comment: Thanks. I actually looked for these not realizing neutral was a factor, but because I thought it might be cheaper but didn't find any. I have in fact found some online for ~10$ instead of ~$25, so that plus avoiding this neutral situation might be the ticket.
Answer: Check if a blue wire (CENELEC) or white wire (NEC). Be carefull to identify "switch loops" those may have a neutral-colored wire actually used for live.
A simple contact test-light will tell you if a wire is live or not, switched loops go from 0 to live potential after switch is operated, so testlight is off if switch is off and on if switch is on.
You can identify those by checking if a live wire is enetering the switch and a neutral colored wire is coming out of it.
Comment: Switch loops would not have a group of 4 white wires connected at a switch box. See @jack answer it is correct.
Answer: I believe that up until the NEC 2017 version, neutral conductors were not required in a box with switches in it. So the only reason there would be a neutral present would be if the circuit fed through the box. From what we can see of the box, it appears that the lighting circuits are fed to the light fixture first and the a line leg is sent down to the box and a switch leg is fed back to control the light. Since most NM comes with a white and a black conductor, white does not always indicate a neutral.
The bundle wires you have labeled 1, have a green wire nut on them. That would indicate that they are a ground. Then again it could be the neutrals with an incorrect wirenut on them.
So unless you can use a voltmeter to find 120V power between a line side conductor and another conductor other than the ground wires or verify that the #1 bundle are the neutrals.  I would guess that there is no neutral in the box.
Good luck
Comment: With a name like retired master electrician I would expect a better answer, a group of white wires in a switch box, come on , code required or not. Green wirenut in a metal box with no visible grounding conductors. This wiring method Is at least pre 70's.
Comment: I'm upvoting the answer because "code be damned" we cannot know who wired that box as it is today, and just because it looks like the white is the neutral bundle, do any of us on the internet know it is??? All it takes is one idiot to have wired it before and then all bets are off. (but again, 99.99% it is!!! lol)
Comment: One of us is color blind, I don't see a green wire nut. It looks like an old tan twister.
Comment: It's not green. My impression in person was that it was clear and super dirty.
Comment: @JACK - I'm the one who's color blind. Not a joke fact.
Comment: @RetiredMasterElectrician  Sorry to hear that.  Must make the wiring difficult.
Answer: There are only a few ways this can go
There are only four ways switches ever get wired:

Power-to-the-switch, where always-hot and neutral are brought to the switch location, the switch breaks the hot, then switched-hot and neutral are brought from the switch location to the outlet location
An "old-style" switch loop, where always-hot and neutral are brought to the switched outlet, with neutral terminating there, but always-hot carrying on in another cable to the switch location, which breaks hot, leaving the switched-hot to run back with the always-hot from the switch to the outlet
A "new-style" switch-loop, which works as before, save for the fact that neutral is run on from the switched outlet to the switch location and capped off at the switch (since a Plain Old Light Switch has no use for neutral, but fancy doodads like dimmers, timers, wifi/... switches, and occupancy sensors can make productive use of it)
Or a traveller spur, where either always-hot or switched-hot and the travelers of a 3-way setup (with multiple switches controlling the light) are brought from one 3-way location out to the other, instead of having always-hot come in one end of the 3-way and switched-hot come out the other

Since this is a single-pole situation (only one switch controls the fan in question), we can rule out #4.  #3 can be ruled out by the lack of any wire colors other than white or black in the box, given that the wiring is done using cables, with their fixed internal color scheme (instead of individual wires in conduit, where one has the power of the rainbow at their disposal).  We then rule out #2 in your situation because that requires a white wire to be attached to a hot terminal on a switch, and that's not the case; instead, all the white wires run into a bundle (nut 1), alongside a bunch of bundled black wires (nut 2) (although they're partly masked by white paint/drywall-compound splatter), which means we have case 1, and the bundled white wires must be the neutrals.
So, you can add your new timer's neutral to the existing bundle, alongside all the existing wires.  Note that you may need to upsize to a larger wirenut to do this if the existing wirenut is too small for the new bundle of wires.


How could I Deserialize this xml to class

Question: I want to deserialize a XML file to a class but it fails. Please Help!!
XML file like this:
<messages>
   <message name="a">
  <field name="ab"/>
  <field name="ab1"/>
  <field name="ab2"/>
 </message>
   <message name="b">
      <field name="bc"/>
      <group name="ab">
         <field name="ab"/>
         <field name="ab1"/>
         <field name="ab2"/>
          <group name="ab">
             <field name="4"/>
           </group>
      </group>
       <field />
       ....

    </message>
</messages>

this is just a demo.The reality is a "message" include several "field" and "group",and the group include several field and also group!!!
It is random not constant.
I have try this:
[XmlInclude(typeof(GroupInMsg))]
[XmlType("field")]
public class FieldBase
{
    [XmlAttribute("name")]
    public string name { get; set; }

}

[XmlType("message")]
public class Message
{
    public Message()
    {

    }
    [XmlAttribute("name")]
    public string name { get; set; }

    public FieldBase[] Fields { get; set; }
}

public class GroupInMsg : FieldBase
{
    public GroupInMsg()
    {

    }

    //[XmlArrayItem(Type = typeof(FieldBase))]
    //[XmlArrayItem(Type = typeof(GroupInMsg))]
    public FieldBase[] Fields { get; set; }
}

My final target is to Deserialize the Quickfix Something like this
<messages>
    <message name="Heartbeat" msgtype="0" msgcat="admin">
      <field name="TestReqID" required="N"/>
    </message>
    <message name="Logon" msgtype="A" msgcat="admin">
      <field name="EncryptMethod" required="Y"/>
      <field name="HeartBtInt" required="Y"/>
      <field name="RawDataLength" required="N"/>
      <field name="RawData" required="N"/>
      <field name="ResetSeqNumFlag" required="N"/>
      <field name="MaxMessageSize" required="N"/>
      <group name="NoMsgTypes" required="N">
        <field name="RefMsgType" required="N"/>
        <field name="MsgDirection" required="N"/>
      </group>
    </message>
    <message name="TestRequest" msgtype="1" msgcat="admin">
      <field name="TestReqID" required="Y"/>
    </message>
    <message name="ResendRequest" msgtype="2" msgcat="admin">
      <field name="BeginSeqNo" required="Y"/>
      <field name="EndSeqNo" required="Y"/>
    </message>
    <message name="Reject" msgtype="3" msgcat="admin">
      <field name="RefSeqNum" required="Y"/>
      <field name="RefTagID" required="N"/>
      <field name="RefMsgType" required="N"/>
      <field name="SessionRejectReason" required="N"/>
      <field name="Text" required="N"/>
      <field name="EncodedTextLen" required="N"/>
      <field name="EncodedText" required="N"/>
    </message>
    <message name="SequenceReset" msgtype="4" msgcat="admin">
      <field name="GapFillFlag" required="N"/>
      <field name="NewSeqNo" required="Y"/>
    </message>
    <message name="Logout" msgtype="5" msgcat="admin">
      <field name="Text" required="N"/>
      <field name="EncodedTextLen" required="N"/>
      <field name="EncodedText" required="N"/>
    </message>
......

many messges.many feild and group in messge.And also many group and field in group!!!
Forgive me!Thanks!
Comment: Can you also provide your class structure?
Comment: Regarding deserialization there is a good example in documentation: https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer.deserialize?view=netframework-4.8
Comment: "_but it fails_"  tells us nothing.  In what way does it fail?  Show the code you used to deserialize the xml.
Comment: I know the biasic Deserialize.but this is nested
Answer: @ppz.whenever you want to ask something help or solution On StackOverflow community. I mean what you expect or facing some error You have to describe a proper way.so that the community will understand and provide a better solution asap.
You can refer below code
As per XML data you provided to us.
  Model
[XmlRoot(ElementName = "field")]
    public class Field
    {
        [XmlAttribute(AttributeName = "name")]
        public string Name { get; set; }
    }

    [XmlRoot(ElementName = "message")]
    public class Message
    {
        [XmlElement(ElementName = "field")]
        public List<Field> Field { get; set; }
        [XmlAttribute(AttributeName = "name")]
        public string Name { get; set; }
        [XmlElement(ElementName = "group")]
        public Group Group { get; set; }
    }

    [XmlRoot(ElementName = "group")]
    public class Group
    {
        [XmlElement(ElementName = "field")]
        public List<Field> Field { get; set; }
        [XmlAttribute(AttributeName = "name")]
        public string Name { get; set; }
    }

    [XmlRoot(ElementName = "messages")]
    public class Messages
    {
        [XmlElement(ElementName = "message")]
        public List<Message> Message { get; set; }
    }

And you deserialize your XML like below
string path = string.Empty;
            string xmlInputData = string.Empty;
            try
            {
               path = "XML file path";
                xmlInputData = File.ReadAllText(path);
                Messages _Messages = Deserialize<Messages>(xmlInputData);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        public static T Deserialize<T>(string input) where T : class
        {
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

            using (StringReader sr = new StringReader(input))
            {
                return (T)ser.Deserialize(sr);
            }
        }

I hope It helps you. Thank you..!
Comment: Thank you very much!Forgive me for the unclear question.The reality is a "message" include several "field" and "group",and the group include several field and also group!!! It is random not constant.
Comment: could you please read the question. I edit it. Thanks again!!


Error in HTA with fileopen

Question: I'm using a script from Rob van der Woude for the open file dialog (top post from here) which is apparently supposed to work in HTA but I get an error saying:

"ActiveX component can't create object: 'UserAccounts.CommonDialog'"
Comment: Read under code snippet: _Summarized: Works in Windows XP only_
Comment: Perhaps [this my answer could help](http://stackoverflow.com/a/28672540/3439404)... It's a basic small HTA sample opening either file or folder dialogue... Also I found a simple customization of the Win32 open file dialog that enables it to be used to select either a file or a folder. Copyright (C) 2010 Scott Wisniewski; he says [_It's free, and in the public domain. Use it as you see fit_](http://stackoverflow.com/a/514368/3439404). HTH.
Answer: This function may be helps you !
BrowseForFile.vbs
   '**************************************************************************************
    ' GetFileDlg() And GetFileDlgBar() by omen999 - may 2014 - http://omen999.developpez.com
    ' Universal Browse for files function
    ' compatibility : all versions windows and IE - supports start folder, filters and title
    ' note : the global size of the parameters cannot exceed 191 chars for GetFileDlg and 227 chars for GetFileDlgBar
    '**************************************************************************************
    Function GetFileDlg(sIniDir,sFilter,sTitle)
     GetFileDlg=CreateObject("WScript.Shell").Exec("mshta.exe ""about:<object id=d classid=clsid:3050f4e1-98b5-11cf-bb82-00aa00bdce0b></object><hta:application showintaskbar=no />""").StdOut.ReadAll
    End Function

    Function GetFileDlgBar(sIniDir,sFilter,sTitle)
     GetFileDlgBar=CreateObject("WScript.Shell").Exec("mshta.exe ""about:<object id=d classid=clsid:3050f4e1-98b5-11cf-bb82-00aa00bdce0b></object>""").StdOut.ReadAll
    End Function

    ' sample test
    sIniDir = "C:\Windows\Fonts\*"
    sFilter = "All files (*.*)|*.*|Microsoft Word (*.doc;*.docx)|*.doc;*.docx|Adobe pdf (*.pdf)|*.pdf|"
    sTitle = "GetFileDlg by omen999 2014 - omen999.developpez.com"

    ' (sIniDir + sFilter + sTitle) size doesn't exceed 191 chars (227 for GetFileDlgBar)
    ' MsgBox Len(Replace(sIniDir,"\","\\")) + Len(sFilter) + Len(sTitle)

    ' sIniDir must be conformed to the javascript syntax
    rep = GetFileDlg(Replace(sIniDir,"\","\\"),sFilter,sTitle)
    MsgBox rep & vbcrlf & Len(rep)

Answer: As @JosefZ mentioned in the comments, the UserAccounts.CommonDialog library is available in Windows XP only. However, there are other ways to display an "Open File" dialog.
The Shell.Application object has a BrowserForFolder() function that, by default, displays a dialog asking you to select a folder. However, you can configure this dialog in a number of ways by using combinations of the ulFlags values. For example, if you include the BIF_BROWSEINCLUDEFILES flag, the dialog will also show files in addition to folders.
Here's a minimal example showing how you can have the BrowserForFolder dialog to display files and prompt the user to select a file:
' BROWSEINFO Flags...
Const BIF_NONEWFOLDERBUTTON  = &H0200   ' Hide the [New Folder] button
Const BIF_BROWSEINCLUDEFILES = &H4000   ' Show files in addition to folders

' ShellSpecialFolderConstants...
Const ssfDESKTOP = 0

Dim objStartIn, objFile
With CreateObject("Shell.Application")

    ' Specify the folder the dialog should start in...
    Set objStartIn = .NameSpace(ssfDESKTOP)   ' Start in a special folder
    Set objStartIn = .NameSpace("c:\")        ' Or, start in custom path

    ' Args = (parent window, dialog title, flags, start folder)
    Set objFile = .BrowseForFolder(0, "Select a file:", _
        BIF_BROWSEINCLUDEFILES Or BIF_NONEWFOLDERBUTTON, objStartIn)

End With

If Not objFile Is Nothing Then
    WScript.Echo objFile.Self.Path
End If

Of course, the user could still select a folder. There's no way to stop that from happening. But you can check the item returned to see if it's a folder and prompt them to reselect (perhaps in a loop).
If objFile.Self.IsFolder Then
    ' Invalid
End If

Error in HTA with fileopen


Missing type Microsoft.CSharp.RuntimeBinder.Binder

Question: My project won't build because of the following error:

Predefined type 'Microsoft.CSharp.RuntimeBinder.Binder' is not defined or imported.

What reference do I need to add?
Comment: First hit in google: https://msdn.microsoft.com/en-us/library/microsoft.csharp.runtimebinder.binder%28v=vs.110%29.aspx
Answer: Thank you to Alex. Add a reference to Microsoft.CSharp.


controlling the width of an div with a percentage

Question: I have a div that is called 'signup_div' that basically houses 5 input textbooks for the user to input the data. I have the div positioned absolute, with the body of the html page being position relative, so basically the body is the container div. I can't seem to make the width of the  signup div 20% of the page, even when i did it with the input types.
Here is my code:
body {
width: 100%;
height: 100%;
min-width: 1200px;
min-height: 100vh;
position: relative;
margin: 0 auto;
}

#signup_div {
position: absolute;
left: 4%;
top: 7%;
width: 20%;
min-height: 580px;
height: 85%;
min-width: 470px;
background-color: #EBEBEB;
border-radius: 3px;
}

All of the inputs are positioned relative and have heights and width determined by percentages. What am i doing wrong?
Comment: Java tag removed -- I don't see how this question deals with Java programming.
Comment: So why is javascript and jQuery tagged? This is clearly a CSS question. Please don't spam tags.
Answer: The CSS for your signup_div includes a min-width: 470px; property which is setting the width of your signup_div until such time as 20% is larger than that.
Be careful mixing percentage and pixel widths, there be dragons.
Also, checkout http://jsfiddle.net/ for mocking up examples when you post here. It helps you to isolate the problem, and it helps us to answer your question.
Answer: The problem is that you are using both width and min-width values.  If you remove the min-width rule, the width with percentage will work.


Installing Ubuntu alongside an existing Windows system without creating a CD?

Question: This Ubuntu help wiki page says that, in order to add Ubuntu on an existing Windows system, I must burn Ubuntu on a CD first. But CDs are becoming less common these days, so I wonder if there is a way to install Ubuntu without burning it on a CD (or a DVD, or a USB stick) - just download the ISO to my Windows machine and then somehow install it as dual boot.
In the past I have tried to use Wubi for that purpose, but this was not stable, and got stuck too many times. So now I want to create a dual-boot system.
Comment: You can use a DVD - it does not have to be a CD.
Comment: I actually meant to ask if it is possible to install Ubuntu without burning it on any external device - CD, DVD or USB stick; just using the ISO image from Windows.
Answer: To install Ubuntu without a CD or DVD or USB, you need to install Ubuntu as WUBI first, then migrate it to a hard drive partition using 'migrate-wubi'. This will work like a normal installation and won't be slow like WUBI. How to do this is written on this page
Answer: If you don't want to use a CD you can check how to boot from a flash drive here. Just follow the instructions, then plug in your usb stick, reboot and set the boot sequence to your USB port in the BIOS menu. The rest is really straightforward.
Comment: I don't think so. But if the problem is to erase the content of your flash drive, you can simply make a backup of your data on your windows partition, then format the stick to make it ubuntu-bootable, install your dual boot, and finally restore your usb stick from the backup you made on windows.
Comment: I think I tried this in the past but it formatted my USB stick... Is there a way to install from USB without wiping its contents?
Comment: It's not possible.
Comment: You can use Lili for windows if you dont want to format your flash drive. It has an option to do it without formatting
Answer: From Ubuntu
USB installation Guide from Ubuntu
There's a package called usb-creator-gtk (and usb-creator-kde for KDE-desktop).
It can be found in the Unity Dash
This application has a GUI to copy an iso/or from cd to a USB-drive and make it bootable.
From Windows
You can use the software LinuxLive to create a Bootable USB in Windows.
Comment: If you dont need it to be formatted,Just uncheck the option format the key in FAT32 and it wont format your pendrive
Answer: Using a USB stick works Great!
use LILI or Universal USB Installer.
Both methods are very fast.
Answer: Yes, you can create bootable Ubuntu USB on Windows through Unetbootin software.
This link explains various methods of creating Ubuntu live USB on Windows.


Can a broken power supply freeze Ubuntu?

Question: Several months ago my Ubuntu 10.04 started to freeze some minutes after booting. I didn't reboot, just get stuck (mouse, keyboard, etc.)
One day it didn't boot at all - ut was dead. I tested the power supply and it was broken, so I changed it (for a more powerful one) and both problems are gone. Since 3 weeks, the PC is working fine. It didn't freezes anymore.

Can the power supply affect the OS in this way? May it because of a leak of current?
Answer: With an hardware failure, the software can reach some random behavior.
I would suggest to check your system logs files (using gnome-system-log application for example) and look at if some errors were reported when you observed the issue.
Comment: Hi Yanok, this never happened again since I changed the broken power supply,... so in some way, my problem is gone. However I wondered if this could be due to an insufficient power supply
Comment: Hi Luso. Great to know your problem is solve then :-)If you did not observe other errors in software logs, feel lucky that your issue was due to power supply failure.


What is the $68^{th}$ term of the sequence- $1, 4, 5, 16, 17, 20,....................?$

Question: Given sequence-  $1, 4, 5, 16, 17, 20, .........$
I have two guesses here.
Firstly, we see that the differences between two consecutive terms are $3, 1, 11, 1,$ and $3$.
 So accordingly if we maintain a  "sequence of differences" it will turn out to be $3, 1, 11, 1, 3, 1, 11, 1, 3,.......$
thus, by adding the differences we can find the $68^{th}$ term of the main sequence  to be $273$.
I thought a second way to solve it.
in the given sequence  $1, 4, 5, 16, 17, 20, ........$
if we separate the $odd^{th}$ $(1st , 3rd, 5th,...etc)$ and even-th $(2nd, 4th, 6th,...etc)$ terms, we see that
the difference between two consecutive odd-th term keeps increasing by $4 [ 1, 5, 17,....],$
Similarly, a difference between two consecutive even terms keeps decreasing by $4.$
$[ 4, 16, 20......]. $
In this way, as $68^{th}$ term is an even-th term, so we follow the above rule and get, $68^{th}$ term $= -8036$
I am not completely sure whether any of my strategies is correct.
So I need a correct answer
Comment: In general, just knowing the first $n$ entries in a sequence will not give you any way of knowing what even the $n+1$'st number is.  The only way to know for sure what the next entry is (or however many entries into the future) is to be told how the sequence is constructed.
Comment: Maybe your sequence be [A000695](http://oeis.org/A000695).
Comment: http://oeis.org/search?q=1%2C4%2C5%2C16%2C17%2C20&sort=&language=english&go=Search
but I don't see how this might be meaningful
Comment: It is, as you remarked, a case of periodic difference sequence $[3,1,11,1,3,1,11,1,\cdots]$. So you need to study these sequences.
Comment: OK, in general, knowing the $n+1$ first entries, you always have a polynomial of degree $n$ (unique) which gives these entries (see answers below). This time, not in the least (unless it be zero) periodic neither its first differences (unless it be constant). All depends what is awaited.
Comment: The $68^{th}$ term is $272$, you are off by one. $1 , 4 , 5 , 16 , 17 , 20 , 21 , 32 , 33 , 36 , 37 , 48 , 49 , 52 , 53 , 64 , 65 , 68 , 69 , 80 , 81 , 84 , 85 , 96 , 97 , 100 , 101 , 112 , 113 , 116 , 117 , 128 , 129 , 132 , 133 , 144 , 145 , 148 , 149 , 160 , 161 , 164 , 165 , 176 , 177 , 180 , 181 , 192 , 193 , 196 , 197 , 208 , 209 , 212 , 213 , 224 , 225 , 228 , 229 , 240 , 241 , 244 , 245 , 256 , 257 , 260 , 261 , 272$.
Answer: Representing the terms in base $4$, we have
$$1_{10} = 1_{4}$$
$$4_{10} = 10_{4}$$
$$5_{10} = 11_{4}$$
$$16_{10} = 100_{4}$$
$$17_{10} = 101_{4}$$
$$20_{10} = 110_{4}$$
so to get the $68th$ term in the sequence we represent $68$ in binary as $1000100$, pretend it's a base $4$ representation, then convert back to decimal to get $4112.$
EDIT: Ah, I should have read the comments first. @Amin$235$ beat me to this by $5$ hours.
Comment: @Amin235: Sorry if this sounded harsh regarding your comment. My point is that having an answer posted as an answer is desirable, even if the core of the answer was already present in a comment. And while a link-only comment is probably appropriate here, it's not enough for an answer. This here lets me understand the sequence while staying on the same page. I shouldn't have called your comment "obscure", sorry. I'd have been happy if you had fleshed out that link by paraphrasing the relevant aspects, thus turning your comment into a full answer similar to this one here.
Comment: @MvG, You know, I could mentioned in the comment that the numbers are obtained by sums of distinct powers of 4, but working with sequences taught me It is possible that the numbers $1, 4, 5, 16, 17, 20$ can be generated with other sequence or something else, that is different from  A000695. By the way, I respect to your attitude and maybe you right.
Comment: I'm happy to have this as an answer, not merely as some obscure link-only comment (and OEIS is currently down).
Comment: @MvG please be fair!
Answer: Using the "sequence of difference" hypothesis, the pattern has a period of $4$ and the difference between every fourth term is $16$. Then the $68^{th}$ term is $$1+17\times16-1=\color{green}{272},$$ as you start from $1$, add $68/4$ periods and backtrack by one term (correction $-1$).

Without this hypothesis and without further information, the $68^{th}$ term can be proven to be $42$.


Do Mobs Recover their Health?

Question: Can I just leave a spawner trap that uses fall damage alone for about half an hour, or will the mobs recover their health, rendering the fall damage trap useless?
Answer: Mobs do not recover health. Refer to this link. However, if it is a fall damage trap, they should ideally be dying when they hit the bottom anyway so them recovering health should be irrellevant. If setup right they die on impact, and you have the ability to get in there and pickup their drops.
Comment: There is a situation where keeping mobs a hit from death is useful, and that's EXP farms. Keep in mind that mobs only give experience when killed by a player.
Comment: Yes, this is an xp farm I'm working with here.
Comment: Exception: Witches

Do Mobs Recover their Health?


GWT Basic Architecture

Question: I am new to client-server application development (only experience with Java desktop).
My query is this: I have followed an excellent GWT tutorial on YouTube and understand basic OO principles being applied to client and server services and implementations. However, what if a class isn't a service - say a data class like Person storing basic information that will be used by the service classes. Where should I store these separate classes?
To give you an insight in to my current structure (using Client package hierarchy).
I have: com.me.example.client - then client.GUI & client.service packages contained here.
Answer: You can choose between

Just setting these in client.
Create an extra package besides client and server : shared

When choosing for a seperate shared package you must add the following line to your gwt.xml
<source path='shared'/>

Extra info : these classes are needed at the client side, and thus need to be compiled to javascript by the gwt compiler. When putting them in client this is already the case (because client is already configured in .gwt.xml). When putting them in shared, you must tell so to the gwt compiler.

GWT Basic Architecture


What's the best way to find a car in Player Unknown's Battlegrounds?

Question: I like playing the outer edges of the map, but sometimes the first circle is all the way on the other side and I end up pretty much guaranteed to die unless I can find a car.
And I'm really, really bad at finding a car.
What kinds of places do they spawn?
Answer: I've done a bit more looking around and found this thread on the forum. It has a quote from a moderator so not sure how accurate that is, though it does seem to fall inline with what I've seen:

From my experience the locations are 100% pre-set, but each spot only has a certain chance to spawn the car each game.
  You're almost always guaranteed to find a car near the coast on the side of a road.
  Other than that, like you said garages are a good place to find them.. and towns in general.

After some further research I found this map on steam that is a work in progress of garage locations that spawn cars:

The next part of the answer is based off of my own experiences.
Disclaimer: I have no official sources on this and it's all based on my own experiences playing the game.
I usually find the best way to find a car is to follow a main road or look near a main road. Usually also looking near buildings/houses and I can find one. This is only purely speculative and based on what I've seen so far.
I have also found a car inside a garage that is attached to a building but only rarely.

I just managed to get into game for a bit and I've noticed that the UAZ seems to spawn in fields near buildings usually the more industrial ones. Something else to look out for.

However, as I usually land middle map-ish on an isolated set of buildings I try to run everywhere. This also has the advantages of:

Not landing near so many players
Not being so loud as you move so it's harder for others to detect you

But it does have the disadvantage of not starting out with much stuff, or as good stuff, as you usually would have unless you get luck.
Comment: If I get time later I will add locations I've seen a car spawn in not in a garage,
Comment: Nice improvements to this answer. Overall, though, I've mostly given up and now I just parachute to a few specific coast areas because they almost always have a boat. :P
Comment: @Sterno Yeah :) I either do that or land at some small group of buildings and hope they have a gun! There isn't really any other information at the moment though. Pretty much look near a main road or a garage seems to be the best advice so far.
Answer: You can also check this map which will tell you what vehicle spawns are more likely,and what spawns are more luck-based.
Comment: One thing to note, this map will probably not be accurate come the new patch on May 25th 2017. The 100% vehicle spawns is supposedly a bug that will be patched.  [Patch notes here](http://steamcommunity.com/games/578080/announcements/detail/1271550628459839077)
Comment: Still the locations will be true, just replace `100% Vehicule` by : `Very high vehicle spawn rate`
Comment: The locations may be true, but the difference between "100% spawn rate" and "High Spawn rate", could be the difference between dying to the blue circle and a chicken dinner. :)


Perl regex substitution not working with global modifier

Question: I have code that looks like the following:
s/(["\'])(?:\\?+.)*?\1/(my $x = $&) =~ s|^(["\'])(.*src=)([\'"])\/|$1$2$3$1.\\$baseUrl.$1\/|g;$x/ge

Ignoring the last bit (and only leaving the part where the problems occur) the code becomes:
s/(["\'])(?:\\?+.)*?\1/replace-text-here/g

I have tried using both, but I still get the same problem, which is that even though I am using the g modifier, this regex only matches and replaces the first occurrence. If this is a Perl bug, I don't know, but I was using a regex that matches everything between two quotes, and also handles escaped quotes, and I was following this blog post. In my eyes, that regex should match everything between the two quotes, then replace it, then try and find another instance of this pattern, because of the g modifier.
For a bit of background information, I am not using and version declarations, and strict and warnings are turned on, yet no warnings have shown up. My script reads an entire file into a scalar (including newlines) then the regex operates directly on that scalar. It does seem to work on each line individually - just not multiple times on one line. Perl version 5.14.2, running on Cygwin 64-bit. It could be that Cygwin (or the Perl port) is messing something up, but I doubt it.
I also tried another example from that blog post, with atomic groups and possessive quantifiers replaced with equivalent code but without those features, but this problem still plagued me.
Examples:
<?php echo ($watched_dir->getExistsFlag())?"":""?>
Should become (with the shortened regex):
<?php echo ($watched_dir->getExistsFlag())?replace-text-here:replace-text-here?>
Yet it only becomes:
<?php echo ($watched_dir->getExistsFlag())?replace-text-here:""?>

<?php echo ($sub->getTarget() != "")?"target=\"".$sub->getTarget()."\"":""; ?>
Should become:
<?php echo ($sub->getTarget() != replace-text-here)?replace-text-here.$sub->getTarget().replace-text-here:replace-text-here; ?>
And as above, only the first occurrence is changed.

(And yes, I do realise that this will spark into some sort of - don't use regex for parsing HTML/PHP. But in this case I think that regex is more appropriate, as I am not looking for context, I am looking for a string (anything within quotes) and performing an operation on that string - which is regex.)
And just a note - these regexes are running in an eval function, and the actual regex is encoded in a single quoted string (which is why the single quotes are escaped). I will try any presented solution directly though to rule out my bad programming.
EDIT: As requested, a short script that presents the problems:
#!/usr/bin/perl -w

use strict;

my $data = "this is the first line, where nothing much happens
but on the second line \"we suddenly have some double quotes\"
and on the third line there are 'single quotes'
but the fourth line has \"double quotes\" AND 'single quotes', but also another \"double quote\"
the fifth line has the interesting one - \"double quoted string 'with embedded singles' AND \\\"escaped doubles\\\"\"
and the sixth is just to say - we need a new line at the end to simulate a properly structured file
";
my $regex = 's/(["\'])(?:\\?+.)*?\1/replaced!/g';
my $regex2 = 's/([\'"]).*?\1/replaced2!/g';

print $data."\n";
$_ = $data; # to make the regex operate on $_, as per the original script
eval($regex);
print $_."\n";
$_ = $data;
eval($regex2);
print $_; # just an example of an eval, but without the fancy possessive quantifiers

This produces the following output for me:
this is the first line, where nothing much happens
but on the second line "we suddenly have some double quotes"
and on the third line there are 'single quotes'
but the fourth line has "double quotes" AND 'single quotes', but also another "double quote"
the fifth line has the interesting one - "double quoted string 'with embedded singles' AND \"escaped doubles\""
and the sixth is just to say - we need a new line at the end to simulate a properly structured file

this is the first line, where nothing much happens
but on the second line "we suddenly have some double quotes"
and on the third line there are 'single quotes'
but the fourth line has "double quotes" AND 'single quotes', but also another "double quote"
the fifth line has the interesting one - "double quoted string 'with embedded singles' AND \"escaped doubles\replaced!
and the sixth is just to say - we need a new line at the end to simulate a properly structured file

this is the first line, where nothing much happens
but on the second line replaced2!
and on the third line there are replaced2!
but the fourth line has replaced2! AND replaced2!, but also another replaced2!
the fifth line has the interesting one - replaced2!escaped doubles\replaced2!
and the sixth is just to say - we need a new line at the end to simulate a properly structured file

Comment: don't eval your regexp string because then you will have to perform extra quoting. just put the regexp into a sub if you want to control when it is called: `sub regexp { $_[0] =~ s/.../.../ge }` then just use `regexp($data)` when you want to execute the substitution. This will have the same effect as `$data =~ s/.../.../ge`
Comment: It would help to show an example of the data that you are applying this substitution to. Applying your second substitution to `q(  "aaa" 'bbb'  )` results in `  replace-text-here replace-text-here  ` which I think is what you intended
Comment: The [page you refer to](http://blog.stevenlevithan.com/archives/match-quoted-string) uses `(?:\\\1|.)*?` rather than `(?:\\?+.)*?`
Comment: @Borodin That page actually states that that particular regex has 'issues' and to use Edit 2 in practical uses. Edit 2 is my regex.
Comment: Ah I see. However you still need to provide us an example of data that doesn't work with your code please
Answer: Update:  this:
my $regex = 's/(["\'])(?:\\?+.)*?\1/replaced!/g';

should be:
my $regex = 's/(["\'])(?:\\\\?+.)*?\1/replaced!/g';

since those single quotes there in the assignment turn \\ into \ and you want the regex to end up with \\.
Please boil your problem down to a short script that demonstrates the problem (including input, bad output, eval and all).  Taking what you do show and trying it:
use strict;
use warnings;
my $input = <<'END';
<?php echo ($watched_dir->getExistsFlag())?"":""?>
END

(my $output = $input) =~ s/(["\'])(?:\\?+.)*?\1/replace-text-here/g;
print $input,"becomes\n",$output;

produces for me:
<?php echo ($watched_dir->getExistsFlag())?"":""?>
becomes
<?php echo ($watched_dir->getExistsFlag())?replace-text-here:replace-text-here?>

as I would expect.  What does it do for you?
Comment: Indeed, that produces the correct output. I think it has something to do with my eval - putting my regex in directly produced the correct result - using it in the eval messes it up.
Comment: @Xenopathic: Well, your example makes your problem obvious.  Updating my answer.
Comment: Thanks for the help! The escapes fixed the problem. You _were_ 2 minutes slower than ruakh to reply with the fix, so unfortunately the credit for the answer goes to him.
Answer: Even within single-quotes, \\ gets processed as \, so this:
my $regex = 's/(["\'])(?:\\?+.)*?\1/replaced!/g';

sets $regex to this:
s/(["'])(?:\?+.)*?\1/replaced!/g

which requires each character in the quoted-string to be preceded by one or more literal question-marks (\?+). Since you don't have lots of question-marks, this effectively means that you're requiring the string to be empty, either "" or ''.
The minimal fix is to add more backslashes:
my $regex = 's/(["\'])(?:\\\\?+.)*?\\1/replaced!/g';

but you really might want to rethink your approach. Do you really need to save the whole regex-replacement command as a string and run it via eval?
Comment: Awesome! Thanks for that. I am saving it as a string because my code splits my file into small segments based on certain criteria, and then runs a certain command (in this case a regex) based on the 'context' of the segment - for example between  is saved as a php context, and the php regex is run on it. In turn, there is an html regex and a js regex.
Comment: @Xenopathic: You're welcome! Re: why you're saving it as a string: it sounds like what you're looking for is an *anonymous subroutine* and/or a *subroutine reference*. (Google either of those terms, plus "Perl", for details and tutorials.)
Comment: @Xenopathic: then you may want a dispatch table instead


In Skyrim, is there a limit to the number of cycles (cycles of 5 times and leveling up) you can train with a particular trainer? Or is this a bug?

Question: I trained maybe 4 or 5 times in a row for Speech with Ogmund in Markarth (I trained 5 times, then leveled up, and repeated this cycle four or five times in a row), and after that there is no longer a dialogue option to train me anymore. I went to another trainer (Babette, who I know trains Alchemy), and she allows me to train. However, I noticed that none of the people at the Mage's college have the option for me to train either. I thought I remembered them having the option.
Is this a bug, or is there a limit to the number of times you can train with a particular trainer?
Answer: Different trainers have different max levels for their respective skill.
For instance, one Archery trainer might only train you up to level 50, while another may train up to 75 or 90.
Check http://www.uesp.net/wiki/Skyrim:Trainers for a comprehensive list.
Answer: The trainers work in a very simple way:
Every level, you can train 5 levels of the skill you want. However, every trainer has a limit to the level he can train you to.
If I am correct there are three levels, common (lvl < 50), expert (lvl < 75) and master(lvl < 90).
When you pass the threshold of the trainer, you have to find another one which can in fact train you further or you have to train it the normal way.
Comment: I think there is still supposed to be a dialog option, but the trainer tells you that you "already know everything I can teach"... ?


Is there a default behavior that I can set to to tell my ships to cease fire when an enemy abandons their ship?

Question: I was just battling a pirate that had attacked one of my freighters. Happily, the pirate decided that they'd had enough and abandoned their lovely fighter. While I was sidling up to capture their ship, my freighter started shooting again. Fortunately, I was able to manually cancel all orders on the freighter and now I just have a lot of repair work to do.
Is there a default behavior setting for my ships that I can set that says "once an enemy has abandoned their ship, don't shoot it anymore"?
Answer: Unfortunately, there is not. All you can is to tell them to cease fire by deleting the attack command, which might be too slow.


Physical meaning of "probability density"

Question: Is there some way of describing the co-domain of probability density functions? Does it relate in some way to something physically meaningful? I was given that question today - and I was at a loss. Density for me, is the co-domain of pdfs - a scalar dimension with values from zero to infinity.
For instance, I fit a normal distribution to a probability vector on N values (a probability mass function). This vector contains normalised values of the actual frequency counts in a histogram with N bins. The normalisation is done by dividing each frequency count by the discrete integral "area" of the pmf - so that the pmf values sum to 1. The pmfs now seems to be scaled similarly to the estimated pdfs.
Is probability density a measure of probability? I am sure that the necessary definitions must be hidden somewhere deep down in the guts of measure theory - which is why I have included that as a tag.
Comment: Just a note. The relevant object is really the measure $p(x)\,dx$ (that you integrate with respect to), not the pdf $p(x)$ itself. For example, under a change of variable $y(x)$, $p(x)$ can be changed almost arbitrarily (multiplied by $1/\frac{dy}{dx}$ which can be almost any function you want), but $p(x)dx=p(y)dy$ stays the same.
Comment: The units of the codomain of the probability *density* function must be reciprocal of the units of the domain so that upon integration, we obtain the unitless probability.
Answer: To add to Kirill's comment, you can write $P_0 = P(x_0\leq X \leq x_0+{\rm d}x) = p(x_0)dx$, so the value of the pdf $p(x)$ at $x_0$ is the height of an infinitesimally narrow interval ('slice') of width d$x$ fitting below this function at $x_0$ that will give you a probablity value $P_0$ to find the random variable lying within this interval d$x$. You could also think of it, perhaps more intuitively, in terms of the derivative of the cdf: the pdf at $x_0$ is then the 'speed' or rate, d$P/$d$x$, at which the probability will increase when going from $x_0$ to $x_0+dx$ (for positive d$x$).
A "physical" meaning is more difficult, because probability is mathematical... Perhaps if you think of the analogy of "mass density" (~pdf) as a measure of concentration of "mass" (~cdf), that may help?


Finding the determinant of a Vandermonde Matrix

Question: I need help with finding the Vandermonde determinant, I really don't understand the rules of the Vandermonde and need further explanation. This is the matrix provided:
$$ \begin{bmatrix} 1 & 1 & 1 & 1 & 1  \\ 1 & 2 & 3 & 1/2 & 1/3
\\ 1 & 4 & 9 & 1/4 & 1/9 \\ 1 & 8 & 27 & 1/8 & 1/27
\\ 1 & 16 & 81 & 1/16 & 1/81 \end{bmatrix} $$
Any help would be great, thank you.
Answer: Note that the $3^{rd}, 4^{th},\text{ and }\,5^{th}$ rows are the square, cube and fourth power of the $2^{nd}$ row.  So using the product formula for the expansion of a Vandermonde determinant gives
$$det = \prod_{1\leq i<j\leq 5}(a_{2,j}-a_{2,i})$$


How to Mask Operations openCV - Frequency masking

Question: I would like to create a frequency mask in openCV but have no idea how to go about it. The frequency mask will be an ideal bandpass filter so image filtering will be done in the frequency domain. For this example lets say frequencies between 100Hz-200Hz will be coupled.
Anyone know how to do this?
Thanks is advance!
Answer:
Perform DFT of your image.
Make an filter matrix with size of your image, where you have ring with radius R1 = wavelength_min, R2=wavelength_max. Ring is filled with ones and the rest elements are zeros.
Multiply DFT of your image by this matrix.
Perform inverse DFT of obtained image.
Comment: I can't vote you up so I will give you my full gratitude and will be forever thankful
Comment: You can approve the answer :)


In gremlin (specifically tinkerpop), how do you query and then make a second query without ANY of the results from the first query?

Question: I'm making a face matching database.  I have a list of faces that may be similar to another face.  I'm trying to get the top 10 faces with the most similar faces.  The first face should include all the faces.  The second face should exclude ANY similar face that matches the first face.
// The graph
graph = TinkerFactory.createModern()
g = graph.traversal()

g.addV('face').property('faceId','face1')
g.addV('face').property('faceId','face2')
g.addV('face').property('faceId','face3')
g.addV('face').property('faceId','face4')
g.addV('face').property('faceId','face5')
g.addV('face').property('faceId','face6')
g.addV('face').property('faceId','face7')
g.addV('face').property('faceId','face8')
g.addV('face').property('faceId','face9')

g.V().has('face','faceId','face1').as('a').V().has('face','faceId','face2').as('b').addE('is similar').from('a').to('b')
g.V().has('face','faceId','face1').as('a').V().has('face','faceId','face3').as('b').addE('is similar').from('a').to('b')
g.V().has('face','faceId','face1').as('a').V().has('face','faceId','face4').as('b').addE('is similar').from('a').to('b')
g.V().has('face','faceId','face1').as('a').V().has('face','faceId','face5').as('b').addE('is similar').from('a').to('b')
g.V().has('face','faceId','face2').as('a').V().has('face','faceId','face3').as('b').addE('is similar').from('a').to('b')
g.V().has('face','faceId','face2').as('a').V().has('face','faceId','face4').as('b').addE('is similar').from('a').to('b')
g.V().has('face','faceId','face5').as('a').V().has('face','faceId','face6').as('b').addE('is similar').from('a').to('b')
g.V().has('face','faceId','face6').as('a').V().has('face','faceId','face7').as('b').addE('is similar').from('a').to('b')
g.V().has('face','faceId','face8').as('a').V().has('face','faceId','face9').as('b').addE('is similar').from('a').to('b')

This gets me the initial list.  Only the top number is right.
:> g.V()
    .hasLabel('face')
    .as('a')
    .project('faceId','count')
    .by(select('a').values('faceId'))
    .by(bothE('is similar').otherV().id().dedup().count())
    .order()
    .by('count',desc)
    .range(0,10)

That gets me this:
    ==>[faceId:face1,count:4]
    ==>[faceId:face2,count:3]
    ==>[faceId:face5,count:3]
    ==>[faceId:face3,count:2]
    ==>[faceId:face4,count:2]
    ==>[faceId:face6,count:2]
    ==>[faceId:face7,count:1]

I've tried this to get additional lists
g.V().has('face','faceId',without(V().has('face','faceId','face1').bothE('is similar').bothV().values('faceId').dedup().fold())).valueMap()

Ideally, I want to get something like this:
==>[faceId:face1,count:4]
==>[faceId:face6,count:1]
==>[faceId:face9,count:1]

I'm okay fetching the 'master' list first and then processing the first one to get the similar faceIds then running the list again to get the next most if I need to.  I just can't figure out how to get it to work.
This works, but I'm not sure how to combine that into the without() section of the first query.
g.V().has('face','faceId',without('face1','face2','face3','face4','face5')).as('a').project('faceId','count').by(select('a').values('faceId')).by(bothE('is similar').otherV().id().dedup().count()).order().by('count',desc).range(0,10)

Answer: I'm not quite sure if this is what you want but it returns your result. It generally sounds like you don't want to traverse the same vertex more than once in which case you could just lazily store() those vertices and filter them out as you go:
gremlin> g.V().hasLabel('face').
......1>   project('faceId','count').
......2>     by('faceId').
......3>     by(where(without('a')).both('is similar').
......4>        where(without('a')).
......5>        store('a').
......6>        count())
==>[faceId:face1,count:4]
==>[faceId:face9,count:1]
==>[faceId:face2,count:0]
==>[faceId:face3,count:0]
==>[faceId:face4,count:0]
==>[faceId:face5,count:0]
==>[faceId:face6,count:1]
==>[faceId:face7,count:0]
==>[faceId:face8,count:0]

Depending on the graph you use this sort of query may not be deterministic as Gremlin doesn't assume the order of items in the traversal stream to be the same on each execution. You'd need to add your own order() steps to enforce that if it matters. This could end up being an expensive query as it is being globally executed over the graph and needs to track all the vertices traversed. In practice, you might need to further limit the paths traversed or perhaps use a different algorithm to determine similarity.
Comment: This is pretty much exactly what I wanted!  Thank you!  Now I just have to figure out how to filter out the faces that already have an edge named "is" or "is not".  Thanks again!!


Django: allow language prefix and root url

Question: I have a Django application with multiple languaje, in this moment I have the language prefix activated in this way:
urlpatterns += i18n_patterns(
    ...,
    prefix_default_language=True,
    )

And when I load the website in the home url: mysite.com/ it redirects to mysite.com/en/ (the default language)
but I need to load mysite.com/ as home without the redirection and mysite.com/en/ also as home (just when the user load that exact url)
Comment: Why are you passing `prefix_default_language=True` if you don't want it to prefix default language?
Comment: I want both, I need that the same page load with and without the language prefix
Answer: If you visit mysite.com, Django automatically adds the default language code to the URL, mysite.com/en/. So that users will get the same page when they visit mysite.com and mysite.com/en
If you don't want the language code for your default language, you can turn it off:
prefix_default_language=False,

Unfortunately, if you turn off prefix_default_language, then mysite.com/en will no longer work. If you really want that to work too, you could write a url rule /en to point to your homepage as well.
Comment: I want both, I need that the users access home from mysite.com/ but also from mysite.com/en/
Comment: @Nazkter You could write a url rule to point /en to your homepage. This will only work for your homepage and not for sub folders such as mysite.com/en/something-else
Comment: Then just add an url pattern with a redirect from mysite.com/en to mysite.com. https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#redirect
Comment: @Nazkter Currently there doesn't seem to be a way around this. I prefer to keep the prefix for default language as well for consistency


How do I create and array of 10 numbers in PL/SQL and sort it in ascending order

Question: I am trying to combine two arrays, so the values are corelated. I think I've got the code for that part below - but it doesn't work. After this, I want to have them ordered in ascending order too. I'm new to PL/SQL, so any guidance is appreciated. Thanks.
CREATE
type sarray is varray(10) of varchar2(10);
type sno is varray(10) of char(2);

names sarray;
serialno sno;
newtable sarray;

BEGIN

 names:= sarray            (Smith','Diaz', 'Manny', 'Ike','Cruise','Roberts','Fuller','Calabrese' ,'Sharp     e','Khanna');
serialno:= sno('2','4','5','6','9','1','3','7','8', '10');

newtable:= serialno MULTISET UNION names;

FOR i in serialno.first..serialno.last

LOOP
DBMS_output.put_line (i || '. ' || serialno(i));
END LOOP;
END;
/

Comment: If you're having a problem with some code, paste it into your question so we can help!
Comment: replace the assignment of `names` above with `names:= sarray            ('Smith','Diaz', 'Manny', 'Ike','Cruise','Roberts','Fuller','Calabrese' ,'Sharp   e','Khanna');` i.e. `Smith'` needs a quote before.
Answer: I'm not sure I understand the question. What do you mean by "combining" them? Correlated? How? You should provide INPUT as well as desired OUTPUT.
In the meantime, have a look at this code. It uses predefined collections (owned by SYS, one for strings - ODCIVarchar2List, another for numbers, ODCINumberList). I put some values in there and displayed them as they are (no sorting), and sorted by using the TABLE function.
SQL> declare
  2    names    sys.odcivarchar2list;
  3    serialno sys.odcinumberlist;
  4  begin
  5    names    := sys.odcivarchar2list('Smith', 'Diaz', 'Manny');
  6    serialno := sys.odcinumberlist(3, 1, 2);
  7
  8    dbms_output.put_line('--> display SERIALNO/NAMES "as is"');
  9    for i in serialno.first..serialno.last loop
 10      dbms_output.put_line(i ||'. '|| serialno(i) ||', '|| names(i));
 11    end loop;
 12
 13    dbms_output.put_line('--> display NAMES alphabetically');
 14    for cur_r in (select column_value from table(names) order by column_value)
 15    loop
 16      dbms_output.put_line(cur_r.column_value);
 17    end loop;
 18  end;
 19  /
--> display SERIALNO/NAMES "as is"
1. 3, Smith
2. 1, Diaz
3. 2, Manny
--> display NAMES alphabetically
Diaz
Manny
Smith

PL/SQL procedure successfully completed.

SQL>

Comment: Thank you! I wanted this result, but in order of serial number like 1. Diaz 2.Manny 3. Smith etc. I now know how to do this from your code by selecting the serial number column and ordering it. Can I do the reverse too for descending order? So that the display is 3.Smith, 2.Manny 1.Diaz etc?
Comment: So, what should be desired output?
Comment: Desired output would be --> Serial number is ascending order 1.Diaz 2.Manny 3.Smith and ----> Serial number in descending order 3.Smith 2.Manny 1.Diaz .
Comment: That's what the output shows (in ascending order), doesn't it? Below the "--> display NAMES alphabetically" comment. put `order by column_value desc` if you want descending order.
Comment: Yes, that's exactly what I was looking for. Thanks so much!


GNOME showing double top bar and search box on display

Question: Double icons in the top bar and this overlapping search box of GNOME on the front desktop.The top bar looks normal when I open any application but  getting back to the desktop, it looks like in the screenshot.

Is there any way to reset the GNOME or any other solution to this?
Comment: What happens if you run the following command in Terminal `gsettings reset org.gnome.desktop.background picture-uri`?
Answer: It seems someone has changed your desktop background image to an old screenshot of your desktop.
Open Settings and change your desktop background.
Comment: :D Yeah! That someone would be me!!
Comment: @TakshakRajput I actually thought someone was playing a practical joke on you :-D


Grounding Power at an Isolated Outbuilding?

Question: I am looking to draw off some electricity from an outbuilding. It looks like we have an 60 amp fuse hooked up to 3 wires binging power to this outbuilding. So no ground standard 240v power. I don't own this building or the land it is on, so don't really want to mess with it.
This is in Canada.
I want to take power from this outbuilding breaker box to another location, right beside it. Are their any best practices for this? My understanding is that I would want to be running a ground wire between as well as installing more grounding rods at the new location. But it seems like the one will be impossible. I can drop grounding rods down to ground water easily, or even chuck some in nearby ponds or wells.
The Current Setup:
The utility sends in 3 wire standard 240V to Building A (200amp fuze).
We installed a single grounding bar next to this for ground.
It looks like neutral and ground are connected, my understanding is this is not always how it is done.
This was all certified and signed off on like 25 years ago.
We then take a 60 amp fuse and send ground and a 4-4-4 copper wire to some shutoff with cylindrical fuses like 20 feet away. Then just the 4-4-4 gets sent with a defunct water line through a 4" perforated drainage tile , as was the code at the time.
This ends up in building B, without any ground, about 180 feet away.
Comment: Are those 3-wires a *service* from the utility, or a *feeder* from another building on your property?
Comment: What country are we talking about and do you have applicable codes? Without more information we cannot answer the question; It is a bit confusing 1 fuse 3 wires no ground? Is it three phase? what voltage?
Comment: @ThreePhaseEel The three wires are -120V, +120V and neutral. So single phase, standard 240v power.
Comment: @ThreePhaseEel Power from the utility enters into building 1 at its breaker box (standard 240v). This goes off a 60amp to a 2nd building and breaker box. I want to take it a third time a very short additional distance to a third breaker box.
Comment: @Gil I updated the question to hopefully answer all your questions.
Comment: Are those 3 wires coming into building 2 in a conduit, or directly buried?
Comment: I can try to ask and see if anyone remembers. The wires are in a conduit while in the building, but I am not sure what they are doing while in the ground
Comment: @ThreePhaseEel The wire is in a conduit with the now unused water line as was the code back then.
Comment: For example, Solar power installations are often made at locations that do not have utility  access. Their is no central grounding wire entering the location. Is their any way I could copy whatever they do for ground?
Comment: @Jonathon -- what size is the conduit in question, and I take it you're dealing with that 4-4-4 URD (Direct Burial) cable from your other post?
Comment: @ThreePhaseEel Just found out a bunch of new information and posted an update that should answer all of these questions and more. No idea if it is direct burial cable or not as it has no markings.
Answer: I will take a SWAG, I do not know the Canadian code. It sounds like you have single phase power, phase A, Phase B and Neutral through a two pole breaker. The transformer that supplies this has either two secondary windings with one of each connected as a center tap or a center tapped winding with the neutral on the 'center tap'. These two phases are 180 degrees apart. Between neutral and either phase you get 120VAC. Between the phases you get 240VAC. In the US this neutral will typically be grounded at the pole and at the entrance panel with a 4th wire called ground (green or bare), in my case it is the transfer switch for the standby generator. Normally etucetly bonded to a ground rod driven into into the ground to make electrical contact with the earth at the entrance. The ground wire must be continuous, not spliced although etucticly bonding may be acceptable. This varies with location and local requirements. I have 5 rods in an array. We bond the neutral to the ground at only the main entrance panel. The end result we have for a typically outlet one of the phases supplying power through a breaker (type varies by location), a neutral wire and the ground wire, three in total.  I do not know the code in canada so you should check with the local authority. You may have to run a seperate wire or change the cable to source the ground from the main panel or you may just be able to add a ground rod. In either case do not use the neutral for a safety ground.


if $R^m \cong R^n$, then $m=n$?

Question:
Suppose $R$ is a commutative ring with $1$. Further we have an isomorphism $R^m \cong R^n$. Then does that imply $m=n$?

If I consider $R=\mathbb{Z} \times \mathbb{Z} \times \mathbb{Z} \times \mathbb{Z} \times \cdots $, then I think $R^m=R^n$ as both $R^m$ and $R^n$ has countably infinite copies of $\mathbb{Z}$. Hence $R^m \cong R^n$ for any natural numbers $m \neq n$?
Comment: Perhaps the question could be clarified a bit,i.e., the first part is indeed a popular duplicate - see [here](https://math.stackexchange.com/questions/1428171/r-is-a-commutative-ring-with-1-ne-0-and-rm-cong-rn-then-m-n?noredirect=1&lq=1).
Comment: Atiyah's "Intoduction to Commutative Algebra", chapter 2 is all about modules. And that's the context of this question (which you should include in the question @zero2infinity ). Especially since $R^n$ may be ring isomorphic to $R^m$ (the example in the question works).
Comment: If you claim $R^m$ and $R^n$ are isomorphic in your example then you should show us a specific function which you think is an isomorphism. Just because two modules have the same cardinality it doesn't mean they are isomorphic.
Answer: Since you've mentioned Atiyah's "Intoduction to Commutative Algebra", chapter 2 in the comments I will assume we talk about module isomorphisms here (because that's what the chapter is about).
Note that it may happen that $R^n$ is ring isomorphic to $R^m$ for $n\neq m$. Actually the example in the question works just fine (the bijection later in this answer is a ring homomorphisms, but not a module homomorphism).

Suppose $R$ is a commutative ring with $1$. Further if we have the isomorphism given by $R^m \cong R^n$, then does that imply $m=n$?

This is answered here: R is a commutative ring with $1\ne 0$ and $R^m \cong R^n$, then $m=n$

If I consider $R=\mathbb{Z} \times \mathbb{Z} \times \mathbb{Z} \times \mathbb{Z} \times \mathbb{Z} \dots $, then I think $R^m=R^n$ as both $R^m$ and $R^n$ has countably infinite copies of $\mathbb{Z}$. Hence $R^m \cong R^n$ for any natural numbers  $m \neq n$?

I could simply answer this question with "$R^m$ is not module isomorphic to $R^n$ for $n\neq m$ because the first part says so".
But lets have a closer look at this case. Is $R^m$ really isomorphic to $R^n$ as modules when $n\neq m$? Consider the simple case $n=1$, $m=2$. So what would $f:R^2\to R$ isomorphism look like? Well, one idea is to take a pair of sequences $(r,t)\in R^2$ and combine them into one sequence by mixing $(r_0,t_0,r_1,t_1,r_2,t_2,\ldots)$. Formally with a formula like this:
$$f(r,t)_n=\begin{cases}
r_{n/2} &\text{for even } n \\
t_{(n-1)/2}&\text{otherwise}
\end{cases}$$
Clearly $f$ is a bijection. The standard one when proving that a countable set $X$ is equinumerous with $X^2$. But is it a module homomorphism? Well, remember that the underlying ring is $\mathbb{Z}\times\mathbb{Z}\times\cdots$ itself. And so given a sequence $s\in \mathbb{Z}\times\mathbb{Z}\times\cdots$ is it true that $f(sr,st)=sf(r,t)$? I think you can easily verify that it is false, for example by considering $s_n=r_n=t_n=n$.
Anyway, no matter what function you come up with, as long as it is a bijection $R^2\to R$ it cannot be a module homomorphism (due to our general result).

if $R^m \cong R^n$, then $m=n$?


proving "$C^1([−1,1])$ is dense in the given space with given norm"

Question: Define $$E = \left \{ f \in W^{1,2} (-1,1) \; | \; \| f \|_E := \left( \int_{-1}^1 (1-x^2 ) | f' (x) |^2 dx + \int_{-1}^1 | f(x) |^2 dx \right)^{\frac{1}{2}} < \infty   \right \}.$$ Then how can I prove that $ C^1 ([-1,1]) $ is dense in $E$ ? Is this concerned with Sobolev inequality?
Comment: @DavideGiraudo Of course, I edited it.
Comment: @DavideGiraudo The space $E$ now is just $W^{1,2}$ equipped with a smaller norm. I wonder if Ann didn't want to take a *genuinely larger space*: all $f\in L^2$ with a weak derivative $f^\prime$ satisfying $\int_{-1}^1 (1-x^2) |f^\prime(x)|^2\,dx<\infty$? This makes more sense to me...
Comment: @ByronSchmuland I guess it's what you mean. But when I edited, I just changed formatting, not the body of the question. So we have to wait Ann coming back.
Answer: I assume that Ann wants the space
$$E = \left \{ f \in L^2(-1,1) \; \bigg| \; \| f \|_E := \left( \int_{-1}^1 (1-x^2 )
 | f' (x) |^2 dx + \int_{-1}^1 | f(x) |^2 dx \right)^{\frac{1}{2}} < \infty   \right \}.$$
That is, $f\in E$ if it belongs to $L^2(-1,1)$ and  has a weak derivative $f^\prime$ on $(-1,1)$ satisfying
$$ \int_{-1}^1 (1-x^2 ) | f' (x) |^2 dx <\infty.$$
Now for $f\in E$, let $p$ be a polynomial with small
$ \int_{-1}^1 (1-x^2 )\, |p(x)-f'(x)|^2 dx$,
 and then let $q$ be the polynomial with $q(0)=f(0)$ and $q^\prime=p$.
From the aside below, we see
that $q$ is close to $f$ in $E$-norm, which  shows that polynomials are dense in $E$.

For a more general, multivariable version of this result, see Are polynomials dense in Gaussian Sobolev space?

Aside: Suppose that $f\in E$ and $f(0)=0$.
Then for $0\leq x\leq 1$ we have $f(x)=\int_0^x f^\prime(y)\,dy$.
Cauchy-Schwarz gives $f(x)^2\leq x\int_0^x (f^\prime(y))^2\,dy,$  and integrating
in $x$ we find
$$\int^1_0 f(x)^2\,dx\leq \int_0^1 x \int_0^x (f^\prime(y))^2\,dy\,dx={1\over 2}\int_0^1 (1-y^2) (f^\prime(y))^2\,dy.$$
Adding a similar contribution from negative $x$-values, we conclude that
$$\int^1_{-1} f(x)^2\,dx\leq {1\over 2}\int_{-1}^1 (1-y^2) (f^\prime(y))^2\,dy.$$
Answer: $C[-1,1]$ is dense in $L^2[-1,1]$. Any $f \in C[-1,1]$ can be uniformly approximated by a polynomial, hence the polynomials are dense in $L^2[-1,1]$. The polynomials are smooth, hence in $C^1[-1,1]$. It follows that $C^1[-1,1]$ is dense in $L^2[-1,1]$, hence automatically in $E$.
It is not clear to me how this is related to a Sobolev inequality.
Comment: Looks like the question changed after I answered it...


I got error are not allowed to force push code when push to gitlub

Question: When I try to upload my project at gitlab into repository created by other owner(RepositoryOwner), I got error :
<code>MyProject$ git push -uf origin main
Username for 'https://gitlab.com': email@example.com
Password for 'https://email@example.com@gitlab.com':
Enumerating objects: 212, done.
Counting objects: 100% (212/212), done.
Delta compression using up to 4 threads
Compressing objects: 100% (189/189), done.
Writing objects: 100% (212/212), 1.84 MiB | 2.09 MiB/s, done.
Total 212 (delta 28), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (28/28), done.
remote: GitLab: You are not allowed to force push code to a protected branch on this project.
To https://gitlab.com/RepositoryOwner/project-name.git
 ! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://gitlab.com/RepositoryOwner/project-name.git'
</code>
My system :
<code>$ uname -a
Linux master-at-home 5.15.0-41-generic #44~20.04.1-Ubuntu SMP Fri Jun 24 13:27:29 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
$ git -v
git version 2.37.1
</code>
Is it error on my side or at RepositoryOwner side?
RepositoryOwner wrote to me that he gave me full permission.
I tried to login using Username/password of my account, not ssh keys. Can it be the issue of this error ?
Thanks!
Comment: https://stackoverflow.com/search?q=%5Bgitlab%5D+remote%3A+GitLab%3A+You+are+not+allowed+to+force+push+code+to+a+protected+branch+on+this+project
Answer: The error states that you are not allowed to push to a protected branch.
Protected branch has the special meaning in Gitlab: https://docs.gitlab.com/ee/user/project/protected_branches.html
According to documentation, you need the person with at least the Maintainer role to allow your role or group to push to protected branch.


envdte configurationmanager Project StartOptions

Question: I'm writing a c# console application with envdte / envdte80 (no experience with both) to open a project inside a new Visual Studio Instance. Inside this new instance, I'm trying to change the Project.StartOptions through my console application.
When I try to load the ConfigurationManager, I'm receiving this exception:
"System.InvalidOperationException",
"Operation is not valid due to the current state of the object."
My Code:
<code>using EnvDTE;
using EnvDTE80;
using System;

namespace AutomationProject
{
    class Program
    {
        static void Main(string[] args)
        {
            ...
            EnvDTE80.DTE2 dte;
            object obj = null;
            System.Type t = System.Type.GetTypeFromProgID("VisualStudio.DTE.14.0", true);
            System.Threading.Thread.Sleep(1000);
            // Attempt to create an instance of envDTE.
            obj = System.Activator.CreateInstance(t, true);

            // Cast to DTE2.
            dte = (EnvDTE80.DTE2)obj;
            dte.MainWindow.Visible = true;
            //dte.MainWindow.Activate();
            //dte.UserControl = true;
            dte.ExecuteCommand("File.OpenProject", projectLocation + projectName);

            //dte.ExecuteCommand("Project.StartOptions", "-break -lib:ModuleName -exec:TestName");
            // Get a reference to the solution2 object.
            System.Threading.Thread.Sleep(1000);
            Solution2 soln = (Solution2)dte.Solution;
            Project proj = soln.Projects.Item(1);
            try
            {
                dte.Solution.SolutionBuild.SolutionConfigurations.Item(1).Activate();
                ConfigurationManager configmgr;
                Configuration config;
                if (dte.Solution.Projects.Count > 0)
                {
                    configmgr = dte.Solution.Projects.Item(1).ConfigurationManager;
                    config = proj.ConfigurationManager.ActiveConfiguration;
                    config.Properties.Item("StartArguments").Value = "command line arguments";
                ...
                }
            ...
            }
        ...
        }
    }
}
</code>
Answer: [SOLVED]
Project was an executable, this was the reason why it can't initialize a ConfigurationManager.


Term for the sum of products of a number's prime factors, excluding one factor per product.

Question: Is there a term for the sum of products of a number's prime factors, excluding one factor per product?
For example $30 = 2 \cdot 3 \cdot 5$
So the sum of products of "all but one prime factors" is $2 \cdot 3 + 2 \cdot 5 + 3 \cdot 5 = 31$
For $15=3\cdot 5$, it would be $3 + 5 = 8$.
Comment: Do you mean "all but one *prime* factors"?
Comment: So if $N=2^{\nu_2(N)}3^{\nu_3(N)}5^{\nu_5(N)}7^{\nu_7(N)}\cdots$, then the sum you're after is $$N\left({\nu_2(N)\over2}+{\nu_3(N)\over3}+{\nu_5(N)\over5}+{\nu_7(N)\over7}+\cdots\right)$$ right?
Comment: What would that sum be for 100?
Comment: @Spencer, yes, editing the post now
Comment: 100 = 2 * 2 * 5 * 5, so it would be 2*2*5 + 2*2*5 + 2*5*5 + 2*5*5 = 140
Comment: @BarryCipra yes exactly!
Comment: This is related to pseudoperfect numbers.
Answer: This function is called the arithmetic derivative of a number.
Here's a recursive definition:

Define $0' = 1' = 0$
Define $p' = 1$ for any prime.
If a number $m = a\cdot b$, define $m' = a'\cdot b + a \cdot b'$.

By induction you see that this equals your "sum of all but 1 prime factor" function.
Comment: As a general comment: if you have a formula that outputs positive integers for integer inputs, you can try to compute manually the first 7-10 terms and type it into OEIS. More frequently than not you will find what it is and who has previously studied it.
Answer: This is the arithmetic derivative, OEIS A003415.
The arithmetic derivative $n'$ satisfies $(mn)'=m'n+mn'$ for all $m,n$, just like the ordinary derivative. From this we get $(abc)'=a'bc+ab'c+abc'$ and so on, and clearly these also apply in the cases where all the variables are prime numbers and $p'=1$.
Comment: It makes sense to define $f(p)=1$ because $f(p)$ is the sum of one empty product and we usually define the empty product as $1$.  This is one example of where it is convenient to do so.
Comment: @RossMillikan: there's an interesting parallel between arithmetic derivatives and tensor derivations. For tensor derivations one requires that Leibniz rule holds, and then the specification of the action on scalars (as action by a vector field) and on vectors uniquely determines the derivation. Here, the action on $1$ is restricted (like the action on scalars). The action on $p$ can be arbitrary, and for each choice of action on $p$ one develops a version of the arithmetic derivative. This is to emphasize the **convenience** you mentioned in your comment, and how it relates to the OP.


How can i resolve the Internal React error?

Question: I keep getting an Error message anytime my splash screen runs and redirects to a new screen
Warning: Internal React error: Attempted to capture a commit phase error inside a detached tree. This indicates a bug in React. Likely causes include deleting the same fiber more than once, committing an already-finished tree, or an inconsistent return pointer.
I tried running "npm install" for fix all dependencies but no results
Comment: Is this a fresh project or does it have any logic happening on the splash screen ? Maybe it would be better if you include any relevant code  in your question.
Comment: Did you fix this? I got same error today :(
Answer: Check if you have some useEffect that do "things" inside your component that loads before everything.
Or maybe an import that is not marked as "invalid" (such as react-native/types) but actually causes many problems (should be just react-native).
Or you're returning some wrong objects in your render (like using an object {myView} instead of <MyView />).
Check with npm outdated if you have any packages to update: do not update it "as is", but check compatibility.


Angular raise Error in a view with Internet Explorer

Question: I'm writing an application using aps.net, mvc 5, angular js and typescript.
In the layout file I added the ng-app name using  but I added the external js files, result of the typescript comilation, in just a few of the views.
Running the application in debug mode from visual studio 2013 and internet explorer, I receive the following error:
/Scripts/angular.js

0x800a139e - JavaScript runtime error: [$injector:modulerr] Failed to instantiate module myApp due to:

Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

This happens when I hope views without angular controllers, but I don't receive messages when the javascript files with the angular code is loaded. What am I missing?
Comment: Have you checked off each recommendation from [this article](http://docs.angularjs.org/guide/ie)? Notably, the `id="ng-app"` and namespace declarations
Comment: thanks, I have checked, but it's of no help, the problem happens with ie 11 in windows 8.1
Answer: i think what is happening over here is when your route which don't have js files the angular bootstraps the DOM and try searching for myApp but since there is no angular.module named myApp is decalred it throws an error.
 what you can do is instead of keeping the ng-app in layout page keep in the routes where you require angular to bootstrap
Answer: you probably did angular.module('myApp') which is used to get an existing module. You need to do angular.module('myApp',[]) to create the module.
Comment: I have looked better, but the problem happens in the pages where i don't have any angular code, and works fine with pages with its own controller
Comment: files where you have `` *must* have the code I mentioned to create the module


Attach to process WCF service from another machine

Question: I'm trying attach to WCF service which is published at Windows Server 2008.
I have this WCF at my machine with XP. I have some weird errors at server and I want to attach to this wcf from server with Windows Server 2008.
I can't find good tutorial aobut this issue.
Could you recommend me good tutorial ?
Answer: Look into remote debugging, basically you install a small client on the remote machine and connect to it from your machine.