text:
Q: How do I perform the SQL Join equivalent in MongoDB? How do I perform the SQL Join equivalent in MongoDB?
For example say you have two collections (users and comments) and I want to pull all the comments with pid=444 along with the user info for each.
comments
  { uid:12345, pid:444, comment="blah" }
  { uid:12345, pid:888, comment="asdf" }
  { uid:99999, pid:444, comment="qwer" }

users
  { uid:12345, name:"john" }
  { uid:99999, name:"mia"  }

Is there a way to pull all the comments with a certain field (eg. ...find({pid:444}) ) and the user information associated with each comment in one go?
At the moment, I am first getting the comments which match my criteria, then figuring out all the uid's in that result set, getting the user objects, and merging them with the comment's results. Seems like I am doing it wrong.

A: You can run SQL queries including join on MongoDB with mongo_fdw from Postgres.

A: You have to do it the way you described. MongoDB is a non-relational database and doesn't support joins.

A: With right combination of $lookup, $project and $match, you can join mutiple tables on multiple parameters. This is because they can be chained multiple times.
Suppose we want to do following (reference)
SELECT S.* FROM LeftTable S
LEFT JOIN RightTable R ON S.ID = R.ID AND S.MID = R.MID
WHERE R.TIM > 0 AND S.MOB IS NOT NULL

Step 1: Link all tables
you can $lookup as many tables as you want.
$lookup - one for each table in query
$unwind - correctly denormalises data , else it'd be wrapped in arrays
Python code..
db.LeftTable.aggregate([
                        # connect all tables

                        {"$lookup": {
                          "from": "RightTable",
                          "localField": "ID",
                          "foreignField": "ID",
                          "as": "R"
                        }},
                        {"$unwind": "R"}

                        ])

Step 2: Define all conditionals
$project : define all conditional statements here, plus all the variables you'd like to select.
Python Code..
db.LeftTable.aggregate([
                        # connect all tables

                        {"$lookup": {
                          "from": "RightTable",
                          "localField": "ID",
                          "foreignField": "ID",
                          "as": "R"
                        }},
                        {"$unwind": "R"},

                        # define conditionals + variables

                        {"$project": {
                          "midEq": {"$eq": ["$MID", "$R.MID"]},
                          "ID": 1, "MOB": 1, "MID": 1
                        }}
                        ])

Step 3: Join all the conditionals
$match - join all conditions using OR or AND etc. There can be multiples of these.
$project: undefine all conditionals
Complete Python Code..
db.LeftTable.aggregate([
                        # connect all tables

                        {"$lookup": {
                          "from": "RightTable",
                          "localField": "ID",
                          "foreignField": "ID",
                          "as": "R"
                        }},
                        {"$unwind": "$R"},

                        # define conditionals + variables

                        {"$project": {
                          "midEq": {"$eq": ["$MID", "$R.MID"]},
                          "ID": 1, "MOB": 1, "MID": 1
                        }},

                        # join all conditionals

                        {"$match": {
                          "$and": [
                            {"R.TIM": {"$gt": 0}},
                            {"MOB": {"$exists": True}},
                            {"midEq": {"$eq": True}}
                        ]}},

                        # undefine conditionals

                        {"$project": {
                          "midEq": 0
                        }}

                        ])

Pretty much any combination of tables, conditionals and joins can be done in this manner.

A: As of Mongo 3.2 the answers to this question are mostly no longer correct. The new $lookup operator added to the aggregation pipeline is essentially identical to a left outer join:
https://docs.mongodb.org/master/reference/operator/aggregation/lookup/#pipe._S_lookup
From the docs:
{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

Of course Mongo is not a relational database, and the devs are being careful to recommend specific use cases for $lookup, but at least as of 3.2 doing join is now possible with MongoDB.

A: MongoDB does not allow joins, but you can use plugins to handle that. Check the mongo-join plugin. It's the best and I have already used it. You can install it using npm directly like this npm install mongo-join. You can check out the full documentation with examples.
(++) really helpful tool when we need to join (N) collections
(--) we can apply conditions just on the top level of the query
Example
var Join = require('mongo-join').Join, mongodb = require('mongodb'), Db = mongodb.Db, Server = mongodb.Server;
db.open(function (err, Database) {
    Database.collection('Appoint', function (err, Appoints) {

        /* we can put conditions just on the top level */
        Appoints.find({_id_Doctor: id_doctor ,full_date :{ $gte: start_date },
            full_date :{ $lte: end_date }}, function (err, cursor) {
            var join = new Join(Database).on({
                field: '_id_Doctor', // <- field in Appoints document
                to: '_id',         // <- field in User doc. treated as ObjectID automatically.
                from: 'User'  // <- collection name for User doc
            }).on({
                field: '_id_Patient', // <- field in Appoints doc
                to: '_id',         // <- field in User doc. treated as ObjectID automatically.
                from: 'User'  // <- collection name for User doc
            })
            join.toArray(cursor, function (err, joinedDocs) {

                /* do what ever you want here */
                /* you can fetch the table and apply your own conditions */
                .....
                .....
                .....

                resp.status(200);
                resp.json({
                    "status": 200,
                    "message": "success",
                    "Appoints_Range": joinedDocs,

                });
                return resp;

            });

    });

A: You can do it using the aggregation pipeline, but it's a pain to write it yourself.
You can use mongo-join-query to create the aggregation pipeline automatically from your query.
This is how your query would look like:
const mongoose = require("mongoose");
const joinQuery = require("mongo-join-query");

joinQuery(
    mongoose.models.Comment,
    {
        find: { pid:444 },
        populate: ["uid"]
    },
    (err, res) => (err ? console.log("Error:", err) : console.log("Success:", res.results))
);

Your result would have the user object in the uid field and you can link as many levels deep as you want. You can populate the reference to the user, which makes reference to a Team, which makes reference to something else, etc..
Disclaimer: I wrote mongo-join-query to tackle this exact problem.

A: You can join two collection in Mongo by using lookup which is offered in 3.2 version. In your case the query would be
db.comments.aggregate({
    $lookup:{
        from:"users",
        localField:"uid",
        foreignField:"uid",
        as:"users_comments"
    }
})

or you can also join with respect to users then there will be a little change as given below.
db.users.aggregate({
    $lookup:{
        from:"comments",
        localField:"uid",
        foreignField:"uid",
        as:"users_comments"
    }
})

It will work just same as left and right join in SQL.

A: As others have pointed out you are trying to create a relational database from none relational database which you really don't want to do but anyways, if you have a case that you have to do this here is a solution you can use. We first do a foreach find on collection A( or in your case users) and then we get each item as an object then we use object property (in your case uid) to lookup in our second collection (in your case comments) if we can find it then we have a match and we can print or do something with it.
Hope this helps you and good luck :)
db.users.find().forEach(
function (object) {
    var commonInBoth=db.comments.findOne({ "uid": object.uid} );
    if (commonInBoth != null) {
        printjson(commonInBoth) ;
        printjson(object) ;
    }else {
        // did not match so we don't care in this case
    }
});

A: Here's an example of a "join" * Actors and Movies collections:
https://github.com/mongodb/cookbook/blob/master/content/patterns/pivot.txt
It makes use of .mapReduce() method
* join - an alternative to join in document-oriented databases

A: We can merge/join all data inside only one collection with a easy function in few lines using the mongodb client console, and now we could be able of perform the desired query.
Below a complete example,
.- Authors:
db.authors.insert([
    {
        _id: 'a1',
        name: { first: 'orlando', last: 'becerra' },
        age: 27
    },
    {
        _id: 'a2',
        name: { first: 'mayra', last: 'sanchez' },
        age: 21
    }
]);

.- Categories:
db.categories.insert([
    {
        _id: 'c1',
        name: 'sci-fi'
    },
    {
        _id: 'c2',
        name: 'romance'
    }
]);

.- Books
db.books.insert([
    {
        _id: 'b1',
        name: 'Groovy Book',
        category: 'c1',
        authors: ['a1']
    },
    {
        _id: 'b2',
        name: 'Java Book',
        category: 'c2',
        authors: ['a1','a2']
    },
]);

.- Book lending
db.lendings.insert([
    {
        _id: 'l1',
        book: 'b1',
        date: new Date('01/01/11'),
        lendingBy: 'jose'
    },
    {
        _id: 'l2',
        book: 'b1',
        date: new Date('02/02/12'),
        lendingBy: 'maria'
    }
]);

.- The magic:
db.books.find().forEach(
    function (newBook) {
        newBook.category = db.categories.findOne( { "_id": newBook.category } );
        newBook.lendings = db.lendings.find( { "book": newBook._id  } ).toArray();
        newBook.authors = db.authors.find( { "_id": { $in: newBook.authors }  } ).toArray();
        db.booksReloaded.insert(newBook);
    }
);

.- Get the new collection data:
db.booksReloaded.find().pretty()

.- Response :)
{
    "_id" : "b1",
    "name" : "Groovy Book",
    "category" : {
        "_id" : "c1",
        "name" : "sci-fi"
    },
    "authors" : [
        {
            "_id" : "a1",
            "name" : {
                "first" : "orlando",
                "last" : "becerra"
            },
            "age" : 27
        }
    ],
    "lendings" : [
        {
            "_id" : "l1",
            "book" : "b1",
            "date" : ISODate("2011-01-01T00:00:00Z"),
            "lendingBy" : "jose"
        },
        {
            "_id" : "l2",
            "book" : "b1",
            "date" : ISODate("2012-02-02T00:00:00Z"),
            "lendingBy" : "maria"
        }
    ]
}
{
    "_id" : "b2",
    "name" : "Java Book",
    "category" : {
        "_id" : "c2",
        "name" : "romance"
    },
    "authors" : [
        {
            "_id" : "a1",
            "name" : {
                "first" : "orlando",
                "last" : "becerra"
            },
            "age" : 27
        },
        {
            "_id" : "a2",
            "name" : {
                "first" : "mayra",
                "last" : "sanchez"
            },
            "age" : 21
        }
    ],
    "lendings" : [ ]
}

I hope this lines can help you.

A: This page on the official mongodb site addresses exactly this question:
https://mongodb-documentation.readthedocs.io/en/latest/ecosystem/tutorial/model-data-for-ruby-on-rails.html

When we display our list of stories, we'll need to show the name of the user who posted the story. If we were using a relational database, we could perform a join on users and stores, and get all our objects in a single query. But MongoDB does not support joins and so, at times, requires bit of denormalization. Here, this means caching the 'username' attribute.
Relational purists may be feeling uneasy already, as if we were violating some universal law. But let's bear in mind that MongoDB collections are not equivalent to relational tables; each serves a unique design objective. A normalized table provides an atomic, isolated chunk of data. A document, however, more closely represents an object as a whole. In the case of a social news site, it can be argued that a username is intrinsic to the story being posted.

A: $lookup (aggregation)

Performs a left outer join to an unsharded collection in the same database to filter in documents from the "joined" collection for processing. To each input document, the $lookup stage adds a new array field whose elements are the matching documents from the "joined" collection. The $lookup stage passes these reshaped documents to the next stage.
The $lookup stage has the following syntaxes:

Equality Match

To perform an equality match between a field from the input documents with a field from the documents of the "joined" collection, the $lookup stage has the following syntax:

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

The operation would correspond to the following pseudo-SQL statement:
SELECT *, <output array field>
FROM collection
WHERE <output array field> IN (SELECT <documents as determined from the pipeline>
                               FROM <collection to join>
                               WHERE <pipeline> );

Mongo URL

A: There is a specification that a lot of drivers support that's called DBRef.

DBRef is a more formal specification for creating references between documents.  DBRefs (generally) include a collection name as well as an object id.  Most developers only use DBRefs if the collection can change from one document to the next.  If your referenced collection will always be the same, the manual references outlined above are more efficient.

Taken from MongoDB Documentation: Data Models > Data Model Reference >
Database References

A: It depends on what you're trying to do.
You currently have it set up as a normalized database, which is fine, and the way you are doing it is appropriate.
However, there are other ways of doing it.
You could have a posts collection that has imbedded comments for each post with references to the users that you can iteratively query to get.  You could store the user's name with the comments, you could store them all in one document.
The thing with NoSQL is it's designed for flexible schemas and very fast reading and writing.  In a typical Big Data farm the database is the biggest bottleneck, you have fewer database engines than you do application and front end servers...they're more expensive but more powerful, also hard drive space is very cheap comparatively.  Normalization comes from the concept of trying to save space, but it comes with a cost at making your databases perform complicated Joins and verifying the integrity of relationships, performing cascading operations.  All of which saves the developers some headaches if they designed the database properly.
With NoSQL, if you accept that redundancy and storage space aren't issues because of their cost (both in processor time required to do updates and hard drive costs to store extra data), denormalizing isn't an issue (for embedded arrays that become hundreds of thousands of items it can be a performance issue, but most of the time that's not a problem).  Additionally you'll have several application and front end servers for every database cluster.  Have them do the heavy lifting of the joins and let the database servers stick to reading and writing.
TL;DR: What you're doing is fine, and there are other ways of doing it.  Check out the mongodb documentation's data model patterns for some great examples. http://docs.mongodb.org/manual/data-modeling/

A: Before 3.2.6, Mongodb does not support join query as like mysql. below solution which works for you.
 db.getCollection('comments').aggregate([
        {$match : {pid : 444}},
        {$lookup: {from: "users",localField: "uid",foreignField: "uid",as: "userData"}},
   ])

A: playORM can do it for you using S-SQL(Scalable SQL) which just adds partitioning such that you can do joins within partitions.

A: We can merge two collection by using mongoDB sub query. Here is example,
Commentss--
`db.commentss.insert([
  { uid:12345, pid:444, comment:"blah" },
  { uid:12345, pid:888, comment:"asdf" },
  { uid:99999, pid:444, comment:"qwer" }])`

Userss--
db.userss.insert([
  { uid:12345, name:"john" },
  { uid:99999, name:"mia"  }])

MongoDB sub query for JOIN--
`db.commentss.find().forEach(
    function (newComments) {
        newComments.userss = db.userss.find( { "uid": newComments.uid } ).toArray();
        db.newCommentUsers.insert(newComments);
    }
);`

Get result from newly generated Collection--
db.newCommentUsers.find().pretty()

Result--
`{
    "_id" : ObjectId("5511236e29709afa03f226ef"),
    "uid" : 12345,
    "pid" : 444,
    "comment" : "blah",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f2"),
            "uid" : 12345,
            "name" : "john"
        }
    ]
}
{
    "_id" : ObjectId("5511236e29709afa03f226f0"),
    "uid" : 12345,
    "pid" : 888,
    "comment" : "asdf",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f2"),
            "uid" : 12345,
            "name" : "john"
        }
    ]
}
{
    "_id" : ObjectId("5511236e29709afa03f226f1"),
    "uid" : 99999,
    "pid" : 444,
    "comment" : "qwer",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f3"),
            "uid" : 99999,
            "name" : "mia"
        }
    ]
}`

Hope so this will help.

A: I think, if You need normalized data tables  - You need to try some other database solutions.
But I've foun that sollution for MOngo on Git
By the way, in inserts code - it has movie's name, but noi movie's ID.
Problem
You have a collection of Actors with an array of the Movies they've done.
You want to generate a collection of Movies with an array of Actors in each.
Some sample data
 db.actors.insert( { actor: "Richard Gere", movies: ['Pretty Woman', 'Runaway Bride', 'Chicago'] });
 db.actors.insert( { actor: "Julia Roberts", movies: ['Pretty Woman', 'Runaway Bride', 'Erin Brockovich'] });

Solution
We need to loop through each movie in the Actor document and emit each Movie individually.
The catch here is in the reduce phase. We cannot emit an array from the reduce phase, so we must build an Actors array inside of the "value" document that is returned.

The code

map = function() {
  for(var i in this.movies){
    key = { movie: this.movies[i] };
    value = { actors: [ this.actor ] };
    emit(key, value);
  }
}

reduce = function(key, values) {
  actor_list = { actors: [] };
  for(var i in values) {
    actor_list.actors = values[i].actors.concat(actor_list.actors);
  }
  return actor_list;
}

Notice how actor_list is actually a javascript object that contains an array. Also notice that map emits the same structure.
Run the following to execute the map / reduce, output it to the "pivot" collection and print the result:
printjson(db.actors.mapReduce(map, reduce, "pivot"));
  db.pivot.find().forEach(printjson);
Here is the sample output, note that "Pretty Woman" and "Runaway Bride" have both "Richard Gere" and "Julia Roberts".
{ "_id" : { "movie" : "Chicago" }, "value" : { "actors" : [ "Richard Gere" ] } }
{ "_id" : { "movie" : "Erin Brockovich" }, "value" : { "actors" : [ "Julia Roberts" ] } }
{ "_id" : { "movie" : "Pretty Woman" }, "value" : { "actors" : [ "Richard Gere", "Julia Roberts" ] } }
{ "_id" : { "movie" : "Runaway Bride" }, "value" : { "actors" : [ "Richard Gere", "Julia Roberts" ] } }

A: Nope, it doesn't seem like you're doing it wrong.  MongoDB joins are "client side".  Pretty much like you said:

At the moment, I am first getting the comments which match my criteria, then figuring out all the uid's in that result set, getting the user objects, and merging them with the comment's results. Seems like I am doing it wrong.

1) Select from the collection you're interested in.
2) From that collection pull out ID's you need
3) Select from other collections
4) Decorate your original results.

