Mongoose: Aggregating and Counting

Question: I have a NodeJS/MongoDB app which has data stored in a collection called "Feedback". The data looks like the following:
[
    {
        "__v": 0,
        "_id": "57d6b2d09f46ca14440ac14e",
        "customerFeedback": [
            {
                "_id": "57d6b2d09f46ca14440ac14f",
                "answer": [
                    {
                        "_id": "57d6b2d09f46ca14440ac150",
                        "answerValue": "cat",
                        "answerWeight": 0
                    }
                ],
                "question": "What is your favourite thing about this shop?",
                "questionId": "57d65edc0132461120fa0afd"
            },
            {
                "_id": "57d6b2d09f46ca14440ac151",
                "answer": [
                    {
                        "_id": "57d6b2d09f46ca14440ac152",
                        "answerValue": "Okay",
                        "answerWeight": 0
                    }
                ],
                "question": "How was your experience today?",
                "questionId": "57d69ef6dbb25611e46e6bc9"
            }
        ],
        "shopId": "SH0001",
        "feedbackCreatedOn": "2016-09-12T13:51:12.703Z",
        "questionsForDay": "2016-09-12T00:00:00Z"
    },
    {
        "__v": 0,
        "_id": "57d6b3389f46ca14440ac157",
        "customerFeedback": [
            {
                "_id": "57d6b3389f46ca14440ac158",
                "answer": [
                    {
                        "_id": "57d6b3389f46ca14440ac159",
                        "answerValue": "cat",
                        "answerWeight": 0
                    }
                ],
                "question": "What is your favourite thing about this shop?",
                "questionId": "57d65edc0132461120fa0afd"
            },
            {
                "_id": "57d6b3389f46ca14440ac15a",
                "answer": [
                    {
                        "_id": "57d6b3389f46ca14440ac15b",
                        "answerValue": "Very Good",
                        "answerWeight": 0
                    }
                ],
                "question": "How was your experience today?",
                "questionId": "57d69ef6dbb25611e46e6bc9"
            },
            {
                "_id": "57d6b3389f46ca14440ac15c",
                "answer": [
                    {
                        "_id": "57d6b3389f46ca14440ac15d",
                        "answerValue": "Cost",
                        "answerWeight": 0
                    }
                ],
                "question": "What would you like us to improve on?",
                "questionId": "57d6b32d9f46ca14440ac153"
            }
        ],
        "shopId": "SH0001",
        "feedbackCreatedOn": "2016-09-12T13:52:56.939Z",
        "questionsForDay": "2016-09-12T00:00:00Z"
    },
    {
        "__v": 0,
        "_id": "57d6c8eb97157f10a4e5c2e7",
        "customerFeedback": [
            {
                "_id": "57d6c8eb97157f10a4e5c2e8",
                "answer": [
                    {
                        "_id": "57d6c8eb97157f10a4e5c2ea",
                        "answerValue": "Customer Experience",
                        "answerWeight": 0
                    },
                    {
                        "_id": "57d6c8eb97157f10a4e5c2e9",
                        "answerValue": "Others",
                        "answerWeight": 0
                    }
                ],
                "question": "What would you like us to improve on?",
                "questionId": "57d6b7d99ee61e47f01e5334"
            }
        ],
        "shopId": "SH0003",
        "feedbackCreatedOn": "2016-09-12T15:25:31.724Z",
        "questionsForDay": "2016-09-12T00:00:00Z"
    }
]

There are many such entries in the array of results, but the above data serves to illustrate it.
My question is, for a given shopId and questionId, I want to count the number of times each individual answerValue occurs. How do I do it?
I am able to filter the results down to the required datasets using the find method as (for example)
db.Feedback.find({shopId:"SH0001",'customerFeedback.questionId':"57d65edc0132461120fa0afd"})

But I'm not sure how to aggregate the data to the format I want.
Answer: This pipeline should give you the desired result
db.getCollection("yourCollection").aggregate([
    { $unwind: "$customerFeedback" },
    { $unwind: "$customerFeedback.answer" },
    {
        $group: {
            _id: {
                shopId: "$shopId",
                questionId: "$customerFeedback.questionId",
                answerValue: "$customerFeedback.answer.answerValue"
            },
            count: { $sum: 1 }
        }
    }
])

which for your sample data gives the following output
/* 1 */
{
    "_id" : {
        "shopId" : "SH0003",
        "questionId" : "57d6b7d99ee61e47f01e5334",
        "answerValue" : "Others"
    },
    "count" : 1.0
}

/* 2 */
{
    "_id" : {
        "shopId" : "SH0003",
        "questionId" : "57d6b7d99ee61e47f01e5334",
        "answerValue" : "Customer Experience"
    },
    "count" : 1.0
}

/* 3 */
{
    "_id" : {
        "shopId" : "SH0001",
        "questionId" : "57d65edc0132461120fa0afd",
        "answerValue" : "cat"
    },
    "count" : 2.0
}

/* 4 */
{
    "_id" : {
        "shopId" : "SH0001",
        "questionId" : "57d69ef6dbb25611e46e6bc9",
        "answerValue" : "Okay"
    },
    "count" : 1.0
}

/* 5 */
{
    "_id" : {
        "shopId" : "SH0001",
        "questionId" : "57d6b32d9f46ca14440ac153",
        "answerValue" : "Cost"
    },
    "count" : 1.0
}

/* 6 */
{
    "_id" : {
        "shopId" : "SH0001",
        "questionId" : "57d69ef6dbb25611e46e6bc9",
        "answerValue" : "Very Good"
    },
    "count" : 1.0
}

Of course you can filter the result down with an additional $match stage if you are just interested in specific values

Update due to comment:
To filter your result down with $match you could use it after unwinding the nested array of customer feedbacks like so
...
{ $unwind: "$customerFeedback" },
{ $match: { shopId: "SH0001", "customerFeedback.questionId": "57d65edc0132461120fa0afd" } },
{ $unwind: "$customerFeedback.answer" },
{
    $group: {
        _id: {
            shopId: "$shopId",
            questionId: "$customerFeedback.questionId",
            answerValue: "$customerFeedback.answer.answerValue"
        },
        count: { $sum: 1 }
    }
}
...

which would result in
{
    "_id" : {
        "shopId" : "SH0001",
        "questionId" : "57d65edc0132461120fa0afd",
        "answerValue" : "cat"
    },
    "count" : 2.0
}

If you have a large number of documents or an index on shopId and / or customerFeedback.questionId then you might want to duplicate that $match stage to the front of your pipeline so that you unwind only the documents of the corresponding shop and with at least one feedback of the desired question. So with that (optional optimization from the correctness point of view) it would look like so
...
{ $match: { shopId: "SH0001", "customerFeedback.questionId": "57d65edc0132461120fa0afd" } },
{ $unwind: "$customerFeedback" },
{ $match: { shopId: "SH0001", "customerFeedback.questionId": "57d65edc0132461120fa0afd" } },
{ $unwind: "$customerFeedback.answer" },
{
    $group: {
        _id: {
            shopId: "$shopId",
            questionId: "$customerFeedback.questionId",
            answerValue: "$customerFeedback.answer.answerValue"
        },
        count: { $sum: 1 }
    }
}
...

Comment: @DAXaholic Nevermind. I got it working. The mistake was on my part. Your solutions works perfectly! Thanks a lot! :)
Comment: Hey! Thanks a lot for your reply. I want to filter down the result by questionId. Where in the pipeline should I add the $match clause? I tried doing it, but I was not very successful. The questionId is nested inside CustomerFeedback and that stumps me.
Comment: Thanks a lot for your reply. I am able to get it working in the DB shell. However I'm facing difficulties using that in my app. I've updated my question to explain.
Comment: Is there a different way you want your results displayed?
Comment: @dyouberg The output format which DAXaholic suggested is good enough. If you notice his sample results, it'll have all questionIds listed. I simply want to filter it down, which somehow is not working for me in Mongoose. (I can do it manually in Mongo Shell)

Mongoose: Aggregating and Counting


Is it common to combine multiple voices in one piano staff, even if they don't fit the time signature?

Question: I'm a beginner/intermediate sheet reader and struggling a bit with a current piano piece ("He sleeps" from Pretty Woman). The only arrangement I could find uses a notation which makes it hard to separate the voices and bring them in sync with the time signature. I'm currently trying to rearrange the score in an easier way for myself.
Some examples:
1.

what he actually plays in a video is:

or
2.

which looks wrong to me and should be:

and things are just getting worse from there with:
3.
or
or