It's not a "real" join, but it's actually alot more useful than a SQL join because you don't have to deal with duplicate rows for "many" sided joins, instead your decorating the originally selected set.
There is alot of nonsense and FUD on this page.  Turns out 5 years later MongoDB is still a thing.


text:
Q: How to plot a line between two points in a scatter3 plot in MATLAB? I am using the following code for producing a scatter3 plot:
X = [1,2,3,1,2,3,1,2,3,1,2,3,1,2,3];
Y = [0,0,0,20,20,20,40,40,40,60,60,60,80,80,80,];
Z1 = [10,-48.7863,-73.3457, -68.3091, -142.0666,...
      12, -35.7863, -23.347, -29.3091,-141.0660,...
      13,3.2137,-10.3457,-33.3091,-128.0666]
Z2 = [2,8.2137,-2.3457, 46.6909, 12.9334,...
      10,11.2137, 19.6543,35.6909, 45.9334,...
       -1,16.2137,37.6543,50.6909,34.9334]

figure;scatter3(X,Y,Z1,'filled'); hold on;
scatter3(X,Y,Z2,'filled')

Which results in the following image:

What I would like to have is a vertical line between each blue and red dot.
An exemplary output could look like this:

I tried using the line function, however I am not sure how to build up the vector.
I tried:
line(X,Y,Z1) % will only connect the blue dots
line(X,Y,Z2) % will only connect the red dots

line(X,Y,Z1:Z2) % will give an error that the vectors must be the same length

A: You must vertically concatenate your Z1 and Z2 data so that each column defines a line to plot. You will also have to replicate X and Y in the same way:
line([X; X], [Y; Y], [Z1; Z2], 'Color', 'r');

And the result (added to your scatter plot):

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access preferences from different ViewModels I have SettingsViewModel with:
  public class SettingsViewModel : BaseViewModel, ISettingsViewModel
  {
    public SettingsViewModel()
    {
    }

    private string _gaugeColor;
    public string GaugeColor
    {
      get => Preferences.Get("GaugeColor", "#17805d");
      set
      {
        Preferences.Set("GaugeColor", value);
        this.OnSettingsChanged();
        this.OnPropertyChanged();
      }
    }

    public event EventHandler<SettingsChangedEventArgs> SettingsChanged;
    private void OnSettingsChanged() => this.SettingsChanged?.Invoke(this, new SettingsChangedEventArgs(this.Settings));

    public Settings Settings { get; private set; }
  }
}

I set color by HEX string.
Then in PanelViewModel I have:
private Color _gaugeColor;
public Color GaugeColor
{
  get => Color.FromHex(Preferences.Get("GaugeColor", "#17805d"));
  set
  {
    _gaugeColor = value;
    OnPropertyChanged();
  }
}

Now if I change HEX string from Settings view in UI, color does not change in PanelViewModel until I restart an application.
Question is: How to make color change in PanelViewModel right after it has been changed in SettingsViewModel?
I have tried to add this into PanelViewModel, but apparently this creates a new instance of SettingsViewModel and Color does not follow into PanelViewMode. Maybe there is some direct solution and I am using Xamarin.Essentials wrong?
public PanelViewModel()
{
  this.SettingsViewModel = new SettingsViewModel();
  this.SettingsViewModel.SettingsChanged += OnSettingsChanged;
}

private Color _gaugeColor;
public Color GaugeColor
{
  get => Color.FromHex(Preferences.Get("GaugeColor", "#17805d"));
  set
  {
    _gaugeColor = value;
    OnPropertyChanged();
  }
}

private void OnSettingsChanged(object sender, SettingsChangedEventArgs e)
{
  this.GaugeColor = Color.FromHex(e.Settings.GaugeColor);
}

private SettingsViewModel SettingsViewModel { get; }

https://learn.microsoft.com/en-us/dotnet/api/xamarin.essentials.preferences?view=xamarin-essentials

A:
Question is: How to make color change in PanelViewModel right after it
has been changed in SettingsViewModel?

Yes, a simple method is to use  MessagingCenter.
The MessagingCenter class implements the publish-subscribe pattern, allowing message-based communication between components that are inconvenient to link by object and type references. This mechanism allows publishers and subscribers to communicate without having a reference to each other, helping to reduce dependencies between them.
You can refer to the following code:
In SettingsViewModel.cs, we can publish a message in the constuctor of it,just as follows:
public class SettingsViewModel
{
    public string Title { get; set; }

    public SettingsViewModel() {

        Title = "SettingsView";

        MessagingCenter.Send<Object, Color>(this, "Hi", Color.Yellow);
    }

}

And in PanelViewModel.cs ,we can subscribe to this message:
public class PanelViewModel
{
    public string Title { get; set; }

    public PanelViewModel() {

        Title = "PanelView";

         MessagingCenter.Subscribe<Object, Color>(this, "Hi", async (sender, arg) =>
        {
            System.Diagnostics.Debug.WriteLine("----->  receive color= " + arg);

         // here ,we can use the received color to update the UI

        });
    }

}

Note:
Once we receive the color, we can use the received color to update the UI, and the  color field in the  PanelViewModel.cs  should implement interface INotifyPropertyChanged.


text:
Q: Convert String 'shorter' to 'short' using Python nltk stem package I am trying to extract the stem of the words taller and shorter from  a string in python.
I did the following:
>>> from nltk.stem.porter import *
>>> print(stemmer.stem('shorter'))
shorter
>>> print(stemmer.stem('taller'))
taller

And for some reason, I don't get the words tall and short. Anyone knows how to possibly fix this, or possibly guide to an alternative solution?

A: There are a few stemmers.  Here's one:
>>> from nltk.stem.lancaster import LancasterStemmer
>>> stemmer = LancasterStemmer()
>>> stemmer.stem('shorter')
'short'

A: >>> from nltk import stem
>>> s = 'short'; t = 'tall'
>>> porter = stem.porter.PorterStemmer()
>>> lancaster = stem.lancaster.LancasterStemmer()
>>> snowball = stem.snowball.EnglishStemmer()
>>> porter.stem(s)
u'short'
>>> porter.stem(t)
u'tall'
>>> lancaster.stem(s)
'short'
>>> lancaster.stem(t)
'tal'
>>> snowball.stem(s)
u'short'
>>> snowball.stem(t)
u'tall'


text:
Q: Thread Safety with Template Tags After reading this document about thread safety, I am left feeling that there is something missing in the documentation, or my reading of it, or my reasoning.
Let's give a simple example:
class HelloWorldNode(template.Node):
    def render(self, context):
        return "O HAI LOL"

@register.tag(name="hello_world")
def hello_world(parser, tokens):
    """
    Greets the world with wide-eyed awe.
    """
    return HelloWorldNode()

I understood this code to construct a new instance of the HelloWorldNode class whenever the hello_world tag is used. Other examples involve passing arguments to the constructor, like this:
class HelloWorldNode(template.Node):
    def __init__(self, message):
        self.message = message

    def render(self, context):
        return "O HAI LOL " + message

@register.tag(name="hello_world")
def hello_world(parser, tokens):
    """
    Greets the world with wide-eyed awe.
    """

    message = tokens.split_contents()[1]

    return HelloWorldNode(message)

Thus, when hello_world is executed, a new instance of HelloWorldNode is created, and the instance dictionary has an attribute message. This instance surely must be used only for the rendering of only the given instance of the tag, as using it for other renderings would mean that the data bound to it would be incorrect. If this were not the case, the arguments would get mixed up between different uses of the tag.
Looking at other examples from the docs, here's a simplified example from here:
def do_current_time(parser, token):
    tag_name, format_string = token.split_contents()
    return CurrentTimeNode(format_string[1:-1])

As this takes data from the tokens passed to the function, the only way that CurrentTimeNode can work is that a new one is instantiated each time do_current_time is invoked.
Back to the documentation page, where the dissonance sets in. This is 'bad'.
class CycleNode(Node):
    def __init__(self, cyclevars):
        self.cycle_iter = itertools.cycle(cyclevars)
    def render(self, context):
        return self.cycle_iter.next()

The doc says that two pages using the same tag might then experience race conditions if they both use the same node. I don't understand how two templates' rendering could end up sharing the same instance if they both independently instantiate their own.
The way to solve this, says the docs is like this:
class CycleNode(Node):
    def __init__(self, cyclevars):
        self.cyclevars = cyclevars
    def render(self, context):
        if self not in context.render_context:
            context.render_context[self] = itertools.cycle(self.cyclevars)
        cycle_iter = context.render_context[self]
        return cycle_iter.next()

This appears to index context.render_context with self. The implication of that must be that self is used to identify the instance in one of two ways:

*

*self references one specific instance of the class in the whole system

*self references that class only, and in order to reference the instance a render context is required

If 1 is true, why not just associate data with self?
If 2 is true, and the render context is "associated with the context of the template that is currently being rendered", how is it possible to distinguish between two instance of the template tag on the same page?
Is the Node instantiated individually each time the tag is invoked? If so, why the concurrency problems? If not, why not?

A: Got it with closer reading of this.
The template is compiled when it is loaded. Any arguments passed into the tag function are 'static'. They are either literal strings, or they are strings which are used as identifiers to look up bound variables in the render context.
Therefore the Node object is instantiated for each tag, and hangs around ready for use whenever the template is used (and naturally the template may be used in any number of threads).
Thus the self in my question is the identity of the specific Node within the template. Combined with the render context, this gives a unique identity on which to hang instance variables.


text:
Q: Moving a component out of ScrollPane - JavaFX I ask for your help because I have a problem with a ScrollPane in JavaFX.
I added a Group into the scrollPane, added the scrollpane to the Scene and finally put it into a JFXPanel because I use it in a Swing application and it's working well, next I added components into the Group (by components I mean an assembly of Nodes like Rectangles, etc ...). That works well, but when I want to move a component out of the scrollpane layout, the movement of the components is uncontrollable, it starts moving really fast and I don't understand why. It starts troubling just when the border of the component touch the border of the scrollpane layout. I tried to use ScrollBar instead but it seems that the ScrollPane is the most suitable object for this.
There is the code I used to create my view :
public void createView() {
    this.architectureJFXPanel = new JFXPanel();
    this.group = new Group();
    this.scrollPane = new ScrollPane();

    this.scrollPane.setContent(group);
    this.scrollPane.setOnKeyPressed(new KeyPressed());

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            Scene scene = new Scene(scrollPane, Color.WHITE);
            architectureJFXPanel.setScene(scene);
        }
   });
}

To put the components into the view I use group.getChildren.add() and after that I put the JFXPanel into the swing application.
Here is an example of what I'm trying to do. You can see that on the picture I try to move the component out of the layout:

So if someone already had this kind of problem and could help me I would be really greatful :) Ask me if you need more informations to understand where is the problem.

A: Here's my work-around for the ScrollPane using ScrollBar.
public void setStyle() {
    // In my program, TextField controls were generate at run-time, so the prefer height is calculated based on number of controls
    int preHeight = 1000;
    Group root = new Group();

    // This anchor pane contains all control.
    AnchorPane anchorPane = new AnchorPane();
    // TODO: Add control into this anchor pane
    // anchorPane.getChildren().addAll();

    final ScrollBar sc = new ScrollBar();
    root.getChildren().addAll(anchorPane, sc);

    // Set default size for scene to 800 x 600
    int sceneW = 800;
    int sceneH = 600;
    final Scene scene = new Scene(root, sceneW, sceneH);

    // Setting for the scroll bar
    sc.setLayoutX(scene.getWidth()- sc.getWidth()/2 - 1);
    sc.setMin(0);
    sc.setOrientation(Orientation.VERTICAL);
    sc.setPrefHeight(sceneH);
    sc.setMax(preHeight - sceneH);

    // In case prefer height is smaller than scene height then hide the scroll bar
    if(preHeight < sceneH) {
        sc.setVisible(false);
    }

    scene.setRoot(root);

    // Change the scroll bar and the anchor pane when user change scene's width
    scene.widthProperty().addListener(new ChangeListener<Number>() {

        @Override
        public void changed(ObservableValue<? extends Number> arg0,
                Number arg1, Number arg2) {
            sc.setLayoutX(arg2.doubleValue()- sc.getWidth()/2 - 1);
            anchorPane.setPrefWidth(arg2.doubleValue() - sc.getWidth());
        }
    });

    // Change the scroll bar and the anchor pane when user change scene's height
    scene.heightProperty().addListener(new ChangeListener<Number>() {

        @Override
        public void changed(ObservableValue<? extends Number> arg0,
                Number arg1, Number arg2) {
            sc.setMax(preHeight - arg2.doubleValue());
            if(arg2.doubleValue() >= preHeight) {
                sc.setVisible(false);
            }
            else {
                sc.setVisible(true);
            }
            sc.setPrefHeight(arg2.doubleValue());
            anchorPane.setPrefHeight(arg2.doubleValue());
        }
    });

    // Change the Y position of anchor pane when user scroll the scroll bar
    sc.valueProperty().addListener(new ChangeListener<Number>() {
        public void changed(ObservableValue<? extends Number> ov,
                Number old_val, Number new_val) {
            anchorPane.setLayoutY(-new_val.doubleValue());
        }
    });

    anchorPane.setPrefSize(scene.getWidth() - sc.getWidth(), scene.getHeight());
}

There's one issue with this approach, that's if user use tab key to navigate between control in the screen then the Y location of the scroll bar will not change to corresponding position. You may solve this issue by handling focus event for focusable controls in the anchor pane and set Y position for the scroll bar accordingly.


text:
Q: Delete row from sql table where values not found in another table with multiple joins I have the following query which returns the desired data.  What I want to do is delete that data, however when I change the Select DQ.* to DELETE FROM DQ, I get an error indicating that

'... not updatable because the modification affects multiple base table'

I need to delete entries from the tbaccess_groupPermission table where appropriate module records are not found in the tbaccess_companyModules table.
WITH DQ AS
(
SELECT GP.* FROM tbaccess_groupPermission GP
JOIN tbaccess_groups G ON GP.GroupID = G.ID
WHERE G.CompanyID=6
AND GP.RoleName NOT IN
(
select Distinct(R.RoleName)
FROM tbAccess_Roles R
INNER JOIN tbAccess_CompanyModules C on R.ModuleID = C.ModuleID
WHERE C.CompanyID = 6)
)
SELECT * FROM DQ