(all in 4/4)
Is this how multiple voices are usually written? I'm having a hard time figuring out which keys to press when and with what hand and always need to refer to videos so I can watch other people playing - which takes ages.
Can't this be written in an easier, more readable way like I tried in example 1 or am I missing something? I'm thinking about rewriting the entire score, but as I never did that before, it might not be the best approach (or even lead to more errors).
Comment: I think the arrangement you found was probably done on the cheap. It doesn't look good to me.
Comment: @MichaelCurtis The arrangement is not free available, but you can preview page 1 of 3 [here](https://www.pianoplateau.com/content/pretty-woman-he-sleeps-love-theme-james-newton-howard). Examples 1 & 2 are taken from there - the rest is on page 2 or 3. [The original music](https://www.youtube.com/watch?v=Sm14hB0HaEQ) was never released, but yes, it's for an ensemble. The arranger also published a [version for piano+violin](https://www.pianoplateau.com/sheet-music/pretty-woman-he-sleeps-violin-piano-james-newton-howard) and an easy piano version - which I didn't buy to not loose details.
Comment: Is the arrangement online? Add a link. Was the original music for an ensemble?
Comment: Yes this is common, but not so weird as in your example.
Comment: Example #1 is ugly and not fully correct: whole note tied to quarter - one voice, 5 beats. Six eighth-notes should have up-stems, they go with the high D half note.  Bottom voice is the down-stem half plus dotted - half note.
Comment: @CarlWitthoft which basically is what I arranged as "what he plays" in the second picture or did I misunderstand your comment?
Answer:
Is it common to combine multiple voices in one piano staff...

Yes, but stem directions should be used to indicate separate voices and rests should be used so that each voice has complete rhythm values for a measure.

...that might not even fit the time signature?

If the rhythm values for a voice don't fit the measure, that's a notation error.
I'll illustrate with one of the simple examples.
Both the original and your suggested change seem wrong to me.
The original should have had rests added for the upper voice.

You suggested change sets stem directions in a confusing way. When you point the double half note stem up that means it is the upper voice. You created a voice crossing which I think is hard to read, but also needs some strange additional rests to make each voice rhythmically complete.

Obviously, the repeated G5 can't be executed exactly as written on piano, because you have to release the key for the half note in one voice to play the quarter note in the other voice. The only reason to notate it that way is either to show conceptually there are multiple voice, or the arranger might expect a double keyboard set up, like when two organs are stacked up in a rock band. In this particular case, I think it's just a lame arrangement that didn't really attempt to create a good piano texture.
You could try to re-arrange it yourself, get a different arrangement, or just move on to another piece of music that is quality piano music.
Comment: Thanks! I wasn't aware of the stem rules. Wouldn't [this](https://imgur.com/a/qtImC5P) then be the best solution to keep the amount of voices to a minimum? Or is it preferred to keep intervalls of same length in the same voice? That's just the left hand and if my brain has to interpret 5-6 voices that might be a bit too much (yet). And how would you handle 3+ voices like in my other examples? Find the best (but consistent) compromise for the "middle" voices?
Comment: I think the original with the additional rests is better, because it avoids the voice crossing. That's the first image in my answer.


How to use function like 'rtrim' in drupal?

Question: I need to remove extension from string, i'm wondering what function could do that ?
Some like the rtrim($string,'string to remove')
$string could be the filename
I've added a file into database, now to retrieve it, i want to remove the extension '.epub'
this is the postman response :
{
 "code": "0",
 "response": [
{
  "epub": "http://localhost/drupal/sites/default/files/moby-dick.epub",
  "f_id": "5",
  "uid": "64"
   }
 ]
 }

I want to retrieve :
"epub": "http://localhost/drupal/sites/default/files/moby-dick",<== no .epub

This is my first try :
$file = file_load($fid);
            //$realURI = drupal_realpath($file->uri); ca marche

            $realURI = file_create_url($file->uri);
            $new = drupal_basename($realURI, '.epub');
            $n = file_create_url($new);
            $res->epub = $realURI;<== show the new (without .epub)

but now it shows :
"epub": "http://localhost/drupal/moby-dick"

I need to keep /sites/default/files/ because the file is there
What can i add for keep it work with the right path please
Thank you
Comment: Just like any other question? See Help Center - if you have problem with code you wrote, post a sample of said code and explain what exactly you tried to do, and how it fails.
Answer: Use the Drupal file API to do this; file_move() will take care of renaming.
  $file = file_load($fid);
  $new_file_uri = preg_replace('/\\.([a-zA-Z]+)$/', '', $file->uri); //Remove .whatever from the file name
  file_move($file, $new_file_uri);

Comment: Shawn `Thank you it works, and sorry for being late to test it.  thank you very much


Defining class sql-alchemy: loop to assign column types

Question: Is it possible to avoid typing out names and datatypes of columns when defining a class for sql alchemy, for example suppose you have:
from sqlalchemy import Column, Date, Integer, String, Numeric
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Fruit(Base):

   __tablename__ = 'Fruits'

    # names and datatypes of columns
    date_of_record = Column(Date, primary_key=True)
    number_of_apples = Column(Integer)
    number_of_pears = Column(Integer)

Is it possible to recreate this last section using a loop? For example if you wanted to have the column names and types as an input:
column_names = ['date_of_record', 'number_of_apples', 'number_of_pears']
column_types = [Date, Integer, Integer]

class Fruit(Base):

  __tablename__ = 'Fruits'

  def __init__(self, column_names, column_types):
        for index, (name, type) in enumerate(zip(column_names, column_types)):
            if index == 0:
                setattr(self, name, Column(type, primary_key = True))
            else:
                setattr(self, name, Column(type))

However this throws an ArgumentError: Mapper Mapper|Fruit|Fruits could not assemble any primary key columns for mapped table 'Fruits'
Is anyone able to provide a working example of how you can use column names and types as variables in class definition when using sql alchemy ?
Comment: The ORM side is ill suited anyway for bulk jobs. Using Core you can create "one off" `Table` objects easily, or even the light weight `table()` constructs.
Comment: This will not work - the framework expects columns definitions to be declared as class attributes in the `class` statement block (you can check SQLAlchemy source code to find out why), AND this is a _very_ bad idea anyway wrt/ readabilty / maintainability.
Comment: Technically you *can* do this using either a class decorator or a metaclass but I haven't thought how that'd impact inspection tools...
Comment: This approach might create a number of unexpected challenges. Any libraries that rely on model definition. Automatic migration creation too.

That doesn't sould like a good approach. What do you want to achieve ?
Comment: So if you are uploading data using sql alchemy, do you have to manually tell sql alchemy the name of columns and its attributes within the class definition? Can you not do this via a loop? what if you wanted to one off upload hundreds of tables?
Answer: Actually yes, you can do this, but you need to create your database with Table() and sqlalchemy.orm.mapper.
You need to do something like this:
from sqlalchemy import create_engine, MetaData, Table, Column
from sqlalchemy import Integer, Date # Insert your types here
from sqlalchemy.orm import mapper

engine = create_engine('sqlite:///fruits.db') # Here you need to insert your own path to db

column_names = ['date_of_record', 'number_of_apples', 'number_of_pears']
column_types = [Date, Integer, Integer]

# Adding columns

columns = list()
for index, (name, type) in enumerate(zip(column_names, column_types)):
            if index == 0:
                columns.append(Column(name, type, primary_key = True))
            else:
                columns.append(Column(name, type))

metadata = MetaData()
fruits_table  = Table('Fruits', metadata, *columns)
metadata.create_all(engine) # Create table

class Fruit(Base):
    # You can make initialization method here
    pass

print(mapper(Fruit, fruits_table)) # Create a Mapper and print it

Now, to make a session, you need to do this:
from sqlalchemy.orm import sessionmaker

Session = sessionmaker(bind=engine) # Use an engine with your database
session = Session()

test_fruit = Fruit() # You can initialize it, if you will make __init__ method

test_fruit.number_of_apples = 2
test_fruit.number_of_pears = 3

session.add(test_fruit)
session.commit()

I hope, my answer helps you!


visualization of two sets of confidence intervals in a scatterplot

Question: I am seeking some general ideas on how to more effectively present two sets of confidence intervals in a scatterplot. There are a total of 10 point estimates and the associated 20 CIs, 10 on each dimension. The difficulty is that, some confidence interval is very wide, so if I draw them vertically and horizontally for each point, then the plot would be very ugly... Is there a more effective way to incorporate both CIs for each point in a scatterplot? It may not be limited to drawing lines, other solutions using different visualization methods are also good. Thank you.
Comment: Please post the "ugly" version of your visualization so that we can see the problem more clearly.
Answer: Without seeing the data, I would suggest to use log scale for the dimension with wide intervals. If this simple trick does not solve the problem, please add your current visualization to your question.


Books on using SAS to analyze market risk

Question: Is there a book that teaches you how to use SAS to analyze the market risk of a portfolio of stocks,bonds and options?
Answer: check out an old book from SAS Publising on Stock Market Analysis Using the SAS® System: Portfolio Selection and Evaluation


Two point conversion from 15 yard line?

Question: During preseason, the NFL are trialling having extra points snapped from the 15 yard line. During the Giants-Bills preseason opener, all three extra points were successfully kicked.
But what would happen if a team tried to go for two points. Can they call a fake, and try to score from 15 yards out? If they reach the endzone, it still worth 2 points? Or can they declare their intentions, and go for the endzone from the 2 yard line? Or if they are desperate (last seconds of match, two points down), would they have to call a regular play from 15 yards out to score?
Answer: Quoted from the Washington Post

In the NFL's preseason experiment, the ball will be placed at the 15-yard line, making for a 33-yard extra point. Two-point conversion attempts will continue to come from the 2-yard line.

Other articles referencing 15 yards: [1], [2], [3]
But the main point: Yes, if this were to actually be implemented, 2 point conversions would remain the same.
As far as faking from the extra point spot, as @Duncan says, as far as the rule states at the moment, nothing else changes really besides the yard you hike the ball from for an extra point. So of course, if you were going to go for 2, you'd make it clear and hike from the 2 rather than trying to trick them and starting 13 yards further back.
I do see 20 yard extra point hikes referenced in a few articles, but generally it's 15 yards. Since this is just an experiment, I'm sure the NFL was rumoring several different distances they might consider.
Comment: You are right about the 15 yards rather than 20. I changed my link in the question to a newer one from the NFL noting the change.
Comment: 15 and 20 were both being thrown around, but it seems like 15 is what they would actually go with if this were to actually be implemented.
Comment: With regard to the other portion of your question, I don't see any reason why the team couldn't fake an extra point and go for 2. I think it would be an incredibly low value play, but they should be able to do it.
Comment: @Duncan, agreed, thanks for mentioning that I, kind of failed to mention that part. Since this is still an experiment by the NFL, I think it's safe to say all other rules related to extra points would be inherited as they are currently, unless otherwise noted.
Comment: I do wonder about making the rule more like rugby. You kick the extra point from as far back as you like, but it has to be hiked from a point straight back from where the touchdown was actually scored. It would probably make 2 point conversions a more appealing options for touchdowns scored in the corner.
Comment: Can you add the part about the fake to your answer? Like Duncan says it would be a very unlikely play to call. I guess it is more likely that after a fumbled snap the holder would try to improvise a play to get 2 points.
Comment: @Fillet: I saw a game on TV once where the score was tied 11-11 just before halftime because the first point-after snap was fumbled and recovered.

Two point conversion from 15 yard line?


Can phantom power damage an unpowered microphone?

Question: A portable PA system I'm looking at provides 4 XLR inputs and switched phantom power... But this is switched on all 4 not per-channel.
If I have a mix of powered and non powered mics could this be a problem? Can phantom power be damaging to microphones that don't require it?
Comment: @AndyBonner VU Meters work by rectifying the signal to DC and smoothing it.  Most likely your VU meter is measuring one signal line with respect to ground.  If the VU meter were connected differentially between hot and cold signal lines, it would be phantom-immune.
Comment: Hm... I have a tube pre-amp with a VU meter that always used to red-line when I plugged phantom into the output, although it didn't seem to affect the sound, and I'm still on the same tube some 20 years later...
Answer: The existing answers are correct, but just to simplify a bit into a 'common rule'.
If your mic was made any time in the past 50 years or so & you use standard XLR>XLR cables, there is no problem at all.
Mics that don't need phantom just ignore it. They don't even know it's there.
Old ribbon mics are known to be 'not safe' for this - but if you owned one, you'd probably already know this.
Answer: As long as you don't have a ribbon microphone then it will not damage your other microphones.
Comment: It's worth mentioning that unplugging/plugging in an XLR cable without muting the channel is more likely to result in a bang/pop from the speakers if phantom power is on. (Of course you should mute the channel before unplugging anyway.)
Answer: It depends on how your microphone is wired. If your microphone is wired symmetrically the two +48V contacts will just sit on opposite sides and create a 0-potential. This is why it is called phantom power, as you do not see it if you do not need it. If you microphone is NOT wired symmetrically it definitely can. E.g. if you have a microphone on a Mono jack and use some XLR-Jack converter you might give that microphone quite a bad time.
Comment: It's not so much about being "symmetrically" wired as it is about *not* providing a return path for the phantom current passing through a sensitive component.  "Phantom-immune" microphones (like typical dynamics) have their coil floating with no connection to ground.
Comment: I think you're using "symmetrical" where typical English usage is "balanced" or "differential".  But some older microphones have a balanced transformer with a center tap connected to ground.  This is still "symmetrical" by a reasonable reading and will still burn up with phantom power applied. The key is that ground return path.  I think the details belong on electronics.stackexchange.com, not here.
Comment: @Theodore To be totally correct: You do want to connect both +48V pins to anything that does not require a potential. This will result in a 0V potential.


Markov models: Proving that an occupation law is a stationary law

Question: I am currently studying Markov models. I am presented with the following definition, theorem, and proof:

Definition 3. If
$$\pi^*_{ij} := \lim_{n \to \infty} m_{ij}(n)/n$$
exists for all $i, j \in S$ and $\sum_{j \in S} \pi^*_{ij} \equiv 1$, then $\vec{\pi}^*_i = (\pi^*_{ij} : j \in S)$ is called an occupation law. In matrix form,
$$\Pi^* = [\pi^*_{ij}] = \lim_{n \to \infty} n^{-1} (\mathcal{I} + \mathcal{P} + \dots + \mathcal{P}^n). \tag{4}$$
Theorem 5. An occupation law is a stationary law.
Proof. We are assuming that the defining limits exist, so the right-hand side of (4) equals
$$\lim_{n \to \infty} (\mathcal{I}/n) + \lim_{n \to \infty} n^{-1}(\mathcal{P} + \dots + \mathcal{P}^n) = [0] + \lim_{n \to \infty} n^{-1}(\mathcal{I} + \dots + \mathcal{P}^{n - 1})\mathcal{P} = \Pi^* \mathcal{P},$$
i.e., $\Pi^* = \Pi^* \mathcal{P}$. The rows of this matrix identity have the form (3), i.e., $\vec{\pi}^*$ is stationary.

The definition for the stationary laws is as follows:

Stationary laws
Definition 2. A stationary law is any non-negative solution $\vec{\pi}$ of the balance plus mass equations, i.e.,
$$\vec{\pi} = \vec{\pi}\mathcal{P} \ \ \ \ \ \text{&} \ \ \ \ \ \sum_{j \in S} \pi_j = 1. \tag{3}$$
Note that if $\vec{\pi}\mathcal{P} = \vec{\pi}$, then $\vec{\pi} \mathcal{P}^n = \vec{\pi}$ for all $n$. This follows by applying the first result iteratively.

And a related theorem and proof is as follows:

Definition 1. If the limit
$$\pi_{ij} = \lim_{n \to \infty} p^{(n)}_{ij}$$
exists for all $i, j \in S$, and if
$$\sum_{j \in S} \pi_{ij} = 1, \ \ \ (i \in S), \tag{1}$$
then for each $i$ we say that the row vector $\vec{\pi}_i = (\pi_{ij} : j \in S)$ is a limit law (or limiting distribution).
If $\vec{\pi}_i$ is a limit law, then $\vec{\pi}_i = \vec{\pi}_i \mathcal{P}$, i.e.,
$$\pi_{ij} = \sum_{k \in S} \pi_{ik}, \ \ \ (i, j \in S) \tag{2}$$
Proof: Define the square matrix $\Pi = [\pi_{ij}]$, which exists by assumption. Definition 1 can be restated as $\Pi = \lim_{n \to \infty} \mathcal{P}^n$. But $\mathcal{P}^n = \mathcal{P}^{n - 1}\mathcal{P}$, so
$$\Pi = \lim_{n \to \infty} P^n = \lim_{n \to \infty} \mathcal{P}^{n - 1} \mathcal{P} = \Pi \mathcal{P}$$

I am having difficulty understanding this part of the first proof:
$$[0] + \lim_{n \to \infty} n^{-1}(\mathcal{I} + \dots + \mathcal{P}^{n - 1})\mathcal{P} = \Pi^* \mathcal{P}$$
Specifically, I do not understand how we get the result that the limit
$$\lim_{n \to \infty} n^{-1}(\mathcal{I} + \dots + \mathcal{P}^{n - 1})\mathcal{P}$$
results in
$$\Pi^* \mathcal{P}.$$
I would greatly appreciate it if people would please take the time to clarify this.
Answer: This is really not particularly tied to Markov chains. It is simply the following calculation that makes sense for matrices $A$ with complex entries: if $L:=\lim_{n \to \infty} \frac{\sum_{k=0}^n A^k}{n}$ exists, then
$$L=\lim_{n \to \infty} \frac{I}{n} + \lim_{n \to \infty} \frac{\sum_{k=1}^n A^k}{n} = 0 + \left ( \lim_{n \to \infty} \frac{\sum_{k=0}^{n-1} A^k}{n} \right ) A.$$
This follows by linearity of the limit operation (first step) and continuity of linear transformations (second step). Now that inner limit is again $L$, because $\frac{\sum_{k=0}^{n-1} A^k}{n} = \frac{\sum_{k=0}^{n-1} A^k}{n-1} \frac{n-1}{n}$ and $\frac{n-1}{n} \to 1$. So $L=LA$. You could also have obtained $L=AL$, but that is not particularly useful in the Markov chain context, in which you want the rows of $L$ to be invariant under $p \mapsto pA$.


Como transformar(ou concatenar) os elementos de um array em um valor numérico usando JavaScript? Estou tentando usar o método reduce()

Question: Eu quero transformar os elementos de um array em um único número, mas não pode ser a soma de todos os elementos desse array. Eu preciso concatenar todos os elementos do array e transformar eles em um único valor numérico, por exemplo:
const numeros = [2, 5, 6]

Deve retornar o valor numérico de 256.
Eu tentei fazer da seguinte maneira:
const numeros = [2, 5, 6];

const valor = numeros.reduce((accumulator, number) => accumulator.concat(number));

A expectativa era de obter o valor numérico 256, mas ocorre um erro, alguém pode me ajudar?
Comment: `Number(numeros.join(''))`.
Comment: Resumindo: ou faz malabarismos com strings, ou faz malabarismos de sintaxe :)
Comment: Não sei porque existe essa "obsessão" por usar `reduce`, sendo que um loop simples já resolve (além de deixar o código bem mais fácil de entender, na minha opinião): https://ideone.com/zNJiHs
Comment: Se não quiser usar strings, pode usar o `reduce` e ir somando o valor correspondente a cada potência de dez. Não fica tão elegante porque os índices são "invertidos". `[2, 5, 6].reduce((acc, curr, i, arr) => acc + curr * 10 ** (arr.length - (i + 1)), 0);` Não dá para usar o `concat` como você tenta fazer na pergunta porque não existe método `concat` no protótipo de números em JavaScript.
Comment: @hkotsubo, argumentos frequentes que vejo são, por exemplo, deixar em uma só expressão e evitar a _temida_ mutabilidade. Claro que nesse caso a diferença é irrisória e dá para colocar numa função, mas às vezes é legal como exercício, e não necessariamente "obsessão": `[2, 5, 6].reduce((total, n) => total * 10 + n, 0)`. Esse é um caso no qual o `reduce` se encaixa perfeitamente. Eu pessoalmente acho isso mais fácil de ler que um código que ocupa várias linhas, mas talvez eu esteja enviesado pela igreja funcional, hehe.
Comment: @LuizFelipe Acho que os argumentos não se aplicam aqui. O código não modifica o array, e é tão simples que não tem mais o que enxugar (deixar em uma linha é um preciosismo desnecessário). Mas eu também estou enviesado, o paradigma funcional tem pontos positivos mas acho que às vezes é super-valorizado e raros são os casos em que uso `reduce`. E como a linguagem já dá uma alternativa mais simples (o bom e velho loop), prefiro usá-la. E só citei a "obsessão" porque me parece que muita gente vê o `reduce` como primeira (ou única, ou "melhor") opção para resolver tudo, e isso eu acho um erro...
Answer: Eu consegui encontrar essa solução, aqui está funcionando bem, mas eu aceito opiniões para saber se esse método é uma boa prática de desenvolvimento.
const numeros = [2, 5, 6];

const valor = numeros.reduce((accumulator, number) => `${accumulator}${number}`);

const numCriado = Number(valor);

O valor retornado é o número 256 com eu estava querendo
Comment: Você juntou os dois malabarismos que comentei acima na pergunta :)
Comment: Pra ficar bem claro, você juntou o pior dos dois mundos. Não precisa usar reduce E manipulação de string, são duas indireções desnecessárias. Ou use reduce e lide apenas com valores numéricos (sugestão do Luiz Felipe), ou use strings (minha sugestão com join no comentário da pergunta).
Comment: @bfavaretto Obrigado pela sugestão, eu alterei o meu código e agora estou usando o método join(), veja como ficou:

const nums = [2, 5, 6];

const valorNum = nums.join('');

const numRecebido = Number(valorNum);

A variável numRecebido retorna o número 256 como eu estava querendo.


Geometric inequalities using sides, radius and semi-perimeter

Question: Prove that:
$$\frac{a^{2}+b^{2}+c^{2}}{4\sqrt{3}S}+1 \ge 2\cdot\frac{4R+r}{\sqrt{3}p}$$
where $a, b, c$ are the sides of the triangle, $S$ is the area, $R$ is the circumradius, $r$ is the inradius and $p$ is the semi-perimeter.
My initial thoughts on the problem were comparing the numerators with the denominators and I have observed that $a^2 + b^2 + c^2 \geq 4\sqrt{3} S$, while $4R + r \geq p\sqrt{3}$, but these equations didn't lead to any reformulation, even though they both looked like useful known-lemmas.
Answer: $$\frac{a^{2}+b^{2}+c^{2}}{4\sqrt{3}S}+1 \ge 2\cdot\frac{4R+r}{\sqrt{3}p}$$
$$\frac{a^{2}+b^{2}+c^{2}}{4\sqrt{3}S}+1 \ge 2\cdot\frac{\frac{abc}{S}p+S}{\sqrt{3}p^2}$$
$$p^2(a^2+b^2+c^2)+4\sqrt3Sp^2\geq 8abcp+4S^2$$
Let's rephrase this using incircle tangent lengths, where $a=y+z,b=x+z,c=x+y,S^2=(x+y+z)xyz$
$$(x+y+z)(x^2+y^2+z^2+xy+yz+xz)+2\sqrt3(x+y+z)\sqrt{xyz(x+y+z)}\geq4(x+y)(y+z)(x+z)+2xyz$$
$$2\sqrt3(x+y+z)\sqrt{xyz(x+y+z)}\geq4(x+y)(y+z)(x+z)+2xyz-(x+y+z)(x^2+y^2+z^2+xy+yz+xz)$$
$$12(x+y+z)^2xyz(x+y+z)\geq(4(x+y)(y+z)(x+z)+2xyz-(x+y+z)(x^2+y^2+z^2+xy+yz+xz))^2$$
$$12(x+y+z)^2xyz(x+y+z) - (4(x+y)(y+z)(x+z)+2xyz-(x+y+z)(x^2+y^2+z^2+xy+yz+xz))^2\geq 0$$
We can use the symmetric polynomial theorem on this clearly symmetric polynomial to know it is a polynomial in $x+y+z,xy+yz+xz,xyz$.
I want to find the coefficient of $(xyz^2)$, so I'll substitute $1,\omega,\omega^2$. where $\omega^3=1$.
we have $x+y+z=0,xy+yz+xz=0,xyz=1$.
$$P(1,\omega,\omega^2)=-(...)^2$$
what's inside the parentheses is clearly real and thus the coefficient is negative.
Because of that, the minimal value is achieved when $xyz$ achieves extreme values while keeping $xy+yz+xz,x+y+z$ constant.
By uvw method, we have to check either when $x=0$, meaning the triangle is degenerate, $S=0$ and the inequality is clear or when $x=y$ which is when the triangle is isosceles which is a simple one variable inequality


SoapClient returning response with empty stdClass objects

Question: I'm running into a problem with PHP SoapClient. I have the following WSDL https://api.mindbodyonline.com/0_5/DataService.asmx?WSDL and I'm calling the SelectDataXml. It returns the appropriate response, which includes an array of objects which correspond to the rows of data that the SQL query would return. I've checked the response in both Soap UI and through the __getLastResponse method (using the print_r routine and the NetBeans debugger window). I can see the complete response as a string but the array is being built with empty stdClasses. I've seen several answers here suggesting that caching be turned off to work around this. I tried that but nothing. I can't seem to find a way to make it build the objects correctly. Any help would be appreciated.
EDITED
The abstract superclass (sensitive data replaced with 'REMOVED'):
abstract class Mindbody_service {
    protected $_userCredentials = array ( "Username" => 'REMOVED', "Password" => 'REMOVED', 'SiteIDs' => array ( 'REMOVED' ) ),
        $_sourceCredentials = array ( "SourceName" => 'REMOVED', "Password" => 'REMOVED', 'SiteIDs' => array ( 'REMOVED' ) ),
        $_endPoint;

    public function __construct( $wsdl, $options = array () )
    {
        try {
            $this->_endPoint = new SoapClient( $wsdl, $options );
        } catch ( SoapFault $fault ) {
            echo $fault->getMessage();
        }
    }
}

The concrete subclass:
include_once ('Mindbody_service.php');

class MindbodyDataServiceResponse {

    public $Status,
        $ErrorCode,
        $XMLDetail,
        $ResultCount,
        $CurrentPageIndex,
        $TotalPageCount,
        $Results;

    function __construct()
    {
        $Status = '';
        $ErrorCode = 0;
        $XMLDetail = '';
        $ResultCount = 0;
        $CurrentPageIndex = 0;
        $TotalPageCount = 0;
        $Results = new MindbodyDataServiceResults();
    }
}

class MindbodyDataServiceResults {

    public $Row;

    function __construct()
    {
        $row = array ();
    }
}

class Mindbody_data_service extends Mindbody_service {

    private $_query = "Very long SQL command that makes sense to the server";

    public function __construct()
    {
        $wsdl = 'https://api.mindbodyonline.com/0_5/DataService.asmx?wsdl';
        $options = array ();
        $classMap = array ( 'SelectDataXmlResult' => 'MindbodyDataServiceResponse' );

        $options [ 'trace' ] = TRUE;
        $options [ 'cache_wsdl' ] = WSDL_CACHE_NONE;
        $options [ 'compression' ] = SOAP_COMPRESSION_ACCEPT | SOAP   _COMPRESSION_GZIP;
        $options [ 'classmap' ] = $classMap;

        parent::__construct( $wsdl, $options );
    }

    public function getSomething( $since = null )
    {
        $request = array ( 'SourceCredentials' => $this->_sourceCredentials );

        $request [ 'SourceCredentials' ] = $this->_sourceCredentials;
        $request [ 'UserCredentials' ] = $this->_userCredentials;
        $request [ 'XMLDetail' ] = 'Full';
        $request [ 'PageSize' ] = 0;
        $request [ 'CurrentPageIndex' ] = 0;
        $request [ 'SelectSql' ] = $this->_conditionalQuery( $since ) . ' ORDER BY Sales.SaleDate;';

        try {
            $result = $this->_endPoint->SelectDataXml( array ( 'Request' => $request ) );
        } catch ( SoapFault $fault ) {
            echo 'ERROR: [' . $fault->faultcode . '] ' . $fault->faultstring . '.';
            exit;
        } catch ( Exception $e ) {
            echo 'ERROR: ' . $e->getMessage() . '.';
            exit;
        }

        echo '
';
        var_dump ($result->SelectDataXmlResult);
        echo '
';

        return $result->SelectDataXmlResult;
    }
}

The method in question is getSomething. The $since variable is irrelevant, it's used in the query as a cutoff date for the data being retrieved (reason for which I have a private  _conditionalQuery( $since ) method).
The output of var_dump ($result->SelectDataXmlResult) I'm getting on my browser is:
object(MindbodyDataServiceResponse)[22]
  public 'Status' => string 'Success' (length=7)
  public 'ErrorCode' => int 200
  public 'XMLDetail' => string 'Full' (length=4)
  public 'ResultCount' => int 0
  public 'CurrentPageIndex' => int 0
  public 'TotalPageCount' => int 0
  public 'Results' =>
    object(stdClass)[23]
      public 'Row' =>
        array (size=4)
          0 =>
            object(stdClass)[24]
              ...
          1 =>
            object(stdClass)[25]
              ...
          2 =>
            object(stdClass)[26]
              ...
          3 =>
            object(stdClass)[27]
              ...

EDITED
Here's the Server's response:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <SelectDataXmlResponse xmlns="http://clients.mindbodyonline.com/api/0_5">
            <SelectDataXmlResult>
                <Status>Success</Status>
                <ErrorCode>200</ErrorCode>
                <XMLDetail>Bare</XMLDetail>
                <ResultCount>0</ResultCount>
                <CurrentPageIndex>0</CurrentPageIndex>
                <TotalPageCount>0</TotalPageCount>
                <Results>
                    <Row>
                        <Column1>REMOVED</Column1>...(more columns)
                    </Row>
                    <Row>
                        <Column1>REMOVED</Column1>...(more columns)
                    </Row>
                    <Row>
                        <Column1>REMOVED</Column1>...(more columns)
                    </Row>
                    <Row>
                        <Column1>REMOVED</Column1>...(more columns)
                    </Row>
                </Results>
            </SelectDataXmlResult>
        </SelectDataXmlResponse>
    </soap:Body>
</soap:Envelope>

I've removed the actual content of each Row element due to it being customer data, but they are well formed XML elements. It's those elements that I'm getting as empty stdClass objects where I should be getting stdClass objects with members that have a 1:1 correspondence to the Row element's children.
Comment: Impossible, I have no access to the server except as consumer of the service. In any case, I already solved the problem. It would seem that PHP's SoapClient internal parser fails silently under certain conditions (which I happen to hit). What I did was discard the object I was getting and requesting the raw XML response, which I passed to the simplexml_load_string routine to get an object I could actually use. I'll post the code later on as I'm currently unable to because of StackOverflow's restrictions.
Comment: you need an example about how to call a method via soapclient?
Comment: No, that I'm already doing just fine. The problem, as I've stated above, is that the call's returning empty objects where it shouldn't.
Comment: so could you paste your code here?
Comment: Added The code, plus the output of a var_dump :)
Comment: your server will return string and it's not array? you need array result?
Comment: It seems to be. At least I'm seeing an array in the response via the output, the debugger and SoapUI. What I can't get is the contents of the elements of that array. As you can see, they're empty stdObjects, with no members whatsoever, which is wrong.
Comment: As far as I know the server can return string. try to make output as json and then send to client. because `stdObject` is a type for PHP and it's not standard for other langs like Python and so on.
Comment: It ALWAYS returns a string. The response in and of itself is not the problem, it's PHP's SoapClient parsing of this string. It's incorrectly building empty stdObjects as items of the array.
Comment: So could you paste here server output not `stdObject` , just string. and not via `var_dump` just normally `echo` or `print_r`
Comment: Edited again, raw response included.
Comment: I saw it. I'm trying to find your problem. I have created web service for many times. my code response was `JSON`(string) and my client just get me that `JSON` value and I decoded that and used that. so `print_r($result->SelectDataXmlResult['result']);` never returns null value.
Comment: I don't think you understood the problem. I'm not getting null results, I'm getting valid stdClass objects but they have no members. I'm not handling the raw response ANYWHERE. Are you suggesting I get the raw response and feed it to json_decode?
Comment: Could you create an method on the server which return "hello world" string? and test it and you should get exactly that string. means via something like `echo $output`. when you get that string correctly, try to `json_encode` a test array on the server and then test it again. on the client , try to print it via `echo $output` again and then try to `json_decode` and it should works fine.
Answer: I faced similar situation, and almost pulled my hair out, but eventually I sorted it out.
From a Soap server where I can't change anything, SoapUI and Java was able to get response, but the default behaviour with PHP \SoapClient->__soapCall(...) was returning some elements as empty StdClass objects.
The solution I found is not ideal, but allows to get it done.
Basically, I wanted the raw response, so I could parse it myself, and \SoapClient->__getLastResponse() will do just that, if and only if we set options key 'trace' to 1.
So, pseudo-code:
$options = [
   // (login, password, etc...)
   'trace' => 1,
];
$client = new \SoapClient($wsdl, $options);

// (prepare the data for the call...)

$result = $client->__soapCall('save', [$callContext, $name, $inputXml]);

// Because of trace = 1 in options, this will now work.
$rawResult = $soapClient->__getLastResponse();

Now you have full access to the response, just have to parse it.
Hope this helps someone!!
Answer: Solution found! It seems SoapClient has problems parsing responses in some cases. I solved this by rewriting the getSomething method to discard the incorrect result and use the simplexml_load_string routine to generate the object. I based this on the thread simplexml_load_string() will not read soap response with "soap:" in the tags. I had tried this before but was running into a brick wall as I hadn't taken into account the SOAP namespace conflict (i.e. I was using simplexml_load_string alone :P). Here's the working code:
public function getSoldProducts( $since = null )
    {
        $request = array ( 'SourceCredentials' => $this->_sourceCredentials );

        $request [ 'UserCredentials' ] = $this->_userCredentials;
        $request [ 'XMLDetail' ] = 'Full';
        $request [ 'PageSize' ] = 0;
        $request [ 'CurrentPageIndex' ] = 0;
        $request [ 'SelectSql' ] = $this->_conditionalQuery( $since ) . ' ORDER BY Sales.SaleDate;';

        try {
            $this->_endPoint->SelectDataXml( array ( 'Request' => $request ) );
            $xml = simplexml_load_string($this->_endPoint->__getLastResponse ());
            $xml->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
            $result = $xml->xpath('//soap:Body');
        } catch ( SoapFault $fault ) {
            echo 'ERROR: [' . $fault->faultcode . '] ' . $fault->faultstring . '.';
            exit;
        } catch ( Exception $e ) {
            echo 'ERROR: ' . $e->getMessage() . '.';
            exit;
        }

        return $result[0]->SelectDataXmlResponse->SelectDataXmlResult;
    }

Hope this helps anyone with similar problems.


Use the mouse to select only one word in text jquery

Question: I am working on rails 4 project. I need to select only one word from a paragraph. Right now i am able to select the entire paragraph using the below code:
<code> function SelectText(element) {
    var doc = document,
            text = doc.getElementById(element),
            range,
            selection;
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

$(function() {
    $('p').click(function() {
        SelectText('selectme');
    });
});
</code>
Is there any way to modify this code to select only one word from the paragraph?
Comment: share paragraph data and mentioned what is your need ?
Comment: Have you looked at http://stackoverflow.com/questions/2183335/getting-the-text-under-the-mouse-pointer and http://stackoverflow.com/questions/5448701/javascript-highlight-select-word-under-mouse-pointer ?
Comment: It is actually a doc file with a lot of contents. I need to select one word from this file with just one click on that particular word. Once it is selected i am using contextMenu plugin to copy it to the textarea. I googled everywhere but unable to get this working. All i need is with just single mouse click on the word, select it.
Comment: The above two links you shared is for highlighting the text. But i need to select the word so that i can copy.
Answer: May be some browsers doesn't support this code:
<code>document.onclick = globalOnClickHandler;

function globalOnClickHandler() {
    var s = window.getSelection();
    s.modify('move','backward','word');
    s.modify('extend','forward','word');
    // alert(s.toString()); // you can get selected word
}
</code>
https://jsfiddle.net/td745Lk8/1/
Comment: Thanks for posting the valuable code here,  what if I want to select more then one word say 5 or 6 random words. What changes should I make? As this code only highlights a single world at once,  and when you select other, the previous one would be gone.
Answer: I merged the two StackOverflow questions I linked to in the comment above with the code you provided.  Here's the result in code and a JSFiddle:
http://jsfiddle.net/EHCN6/2/
<code>$(document).ready(function()
{
    var words=$("#yourTextContainer").text().split(' ');
    $("#yourTextContainer").html("");

    $.each(words, function(i,val)
    {
        //wrap each word in a span tag
        $('<span/>').text(val +" ").appendTo("#yourTextContainer");
    });

    $("#yourTextContainer span").live("click",function(event)
    {
        event.stopPropagation();
        SelectText($(this));
    });
});

function SelectText(element)
{
    var doc = document,
            text = element.get(0),
            range,
            selection;
    if (doc.body.createTextRange)
    {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    }
    else if (window.getSelection)
    {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}
</code>
Comment: This works perfectly well. But in my project the problem is that I am converting resumes of doc files to html file using pdf2html converter, Where this code does not work. The entire html file displayed is contained in many div's and not able to select any word. Could you please help.
Comment: Is there a top level div that everything is contained in?  If not, maybe selecting $("body") or $("html") instead of $("#yourTextContainer") would work.  I can't give too much more specific help without seeing the HTML.
Comment: @howard : Is there any way where i can send you the HTML file because i cannot attach any files here?
Comment: Can you add it to that JSFiddle I started?
Comment: This is a really complicated case because pdf2htmlEX did a sloppy job creating the HTML, breaking spans in the middle of words: `I was born in Lebanon, lived in Spain,grew up in Canada then moved back to Lebanon.`  Why do you need to make a single click select text anyway?  A double-click will select the text just fine without any JavaScript.


How to, using the definiton of a limit, calculate the limit, if it exists in the first place, of the sequence $ a_{n} = \frac{n + 1}{3n - 4} $?

Question: I've been taught how to evaluate limits in high school, so I know that the limit of the sequence  $ a_{n} = \frac{n + 1}{3n - 4} $ is $ \frac{1}{3} $, but I have no idea how to show that using only the definition of a limit. This is pretty much the first time that I've been exposed to these types of "proof-problems", where, to solve the problem, you have to do more than just manipulate numbers whilst obeying the rules that the teacher had given me, so any kind of help, in whatever form, is most appreciated.
Answer: You have to prove that for every $\epsilon > 0$ you can find $n_0 \in \mathbb{N}$ s.t. $n > n_0 \implies |a_n - \frac 13| < \epsilon$
So now let's see what the equation on the right looks like. (To avoid any inconvinience with negative numbers you can consider $n \ge 2$). Then we have:
$$a_n - \frac 13 = \frac{n+1}{3n-4} - \frac 13 = \frac{3n+3 - 3n+4}{3(3n-4)} = \frac{7}{9n - 12}$$
Set the last value should be less than $\epsilon$ and now we have that:
$$\frac{7}{9n - 12} < \epsilon  \iff 9n - 12 > \frac 7\epsilon \iff n > \frac{7 +12 \epsilon}{9\epsilon}$$
So therefore you can choose $n_0 = \frac{7 +12 \epsilon}{9\epsilon}$ and it's not hard do see that this will give you a formal $\epsilon - \delta $ proof.
Comment: @Stefan4024 You need $3n+3-3n+4$ in your first calculation, to give numerator $7$ rather than $5$.
Comment: So, in this specific case, it is kinda expected of me that I already know that the limit of the sequence is $ \frac{1}{3} $, and that I have to use that fact to solve the problem or could have the problem been solved without me already knowing what the limit of the sequence is? Would I have to try and guess the L then or?
Comment: @FarukČamdžić Well you have to find $frac 13$ and in general the limiting value on your own. One way to do so is to plug some big numbers and make an educated guess about it. Also you can use that:

$$\lim a_n = \lim_{n \to \inf} \frac{n + 1}{3n-4} = \lim_{n \to \inf} \frac{1 + \frac 1n}{3 - \frac 4n} = \frac 13$$

Where you can use the fact that $\lim_{n \to \inf}  \frac cn = 0$. This is an acceptable proof of the claim, but if you want more rigorous proof you should do the $\epsilon - \delta$ proof. But you can still use this method to get the limit value.
Comment: @FarukČamdžić You can use polynomial division to create a fraction where the numerator has lower degree than the denominator. So $n+1=\frac 13 (3n-4)+\frac 73$


Maximum a posteriori on Multinomial distribution with a Dirichlet prior can result in negative probabilities?

Question: I am doing a maximum a posteriori (MAP) estimation of a Multinomial distribution $M(c_1,\dots,c_n|p_1,\dots,p_n)$ with a Dirichlet prior $D(p_1,\dots,p_n|\alpha_1,\dots,\alpha_n)$. The experimental counts for the MAP estimate are $(c_1,\dots,c_n)$.
My understanding is that MAP is equivalent to $\text{argmax}(M(\vec{c}|\vec{p})D(\vec{p}|\vec{\alpha}))$ over $\vec{p}$ for fixed experimental data $\vec{c}$ and a fixed prior $\vec{\alpha}$. The solution seems to be
$p_i = \frac{c_i+\alpha_i-1}{\sum_{i=1}^{n}(c_i+\alpha_i-1)}$.
However this can be negative (because the naive solution using just a Lagrange multiplier does not impose the $p_i>0$ constraints). For instance, for a category $i$ with zero counts $c_i=0$ and a prior $\alpha_i=0.5$ we get $p_i<0$.
Is there a known analytic solution for MAP that ensures the multinomial probabilities are never negative? Do I need to do it numerically instead?
Or maybe I am completely misunderstanding how the MAP is to be performed? Any suggestions or appropriate literature would be welcome.
Comment: But you know that the parameter space for the $p_i$ parameters is $0<p_i<1$ and $\sum p_i=1$, which must be respected in the optimization!
Comment: Indeed! But is a numerical optimization the only way to do this in a general case?
Comment: Did you try with Lagrange multipliers?
Comment: Yes, this is how the expression above was delivered, however this accounts only for the single equality constraint. How would one address the multiple inequality constraints?
Answer: Just to reiterate you have $n$-outcome count data $\vec{c} = (c_1,...,c_n)$ and I will assume this is from a total of $N$ shots.
The heirarchical model you have described then is the following
$$\vec{c}|\vec{p}\sim \text{Mulit}(N,\vec{p}),\\
\vec{p}|\vec{\alpha} \sim \text{Dir}(\vec{\alpha}).
$$
Now, due to the Dirichlet distribution being the conjugate prior for a multinomial likelihood, the posterior is also a Dirichlet distribution. In particular$$\vec{p}|\vec{c},\vec{\alpha}\sim \text{Dir}(\vec{c}+\vec{\alpha}).$$
The mode of this posterior distribution is, as you correctly pointed out$$\vec{p}_{\text{MAP}}=\frac{\vec{c}+\vec{\alpha}-1}{\sum_{k=1}^{n}(c_k+\alpha_k-1) }\\=\frac{\vec{c}+\vec{\alpha}-1}{N-n+\sum_{k=1}^{n}\alpha_k}
$$
but this only holds for $\alpha_i>1$. If your prior parameters $\vec{\alpha}$ do not satisfy this then you will need to resort to numerics, yes.
However, the MAP estimate is only one particular choice of point estimate and possibly not the best for this problem. Another is the posterior mean which, for this posterior, is given by $$
\vec{p}_{\text{CM}} = \frac{\vec{c}+\vec{\alpha}}{N+\sum_{k=1}^{n}\alpha_k}$$
and instead holds for all $\alpha_i>0$. This gives you a closed form point estimate for your unknown $\vec{p}$ for any choice of prior, although it is not the MAP.


Coefficients of homogeneous second order ODE when initial conditions are both 0

Question: I'm currently trying to solve this problem:
Find the unique solution to the differential equation
$y''- y'- 6y = 18x$
With initial conditions $y'(0) = 0 , y(0) = 0$
My current solution is $y = -3x + 1/2 + Ae^{3x} + Be^{-2x}$ and I'm struggling at the last step of finding $A$ and $B$.
Any help would be greatly appreciated
Comment: $0=y(0)=0+\frac{1}{2}+A+B$, $y'(x)=-3+3Ae^{3x}-2Be^{-2x}$, so $0=y'(0)=-3+3A-2B$. Now solve to get $A=\frac{2}{5},B=-\frac{9}{10}$
Answer: Hint: Plug in $x=0$ into your final equation $y(x=0)=...=0$. And then plug in $x=0$ into the derivative of $y$. You will have the second equation $y'(x=0)=...=0$. Now solve this system of linear equations for $A$ and $B$.
Answer: The particular solution to $ y''(x) - 6y(x) - y' = 18x $ is of the form :
$ y_p(x) = a_1 + a_2x $
$ y_p'(x) = a_2 $ and $ y_p''(x) = 0 $
Substitute the particular solution $y_p(x)$ into the differential eq. :
$-a_2 - 6(a_1 + a_2x) = 18x $
Equate the coefficients of 1 on both sides of the equation :
$-6a_2 = 18 \Leftrightarrow a_2 = -3 $ and you will also have $a_1=\frac{1}{2}$
Substitute a_1 and a_2 into $ y_p(x) = a_1 + a_2x $
You get : $ y_p(x) = \frac{1}{2} -3 x $
So your solution is : $ y(x) = -3x + c_1e^{-2x} + c_2e^{3x} + \frac{1}{2}$


Interval of parallel 5ths in the resolution of a German 6th chord

Question: In a music theory workbook, there was an example of a German 6th chord, which resolves to chord V. However, there is an interval of parallel 5ths in this (A♭ & E♭ going to G & D).

How are these parallel 5ths allowed or ok to do? Is it typical to do so?
Comment: Can you share the name of the music theory workbook?
Comment: @LuckyB TCL's Theory book for Grade 8.
Answer: You are correct that resolving the German 6th to a V results to parallel fifths (Ab + Eb -> G + D). This is one of the rare times where the parallel fifths are allowed. People refer to these specific parallel fifths as Mozart fifths.
They call them as such because Mozart did this quite often. Wikipedia provides some examples from his works and this one from his Symphony No. 39:

In the Wikipedia link on German 6ths there are some examples on how to avoid these.
Answer: Typically the German augmented-sixth chord resolves to a cadential six-four before resolving to the root-position dominant chord. Since the cadential six-four has scale-degree 3, there's no possibility of having these parallel perfect fifths between scale-degrees 3/6 and 2/5.
The Italian and French augmented-sixth chords don't have scale-degree 3 either, so they have no risk of parallels; you can resolve them freely to a cadential six-four or to a root-position dominant without issue.
Interestingly, Mozart seemed not to care about parallel fifths from a German to a V. He did this so often, in fact, that we often call such resolutions "Mozart fifths."
Answer: more about "Mozart fifths":
(translated by google)
"Mozart has more than once resolved the augmented German 6th chord with parallel fifths. He has done this so often that one may speak of "Mozart's fifths."

Wilhelm Tappert: Leipziger Allgemeine Musikzeitung. 3rd ed. Leipzig and Winterthur 1868, p. 275
In his study The Prohibition of fifhts parallels (1869) Tappert dedicates a separate section to the "Mozart Quintet". [1] Previously, Adolf Bernhard Marx had already provided an example such as the above in a discussion of the excessive Sextakkords with the words "Mozart", but without commenting on this in more detail.

In recent literature is highlighted that such parallels of fifths occur in Mozart, but in his oeuvre are altogether a rarity. Examples are u. a .:
Dans un bois solitaire KV 308, T. 54-57
Symphony in D major KV 504, 2nd movement, bars 25-26, bass / viola
Symphony in E Flat Major K. 543, 1st movement, bars 167-168, bass / violin II
In some of the examples cited by Tappert (inter alia The Abduction from the Serail No. 16, T. 96-97), the voices are conducted in such a way that, in fact, there are no 5th parallels
However, Mozart fifths are hardly a rarity in nineteenth-century music. B .:
Frédéric Chopin: Nocturne in C sharp minor, KK IVa No. 16 (1827), m. 1.
Robert Schumann: Album for the Youth op. 68 (1848), First Loss, T. 21-22.
Already in 1802, Charles-Simon Catel expressly allows this kind of 5th parallels in his influential Traité d'harmonie, unless it takes place between the outside voices. [4] In German-speaking harmonies of the 20th century, it is also explicitly endorsed as the "Mozart fifths".
https://de.wikipedia.org/wiki/Mozart-Quinten


drupal_goto() not remove url path of 404 page

Question: I have a search form which returns to search page.
drupal_goto('/searchyour/trips', array('query' => $query));

this is work fine if a user in active page. search url will replace as eg: example.com/searchyour/trips
But if user in 404 page (example.com/nopage) and click search, search url will set to example.com/nopage/searchyour/trips I want to change this to example.com/searchyour/trips.
I'm new to drupal. Help me to solve this. :-)
Comment: are you sure your drupal_goto and any redirects within your form all specify an absolute and not relative path, eg '/searchyour/trips' not 'searchyour/trips'.
Comment: yep, sure it's relative. because it works for valid page, like example.com/countyrpage is a valid page. In this page  drupal_goto('/searchyour/trips', array('query' => $query)); works fine. (i.e direct to :example.com/searchyour/trips )
Answer: Hope this will help you,
In Drupal 7 , you can check whether the page is 404 page or not. If it is a 404 page then change the drupal_goto $path parameter.

drupal_get_http_header : Gets the HTTP response headers for the current page.

  $status = drupal_get_http_header("status");
  $path = ($status == '404 Not Found'){
    //change the path from example.com/nopage/searchyour/trips to example.com/searchyour/trips
    drupal_goto('/searchyour/trips', array('query' => $query));
  }else{
    drupal_goto('/searchyour/trips', array('query' => $query));
  }

Comment: The thing is if user in 404 not found page that means there will be some values in the url. like example.com/nopage/ what I want is to remove appended value and change to original url (example.com)
Answer: As I understood the question, there is search link on the page or in header section, which takes the user to 'searchyour/trips' URL. The URL for this link becomes invalid when you are on 404 URL.
I believe you can use url() function to make your search link on the page. For example,
url('searchyour/trips')
Answer: Thanks for your comments. I have solved this problem but it seems it isn't the correct way.
The problem I found here is drupal_goto() function has used GET['destination'] value if the url is not secure (this is what I understand after reading the code). Otherwise it will empty.
  // A destination in $_GET always overrides the function arguments.
  // We do not allow absolute URLs to be passed via $_GET, as this can be an attack vector.

  if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
    $destination = drupal_parse_url($_GET['destination']);
    $path = $destination['path'];
    $options['query'] = $destination['query'];
    $options['fragment'] = $destination['fragment'];
  }

If it's empty, then search your/trips path used in $path. Otherwise it will override to the $GET['destination']. So if I clear the $GET['destination'], it works.
I doubt this is a good practice. So any comments about it will be appreciated.


What is the difference between publish / subscribe and method ? where/when we use method and publish / subscribe?

Question: Today I try to work on meteor and getting an issue to get data from the server page..
I try to search it on google and meteor side but there is two way to get data publish / subscribe and Method
Have a below code, I didn't know  how to write it on meteor server-side and get that data in client-side
function (x)
{
var y =2
var z  = y*x
return z;
}

Now I want to call this method in client side
Answer: With publish/subscribe you keep track on datas collected.
https://docs.meteor.com/api/pubsub.html
According to the documentation:

Methods are remote functions that Meteor clients can invoke with
  Meteor.call.

So, to answer the last question: to call your function from client side, you have to use "Meteor.call('yourMethodName', optionalCallBacks);"
EDIT:
Ok, as suggested in the comments, here an example, with your function.
In the server side, lets say on a file called "methods.js" or somethings:
import { Meteor } from 'meteor/meteor';

Meteor.methods({
  myMethod(x) {
    const y = 2;
    const z = y * x;
    return z;
  }
});

then in client side, you could call this mehod, like:
Meteor.call('myMethod', x, (error, result) => {
  // OPTIONAL CALLBACK RESULT
  console.log(error, result);
});

Arguments here, are respectivelly, name of the method, variable named x, callback.
Comment: Please provide an example according to OP's code and correct the code formatting. Thank you.
Answer:
What is the difference between publish / subscribe and method ? where/when we use method and publish / subscribe?

So if you want a logic you don't need pub/sub.
Methods are for logic pub/sub for data handling.
Important note:
If you need to work with data from meteor's collection on the method you need to take into account this if method is executed on the server side it has access to all data (collections).
If the method is executed on the client side it has access only to published data.
On the other hand, according to your example, you don't need any data, so I'll skip it.
I strongly suggest using validated methods:
https://github.com/meteor/validated-method
Now let's go to examples
Imagine you have a method
export const calculate = new ValidatedMethod({
  name: 'logic.calculate', // methods are usually named like this
  validate: new SimpleSchema({ // use SimpleSchema to autovalidate parameters
    x: {
      type: Number
    }
  }).validator(),
  run({ x }) {
    const y = 2;
    return y*x;
  }
});

Things to note:
 1. The file should be imported on the server somewhere.
 2. You need to use validation
Now call it on the client
Meteor.call('logic.calculate', { x }, (error, result) => {
  if (error) {
    do something
  }
  console.log(result);
});

Also, you can import the method directly and call it like this:
import { calculate } from '../../api/logic/methods';// use real method path here

calculate.call({ x }, (error, result) => {
     if (error) {
        do something
     }
     console.log(result);
});

Note that for validated methods argument is an object
Answer: In meteor, we can create a meteor method and can pass data to client side by Meteor.call('methodName', 'param') . But in case of async operation we need to use future. Take a look on below example :
Future = Npm.require('fibers/future');

Meteor.methods({
  foo: function() {
    const future = new Future();
    someAsyncCall(foo, function bar(error, result) {
      if (error) future.throw(error);
      future.return(result);
    });
    // Execution is paused until callback arrives
    const ret = future.wait(); // Wait on future not Future
    return ret;
  }
});


Retorno dados do SQL mysqli_fetch_assoc organizados em uma tabela

Question: Tenho o seguinte SQL
<?php

   require_once("php/conexao.php");

   $strSQL = "SELECT id, titulo FROM questoes ORDER by id DESC";

   if($result = mysqli_query($conexao, $strSQL)) {

      while($row = mysqli_fetch_assoc($result)) {
         $ID = $row['id'];
         $titulo = $row['titulo'];
      }
   }
?>

E a seguinte tabela:

Lista de Questões

                        <input type="text" class="form-control" id="dev-table-filter" data-action="filter" data-filters="#dev-table" placeholder="Filter Developers" />

                                ID
                                Título da Questão

                                1
                                Exemplo

                                2
                                Exemplo

                                3
                                Exemplo

Estou tentando organizar os dados "ID" e "titulo" que retiro do SQL de forma correta na tabela, mas estou batendo bastante a cabeça. É uma duvida bem principiante, mas realmente estou sem um caminho, rs. Sou iniciante no PHP e SQL e é meu primeiro sisteminha.
Answer: Você tem que printar os dados no meio do seu html:

            ID
            Título da Questão

        <?php

        while($row = mysqli_fetch_assoc($result)) {
            $ID = $row['id'];
            $titulo = $row['titulo'];
        ?>

            <?php echo $ID; ?>
            <?php echo $titulo; ?>

        <?php
        } // fecha while
        ?>

Claro que estou considerando que essa query esteja sendo feita no mesmo arquivo - e antes - tabela.
Comment: Amigo, perfeito! Estava na cara o resultado, mas clareou minha mente você colocando dessa forma. Ajeitei do jeito do meu código aqui e ficou perfeito, claro, só tive que trocar a consulta do SQL para ASC que deu tudo OK. Mais uma vez obrigado pela ajuda, novamente!
Comment: @RodrigoBRF tranquilo amigo, precisando estamos aí!!


How to avoid writing to database in form submit?

Question: I have a webform and I need to validate a condition before you type in the database.
Use the hook_form_alter, this is my code:
function validate_entry_form_alter(&$form, $form_state, $form_id){
  if($form_id == 'webform_client_form_1'){
    $form['#submit'][] = "_validate_entry_webform_client_form_submit_handler";
  }
}

/* function HOOK_FORM_SUBMIT */

function _validate_entry_webform_client_form_submit_handler($form, &$form_state){
  $option = $form['submitted']['eventos']['#value'];
  $data_total = db_query("SELECT count(data) FROM webform_submitted_data WHERE data = $option")->fetchField();

  print_r('
');
  print_r($data_total);
  print_r('
');
  exit();
}

I've noticed that my function to handle the submit is handled when it wrote in database.
I need a "hook" where you can get all the results before they are written to database. Validate the data and if everything is correct, follow the workflow in database insert.
Answer: Form validation is called in the the first part af your code not in the submit function. Add another parameter to your form_alter:
$form['#validate'][] = 'nameOfMyModule_functionName_validate';
$form['#submit'][] = "_validate_entry_webform_client_form_submit_handler";

When validation passes, the submit function will be called. if not form_set_error can be called displaying a message like so:
function nameOfMyModule_functionName_validate($form, &$form_state) {
// Check for the color 'blue'.
    if ($form_state['values']['color'] == 'blue') {
    form_set_error('color', 'Sorry, your favorite color is actually yellow.');
    }
}

Comment: after implementing my validation function. If it passes validations How do I submit the workflow to continue normally? And if it fails How do I stop and only display a message?
Comment: @Dvex I updated my answer to show you how this could be done.


Find the closest numbers in double precision

Question: I am reading a numerical analysis book which talks about nearest numbers.
They quickly state that you can easily find nearest machine numbers, but never go on to show how exactly to do so.
Can someone please explain how you can find the two closest numbers $y'$ and $y''$ of a given number $y$, where $y'$ is the number below and $y''$ is the number above for double precision?
That is, to be precise, for $\mathbb{D}$ the set of floating point (double) values, $y' = \max\{x \in \mathbb{D} | x \leq y \} $ and $y'' = \min \{ x \in \mathbb{D} | x > y \}$.
Let say the number is $y = 0.8$.
How do you number the closest number above and below that number in double precision?
Answer: You would have to determine the 53 binary digits of the mantissa in
$$
x=2^e·(1.m_1…m_{53})_2
$$
The exponent is obtained from the condition $2^e\le x <2^{e+1}$.
Then for the mantissa compute the integer part of $x·2^{53-e}$.
As for $x=0.8$ you get $e=-1$, you need to compute the integer part of $0.8·2^{54}$, $14411518807585587$, and its successor, $14411518807585588$, (and additionally the binary representation of them if you want to construct the floating point format).
Comment: thank you for this, is the integer part the mantissa?
Comment: Yes. The integer part is the mantissa.


One amp volume, multiple guitars

Question: When performing, I play several guitars. Volume and response of effects pedals varies from guitar to guitar. Simply adjusting volume changes my sound...any suggestions on how to keep my sound more uniform despite changing guitars?
Comment: You could try using a small mixer, say four channel. One guitar into each channel. That would give you gain, volume and eq separately for each. Output straight into amp - pre or post, your choice!
Comment: Have a volume pedal at the start of the effects chain?
Comment: There are also 'instrument switcher' pedals. An ABY but usually outfitted with separate volumes.
Answer: A pedal or three at the start of your effects chain should help. I would look at buffers, boosters, and compressors. For the latter, it's probably best to have something more transparent and less squashed sounding.
It might be that a buffer is good enough to bring hit your signal chain with the same intensity between guitars, or a compressor set just right and left on. Otherwise you might want to be able to turn on a boost for the quieter guitars, or have a compressor that also slightly boosts the level that you can turn on when needed.
The ultimate precise control would be some kind of MIDI controlled volume or boost pedal that can be configured with a different preset for each guitar. Or a small format multi effect unit like an Eventide H9 where you can select a preset for each guitar that has whatever boost or compression appropriate to match levels.

One amp volume, multiple guitars


Switch animation based on property value

Question: I have a ViewModel with a State property and a Datatemplate wich contains a simple rectangle with a background brush. Whenever the State of the ViewModel changes I want to trigger an animation that starts with the color the brush currently has and animates it to the new color representing the new state. I have done this with datatriggers. And it almost works. The only problem I have is that it does not start with the color the brush currently has but with the unanimated base color. This is probably because I remove the animation in the exit action. But if I don't do that I can only animate once. What am I missing?
Another question I have is: I need this stateanimation in a lot of different datatemplates it always binds to the same property ("State") and they always animate a SolidColorbrush. Is there a way I can share these datatrigger animations across datatemplates using resources and/or styles?
<code><DataTemplate.Triggers>
    <DataTrigger Binding="{Binding Path=State}" Value="Active">
        <DataTrigger.EnterActions>
            <BeginStoryboard x:Name="activeStoryboard" HandoffBehavior="SnapshotAndReplace">
                <Storyboard>
                    <ColorAnimation To="Green" FillBehavior="HoldEnd" Duration="00:00:0.25" Storyboard.TargetName="stateBrush" Storyboard.TargetProperty="Color" />
                </Storyboard>
            </BeginStoryboard>
        </DataTrigger.EnterActions>
        <DataTrigger.ExitActions>
            <RemoveStoryboard BeginStoryboardName="activeStoryboard" />
        </DataTrigger.ExitActions>
    </DataTrigger>
    <DataTrigger Binding="{Binding Path=State}" Value="Error">
        <DataTrigger.EnterActions>
            <BeginStoryboard x:Name="errorStoryboard" HandoffBehavior="SnapshotAndReplace">
                <Storyboard>
                    <ColorAnimation To="Red" FillBehavior="HoldEnd" Duration="00:00:0.25" Storyboard.TargetName="stateBrush" Storyboard.TargetProperty="Color" />
                </Storyboard>
            </BeginStoryboard>
        </DataTrigger.EnterActions>
        <DataTrigger.ExitActions>
            <RemoveStoryboard BeginStoryboardName="errorStoryboard" />
        </DataTrigger.ExitActions>
    </DataTrigger>
    <DataTrigger Binding="{Binding Path=State}" Value="Wait">
        <DataTrigger.EnterActions>
            <BeginStoryboard x:Name="waitStoryboard" HandoffBehavior="SnapshotAndReplace">
                <Storyboard>
                    <ColorAnimation To="Yellow" FillBehavior="HoldEnd" Duration="00:00:0.25" Storyboard.TargetName="stateBrush" Storyboard.TargetProperty="Color" />
                </Storyboard>
            </BeginStoryboard>
        </DataTrigger.EnterActions>
        <DataTrigger.ExitActions>
            <RemoveStoryboard BeginStoryboardName="waitStoryboard" />
        </DataTrigger.ExitActions>
    </DataTrigger>
    <DataTrigger Binding="{Binding Path=State}" Value="Inactive">
        <DataTrigger.EnterActions>
            <BeginStoryboard x:Name="inactiveStoryboard" HandoffBehavior="SnapshotAndReplace">
                <Storyboard>
                    <ColorAnimation To="Gray" FillBehavior="HoldEnd" Duration="00:00:0.25" Storyboard.TargetName="stateBrush" Storyboard.TargetProperty="Color" />
                </Storyboard>
            </BeginStoryboard>
        </DataTrigger.EnterActions>
        <DataTrigger.ExitActions>
            <RemoveStoryboard BeginStoryboardName="inactiveStoryboard" />
        </DataTrigger.ExitActions>
    </DataTrigger>
</DataTemplate.Triggers>
</code>
Answer: I can't completely answer your question but I can at least point out that you can share the Storyboards but I'm not sure about the DataTriggers themselves. An interesting idea though. I've wondering the same sort of thing about Bindings because I often have many repeated uses of a single binding and was trying to find a way to declare it once and reuse at least within a single Control or XAML ResourceDictionary.


SoapFormatter in .NET Core 3.1?

Question: How should I migrate the following c# 4.8 framework to .NET Core 3.1 ?
Code is:
public enum E { V }
[Serializable]
public class Person
{
    public E my_enum;
    public bool my_bool;
}
[...]
Person p = new Person();
using (FileStream fs = new FileStream("myfile.soap", FileMode.Create))
{
    SoapFormatter f = new SoapFormatter();
    f.Serialize(fs, p);
    fs.Close();
}

Give me the expected:
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<a1:Person id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/ConsoleApp/ConsoleApp%2C%20Version%3D22.214.171.124%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<my_enum>V</my_enum>
<my_bool>false</my_bool>
</a1:Person>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

After reading:

https://learn.microsoft.com/en-us/dotnet/standard/serialization/how-to-serialize-an-object-as-a-soap-encoded-xml-stream

and:

https://learn.microsoft.com/en-us/dotnet/standard/serialization/attributes-that-control-encoded-soap-serialization

and also:

https://github.com/dotnet/corefx/pull/15352

I tried:
static void Main(string[] args)
{
    Person p = new Person();
    using (FileStream fs = new FileStream("myfile.soap", FileMode.Create))
    {
        XmlTypeMapping myTypeMapping = new SoapReflectionImporter()
          .ImportTypeMapping(typeof(Person));
        XmlSerializer mySerializer = new XmlSerializer(myTypeMapping);
        mySerializer.Serialize(fs, p);
        fs.Close();
    }
}

Which gives me:
<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1">
  <my_enum xsi:type="E">V</my_enum>
  <my_bool xsi:type="xsd:boolean">false</my_bool>
</Person>

Comment: I said in previous posting the "xsi:type" is being added because of your inherited class.
Answer: It depends which parts you're trying to fix; if it is the namespaces: tell XmlSerializer about them:
// note: this would be [XmlType(...)] if it wasn't the root element
[XmlRoot(Namespace = "http://schemas.microsoft.com/clr/nsassem/ConsoleApp/ConsoleApp%2C%20Version%3D126.96.36.199%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull")]
public class Person
{
    [XmlElement(Namespace = "")]
    public E my_enum;
    [XmlElement(Namespace = "")]
    public bool my_bool;
}

If it is the namespace-alias (although that doesn't change the meaning):
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("a1", "http://schemas.microsoft.com/clr/nsassem/ConsoleApp/ConsoleApp%2C%20Version%3D18.104.22.168%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull");
XmlSerializer mySerializer = new XmlSerializer(typeof(Person));
mySerializer.Serialize(fs, p, ns);

If it is the wrapper nodes: you'll need to add those, perhaps via types, perhaps manually as fixup.
However, fundamentally XmlSerializer and SoapFormatter are not 1:1 interchangeable, and you shouldn't attempt to make them so. Honestly, it would be safer to think of it as a fundamental serialization switch, than to try and hack it until it kinda-sorta works.
Comment: Thanks ! I'll check if I can read legacy SoapFormatter serialized data in my new app using your solution.

SoapFormatter in .NET Core 3.1?


python - how to run background thread without stopping main thread

Question: This simple code example:
import threading
import time

class Monitor():

    def __init__(self):
        self.stop = False
        self.blocked_emails = []

    def start_monitor(self):
        print("Run start_monitor")
        rows = []
        while not self.stop:
            self.check_rows(rows)
            print("inside while")
            time.sleep(1)

    def check_rows(self, rows):
        print('check_rows')

    def stop_monitoring(self):
        print("Run stop_monitoring")
        self.stop = True

if __name__ == '__main__':
    monitor = Monitor()

    b = threading.Thread(name='background_monitor', target=monitor.start_monitor())
    b.start()
    b.join()

    for i in range(0, 10):
        time.sleep(2)
        print('Wait 2 sec.')
    monitor.stop_monitoring()

How can I run background thread, in mine case background_monitor without blocking main thread?
I wanted to background_monitor thread stopped on after stop_monitoring will be called
I mine example, the for loop from main thread never called and the background is running forever.
Answer: There are two issues with your current code. Firstly, you're calling monitor.start_monitor on this line, whereas according to the docs

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called

This means that you need to pass it as a function rather than calling it. To fix this, you should change the line
b = threading.Thread(name='background_monitor', target=monitor.start_monitor())

to
b = threading.Thread(name='background_monitor', target=monitor.start_monitor)

which passes the function as an argument.
Secondly, you use b.join() before stopping the thread, which waits for the second thread to finish before continuing. Instead, you should place that below the monitor.stop_monitoring().
The corrected code looks like this:
import threading
import time

class Monitor():

    def __init__(self):
        self.stop = False
        self.blocked_emails = []

    def start_monitor(self):
        print("Run start_monitor")
        rows = []
        while not self.stop:
            self.check_rows(rows)
            print("inside while")
            time.sleep(1)

    def check_rows(self, rows):
        print('check_rows')

    def stop_monitoring(self):
        print("Run stop_monitoring")
        self.stop = True

if __name__ == '__main__':
    monitor = Monitor()

    b = threading.Thread(name='background_monitor', target=monitor.start_monitor)
    b.start()

    for i in range(0, 10):
        time.sleep(2)
        print('Wait 2 sec.')
    monitor.stop_monitoring()
    b.join()

Comment: Looks like I did something wrong last time. it works now. thanks
Comment: I have changed code as you described but looks like nothing changed, I see only ```inside while``` as output. the text ```Wait 2 sec.``` doesn't appear
Comment: @Roman hmmmm... that's strange. It seems to work in my tests (https://repl.it/@minion3665/background-threads#main.py). Can you put up a link with your code (in repl.it or similar) so that I can try and see what's going wrong


Factoring with integer coefficients vs factoring with real coefficients

Question: What is the difference between factoring with integer coefficients and factoring with real coefficients? Although the answer to this question probably sounds pretty obvious, I'm not sure how my answer changes in the question below.
If I was to factor $$3x^5-x^4-3x^3+x^2-6x+2$$
with integer coefficients, the answer is $$(3x-1)(x^2-2)(x^2+1)$$
How does my answer change if I am factoring with real (not necessarily integer) coefficients?
Comment: If you allow real coefficients, you can factorize further : $3(x-\frac{1}{3})(x-\sqrt{2})(x+\sqrt{2})(x^2+1)$.
Comment: Only $x^2-2$ would change to $(x-\sqrt 2)(x+\sqrt 2)$ (and $x^2+1$ to $(x-i)(x+i)$ if you factor with coefficients in $\bf C$).
Answer: Factoring over the integers, we see that $$3x^5 - x^4 - 3x^3 + x^2 - 6x + 2 = (3x - 1)(x^2 - 2)(x^2 + 1).$$ Factoring over the reals, we see that $$3x^5 - x^4 - 3x^3 + x^2 - 6x + 2 = 3(x - 1/3)(x - \sqrt{2})(x + \sqrt{2})(x^2 + 1).$$
Factoring over the complex numbers, we have $$3x^5 - x^4 - 3x^3 + x^2 - 6x + 2 = 3(x - 1/3)(x - \sqrt{2})(x + \sqrt{2})(x + i)(x - i).$$
Comment: For your second case, do you mean reals rather than rationals?  $\sqrt2$ is not rational.
Comment: @badjohn No, it should've been reals.


How to capture an image remotely using Hyper-V?

Question: I have a VM which I am accessing locally. To convert the VHDX to a WIM, I have found a number of powershell commands to do this and it works perfectly.
However, I want to do this when I do NOT have access to the host OS of the VM (i.e. I am working remotely). Would I need to do the same with powershell but running powershell remotely or are there other ways/tools to do this?
If you could list the options/steps that would be great.
I am building a custom Windows 10 image.
Answer: I think you have answered you won question. If you have PowerShell commands that already work to covert a .vhdx to .WIM then id stick with them. Either user Enter-PSSession to access a remote PowerShell session (you will need to make sure PSRemoting is enabled on the remote Host server) or use the Invoke-Command command to run a command remotely.
Invoke-Command
https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/invoke-command
Enter-PSSession
https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/enter-pssession


Uniform convergence of a sequence on limited t range

Question: Hi I know the following sequence converges pointwise to $t$ from the limit but I am not sure if it converges uniformly for $t \in [0,1]$ and $n≥1$
$$f_n(t)= \frac {nt}{n+t}$$
I have found $|f_n(t)-f(t)|$ to be $$\frac {-t^2}{n+t}$$
But I am not sure how to get to uniform convergence from here.
I believe it converges to $t$ uniformly, but could someone please clarify?
Comment: You recieved an answer to your question. Is it what you needed? If so, you should upvote and accept it.
Answer: First of all, a minor mistake, your calculation $$|f_n(t)-f(t)|=\frac{-t^2}{n+t}$$ is wrong. For example, for $n=1,t=1$, the left side equals
$$\left|\frac{1\cdot 1}{1+1} - 1\right| = \left|\frac12\right|=\frac12$$ while the right side equals $$\frac{-1^2}{1+1}=-\frac12$$ Similar, but not the same :)

You are almost there. Remember, convergence is uniform if, for all $\epsilon$, there exists some $N$ such that $\sup_{t\in[0,1]} |f_n(t)-f(t)| < \epsilon$ for all $n>N$.
In your case, the supremum becomes a maximum, and you already (almost) calculated $|f_n(t)-f(t)|$. The fact that $$\frac{t^2}{n+t} \leq \frac{1}{n+t}\leq \frac1n$$ should help you through the final steps.
Comment: Does $ \frac {-t^2}{n+t}$ being negative affect this? Also I'm not quite sure how to find the supremum on [0,1] or pick a suitable n. Could you please help me with this?
Comment: @MathExchange123 Please, carefully read the first part of my answer.
Comment: Thank you, I missed that the first time.


Exercicio: transformar decimal para binario e encontrar 1's

Question:
<code>#include<stdio.h>

int main()
{
int k,repeticao;
int valor, numero;
int paridade = 0;
scanf("%d", &repeticao);

for( k = 0; k < repeticao; k++ ){
    int numero,sequencia;
    scanf("%lld", &numero);
    valor = numero/2;
    while( valor != 0 ){
        sequencia = numero%2;
        if( sequencia == 1)
        {
            paridade++;
        }
        numero = valor;
        valor = numero/2;
        if (valor == 0)
    {
        paridade++;
    }

    }

    printf("%d\n", paridade);
    paridade = 0;
}
return 0;

}
</code>
O meu código está funcionando para as duas entradas dada no exemplo: 3 e 21, mas na terceira entrada ele retorna 15, ao invés de 50.
essa terceira entrada é a repetição de 1 a 9 (3 vezes), sendo que quando eu repito ela duas vezes(123456789123456789)  a minha saída é 1( errado também) quando coloco apenas uma repetição(123456789) minha saida sai correta ( 16). Podem me ajudar, por favor?
Comment: Você quer só contar os bits 1 de um inteiro? Acho que o código para fazer isso é bem mais simples. Basta fazer divisões sucessivas e contar quando houver resto.
Comment: Mas eu estou fazendo divisões sucessivas e quando o resto for 1 eu estou incrementando a variável "paridade". Deve existir um jeito mais simples, mas eu não conseguir enxergar, também gostaria de saber o motivo de não funcionar para todos os casos do jeito que está aí.
Comment: Vou postar minha solução.
Comment: Em Python seria muito fácil fazer isso porque as variáveis não tem tamanho definido, já em C acredito que não seja possível, nem o double suporta um número com tantos dígitos, o maior número suportado tem 16/17 dígitos já que é uma variável de 8 bytes. Assim não seria possível resolver esse caso.
Comment: @LuanPrado: Não diga "em C não é possível", não; é só fazer como Python faz e usar uma biblioteca de precisão arbitrária, como a [GMP](https://gmplib.org/) e a [MPFR](http://www.mpfr.org/). Aliás, [eis uma lista](https://en.wikipedia.org/wiki/List_of_arbitrary-precision_arithmetic_software).
Answer: Eis uma solução simplificada e devidamente comentada para determinar o número de bits de um inteiro. Como se trata de um exercício e não de um problema prático. Recomendo que estude o código e entenda o seu funcionamento.
<code>#include<stdio.h>

int main()
{
//variavel que recebera o inteiro
int a;
scanf("%d", &a);
//contador de bits setados como 1
int p = 0;

//enquanto a for maior que zero...
while (a > 0) {
    //verifica se a é impar
    if (a%2!=0) {
        p++;
    }
    //realiza divisões sucessivas
    a = a/2;

}

printf("Saída:%d",p);

}
</code>
Atualização:
O cálculo não funciona para o terceiro caso, pois o valor extrapola a capacidade de armazenamento do int, long, long long int....

prog.cpp:7:32: warning: integer constant is too large for its type
       unsigned long long int a = 123456789123456789123456789;
Comment: quando eu coloco a terceira entrada do exercicio ( 123456789123456789123456789) está com o mesmo erro que o meu codigo tinha: diz que são 15 ao invés de 50 bits  1
Comment: A sim, ocorre um overflow. Nesse caso o problema não está na sua solução e sim na capacidade de armazenamento do inteiro. Tenta utilizar long int.
Comment: se eu usar long int, qual flag eu devo usar?
Comment: vou adaptar a solução para calcular o número do enunciado.
Comment: Testei com unsigned long long int e esta retornando 35. Não estou conseguindo reproduzir esse calculo em algum lugar para confirmar se são 50 1s mesmo.
Comment: Achei muito estranho esse comportamento... mas de qualquer forma ,muito obrigado pela ajuda
Comment: Será que quem propôs esse enunciado verificou a viabilidade de fazer isso em C? ... ou talvez há outra técnica que eu desconheço.


LINQ Query Not Selecting Files

Question: I am trying to LINQ query a set of files where I can find the file names with a specific string in them.
I was using:
var docs = directory.enumerateFiles(searchFolder, "* " + strNumber+ "*", SearchOption.AllDirectories);

That was working fine, but some of my file searches were taking 30+ minutes due to the fact that one of the directories has 1+ million files. I was hoping to speed up the search process with a PLINQ query. However, while my syntax is good, I'm not getting the results I would expect. It looks like my problem may be in the Where statement. Any help would be helpful.
foreach (strNumber in strNumbers)
{
    DirectoryInfo searchDirectory = new DirectoryInfo(searchFolder);
    IEnumerable<System.IO.FileInfo> allDocs = searchDirectory.EnumerateFiles("*", SearchOPtion.AllDirectories);

    IEnumerable<System.IO.FileInfo> docsToProcess = strNumbers
        .SelectMany(strNumber => allDocs
        .Where(file => file.Name.Contains(strNumber)))
        .Distinct();
}

Any help would be much appreciated.
Comment: With that many files you will probably need to utilize an indexing solution, like maybe Lucene.Net.
Comment: What is the difference in the results you are getting and the results you expect?
Comment: I am not getting any results. I am expecting to get any document with the strNumber in it to be collected so I can use it like below.
Comment: foreach (var docToProcess in docsToProcess) {}
Comment: So for example, before I was getting xxx_strNumber_xxx.docs and now I'm not getting any of those documents.
Answer: I would change the order of the problem.

Create a list of all files (into memory)
Perform the search over the memory list

Then, you can use a Parallel Foreach over the memory array and your disk usage is limited to the initial search.
var searchDirectory = new DirectoryInfo(searchFolder);
var allDocs = searchDirectory.EnumerateFiles("*", SearchOPtion.AllDirectories).ToArray();

// For extra points, use a Parallel.ForEach here for multi-threaded work
Parallel.Foreach(strNumbers, strNumber =>
{
   // Work on allDocs here, it should be in memory
});

Comment: I love the idea of this solution. My concern is that there will be a race issue.  In the Parallel.ForEach statement, I will be creating a string of file names to be used to copy the files found to another folder. I don't know how to negate the race issue. Do you have a suggestion as to how to do that?

For example:

Parallel.Foreach (strNumbers, strNumber =>
{
    // Get string of files to copy
    // Create the roboCopy string (using this to multithread and log the copy procedure)
    // Copy files to new folders
}
Comment: Can always make a List of jobs to perform during the `Parallel.ForEach` and then run the copy operations afterwards?

LINQ Query Not Selecting Files


How can a class be loosely coupled to an application if it is reading from a database and interpreting the results?

Question: As a PHP dev, most of my projects are database-driven. I'm a fond lover of OOP & while new to the object world, I attempt to follow best practices to improve on my abilities.
My burning question
If I have an object that requires information from my database, how is that object loosely coupled because it is heavily reliant on the returning results of the database?
Code example:
<code><?php

class Test {

protected $repository;

public function __construct(Repository $repository)
{
    $this->repository = $repository;
}

public function process()
{
    $results = $this->repository->where('id', 1)->get();

    ( ! empty($results) ) ?: ''; // do something bad.

    foreach ($results as $result) {

        // This is my problem, my class now knows it needs an array key of name to be available.
        // Is this bad?
        echo $result['name'];

    }
}
</code>
}
Here, my class is expecting an array key of name. This just feels wrong to me, because now my class is tightly coupled to the result set...
Layers
I have been doing a lot of reading on application layers, such as the domain layer, service layer, transaction scripts, application layer etc.
Even equipped with this knowledge I cannot see a solution to my problem.
To Finalise
It would be great to hear your thoughts on whether I'm driving myself mad for no reason.
It would also be great to see some code examples or further reading materials, books etc links.
Answer: I think you may be going too extreme with this. I wouldn't spend too much time trying to figure out how the repo can not know that you have a key called name. Someone will have to depend on that somewhere in your code and I don't think your repo class is a bad place to put that.
In the end, your goal should just be to save you and the maintainers of this codebase time when implementing new features, business rules or fixing bugs. And in my experience you can do this by isolating the parts of your application that you can foresee being complex or changing a lot.
So I wouldn't worry about the repo knowing the name of a key in the result set unless that key needed to be changed a lot, or if retrieving data from the result set was going to be a complex process.
Comment: I was slowly going insane with my own thought process, It's a breathe of fresh air to hear that! Thanks.