A: Why not change the WITH statement to use an IN clause?
Something like
WITH DQ AS
(
SELECT GP.* FROM tbaccess_groupPermission GP
WHERE GP.GroupID IN (SELECT G.ID FROM tbaccess_groups G WHERE G.CompanyID=6)
AND GP.RoleName NOT IN
(
select Distinct(R.RoleName)
FROM tbAccess_Roles R
INNER JOIN tbAccess_CompanyModules C on R.ModuleID = C.ModuleID
WHERE C.CompanyID = 6)
)


text:
Q: CS1503 C# Argument 1 : cannot convert from 'System.Reflection.Assembly' to 'System.Type' I try to make a discord bot but i get this error:

CS1503 C# Argument 1 : cannot convert from 'System.Reflection.Assembly' to 'System.Type'.

I want to create a discord bot but because of this error I can't run it.

My Code :
using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;

using Discord;
using Discord.Commands;
using Discord.WebSocket;

namespace Risk
{
    class Program
    {
        private DiscordSocketClient Client;
        private CommandService Commands;

        static void Main(string[] args)
            => new Program().MainAsync().GetAwaiter().GetResult();

        private async Task MainAsync()
        {
            Client = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel = LogSeverity.Debug
            });

            Commands = new CommandService(new CommandServiceConfig
            {
                CaseSensitiveCommands = true,
                DefaultRunMode = RunMode.Async,
                LogLevel = LogSeverity.Debug
            });

            Client.MessageReceived += Client_MessageReceived;
            await Commands.AddModuleAsync(Assembly.GetEntryAssembly());

            Client.Ready += Client_Ready;
            Client.Log += Client_Log;

            string Token = "";
            using (var Stream = new FileStream((Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)).Replace(@"bin\Debug\netcoreapp2.0", @"Data\Token.txt"), FileMode.Open, FileAccess.Read))
            using (var ReadToken = new StreamReader(Stream))
            {
                Token = ReadToken.ReadToEnd();
            }

            await Client.LoginAsync(TokenType.Bot, Token);
            await Client.StartAsync();

            await Task.Delay(-1);
        }

        private async Task Client_Log(LogMessage arg)
        {
            Console.WriteLine($"{DateTime.Now} at (Message.Source)] (Message.Message)");
        }

        private async Task Client_Ready()
        {
            await Client.SetGameAsync("Risk Bot...", "", StreamType.NotStreaming);
        }

        private async Task Client_MessageReceived(SocketMessage arg)
        {

        }
    }
}

A: Why would you pass an Assembly when you have a Type expected?
Just rename AddModuleAsync to AddModulesAsync and it should work.
Sorry, I don't have the source code to make sure it actually works but it should.


text:
Q: Javascript this keyword refer to another object I have this script:
Bla = function() {
  this.prop = 123;
}
Bla.prototype.yay = function() {
  console.log(this,this.prop);
}
X = new Bla();

$(document).ready(X.yay); // output: #document undefined --> why?
$(document).ready(function(){
  X.yay(); // output: Bla 123 --> desired result
});

How to make the first one calls correctly (this should refer to X) without extending Object ?

A: Short answer, no matter where a function is called, this refers to object it is a property of, or the global object is not a property of an object.
When you pass the method into a function, that function is no longer a method of an object, but a local variable to the function, in which, in this case anyway, this refers to the document object, since that is the object the document ready event is called on.
In modern JavaScript implementations, you can bind the method to the object.
Example:
$(document).ready(X.yay.bind(X));

Note that this requires IE9 or better. The anonymous function you use is also an acceptable solution, and will work in older versions of IE.

A: You can use bind:
$(document).ready(X.yay.bind(X));

This creates a "wrapper" around the function that sets this to X when it is invoked.


text:
Q: Cannot pass data from signup form to installation profile I have recently installed Aegir (6.x-2.1) on a Debian 6.0.10 (squeeze) following the instructions found here http://community.aegirproject.org/node/400.
I have followed the instructions found here: https://groups.drupal.org/node/97039, to pass data from signup form to platform's installation profile, but with no luck.
in more details I created a drush script hosting_school.drush.inc in my hosting_school module and inside the script i have implemented hook pre_hosting_task, drush_hosting_school_pre_hosting_task . Then I created drush script school_name.drush.inc in .drush folder and I have implemented hook pre_provision_install, drush_school_name_pre_provision_install.
The problem is that while method drush_hosting_school_pre_hosting_task is properly invoked, method drush_school_name_pre_provision_install is not.
Am i missing something from the instructions ?


text:
Q: Investigate the convergence of $\iint_{x+y\ge1}\frac{\sin x\sin y}{(x+y)^p}\,dx\,dy$ Investigate the convergence of the improper integral
$$\iint\limits_{x+y\ge1}\dfrac{\sin x\sin y}{(x+y)^p}\,dxdy$$
Let $u=x+y$, $v= x-y$, then
$$\frac14\int\limits_1^{+\infty}du\int\limits_{-\infty}^{+\infty}\dfrac{\cos v-\cos u}{u^p}\,dv=\frac12\int\limits_1^{+\infty}du\int\limits_0^{+\infty}\dfrac{\cos v-\cos u}{u^p}\,dv.$$
Let's move from the double integral to the repeated integral
$$\lim\limits_{k\to+\infty}\frac12\int\limits_1^k\dfrac{du}{u^p}\int\limits_0^k(\cos v-\cos u)\,dv=\frac12\lim\limits_{k\to+\infty}\left(\sin k\int\limits_1^k\dfrac{du}{u^p}-k\int\limits_1^k\dfrac{\cos u}{u^p}\right)\!.$$
What to do next?

A: By a change of variables
$$\begin{eqnarray*} \iint_{\substack{x+y\geq 1\\ x,y\geq 0}}\frac{\sin(x)\sin(y)}{(x+y)^p}\,dx\,dy &=& \int_{1}^{+\infty}\frac{1}{s^p}\int_{0}^{s}\sin(x)\sin(s-x)\,dx\,ds\\ &=& \frac{1}{2}\int_{1}^{+\infty}\frac{\sin(s)-s\cos(s)}{s^p}\,ds.\end{eqnarray*} $$
By Dirichlet's test the integral $\int_{1}^{+\infty}\frac{\sin(s)}{s^p}\,ds$ is convergent for any $p>0$ and absolutely convergent for any $p>1$.
For the same reason the integral $\int_{1}^{+\infty}\frac{\cos(s)}{s^{p-1}}\,ds$ is convergent for any $p>1$ and absolutely convergent for any $p>2$.


text:
Q: Angular 4 @HostListener Window scroll event strangely does not work in Firefox I'm using @HostListener('window:scroll', []) in Angular 4 app in order to add additional class to the header on scrolling. It works fine in Chrome but I noticed that in Firefox 54.0 (I think it's the last current version) the class is not added, it does not execute onWindowScroll() method at all. What can be the reason?

Here is a part of the code and a Plunker Demo (which by the way, also works fine in Chrome but not in Mozilla):
public isScrolled = false;
constructor(@Inject(DOCUMENT) private document: any) {}
@HostListener('window:scroll', [])
onWindowScroll() {
    const number = this.document.body.scrollTop;
    if (number > 150) {
        this.isScrolled = true;
    } else if (this.isScrolled && number < 10) {
        this.isScrolled = false;
    }
}

Any help would be much appreciated.

A: This Angular directive will work in both Chrome and Firefox:
import { Directive, Output, EventEmitter, HostListener, ElementRef, OnDestroy
} from '@angular/core';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/fromEvent';

@Directive({
  selector: '[scroll]'
})
export class ScrollEventDirective implements OnDestroy {
  @Output() scrollPosition: EventEmitter<number> = new EventEmitter<number>
  ();

  private scrollEvent$;

  constructor(private el: ElementRef) {
    this.scrollEvent$ = Observable.fromEvent(this.el.nativeElement,
    'scroll').subscribe((e: any) => {
      this.scrollPosition.emit(e.target.scrollTop);
    });
  }

  ngOnDestroy() {
    this.scrollEvent$.unsubscribe();
  }
}

Using the directive on a DIV element:
<div scroll (scrollPosition)="scrollChanged($event)">...</div>

A: try this:
@HostListener('window:scroll', ['$event'])
onWindowScroll($event) {
    console.log("scrolling...");
}

I prefer this:
import { fromEvent } from "rxjs";

...

this.eventSubscription = fromEvent(window, "scroll").subscribe(e => {
    this.onWindowScroll();
});

A: I did face the same issue and resolved it by using window.scrollY rather than using this.document.body.scrollTop to make it work in Mozila Firefox. I know it is strange but it works.

A: How i solved this
Works perfectly on Firefox, chrome and other browsers
Concept:  You can listen to the properties of scrolling element that is body  for now if you don't have any other scrolling element
@HostListener('window:scroll', ['$event']) onWindowScroll(e) {
    console.log(e.target['scrollingElement'].scrollTop)

    // Your Code Here

  }


text:
Q: Trying to create a dynamic merge script and passing the variables dynamically I am trying to create a dynamic merge script and pass the variables dynamically, but the variable are not getting substituted in the code. Can someone help on this?
create or replace PROCEDURE MERGE_APPMODULE(institutionKey varchar2,applname varchar2,modulename varchar2,DESCRIPTION varchar2 )
as
--set serveroutput on;
--SET FEEDBACK OFF;

DATA long;
BEGIN
select

CONCAT ('declare
  institutionkey varchar2(100) := '|| '''institutionkey''' ||' ;
  actiondate DATE  := SYSDATE;
  actionuser VARCHAR2(100) := sys_context(''USERENV'', ''AUTHENTICATED_IDENTITY'');
  supportedLanguages varchar2(100) := ''en'';
BEGIN',
  '
    MERGE INTO APPMODULE TARGET
        USING (
                SELECT  0 DISALLOW, NULL IMAGE, NULL IsMaintainence, moduleclass,1 ModuleIndex, ''modulename'' ModuleName , ApplId FROM APPLICATION WHERE  ApplName = ''applname''  and FinInstKey = ''institutionKey'')
               ) source
        ON (
            target.ApplId=source.ApplId and target.ModuleName=source.ModuleName
            )
       WHEN NOT MATCHED THEN
          insert (createddate, creatorusr, Disallow, Image, IsDefault, IsMaintainence, moduleClass, ModuleIndex, ModuleName, updatordate, updatorusr, ApplId)
          values (actionDate, actionUser, source.Disallow, source.Image, 1, source.IsMaintainence, source.moduleClass, source.ModuleIndex, source.ModuleName, actionDate, actionUser, source.ApplId);

    MERGE INTO APPMODULETXT target
        USING (
                SELECT ''DESCRIPTION'' DESCRIPTION, ModuleId FROM AppModule m JOIN Application a ON m.ApplId = a.ApplId WHERE m.ModuleName = ''ACCOUNTS_SERVICES_MODULE'' AND a.ApplName = applicationName AND a.finInstKey = ''institutionKey''

        ) source
        ON (
               target.ModuleId = source.ModuleId
            )
        WHEN NOT MATCHED THEN
            insert (Description, TxtLanguage, ModuleId)
            values (source.Description, ''en'', source.ModuleId);') INTO DATA from dual;

        dbms_output.put_line(DATA);
  END;

A: You are not doing concatanation properly.
Strings can be concated using || operaror or concat method.
In your code you used both and mess happened. Here, I tried using || operator as following:
create or replace PROCEDURE MERGE_APPMODULE(institutionKey varchar2,applname varchar2,modulename varchar2,DESCRIPTION varchar2 )
as
--set serveroutput on;
--SET FEEDBACK OFF;

DATA VARCHAR2(32767); -- using varchar2 data type variable
BEGIN
DATA := 'declare
  institutionkey varchar2(100) := '''|| institutionkey ||''' ;
  actiondate DATE  := SYSDATE;
  actionuser VARCHAR2(100) := sys_context(''USERENV'', ''AUTHENTICATED_IDENTITY'');
  supportedLanguages varchar2(100) := ''en'';
BEGIN' || chr(10) ||
  ' MERGE INTO APPMODULE TARGET
        USING (
                SELECT  0 DISALLOW, NULL IMAGE, NULL IsMaintainence, moduleclass,1 ModuleIndex, '''|| modulename ||''' ModuleName , ApplId FROM APPLICATION WHERE  ApplName = ''' || applname || ''' and FinInstKey = ''' || institutionKey || '''
               ) source
        ON (
            target.ApplId=source.ApplId and target.ModuleName=source.ModuleName
            )
       WHEN NOT MATCHED THEN
          insert (createddate, creatorusr, Disallow, Image, IsDefault, IsMaintainence, moduleClass, ModuleIndex, ModuleName, updatordate, updatorusr, ApplId)
          values (actionDate, actionUser, source.Disallow, source.Image, 1, source.IsMaintainence, source.moduleClass, source.ModuleIndex, source.ModuleName, actionDate, actionUser, source.ApplId);

    MERGE INTO APPMODULETXT target
        USING (
                SELECT ''' || DESCRIPTION || ''' DESCRIPTION, ModuleId FROM AppModule m JOIN Application a ON m.ApplId = a.ApplId WHERE m.ModuleName = ''ACCOUNTS_SERVICES_MODULE'' AND a.ApplName = applicationName AND a.finInstKey = ''' || institutionKey || '''
               ) source
        ON (
               target.ModuleId = source.ModuleId
            )
        WHEN NOT MATCHED THEN
            insert (Description, TxtLanguage, ModuleId)
            values (source.Description, ''en'', source.ModuleId);';

        dbms_output.put_line(DATA);
  END;

Check if it is working for you.
Cheers!!

A: Why are you using type LONG in this century?
It has been sort of deprecated since Oracle 8.0 came out in 1997.
Using CLOB will generally make your life a lot easier, but in this case even a VARCHAR2 is probably large enough to fit your query.


text:
Q: Check if a value exists per group and remove groups without this value in a pandas df I have a pandas df that looks like this:
import pandas as pd
d = {'value1': [1, 1, 1, 2, 3, 3, 4, 4, 4, 4], 'value2': ['A', 'B', 'C', 'C', 'A', 'B', 'B', 'A', 'A', 'B']}
df = pd.DataFrame(data=d)
df

Per group in column value1 I would like to check if that group contains at least one value 'C' in column value2. If a group doesn't have a 'C' value, I would like to exclude that group
    value1  value2
    1       A
    1       B
    1       C
    2       C
    3       A
    3       B
    4       B
    4       A
    4       A
    4       B

The resulting df should look like this:
    value1  value2
    1       A
    1       B
    1       C
    2       C

What's the best way to achieve this?

A: use groupby filter
df.groupby('value1').filter(lambda x: x['value2'].eq('C').sum() > 0)

A: Here is another solution:

*

*First establish a list containing the value1 values for which value2 is equal to C: mylist = df[df.value2=='C']['value1'].unique()

*Then filter the dataframe df, keeping only rows for which value1 is in this list: df[df.value1.isin(mylist)].

Or as a one-liner:
df[df.value1.isin(df[df.value2=='C']['value1'].unique())]


text:
Q: $this->validate causes "Failed to load response data" I have the following external form:
  <form method="POST" action="http://infused.local/leads/post">

      first_name
      <input type="text" name="first_name" class="form-control">

      last_name
      <input type="text" name="last_name" class="form-control">

      email
      <input type="text" name="email" class="form-control">

      postal_code
      <input type="text" name="postal_code" class="form-control">

    <button type="submit" class="btn btn-primary">Submit</button>
  </form>

Which points to the following controller method:
public function post()
{
    $this->validate(request(), [
        'email' => 'required|email',
    ]);

    echo 'hello';
}

Via this route:
Route::post('leads/post', 'LeadController@post');

I've disabled CSRF protection for the form route.

*

*When I submit the form, I get "Failed to load response data" from
Chrome.

*When I remove the $this->validate call, I get "hello".

Why is this not working?

A: You need to return JSON and you can use the helper function:
response()->json([
    'message' => 'hello'
]);

Then in your JS:
console.log(response.message);

A: OK apparently the validate method just redirects you back to the previous page if there are errors, unless the response is expected to be JSON. Ended up using the Validator facade instead.
Edit: Thanks for the downvotes. This website is cancer.


text:
Q: Pyqt5 transparent background but also interactable So I'm trying to have a background that's interactable but also transparent. I want to be able to draw on the screen. As shown in the video below, if I use self.background.fill(Qt.transparent), the background is not transparent like it's supposed to, it's black. But when I use self.setAttribute(Qt.WA_TranslucentBackground), I can't draw at all, and it's just interacting with the window underneath it. How do I make a transparent window but also being able to draw on it?
As seen, self.setStyleSheet("background: transparent;") does nothing too. The background is still black
https://streamable.com/pjro9e
Here is my code:
import sys

from PyQt5.QtCore import QPoint, Qt
from PyQt5.QtGui import QPainter, QPen, QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow
from screeninfo import get_monitors

class Canvas(QMainWindow):

    def __init__(self):
        super().__init__()
        self.drawing = False
        self.lastPoint = QPoint()
        self.initUI()

    def initUI(self):
        monitor = get_monitors()[0]

        self.setStyleSheet("background: transparent;")
        self.background = QPixmap(monitor.width, monitor.height)
        self.background.fill(Qt.transparent)
        self.setGeometry(0, 0, 1920, 1080)
        self.resize(monitor.width, monitor.height)
        # self.setWindowOpacity(0.5)
        self.setWindowFlags(Qt.Window | Qt.CustomizeWindowHint | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), self.background)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.drawing = True
            self.lastPoint = event.pos()

    def mouseMoveEvent(self, event):
        if event.buttons() and Qt.LeftButton and self.drawing:
            painter = QPainter(self.background)
            painter.setPen(QPen(Qt.magenta, 5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
            # print(self.lastPoint, event.pos())
            painter.drawLine(self.lastPoint, event.pos())
            self.lastPoint = event.pos()
            self.update()

    def mouseReleaseEvent(self, event):
        if event.button == Qt.LeftButton:
            self.drawing = False

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Canvas()
    window.show()
    sys.exit(app.exec_())

A: You can replace self.setStyleSheet('background:transparent) with self.setStyleSheet('background-color:transparent).

A: This one worked for me:
self.setStyleSheet('''QMainWindow {background:transparent}''')


text:
Q: Any way to list all apps in the google play store in parsable format? Similar to this post regarding the Apple iTunes App store, would there be any way to find all the apps on the Google Play store?
Are there any APIs available or a simple page like the apple one with lots of hyperlinks? Or an RSS Feed?
Any portal I can find into the google play store seems very interactive, and not really a complete list, but lots of 'top' lists of apps/games.

A: I ended up using a paid service called 42Matters.
They provide an API that you can call for a subscription fee.


text:
Q: Python - не показываются значение Пытаюсь вывести информацию о Raspberry Pi.
    @app.route('/sys_test', methods=['GET'])
    def system_test():
    hostname = subprocess.check_output('uname -n', shell=True).strip()
    linux = subprocess.check_output('uname -o', shell=True).strip()
    cpu_usage = psutil.cpu_percent()
    d = collections.OrderedDict()
    d['status'] = 200
    d['model'] = model_name
    d['revision'] = myrevision
    d['hostname'] = hostname
    d['firmware'] = firmware
    d['version'] = website
    d['linux'] = linux
    d['cpu'] = cpu_usage
    d['systemUptime'] = time.clock()
    d['uptime'] = time.time() - uptime
    return flask_json.dumps(d, sort_keys=False, indent=True)

Выводится все кроме revision и model вот код получения их значений
RaspiName
@app.route('/raspname', methods=['GET'])
def raspiname():
    global model_name
    if myrevision == 'a01041' or 'a21041':
        model_name = 'Pi 2 Model B'
    elif myrevision == 'a02082' or 'a22082':
        model_name = 'Pi 3 Model B'
    elif myrevision == '0002':
        model_name = 'Model B Revision 1.0'
    elif myrevision == '0003':
        model_name = 'Model B Revision 1.0 + ECN0001'
    elif myrevision == '0004' or '0005' or '0006':
        model_name = 'Model B Revision 2.0'
    elif myrevision == '0007' or '0008' or '0009':
        model_name == 'Model A'
    elif myrevision == '000d' or '000e' or '000f':
        model_name = 'Model B Revision 2.0'
    elif myrevision == '0010':
        model_name = 'Model B+'
    elif myrevision == '0011':
        model_name = 'Compute Module'
    elif myrevision == '0012':
        model_name = 'Model A+'
    else:
        model_name = 'Raspberry Pi'
    return 'Model name - %s' % model_name

Model
@app.route('/model', methods=['GET'])
def raspmodel():
  # Extract board revision from cpuinfo file
  global myrevision
  myrevision = "0000"
  try:
    f = open('/proc/cpuinfo','r')
    for line in f:
      if line[0:8]=='Revision':
        length=len(line)
        myrevision = line[11:length-1]
    f.close()
  except:
    myrevision = "0000"
  return 'Revision - %s' % myrevision

A: Ошибку я нашел, в данном случае, без вызова двух других функций, глобальная переменная не перезаписывается и остается как '' . Для того, чтобы правильно отображались значение в моих двух переменных, нужно было сначала вызвать две других функций.


text:
Q: Rendering head :ok vs head :no_content. Any good practices? Whenever I take in data and do something like delete a post, etc. I generally return head :no_content.
For example:
def destroy
  @post = Post.find_by(external_id: params[:post_id])
  @post.destroy!

  head :no_content
end

Is it good practice to use head :no_content over head :ok? Not too sure when to use either.

A: This is the expected behavior in case of a DELETE request. So much so that in rails if you generate a resource or scaffold (using rails generate), this is what is generated.
All 2xx statuses are "success" statuses. So if you are actually not sending any content, it is best to mention it with a no_content
So rest assured that what you are doing is in fact correct and expected.


text:
Q: Dependency Inversion Principle: High Level and Low Level module example I was going through the following link to understand what high-level and low-level modules mean in the context of Dependency Inversion Principle.
As per the explanation given there, is the following code snippet a good/appropriate example?
public class HighLevel
{
    private IAbstraction _abstraction;

    public HighLevel(IAbstraction abstraction)
    {
        _abstraction = abstraction;
    }

    public void Act()
    {
        _abstraction.DoSomething();
    }

}

public interface IAbstraction
{
    void DoSomething();
}

public class LowLevel: IAbstraction
{
    public void DoSomething()
    {
        //Do something
    }
}

A: To make a long answer short: yes, this is an example of a Dependency Inversion Principle


text:
Q: REST (HATEOAS) and ReactJS I'm interested in using the HATEOAS principle of REST to reduce business logic in a SPA application.  In a React-specific context, I'd like to know if there are challenges that make this impractical and, if not, what is a good strategy to follow?
Conceptual examples of using HATEOAS to remove business logic from the UI:

*

*Delegating valid bank account actions to the REST service

*Delegating role-based access control to the REST service
I've only found one link that suggests React/Flux is not compatible with a HATEOAS strategy, and no meaningful discussion elsewhere.  Is it really not feasible in a React/Flux app? That SO post didn't get enough attention.  Does anyone have a favorite or recommended approach for achieving success (with or without Flux or Redux)?
Someone gave a fairly detailed example of leveraging HATEOAS in the context of Angular.  I'm looking for something similar for React.
Personally, I'm picturing the rel tag in hypermedia links controlling which JSX components are rendered (conditional JSX).  Is that naive for a real-world React app?  Perhaps conditionally rendered React components are too coarse-grained to be used this way?
I am assuming that hypermedia links are provided by a HAL implementation, or otherwise conform to the ATOM feed convention (RFC4287).

A: 100% HATEOAS IS compatible with React & Flux, HATEOAS is compatible with Angular, HATEOAS is compatible with JQuery and even vanilla JS.
HATEOAS doesn't not impose any technical or implementation requirements on a consuming client.
HATEOAS is in fact simply a concept to which you can design your API (you can use one of several standards though like HAL)
Basically if you can call an API then you can implement a HATEOAS client.
So how to get there:

*

*Step 1, how would you normally do an API call in React? Do it the same way.

*Step 2, interrogate response.

*Step 3, based on response, respond in the UI appropriately.

For example given a call to the order api /orders, I get the following response:
{
    "_links": {
        "self": { "href": "/orders" },
        "next": { "href": "/orders?page=2" }
    }
}

From this I can infer that next is a valid relation, and that if I go to that href I would in fact receive a second page of orders, so in this case in the UI show the next button.
However if I had received the following response:
{
    "_links": {
        "self": { "href": "/orders" },
    }
}

Then I could infer that next is not a valid relation, and in my UI I should disabled or not display a next button.
There is no magic, it is simply a change in thinking, a new paradigm.

A: Before I spout off my most likely wrong/irrelevant answer, I just want to let you know that I just now read up on what HATEOAS is. That warning there, from what I've briefly read, HATEOAS seems to be mostly about the API telling you how to navigate through itself by providing you a link back to the resources that are relevant to the resource you had just requested.
That being the case, I don't see a reason why you can't implement dynamic url ajax calls in your actions that will alter your SPA's application state (i.e. Redux) based on what has been provided to you, however, you'll still need to have something to represent the state in a visual manner for all parts of your application. Here's a crude semi-pseudo and not very well thought-out representation of what I mean based loosely on your bank account example:
// our component file
import React from 'react'
import { makeAWithdrawl } from './actions'

export default React.createClass({
  handleClick: function(e) {
    e.preventDefault()
    makeAWithdrawl(this.props.account.withdraw.href)
  },
  render: function () {

{this.props.account.accountNumber}

{this.props.account.balance}

Deposit

      {this.props.account.withdraw ?
Withdraw
 : ''}

  }
})

// our actions file
import store from 'store' // our redux store
import axios from 'axios' // an ajax library

export function makeAWithdrawl(url) {
  return axios.post(url).then(function(resp){
    store.dispatch({
      type: 'MAKE_WITHDRAWL',
      action: resp.data
    }) // do your reducer stuff
  })
}

Your application still knows what it's doing in the SPA, however, this will allow the API to direct you where to call to for whatever action needs to be performed. Hope it helps.


text:
Q: SQL JOIN error in vb.net I have this sql string:
Dim sqlQuery As String = "SELECT TOP 1 ID, FName, FoodGroup, Calories, Protein, Carbohydrates, Fat, category.ID" &
        " FROM food where Protein<='" & txtProt.Text.ToString() & "' and FoodGroup = 4 " & "and category.ID = 1 " & "JOIN foodCategory ON food.ID = foodCategory.Food_ID" & "JOIN category ON foodCategory.Category_ID = category.ID " & "ORDER BY NEWID() "

What i want to do is this: I want to type the value "FName" from table "food" to an textBox where the "ID" field of table "category" is 1.
I have 3 tables. The first is table food, the second one is table category and the third one is foodCategory.
The table foodCategory has the ID's from the first 2 tables to a one-to-many relationship.
I get the following error : Incorrect syntax near JOIN.
What do i do wrong?

A: your query is incorrect, the JOINs have to be set within the FROM clause, not in the WHERE clause.

A: Try the following query
dim sqlQuery As String
sqlQuery = "SELECT TOP 1 ID, FName, FoodGroup, Calories, Protein, " & _
           "Carbohydrates, Fat, category.ID " &_
           "FROM food JOIN foodCategory ON " & _
           "food.ID = foodCategory.Food_ID JOIN category ON " & _
           "foodCategory.Category_ID = category.ID " & _
           "where Protein<='" & txtProt.Text.ToString() & "' and " & _
           "FoodGroup = 4 and category.ID = 1 " & _
           "ORDER BY NEWID() "

Furthermore you should have look at Parameter as your code is very vulnerable to SQL injection!

A: It's probably your concatenation:
... foodCategory.Food_ID" & "JOIN category ...

would evaluate to
foodCategory.Food_IDJOIN category

A: Your JOIN must be before the WHERE clause:
 " FROM food" & " JOIN foodCategory ON food.ID = foodCategory.Food_ID" & "JOIN category ON       foodCategory.Category_ID = category.ID " & " WHERE Protein<='" & txtProt.Text.ToString() & "'  and FoodGroup = 4 " & "and category.ID = 1 " & " ORDER BY NEWID() ";


text:
Q: Two rows in a single table cell? I like to add three rows in a single td table cell by using HTML5. I've tried adding a new table element inside the td, like this:

                    Lorem ipsum

                    Lorem ipsum

                            Row 1

                            Row 2

I get two rows, but this just breaks my markup.
Any alternative solutions? Maybe with flexbox?

A: Here's something you may try, I don't know if it's the thing you want but still.

                Lorem ipsum

                Lorem ipsum

               Row 1

               Row 2

A: The answer from qocu kind of works as well, but I don't want to add rowspans everywhere. So I ended up using the almighty flexbox. Not sure about which versions of IE this method supports, but luckily I do not have to support anything prehistoric. The solution:

                Lorem ipsum

                Lorem ipsum

                    Row 1
                    Row 2


text:
Q: Замена слова в python Как сделать так что если в args есть буква "я" оно заменялось на ты
async def process_message(self, msg):
    c, args = self.parse_message(msg)

    if not args:
        return await msg.answer(f"Используйте {self.command_example()} <текст>\n(без `<` или `>`)")

    if msg.is_multichat:
        tipo = random.choice(self.tipo)
        tochno = random.choice(self.tochno)
        users = await msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields='name')
        user = random.choice(users)

        await msg.answer(f"✳ {tipo}, это @id{user['id']} ({user['first_name']} {user['last_name']}) {tochno}")

    else:
        await msg.answer("Эту команду можно использовать только в беседе.")

A: При условии, что args - это строка, то можно обойтись стандартными методами:
agrs.replace('я', 'ты ')

A: Попробуй сделать условия if in agrs я и дальше пропиши замену Я с помощью agrs.replace() на ты


text:
Q: How to find the error detail on Sharepoint Services 3? I remembered that there is a log file that you can check for Sharepoint Services 3.0. I don't remember where I can find this. The reason I ask this I have an error when implementing the new template and it works on one, but not on the other machine. The error on the page is very generic: "The template you have choosen is invalid or can not be found".
Thanks

A: SharePoint log files are usually in the "Logs" folder in the '12 Hive' which by default is in C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\Logs.

A: It's easier to have the error displayed completely. You can enable this by modifying the web.config.
Find the SafeMode entry in your web.config and change CallStack="false" to CallStack="true". Then find the customErrors entry and set mode to mode="Off".
Now errors will be shown as a complete ASP.NET error screen


text:
Q: Does zero vector have zero dimension? I know this sounds like a stupid question, but I just want to organize and clear what I studied.
For an $n\times n$ matrix $A$, it has independent columns when nullspace only has zero vector. And independent columns mean $A$ has rank $n$, therefore by the rank theorem, nullspace has zero dimension. That is, zero vector is zero dimension, is that right?
AND one more thing. I want to show that $\lbrace Av_1,...,Av_n \rbrace$ span $R^n$ when $\lbrace v_1,...,v_n \rbrace$ form a basis. Dimension theorem is used in here? If so, how can I show that $\lbrace Av_1,...,Av_n \rbrace$ span $R^n$?

A: Yes but here's a minor nit pick: A vector doesn't have a dimension, you want to say that the subspace spanned by the zero vector has dimension zero.
For the second question you may use the rank nullity theorem. You have $\mathrm{dim} \mathrm{ker} A = 0$ and hence $\mathrm{dim} \mathrm{im} A = \mathrm{dim}R^n - \mathrm{dim} \mathrm{ker} A =  \mathrm{dim}R^n$ hence the $v_i$ span $R^n$.

A: The concept of dimension is applied to sets of vectors, in particular subsets of vector spaces that are also subspaces. Thus, it more appropriate to say that the subspace consisting of the zero vector has dimension zero.
If you are assuming that $A$ is a square matrix and has independent columns, it has maximal rank. A matrix with maximal rank is invertible and the linear map induced by left multiplication by $A$ is an isomorphism. Isomorphisms always map a basis to another basis.


text:
Q: Websites occasionally don't load all the way. What are some possible causes? Sometimes when I load a webpage, it stops before the entire page has loaded. Maybe the CSS didn't register correctly, or the layout is funky. But when I refresh it loads properly.
What causes this? Does the connection get interrupted? What would cause the interruption and why doesn't the browser recognize this? I'm just curious.

A: Some reasons I encountered are:

*

*Cross-site: Content on the page comes from several sources, some of them are slow or non-existent

*Some part of the page is generated dynamically by javascript that needs to access Web data or has a bug

*The item referred to on the page was deleted or renamed

*Some part of the page was blocked by an extension such as Adblock or NoScript

*Badly written or badly maintained page

A: Do you have a DSL connection?  PPPoE, which many DSL providers use to transport your traffic from the DSL modem to the DSL provider's routers, has an MTU of 1492 (because the PPPoE overhead is 8 bytes).  The standard Ethernet MTU is 1500.
I believe if you change the MTU of the network interface connected to your DSL router to 1492 as well the problem should clear up if this is cause.
You may try upgrading the firmware in your DSL modem as well while you are at it.


text:
Q: K / Kestrel Combinator for monads? implicit class KComb[A](a: A) {
  def K(f: A => Any): A = { f(a); a }
}

Given this implementation of the K combinator, we can chain method calls on a value while applying side effects, without the need for temp variables.
E.g.:
case class Document()
case class Result()

def getDocument: Document = ???
def print(d: Document): Unit = ???
def process(d: Document): Result = ???

val result = process(getDocument.K(print))
// Or, using the thrush combinator
// val result = getDocument |> (_.K(print)) |> process

Now, I need to do something similar, but using the IO monad instead.
def getDocument: IO[Document] = ???
def print(d: Document): IO[Unit] = ???
def process(d: Document): IO[Result] = ???

My question is: does a combinator for this operation exist already? Is there anything in Scalaz, or maybe some other library, that does this?
I couldn't find anything, so I rolled out this variant of the K combinator for monads myself.
I called it tapM because 1) the K combinator is called tap in  Ruby and unsafeTap in Scalaz and 2) it seems Scalaz follows the pattern of appending M to monadic variants of well known methods (e.g. foldLeftM, foldMapM, ifM, untilM, whileM).
But I'd still like to know if anything of the sort exists already and I'm just reinventing the wheel.
implicit class KMonad[M[_]: Monad, A](ma: M[A]) {

  def tapM[B](f: A => M[B]): M[A] =
    for {
      a <- ma
      _ <- f(a)
    } yield a
}

// usage
getDocument tapM print flatMap process

A: Edit: My initial answer was misguided. Here's the correct one.
There's a flatTap method on FlatMap in cats and >>! on BindOps in scalaz.
getDocument flatTap print >>= process

getDocument >>! print >>= process

Edit^2: Changed flatMap to >>= to more easily show the relationship between tap and bind.


text:
Q: How to pass and execute anonymous function as parameter in C++11? The code I'm looking for is like following.
bool Func1(int Arg1, C++11LambdaFunc Arg2){
    if(Arg1 > 0){
        return Arg2(Arg1);
    }
}

Later I'll be using this code.
Func1(12, [](int D) -> bool { ... } );

A: Basic version, for use in a header file:
template<typename Lambda>
bool Func1(int Arg1, Lambda Arg2){ // or Lambda&&, which is usually better
  if(Arg1 > 0){
    return Arg2(Arg1);
  } else {
    return false; // remember, all control paths must return a value
  }
}

More complex version, if you want to split your interface from your implementation (it has run time costs):
bool Func1(int Arg1, std::function<bool(int)> Arg2){
  if(Arg1 > 0){
    return Arg2(Arg1);
  } else {
    return false; // remember, all control paths must return a value
  }
}

std::function uses type erasure to create a custom-created wrapper around your lambda, and then exposes a non-virtual interface that uses the pImpl pattern to forward it to the custom-created wrapper.1
Or, in less technical terms, std::function<bool(int)> is a class that can wrap nearly anything that you can call like a function, passing one parameter that is compatible with passing an int, and it returns something that is compatible with returning a bool.
A call through a std::function has a run time cost roughly equal to a virtual function call (caused by the above type erasure), and when you create it it has to copy the state of the function object (aka functor) passed in (which can be cheap -- stateless lambdas, or lambdas capturing arguments by reference -- or expensive in some other cases) and store it (typically on the free store or heap, which has a cost), while the pure-template versions can be "inlined" at the point of call (ie, can not only cost less than a function call, the compiler can even optimize over the function call and return boundaries!)
If you want to split interface/implementation without all of the runtime costs of std::function, you can roll your own function_ref (in c++17, because that cuts down on some boilerplate):
template<class Sig>
struct function_ref;

template<class R, class...Args>
struct function_ref<R(Args...)> {
  R operator()(Args...args) const {
    return pf(state, std::forward<Args>(args)...);
  }
  function_ref()=default;
  function_ref(function_ref const&)=default;
  function_ref& operator=(function_ref const&)=default;
  explicit operator bool()const{ return pf!=nullptr; }

  // this overload reduces indirection by 1 step
  // and allows function_ref<Sig> to resolve overloads
  // on an overload set sometimes.
  function_ref( R(*f)(Args...) ):
    pf([](State const& state, Args&&...args)->R{
      return reinterpret_cast<R(*)(Args...)>(state.pfunstate)(std::forward<Args>(args)...);
    })
  {
    state.pfunstate = reinterpret_cast<void(*)()>(f);
  }

  // this grabs anything callable (that isn't this own type)
  // and stores a pointer to it to call later.
  template<class F>
  requires (
    std::is_convertible_v<
      std::invoke_result_t< std::remove_reference_t<F>, Args... >, R
    >
    && !std::is_same_v< std::decay_t<F>, function_ref >
  )
  function_ref( F&& f ):
    pf([](State const& state, Args&&...args)->R{
      return (*(std::remove_reference_t<F>*)state.pstate)(std::forward<Args>(args)...);
    })
  {
    state.pstate = std::addressof(f);
  }
private:
  union State {
    void* pstate = nullptr;
    void(*pfunstate)();
  };
  State state;
  R(*pf)(State const&, Args&&...) = nullptr;
};
// a deduction guide permitting function_ref{foo} to work
// if foo is a non-overloaded function name.
template<class R, class...Args>
function_ref( R(*)(Args...) )->function_ref<R(Args...)>;

Live example.
This removes the need to ever do any allocation from std::function by removing ownership semantics from it and just type-erasing calling.
A fancy version of the first example that also handles some corner cases a tad better: (also must be implemented within a header file, or in the same translation unit as it is used)
template<typename Lambda>
bool Func1(int Arg1, Lambda&& Arg2){
  if(Arg1 > 0){
    return std::forward<Lambda>(Arg2)(Arg1);
  } else {
    return false; // remember, all control paths must return a value
  }
}

which uses a technique known as "perfect forwarding".  For some functors, this generates slightly different behavior than #1 (and usually more correct behavior).
Most of the improvement comes form the use of && in the argument list: this means that a reference to the functor is passed in (instead of a copy), saving some costs, and allows both a const or non-const functor to be passed in.
The std::forward<Lambda>(...) change would only cause a change in behavior if someone used a relatively new C++ feature that allows methods (including operator()) to override on the rvalue/lvalue status of the this pointer.  In theory, this could be useful, but the number of functors I've seen that actually override based on the rvalue status of this is 0.  When I'm writing serious library code (tm) I go to this bother, but rarely otherwise.
There is one more possible thing to consider.  Suppose you want to take either a function that returns bool, or a function that returns void, and if the function returns void you want to treat it as if it returned true.  As an example, you are taking a function that is being called when iterating over some collection, and you want to optionally support early halting.  The function returns false when it wants to stop prematurely, and true or void otherwise.
Or, in a more general case, if you have multiple overrides of a function, one of which takes a function and others take some other type at the same location.
This is possible, which is as far as I'm going to get into here (either with a smart adapter, or via SFINAE techniques).  However, you are probably better off just creating two different named functions, because the techniques required are way too heavy weight.

1 Technically std::function could use magic fairy dust to do what it does, as its behavior is described by the standard, and not its implementation.  I'm describing a simple implementation that approximates the behavior of the std::function implementation I have interacted with.

A: First solution:
You can make your Func1() function a function template:
template<typename T>
bool Func1(int Arg1, T&& Arg2){
    if(Arg1 > 0){
        return Arg2(Arg1);
    }

    return false; // <== DO NOT FORGET A return STATEMENT IN A VALUE-RETURNING
                  //     FUNCTION, OR YOU WILL GET UNDEFINED BEHAVIOR IF FLOWING
                  //     OFF THE END OF THE FUNCTION WITHOUT RETURNING ANYTHING
}

You could then invoke it as you desire:
int main()
{
    Func1(12, [](int D) -> bool { return D < 0; } );
}

Second solution:
If you do not want to use templates, an alternative (that would bring some run-time overhead) is to use std::function:
#include <functional>

bool Func1(int Arg1, std::function<bool(int)> Arg2){
    if(Arg1 > 0){
        return Arg2(Arg1);
    }

    return false;
}

Once again, this would allow you to call Func1() the way you desire:
int main()
{
    Func1(12, [](int D) -> bool { return D < 0; } );
}

A: For those whose tastes are more traditional, note that non-capturing lambdas can convert to function pointers.  So you can write your function above as:
bool Func1(int Arg1, bool (*Arg2)(int)) { ... }

And it will work correctly for both traditional functions and lambdas.


text:
Q: Uninitialized constant Project (NameError) in setting up Figaro gem I updated a Rails 2.3 app to 3.2 and it seemed to be a pretty simple process but when setting up the Figaro gem I came across this error:
C:\Sites\JustManage>rails generate figaro:install
C:/Sites/JustManage/config/environment.rb:5:in `<top (required)>': uninitialized
 constant Projectmanagement (NameError)
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.1
/lib/rails/application.rb:103:in `require_environment!'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.1
/lib/rails/commands.rb:25:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'

Here is what my environment.rb looks like:
# Load the rails application
require File.expand_path('../application', __FILE__)

# Initialize the rails application
Projectmanagement::Application.initialize!

Here is my application.rb file:
require File.expand_path('../application', __FILE__)

require 'rails/all'

if defined?(Bundler)
  Bundler.require(*Rails.groups(:assets => %w(development test)))
end

module Railsapp
  class Application < Rails::Application
    config.encoding = "utf-8"

    config.filter_parameters += [
      :password,
      :password_clear,
      :password_verify
    ]

    config.assets.enabled = true
    config.assets.version = '1.0'

  end
end

I've never run into this error before and don't know why it's happening.

A: It seems like the name of your application is not the same in the different places it needs to appear in. Check the following files and see if they contain either Projectmanagement::Application or Railsapp::Application:

*

*config/application.rb (Actually initializes the constant)

*config/environment.rb

*config/environments/development.rb

*config/environments/production.rb

*config/environments/test.rb

*config/initializers/secret_token.rb

*config/initializers/session_store.rb

*config/mongoid.yml (if using Mongoid)

*config/routes.rb

*config.ru

*Rakefile

*app/views/layouts/application.html.erb, in title tag

Then pick a name (either Projectmanagement or Railsapp) and change all the names in the above files so they match. That should resolve the uninitialized constant error you are having.

A: I can't be certain that they are not errors from copy/pasting, but your application.rb appears to be incorrect. Issues I see:

*

*L1: You are requiring application.rb a second time where you mean to be requiring boot.rb.

*L12: The name of this module (i.e. the name of your app) is not consistent here with what is in your environment.rb file (Railsapp vs. Projectmanagement).

The second issue is actually causing the error you are seeing - you have not defined the Projectmanagement constant before calling a method on it.


text: Q: PDO inserting zero into my data base instead of the variable content I'm trying to insert data into my database using PDO prepare statement but its inserting zero into my table instead of the variable content


text:
Q: Add Model Project (EntityFramwork) to Asp.net Core 3 Project I have 3 projects in my Solution like below:

*

*ModelProject (EntityFramework)

*ProjectA (ASP.NET MVC)

*ProjectB (ASP.NET CORE 3 with Blazor)

So in model project i defined my tables ,relations, queries and their classes then added that on ProjectA and ProjectB.
on ProjectB (.net core) in startup.cs by services.AddDbContext tries to add dbcontext (ModelProject) but get this error:

Cannot convert lambda expression to type 'ServiceLifetime' because it is not a delegate type

Is this error for using EF on Core Project? how can i solve it?
ProjectB (Core):
services .AddEntityFrameworkSqlServer() .AddDbContext<Models.DataContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("DataContext")); });

and dbcontext (EntityFramework Standard):
namespace ModelProject
{
    public class DataContext : DbContext
    {
        public DataContext() : base("DataContext")
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, Migrations.Configuration>());
            (this as IObjectContextAdapter).ObjectContext.ContextOptions.UseCSharpNullComparisonBehavior = true;
            ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 300;
         }
     }
}

A: It needs to be:
.AddDbContext<Models.DataContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DataContext")));

In other words, without the curly brackets. You could alternatively just return the options instance, but that's all just unnecessary code-bloat. The exception is a red herring. Because your lambda currently is essentially an action (no return) rather than a func, it's not matching the right param for AddDbContext.


text:
Q: Why are the loops in my program not terminating? My code is meant to display the least number of coins that a person would need for a certain amount of money. I converted the value into cents and then used loops to test for every different coin. You may see printf for variables that I used for testing purposes to see where it was going wrong. The loops just continue forever and do not subtract the value of C as many times as the loop repeats. ex. c-25 stays at 475 cents instead of going down by 25 each time the loop repeats (for value of $5.00).
#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main(void)
{
float c=0;
int i=0;
int y=0;

    printf("How much change do you owe?\n");
    c=GetFloat();
    c=c*100;
    printf("%f\n", c);
    do
    {
        c-25;
        printf("%d\n", c-25);
        if (c>25)
        {
            i++;
            printf("%d\n", i);
        }
    }
        while (c>=25);
    printf("%d\n", i);

    do
    {
        y=c-10;
        if (y>0)
        {
            i++;
        }
    }
        while (y>10);
    if (y<=10)
    {
        printf("%d\n", i);
    }
    do
    {
        y=c-5;
        if (y>0)
        {
            i++;
        }
    }
        while (y>5);
    if (y<=5)
    {
        printf("%d\n", i);
    }
    do
    {
        y=c-1;
        if (y>0)
        {
            i++;
        }
    }
        while (y>1);
    if (y==0)
    {
        printf("%d\n", i);
    }
}

Note: This is for the "Time For Change" program in CS50

A: c is never changed.
There is no effect to the statement:
c-25;

which should probably be:
c = c - 25;

or
c -= 25;

A: Here are some remarks on your code:
#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main(void){
// use self-explanatory and meaningful names of your variables
float c = 0;
int i = 0;
int y = 0;

// input
printf("How much change do you owe?\n");
c = GetFloat();
c = c * 100;
// print input
printf("%f\n", c);

// add comment explaining the purpose of this loop
do{
    c = c - 25; // corrected to decrement by 25

    printf("%d\n", c);
    if (c > 25){
        i++;
        printf("%d\n", i);
    }
}while(c >= 25);

printf("%d\n", i);

// add comment explaining the purpose of this loop
do{
    y = c - 10;
    if (y > 0){
        i++;
    }
}while(y > 10);

// add comment explaining the purpose of this condition statement
if (y <= 10){
    printf("%d\n", i);
}

// add comment explaining the purpose of this loop
do{
    y = c-5;
    if (y > 0){
        i++;
    }
}while(y > 5);

// add comment explaining the purpose of this condition statement
if (y <= 5){
    printf("%d\n", i);
}

// add comment explaining the purpose of this condition statement
do{
    y = c-1;
    if (y > 0){
        i++;
    }
}while(y > 1);
// add comment explaining the purpose of this condition statement
if(y == 0){
    printf("%d\n", i);
}
}

The main problems come from the termination conditions and the counter variables incrementation/ decrementation, which are wrong or missing and that is leading to infinite loops.


text:
Q: Sort Sitemap URLs By Last Modified Date I have an XML 1.0 sitemap like this:
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://localhost/page-1</loc>
<lastmod>2020-09-21</lastmod>
</url>
<url>
<loc>http://localhost/page-2</loc>
<lastmod>2020-09-23</lastmod>
</url>
</urlset>

Here's the XSLT 1.0 stylesheet for the above XML sitemap:
<xsl:template match="sm:urlset">

URL
Last Modified

<xsl:for-each select="sm:url">

<xsl:variable name="pos">
<xsl:value-of select="position()" />
</xsl:variable>
<xsl:variable name="loc">
<xsl:value-of select="sm:loc" />
</xsl:variable>
<xsl:variable name="lastmod">
<xsl:value-of select="sm:lastmod" />
</xsl:variable>

<xsl:value-of select="$pos" />

<xsl:value-of select="$loc" />

<xsl:value-of select="$lastmod" />

</xsl:for-each>

</xsl:template>

How can I sort the sitemap by sm:lastmod (last modified) date? Please note that I'm using Microsoft Edge Version 87.0.664.60 (Chromium Embedded Framework based) at the moment.

A: With XSLT 3 and higher order functions (Saxon 10 all editions, Saxon 9.8 and 9.9 PE and EE, Saxon JS 2) support the most compact would be xsl:for-each select="sort(sm:url, (), function($url) { $url/sm:lastmod })".
Otherwise of course use xsl:sort inside of the for-each: <xsl:sort select="sm:lastmod"/>.


text:
Q: NIC binding order I wrote a command to check NIC binding order. But the problem here is, I am getting all NIC details of the machine, but the binding order listed is not correct.
Can anyone help me to correct this command, so that I can get the NIC details in binding order ?
$adapter = Invoke-Command -ComputerName $ComputerName {(Get-NetAdapter).Name }

A: I believe the InterfaceMetric is the 'weight' of a specific Interface in Get-NetIPInterface, hopefully that's what you're looking for.
Get-NetIPInterface | Select Interface*,AddressFamily | Sort InterfaceMetric -Descending

Narrowing it down to only 'valid' endpoints (you can exclude IPv6 from this afterwards if needed)
Get-NetAdapter | Get-NetIPInterface | Select Interface*,AddressFamily | ? {$_.InterfaceMetric} | Sort InterfaceMetric -Desc


text:
Q: Running hadoop job: Class not found - org.apache.tools.ant.launch.AntMain I have locally installed Hadoop on Debian linux distribution in vmware and I am having difficulties running my test jobs.
I can easily build create the package with IntelliJ Idea, even my mrunit tests pass as expected.
Once I try to run the job, I get following exception:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/tools/ant/launch/AntMain
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:190)
Caused by: java.lang.ClassNotFoundException: org.apache.tools.ant.launch.AntMain
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)

I made sure, all the dependencies, are included in the jar - I can see, that ANT 1.6.5 is included.
I even tried to install ANT and set $ANT_HOME to its location, but with no effect.
What I might be doing wrong?
I am using following pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>tl.knyt</groupId>
    <artifactId>hanoi</artifactId>
    <version>1.0</version>
    <name>Hanoi</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-core</artifactId>
            <version>0.20.2-cdh3u4</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-mrunit</artifactId>
            <version>0.20.2-cdh3u4</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>

    </dependencies>
    <repositories>
        <repository>
            <id>cloudera.repos</id>
            <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
            <name>Cloudera Repos</name>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

Thanks!

A: Make sure in your hadoop classpath you have the  jar file for org/apache/tools/ant/launch/AntMain
you can edit the jar file in $HADOOP_HOME/conf/hadoop-site file
you'll have to restart hadoop for the change to take effect.


text:
Q: Android studio import module button missing I've got a long history with Eclipse, but I wanted to try Android Studio. So I created new project and now I want to add SlidingMenu library to it. I found some tutorials whose say to go to Project structure, click plus button and select Import module.
But there is no Import module option, when I click plus then New Module window pops up. I'm currenty using Android studio v0.3.6. Is now proccess to import module different?
Thanks

A: The Import Module feature has been removed for Gradle-based projects because it previously didn't do the right thing with your Gradle build files and it would put your project in a confusing state; it will be re-enabled when it's properly implemented. The bug tracking it is at https://code.google.com/p/android/issues/detail?id=62122.
In the meantime, to add a module, you need to write a build.gradle file for it by hand, add a reference to the module to your settings.gradle file, and if the project is still open in Android Studio after you make the changes, click on the "Sync Project with Gradle Files" button in the toolbar.
If you're not familiar with Gradle, you can get docs on the particulars of Android Gradle projects at http://tools.android.com/tech-docs/new-build-system/user-guide.


text:
Q: How do I fix the width of bootstrap navbar on a tablet This is what it looks like on my tablet:

When I inspect remotely in chrome, I see that the body width(600px) is not that of the document, being set by a div with a min-width:1000px;.
How can i get the bootstrap navbar to fill the full width?
You can access the website suphearst.ca

A: the solution is too simple
just add min-width:1000px; to body

A: It sounds to me that you are missing the viewport meta tag in your html document. It will fix your problem and render the document after the device scale.
<meta name="viewport" content="width=device-width, initial-scale=1">

You can read more about it here