Q: How to fetch only the documents that have 3 different values in mongodb? I have the following data in mongodb:
    {
        "_id" : ObjectId("111"),
        "id" : "111",
        "classification" : [
            {
                "annotator" : "annotatorName1",
                "category" : "white"
            },
            {
                "annotator" : "annotatorName2",
                "category" : "white"
            },
            {
                "annotator" : "annotatorName3",
                "category" : "black"
            }
        ]
    }

   {
        "_id" : ObjectId("222"),
        "id" : "222",
        "classification" : [
                   {
                "annotator" : "annotatorName1",
                "category" : "white"
            },
            {
                "annotator" : "annotatorName2",
                "category" : "blue"
            },
            {
                "annotator" : "annotatorName3",
                "category" : "black"
            }
        ]
    }

  {
        "_id" : ObjectId("333"),
        "kind" : "youtube#video",
        "etag" : "tagvalue",
        "id" : "333"
    }

Please note that the classification label does not exists in all my records, as shown in record with id: "333".
I need to get all the records from my database that have different category values.
So, I need a query that when I run it, I will only get the record that has the classification label, and has exactly 3 different category values, in this case, I want a query that will only return this to me:
{
        "_id" : ObjectId("222"),
        "id" : "222",
        "classification" : [
            {
                "annotator" : "annotatorName1",
                "category" : "white"
            },
            {
                "annotator" : "annotatorName2",
                "category" : "blue"
            },
            {
                "annotator" : "annotatorName3",
                "category" : "black"
            }
        ]
    }

What command should I enter in my terminal in order to get all the records that have 3 unique category values under classification, IFF classification exists?
Thank you for your help.

A: The below aggregate can be used to find out the "id"s which have exactly 3 unique categories:
db.collectionName.aggregate([
  {$match : {classification : {$exists : true}}},
  {$unwind: "$classification"},
  {$group: { _id: "$id", uniqueCategories: {$addToSet: "$classification.category"}}},
  {$project: {_id : 1, numberOfCategories: {$size: "$uniqueCategories"}} },
  {$match: {numberOfCategories: 3} }
])

Explanation: We start with matching documents which have the classification element. Then we $unwind it so as to deconstruct the embedded array into separate documents. Then it is grouped by id, and using $addToSet the categories are collected into an array - this takes care of eliminating any dupes. Then we project its $size and match on 'equal to 3'.
This aggregate will yield documents with the _id set to the id field of the documents in your collection that have 3 unique categories, which you can use to get to the documents. If your collection size is quite large, you should consider adding another $match stage in the beginning to restrict the dataset. As it stands now, it will be doing a collection scan.


Q: Why does Keras convert the input shape from (3,3) to (?,3,3)? I am currently trying to get custom keras layers to work, you can see a simplified version here:
class MyLayer(Layer):

    def __init__(self, **kwargs):
        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        print("input_shape: "+str(input_shape))
        self.kernel = self.add_weight(name='kernel',
                                      shape=(input_shape[1], self.output_dim),
                                      initializer='uniform',
                                      trainable=True)
        super(MyLayer, self).build(input_shape)

    def call(self, x):
        print("input tensor: "+str(x))
        return K.dot(x, self.kernel)

inputs = Input(shape=(3,3), dtype='float', name='inputs')
results = MyLayer(input_shape=(3,3))(inputs)

The resulting console output is this:
input_shape: (None, 3, 3)
input tensor: Tensor("inputs:0", shape=(?, 3, 3), dtype=float32)

As you can see, the input_shape that the layer gets is not (3,3) as I specified but actually (None,3,3). Why is that?
The shape of the input tensor is also shaped ( ?, 3,3) which I thought to be a consequence of the weird input_shape ( None, 3,3). But the input tensor also has this shape with a third dimension if you replace super(MyLayer, self).build(input_shape) with super(MyLayer, self).build((3,3)). What is this mysterious third dimension keras automatically adds and why does it do that?

A: It is nothing mysterious, it is the batch dimension, since keras (and most DL frameworks), make computations on batches of data at a time, since this increases parallelism, and it maps directly to batches in Stochastic Gradient Descent.
Your layer needs to support computation on batches, so the batch dimension is always present in input and output data, and it is automatically added by keras to the input_shape.

A: This newly added dimension refers to the batch dimension, i.e., in your case, you will be passing batches of 3x3 dimensional tensors. This additional None dimension refers to the batch dimension, which is unknown during the creation of the graph.
If you have a look at the Input layer explanation in Core Layers webpage for Keras,
https://keras.io/layers/core/, you will see that the shape argument you are passing when creating the Input layer is defined as the following:

shape: A shape tuple (integer), not including the batch size. For instance, shape=(32,) indicates that the expected input will be batches of 32-dimensional vectors.

A: If you want to specify the batch size, you can do this instead:
inputs = Input(batch_shape=(batch_size,height,width,channel))


Q: CSS rotate3d property behaving unexpectedly I was reading about the CSS rotate3d() property to rotate an element. I thought that the first three parameters in the function are multipliers and the fourth one is the degree magnitude.
The value of multipliers has to be between 0 and 1. This means that rotate3d(1, 0, 0, 90deg) will only result in rotateX(90deg). To get more range of rotations I changed it to rotate3d(0.25, 0, 0, 360deg) but it produces entirely different result.
I also noticed that transform: rotateX(45deg) rotateY(45deg); is not the same as transform: rotate3d(1,1,0, 45deg);. etc. If we cannot simply change the multiplier of required dimensions to get desired rotations, how should I calculate the value of three multipliers?
Thanks.

A: When using rotate3d(x, y, z, a) the first 3 numbers are coordinate that will define the vector of the rotation and a is the angle of rotation. They are not multiplier of the rotation.
rotate3d(1, 0, 0, 90deg) is the same as rotate3d(0.25, 0, 0, 90deg) and also the same as rotate3d(X, 0, 0, 90deg) because we will have the same vector in all the cases. Which is also the same as rotateX(90deg)

.box {
  margin:30px;
  padding:20px;
  background:red;
  display:inline-block;
}

From this we can also conclude that rotate3d(0, Y, 0, a) is the same as rotateY(a) and rotate3d(0, 0, Y, a) the same as rotate(a). Note the use of 0 in two of the coordinates which will make our vector always in the same axis (X or Y or Z)

rotate3d(1,1,0, 45deg) is not the same as rotateX(45deg) rotateY(45deg). The first one will perform one rotation around the vector defined by (1,1,0) and the second one will perform two consecutive rotation around the X and Y axis.
In other words, rotate3d() is not a combination of the other rotation but a rotation on its own. The other rotation are particular cases of rotate3d() considering predefined axis.

The multiplier trick apply to the coordinate if you keep the same angle. rotate3d(x, y, z, a) is equivalent to rotate3d(p*x, p*y, p*z, a) because if you multiply all the coordinates with the same value, you keep the same vector direction and you change only the vector dimension which is irrelevant when defining the rotation. Only the direction is relevant.
More details here: https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate3d
You can clearly notice that using values in the range of [-1,1] for x,y,z is enough to define all the combination. In the other hand, any combination of x,y,z can be reduced to values inside the range [-1,1]
Examples:

.box {
  margin:30px;
  padding:20px;
  background:red;
  display:inline-block;
}

We simply divide by the biggest number.


Q: how to count word frequency of words in dictionary? I have a dictionary like below:
[{'mississippi': 1, 'worth': 1, 'reading': 1}, {'commonplace': 1, 'river': 1, 'contrary': 1, 'ways': 1, 'remarkable': 1}, {'considering': 1, 'missouri': 1, 'main': 1, 'branch': 1, 'longest': 1, 'river': 1, 'world--four': 1}, {'seems': 1, 'safe': 1, 'crookedest': 1, 'river': 1, 'part': 1, 'journey': 1, 'uses': 1, 'cover': 1, 'ground': 1, 'crow': 1, 'fly': 1, 'six': 1, 'seventy-five': 1}, {'discharges': 1, 'water': 1, 'st': 1}, {'lawrence': 1, 'twenty-five': 1, 'rhine': 1, 'thirty-eight': 1, 'thames': 1}, {'river': 1, 'vast': 1, 'drainage-basin:': 1, 'draws': 1, 'water': 1, 'supply': 1, 'twenty-eight': 1, 'states': 1, 'territories': 1, 'delaware': 1, 'atlantic': 1, 'seaboard': 1, 'country': 1, 'idaho': 1, 'pacific': 1, 'slope--a': 1, 'spread': 1, 'forty-five': 1, 'degrees': 1, 'longitude': 1}, {'mississippi': 1, 'receives': 1, 'carries': 1, 'gulf': 1, 'water': 1, 'fifty-four': 1, 'subordinate': 1, 'rivers': 1, 'navigable': 1, 'steamboats': 1, 'hundreds': 1, 'flats': 1, 'keels': 1}, {'area': 1, 'drainage-basin': 1, 'combined': 1, 'areas': 1, 'england': 1, 'wales': 1, 'scotland': 1, 'ireland': 1, 'france': 1, 'spain': 1, 'portugal': 1, 'germany': 1, 'austria': 1, 'italy': 1, 'turkey': 1, 'almost': 1, 'wide': 1, 'region': 1, 'fertile': 1, 'mississippi': 1, 'valley': 1, 'proper': 1, 'exceptionally': 1}]

And I want to change it to my desired output like below to calculate score of similarity between two target words:
river 4
    ground: 1
    journey: 1
    longitude: 1
    main: 1
    world--four: 1
    contrary: 1
    cover: 1
    delaware: 1
    remarkable: 1
    vast: 1
    forty-five: 1
    crookedest: 1
    territories: 1
    spread: 1
    country: 1
    longest: 1
    fly: 1
    atlantic: 1
    crow: 1
    supply: 1
    seems: 1
    idaho: 1
    seaboard: 1
    states: 1
    ways: 1
    degrees: 1
    part: 1
    twenty-eight: 1
    pacific: 1
    branch: 1
    water: 1
    considering: 1
    six: 1
    safe: 1
    commonplace: 1
    draws: 1
    drainage-basin: 1
    uses: 1
    seventy-five: 1
    slope--a: 1
    missouri: 1
mississippi 3
    area: 1
    steamboats: 1
    germany: 1
    reading: 1
    france: 1
    proper: 1
    fifty-four: 1
    turkey: 1
    exceptionally: 1
    areas: 1
    carries: 1
    combined: 1
    flats: 1
    receives: 1
    england: 1
    italy: 1
    scotland: 1
    wales: 1
    almost: 1
    navigable: 1
    austria: 1
    region: 1
    wide: 1
    spain: 1
    subordinate: 1
    drainage-basin: 1
    hundreds: 1
    keels: 1
    portugal: 1
    water: 1
    gulf: 1
    ireland: 1
    rivers: 1
    valley: 1
    fertile: 1
    worth: 1
water 3
    steamboats: 1
    spread: 1
    country: 1
    states: 1
    longitude: 1
    fifty-four: 1
    pacific: 1
    vast: 1
    subordinate: 1
    carries: 1
    keels: 1
    flats: 1
    supply: 1
    receives: 1
    atlantic: 1
    forty-five: 1
    river: 1
    rivers: 1
    idaho: 1
    mississippi: 1
    seaboard: 1
    navigable: 1
    discharges: 1
    degrees: 1
    twenty-eight: 1
    drainage-basin: 1
    hundreds: 1
    st: 1
    gulf: 1
    draws: 1
    delaware: 1
    territories: 1
    slope--a: 1
drainage-basin 2
    area: 1
    spread: 1
    country: 1
    states: 1
    mississippi: 1
    longitude: 1
    france: 1
    proper: 1
    vast: 1
    turkey: 1
    forty-five: 1
    areas: 1
    combined: 1
    germany: 1
    exceptionally: 1
    valley: 1
    supply: 1
    fertile: 1
    atlantic: 1
    italy: 1
    river: 1
    idaho: 1
    wales: 1
    almost: 1
    seaboard: 1
    spain: 1
    austria: 1
    region: 1
    degrees: 1
    twenty-eight: 1
    wide: 1
    england: 1
    portugal: 1
    water: 1
    ireland: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    scotland: 1
    slope--a: 1
area 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    england: 1
    turkey: 1
    exceptionally: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
journey 1
    ground: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
seems 1
    ground: 1
    journey: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
states 1
    spread: 1
    country: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
    idaho: 1
slope--a 1
    spread: 1
    country: 1
    states: 1
    degrees: 1
    longitude: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    twenty-eight: 1
    river: 1
    idaho: 1
remarkable 1
    contrary: 1
    river: 1
    commonplace: 1
    ways: 1
vast 1
    spread: 1
    country: 1
    states: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    pacific: 1
    forty-five: 1
    water: 1
    seaboard: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
    idaho: 1
forty-five 1
    spread: 1
    longitude: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    pacific: 1
    water: 1
    seaboard: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    twenty-eight: 1
    river: 1
    idaho: 1
crookedest 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
carries 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
germany 1
    area: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
longest 1
    main: 1
    river: 1
    world--four: 1
    branch: 1
    missouri: 1
    considering: 1
flats 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    gulf: 1
    rivers: 1
    receives: 1
supply 1
    spread: 1
    longitude: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    twenty-eight: 1
    river: 1
    idaho: 1
receives 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
crow 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
scotland 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    spain: 1
    italy: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
country 1
    spread: 1
    idaho: 1
    states: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
thames 1
    thirty-eight: 1
    rhine: 1
    lawrence: 1
    twenty-five: 1
england 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    region: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
navigable 1
    mississippi: 1
    steamboats: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
austria 1
    area: 1
    germany: 1
    mississippi: 1
    france: 1
    proper: 1
    region: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    exceptionally: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
rhine 1
    thirty-eight: 1
    thames: 1
    lawrence: 1
    twenty-five: 1
part 1
    ground: 1
    journey: 1
    seems: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
twenty-eight 1
    spread: 1
    country: 1
    states: 1
    degrees: 1
    longitude: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
    idaho: 1
branch 1
    main: 1
    longest: 1
    river: 1
    world--four: 1
    missouri: 1
    considering: 1
hundreds 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
st 1
    water: 1
    discharges: 1
considering 1
    main: 1
    longest: 1
    river: 1
    world--four: 1
    branch: 1
    missouri: 1
six 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    fly: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
gulf 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    flats: 1
    rivers: 1
    receives: 1
ireland 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    valley: 1
safe 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
commonplace 1
    contrary: 1
    river: 1
    remarkable: 1
    ways: 1
draws 1
    spread: 1
    longitude: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    supply: 1
    delaware: 1
    territories: 1
    atlantic: 1
    twenty-eight: 1
    river: 1
    idaho: 1
delaware 1
    spread: 1
    longitude: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    territories: 1
    atlantic: 1
    supply: 1
    twenty-eight: 1
    river: 1
    idaho: 1
thirty-eight 1
    thames: 1
    rhine: 1
    lawrence: 1
    twenty-five: 1
longitude 1
    spread: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    twenty-eight: 1
    river: 1
    idaho: 1
world--four 1
    main: 1
    longest: 1
    river: 1
    branch: 1
    missouri: 1
    considering: 1
lawrence 1
    thirty-eight: 1
    thames: 1
    rhine: 1
    twenty-five: 1
ground 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
steamboats 1
    mississippi: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
spread 1
    seaboard: 1
    country: 1
    states: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
    idaho: 1
idaho 1
    spread: 1
    country: 1
    states: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
reading 1
    mississippi: 1
    worth: 1
almost 1
    area: 1
    germany: 1
    austria: 1
    france: 1
    proper: 1
    england: 1
    turkey: 1
    exceptionally: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    mississippi: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
contrary 1
    river: 1
    remarkable: 1
    commonplace: 1
    ways: 1
cover 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
france 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    proper: 1
    england: 1
    turkey: 1
    exceptionally: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
spain 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
pacific 1
    spread: 1
    longitude: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    twenty-eight: 1
    river: 1
    idaho: 1
turkey 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
fifty-four 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    hundreds: 1
    keels: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
subordinate 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
territories 1
    spread: 1
    idaho: 1
    states: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    supply: 1
    atlantic: 1
    slope--a: 1
    river: 1
    country: 1
combined 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
exceptionally 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    england: 1
    turkey: 1
    region: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
region 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
twenty-five 1
    thirty-eight: 1
    thames: 1
    lawrence: 1
    rhine: 1
rivers 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    receives: 1
fly 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
atlantic 1
    spread: 1
    longitude: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    river: 1
    supply: 1
    twenty-eight: 1
    idaho: 1
italy 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
main 1
    world--four: 1
    longest: 1
    river: 1
    branch: 1
    missouri: 1
    considering: 1
areas 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    england: 1
    turkey: 1
    exceptionally: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
seaboard 1
    spread: 1
    country: 1
    states: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
    idaho: 1
fertile 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
ways 1
    contrary: 1
    river: 1
    remarkable: 1
    commonplace: 1
discharges 1
    water: 1
    st: 1
degrees 1
    spread: 1
    country: 1
    states: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
    idaho: 1
wide 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
proper 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    england: 1
    turkey: 1
    exceptionally: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
keels 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    water: 1
    fifty-four: 1
    hundreds: 1
    subordinate: 1
    carries: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
portugal 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    ireland: 1
    valley: 1
worth 1
    mississippi: 1
    reading: 1
uses 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    fly: 1
    seventy-five: 1
    river: 1
seventy-five 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    river: 1
    fly: 1
valley 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
missouri 1
    main: 1
    longest: 1
    river: 1
    branch: 1
    world--four: 1
    considering: 1
wales 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1

the first line is the target word and its frequency in the whole dictionary. Underneath is the associated words and their frequency in same sentence with target word. Like the first dictionary, the profile associated with "mississippi" will contain references to "worth" and "reading" and their word frequency in sentence is 1, but the word frequency of mississippi is 3 in entire dictionary. And I want to sort the word frequency of target word in descending order. Anyone can help?

A: It's not exactly clear neither from your desired output nor from your code what exactly are you trying to achieve but if it's just counting words in individual sentences then the strategy should be:

*

*Read your common.txt into a set for a fast lookup.

*Read your sample.txt and split on . to get individual sentences.

*Clear up all non-word characters (you'll have to define them or to use regex \b to capture word boundaries) and replace them with whitespace.

*Split on whitespace and count the words not present in the set from Step 1.

So:
import collections

with open("common.txt", "r") as f:  # open the `common.txt` for reading
    common_words = {l.strip().lower() for l in f}  # read each line and and add it to a set

interpunction = ";,'\""  # define word separating characters and create a translation table
trans_table = str.maketrans(interpunction, " " * len(interpunction))

sentences_counter = []  # a list to hold a word count for each sentence
with open("sample.txt", "r") as f:  # open the `sample.txt` for reading
    # read the whole file to include linebreaks and split on `.` to get individual sentences
    sentences = [s for s in f.read().split(".") if s.strip()]  # ignore empty sentences
    for sentence in sentences:  # iterate over each sentence
        sentence = sentence.translate(trans_table)  # replace the interpunction with spaces
        word_counter = collections.defaultdict(int)  # a string:int default dict for counting
        for word in sentence.split():  # split the sentence and iterate over the words
            if word.lower() not in common_words:  # count only words not in the common.txt
                word_counter[word.lower()] += 1
        sentences_counter.append(word_counter)  # add the current sentence word count

NOTE: On Python 2.x use string.maketrans() instead of str.maketrans().
This will produce sentences_counter containing a dictionary count for each of the sentences in sample.txt, where the key is an actual word and its associate value is the word count. You can print the result as:
for i, v in enumerate(sentences_counter):
    print("Sentence #{}:".format(i+1))
    print("\n".join("\t{}: {}".format(w, c) for w, c in v.items()))

Which will produce (for your sample data):
Sentence #1:
    area: 1
    drainage-basin: 1
    great: 1
    combined: 1
    areas: 1
    england: 1
    wales: 1
    wide: 1
    region: 1
    fertile: 1
Sentence #2:
    mississippi: 1
    valley: 1
    proper: 1
    exceptionally: 1
Keep in mind that (English) language is more complex than this - for example, "A cat wiggles its tail when it's angry so stay away from it." will vastly differ in dependence on how you treat an apostrophe. Also, a dot doesn't necessarily denote the end of a sentence. You should look into NLP if you want to do serious linguistic analysis.
UPDATE: While i don't see the usefulness of reiterating over each word repeating the data (the count won't ever change within a sentence) if you want to print each word and nest all the other counts underneath you can just add an inner loop while printing:
for i, v in enumerate(sentences_counter):
    print("Sentence #{}:".format(i+1))
    for word, count in v.items():
        print("\t{} {}".format(word, count))
        print("\n".join("\t\t{}: {}".format(w, c) for w, c in v.items() if w != word))

Which will give you:
Sentence #1:
    area 1
        drainage-basin: 1
        great: 1
        combined: 1
        areas: 1
        england: 1
        wales: 1
        wide: 1
        region: 1
        fertile: 1
    drainage-basin 1
        area: 1
        great: 1
        combined: 1
        areas: 1
        england: 1
        wales: 1
        wide: 1
        region: 1
        fertile: 1
    great 1
        area: 1
        drainage-basin: 1
        combined: 1
        areas: 1
        england: 1
        wales: 1
        wide: 1
        region: 1
        fertile: 1
    combined 1
        area: 1
        drainage-basin: 1
        great: 1
        areas: 1
        england: 1
        wales: 1
        wide: 1
        region: 1
        fertile: 1
    areas 1
        area: 1
        drainage-basin: 1
        great: 1
        combined: 1
        england: 1
        wales: 1
        wide: 1
        region: 1
        fertile: 1
    england 1
        area: 1
        drainage-basin: 1
        great: 1
        combined: 1
        areas: 1
        wales: 1
        wide: 1
        region: 1
        fertile: 1
    wales 1
        area: 1
        drainage-basin: 1
        great: 1
        combined: 1
        areas: 1
        england: 1
        wide: 1
        region: 1
        fertile: 1
    wide 1
        area: 1
        drainage-basin: 1
        great: 1
        combined: 1
        areas: 1
        england: 1
        wales: 1
        region: 1
        fertile: 1
    region 1
        area: 1
        drainage-basin: 1
        great: 1
        combined: 1
        areas: 1
        england: 1
        wales: 1
        wide: 1
        fertile: 1
    fertile 1
        area: 1
        drainage-basin: 1
        great: 1
        combined: 1
        areas: 1
        england: 1
        wales: 1
        wide: 1
        region: 1
Sentence #2:
    mississippi 1
        valley: 1
        proper: 1
        exceptionally: 1
    valley 1
        mississippi: 1
        proper: 1
        exceptionally: 1
    proper 1
        mississippi: 1
        valley: 1
        exceptionally: 1
    exceptionally 1
        mississippi: 1
        valley: 1
        proper: 1
Feel free to remove the sentence number printing and reduce one of the tab indentations to get something more of a desired output from your question. You can also build a tree-like dictionary instead of printing everything to the STDOUT if that's more what you fancy.
UPDATE 2: If you want, you don't have to use a set for the common_words. In this case it's pretty much interchangeable with a list so you can use list comprehension instead of set comprehension (i.e. replace curly with square brackets) but looking through a list is an O(n) operation whereas set lookup is an O(1) operation and therefore a set is preferred here. Not to mention the collateral benefit of automatic de-duplication in case the common.txt has duplicate words.
As for the collections.defaultdict() it's there just to save us some coding/checking by automatically initializing the dictionary to a key whenever it's requested - without it you'd have to do it manually:
with open("common.txt", "r") as f:  # open the `common.txt` for reading
    common_words = {l.strip().lower() for l in f}  # read each line and and add it to a set

interpunction = ";,'\""  # define word separating characters and create a translation table
trans_table = str.maketrans(interpunction, " " * len(interpunction))

sentences_counter = []  # a list to hold a word count for each sentence
with open("sample.txt", "r") as f:  # open the `sample.txt` for reading
    # read the whole file to include linebreaks and split on `.` to get individual sentences
    sentences = [s for s in f.read().split(".") if s.strip()]  # ignore empty sentences
    for sentence in sentences:  # iterate over each sentence
        sentence = sentence.translate(trans_table)  # replace the interpunction with spaces
        word_counter = {}  # initialize a word counting dictionary
        for word in sentence.split():  # split the sentence and iterate over the words
            word = word.lower()  # turn the word to lowercase
            if word not in common_words:  # count only words not in the common.txt
                word_counter[word] = word_counter.get(word, 0) + 1  # increase the last count
        sentences_counter.append(word_counter)  # add the current sentence word count

UPDATE 3: If you just want a raw word list across all sentences as it seems from your last update to the question, you don't even need to consider the sentences themselves - just add a dot to the interpunction list, read the file line by line, split on whitespace and count the words as before:
import collections

with open("common.txt", "r") as f:  # open the `common.txt` for reading
    common_words = {l.strip().lower() for l in f}  # read each line and and add it to a set

interpunction = ";,'\"."  # define word separating characters and create a translation table
trans_table = str.maketrans(interpunction, " " * len(interpunction))

sentences_counter = []  # a list to hold a word count for each sentence

word_counter = collections.defaultdict(int)  # a string:int default dict for counting
with open("sample.txt", "r") as f:  # open the `sample.txt` for reading
    for line in f:  # read the file line by line
        for word in line.translate(trans_table).split():  # remove interpunction and split
            if word.lower() not in common_words:  # count only words not in the common.txt
                word_counter[word.lower()] += 1  # increase the count

print("\n".join("{}: {}".format(w, c) for w, c in word_counter.items()))  # print the counts


Q: ngTable with ng-if is not working I'm using ng-table with angularJs as shown below.My problem is when I use ngTable it's rendered same column twice (MyColumn).In other words it doesn't consider the ng-if.How can I get rid of that issue ?
Note : But for the normal table it's working fine.Why is that not working with the ngTable ?
ngTable

      {{item.Value}}
       {{item.Value}}

A: I did it as shown below.It works fine. Hurray :D

      {{item.Value}}
      {{item.Value}}


Q: How to get the searched text in a string? I want to get a text that it is a part of an string.For example: I have a string like "I am Vahid" and I want to get everything that it's after "am".
The result will be "Vahid"
How can I do it?

A: Try:
Example1
String[] separated = CurrentString.split("am");
separated[0]; // I am
separated[1]; // Vahid

Example2
StringTokenizer tokens = new StringTokenizer(CurrentString, "am");
String first = tokens.nextToken();// I am
String second = tokens.nextToken(); //Vahid

A: Try:
String text = "I am Vahid";
String after = "am";
int index = text.indexOf(after);
String result = "";
if(index != -1){
    result = text.substring(index + after.length());
}
System.out.print(result);

A: Just use like this, call the method with your string.
public String trimString(String stringyouwanttoTrim)
{
  if(stringyouwanttoTrim.contains("I am")
  {
    return stringyouwanttoTrim.split("I am")[1].trim();
  }
  else
  {
    return stringyouwanttoTrim;
  }
}

A: If you prefer to split your sentence by blank space you could do like this :
 String [] myStringElements = "I am Vahid".split(" ");
 System.out.println("your name is " + myStringElements[myStringElements.length - 1]);


Q: sending mail in php with user informations hii evryone plz i need help i want to know why my code send only the attachment but not the others informations of my contact form here is my code php
here is my code the attachement is sent correctly but the other
informations not  i dont using any framework it is just php
i use a contact form with attachement
error_reporting(E_ALL);
ini_set("display_errors", 1); //Affichage des erreurs

//Eviter les insertions de scripts dans le cas d'un e-mail HTML
$nom = htmlentities($_POST['firstname']);
$email = htmlentities($_POST['email']);
$nom=$_POST['firstname'];
//$prenom = htmlentities($_POST['prenom']);

//Verifie si le fournisseur prend en charge les r
if(preg_match("#@(hotmail|live|msn).[a-z]{2,4}$#", $email)){
$passage_ligne = "\n";
}else{
$passage_ligne = "\r\n";
 }

  $email_to = "mon adresse email"; //Destinataire
  $email_subject = "Recrutement "; //Sujet du mail
  $boundary = md5(rand()); // clé aléatoire de limite

  $headers = "MIME-Version: 1.0\r\n";

  $headers.= "From: EA\r\n";
  $headers.= "Reply-To: EITA" . "\r\n";
  $headers.= "MIME-Version: 1.0" . $passage_ligne;
  $headers.= 'Content-Type: multipart/mixed; boundary='.$boundary .' '.
  $passage_ligne;

   //Pièce jointe
   if(isset($_FILES["fichier"]) && $_FILES['fichier']['name'] != ""){
   //Vérifie sur formulaire envoyé et que le fichier existe
    $nom_fichier = $_FILES['fichier']['name'];

   $source = $_FILES['fichier']['tmp_name'];
   $type_fichier = $_FILES['fichier']['type'];
   $taille_fichier = $_FILES['fichier']['size'];

 if($nom_fichier != ".htaccess"){ //Vérifie que ce n'est pas un .htaccess
 if($type_fichier == "image/jpeg"
 || $type_fichier == "image/pjpeg"
 || $type_fichier == "application/pdf"){ //Soit un jpeg soit un pdf

   if ($taille_fichier <= 2097152) { //Taille supérieure à Mo (en octets)
  $tabRemplacement = array("é"=>"e", "è"=>"e", "à"=>"a"); //Remplacement des
  caractères spéciaux

   $handle = fopen($source, 'r'); //Ouverture du fichier
   $content = fread($handle, $taille_fichier); //Lecture du fichier
    $encoded_content = chunk_split(base64_encode($content)); //Encodage
    $f = fclose($handle); //Fermeture du fichier
   //$message.='--'.$passage_ligne."\r\n";
   $email_message.="Content-Type: pdf; name=".$nom_fichier."\r\n";
    $email_message.="Content-Transfer-Encoding: BASE64"."\r\n";
    $email_message.="Content-Disposition: attachment;
   filename=".$nom_fichier."\r\n\r\n";
   $email_message.=
   chunk_split(base64_encode(file_get_contents($nom_fichier)))."\r\n";

   $email_message.='--'.$passage_ligne.'--'."\r\n";
   $email_message .= $encoded_content."n"; //Pièce jointe
   //$email_message .="Hello";

 }else{
 //Message d'erreur
  $email_message .= $passage_ligne ."L'utilisateur a tenté de vous envoyer
 une pièce jointe mais celle ci était superieure à 2Mo.". $passage_ligne;
 }
 }else{
 //Message d'erreur
 $email_message .= $passage_ligne ."L'utilisateur a tenté de vous envoyer
  une pièce jointe mais elle n'était pas au bon format.". $passage_ligne;
 }
 }else{
 //Message d'erreur
  $email_message .= $passage_ligne ."L'utilisateur a tenté de vous envoyer
  une pièce jointe .htaccess.". $passage_ligne;
   }
   }
  $email_message .= $passage_ligne . "--" . $boundary . "--" .
 $passage_ligne; //Séparateur de fermeture
 $msg.=$email_message.$nom."bonjour";
  if(mail($email_to,$email_subject, $msg, $headers)==true){ //Envoi du mail
  header('Location: index.php'); //Redirection
  }

  ?>


Q: Expose Serializable Enum attributes in WCF I am trying to to expose an Enum from my WCF class (basically as a mechanism for passing a constant). When I look at the service reference code or the WSDL there is no sign of the Enum and I cannot use it. Why not?
[Serializable]
[DataContract]
public class MyRequest
{
    [DataContract]
    public enum Constants
    {
        [EnumMember]
        MaxMaxArticles = 1000
    }
}

A: I suspect you haven't used the enum anywhere in the contract. Unless you have, there is no reason that it would be included in the graph that it builds by walking members from the root contract type. It will not be included just because it is nested: it needs to be actually used somewhere.


Q: Array becomes undefined after page reload I am working on Angular WebApi. I have a database response on localhost in JSON format.
When I run my application, I can see the array oData. But when I reload the page then oData becomes undefined.
How can I solve this?
Here is my code from the .ts file:
  ngOnInit(): void {

    this.mydataser.getDbData().subscribe(data => {
      this.oData = data;
    });
  }

 public importData() {
    console.log(this.oData)
 }

Here is my service:
  getDbData(): Observable<DataFactory[]> {
    return this.http.get<DataFactory[]>("https://localhost:44216/api/dbdata");
  }

P.S. I tried to use localstorage but it does not work.

A: Declare data as an empty array; if you don't do it will be undefined until the API response is completed. If you want to know when the response is actually coming just use tap. So If you want to call importData() after API response is received then call this.importData() method inside subscribe like
// declare as empty array
oData = [];
buttonEnabled = false;

ngOnInit(): void {
    this.mydataser.getDbData().pipe(
        tap(d => this.buttonEnabled = true)
    ).subscribe(data => {
        this.oData = data;
    });
}

importData(): void{
 console.log(this.o.Data);
}

In template:
<button [disabled]="!buttonEnabled">Import</button>


Q: WCF Service Interface - XElement vs. XmlElement vs. xml string I am doing some work which requires a WCF Service interface (in C#). The data exchanged (sent and recieved) will be in the xml format --- I cannot use strong datatypes because the interface needs to support multiple clients which have different requirements.
My question is which one of these is preferable:
XElement MyServiceMethod(XElement inputParam 1)
{

    XElement retValue;

    //
    // Operation occurs here
    //

    return (retValue);

}

vs
XmlElement MyServiceMethod(XmlElement inputParam 1)
{
XmlElement retValue;

//
// Operation occurs here
//

return (retValue);

}
vs
//
//inputParam is an xml formatted string
//
string MyServiceMethod(string inputParam 1)
{

    string retValue;

    //
    // Operation occurs here
    //

        //retValue is an xml formatted string
    return (retValue);

}

The code will be consumed via SOAP interface primarily, though it may ultimately be consumed via REST as well.
Is there a "best" approach"? Likewise, is there one that is completely not desirous.


Q: Unable to change color of first text box in every row of table using jquery I am trying to change the background color of first text box in every row in a table and using below code for same purpose.
Somehow it does not seem to be working. Please help.

text1
<input type="text">
<input type="text">

text2
<input type="text">
<input type="text">

text3
<input type="text">
<input type="text">

A: Use :first selector with .find() to get input descendants.
$('tr').find(':text:first').css('background-color','#C0C0C0');

Demo
$("tr:text:first") in your code, finds tr with :text(type="text") which is invalid.

 does not have :text

A: Have you tried $("tr input:first-child").css('background-color','#C0C0C0'); ?

A: Also, if you can't get jQuery to work, it would be simple enough to add a class to the first table cell in each table row and style it that way, forgoing the time it would take to load jQuery(if that is an issue, as I have sometimes found it to be).


Q: Does Heroku support foreign key and unique constraints? I'm considering moving a Rails app to Heroku.
In general I add FK constraints with ON DELETE behavior to all FKs. Up to now I've done this by writing raw SQL to add the constraints, as Rails Migrations don't provide a way to do that.
I also add UNIQUE keys where needed.
Will I still be able to add constraints in this way if I move to Heroku?
Another way to put this question would be, do I get direct access to my DB with Heroku, or am I limited to what I can do in migrations?

A: You can execute any SQL you want in a migration using connection.execute, for example:
def up
    connection.execute(%q{
        alter table t add constraint c check (x in ('a', 'b', 'c'))
    })
end
def down
    connection.execute('alter table t drop constraint c')
end

You can also use foreigner to add proper FK support to your migrations and schema.rb if you don't want to manage your FKs through raw SQL.
You can use the :unique => true option to add_index to get unique constraints/indexes.
I've done all of this and even added functions (both SQL and Pl/pgSQL) and triggers to a dedicated PostgreSQL database at Heroku. I'm not sure how much is supported on the shared databases but unique indexes certainly will be and I'm pretty sure FKs and CHECKs will be available as well.


Q: How to declare two data types containing same variable in haskell? In a module, I want to add two classes like this.
data Person = Person { name :: String -- and some other details
                     }

data PetAnimal = PetAnimal { name :: String
                           }

I assumed this would work but ghc complains about multiple declrations of name. How do I accomplish this?

A: The problem here, I believe, is that Haskell defines access functions for all the fields in a record, so you get one function
name :: Person -> String

and then one
name :: PetAnimal -> String

which is what the compiler does not like.
You could change one or both of the names, or put them in different modules.

A: Type Classes are another way to achieve a common interface that you may consider.
data Person = Person { personname :: String -- and some other details
                     }

data PetAnimal = PetAnimal { petanimalname :: String
                           }

class HasName a where
  name :: a -> String

instance HasName PetAnimal where
   name = petanimalname

instance HasName Person where
   name = personname


Q: Get current latitude and longitude plus 500 meters Hi friends, I am having one event latitude and longitude, To checkin to this event i must be within 500 meters of that event.
I am getting current location using:
Geolocation.getLocation().then(function(position){
        $scope.position = position.coords;
        // console.log( $scope.position)
        $scope.locationError = null;
    });

Have to validate this current location with event latitude longitude coming from Api, if this current location is equal to or less than 500 meters then only user is able to checkin, Any help would be great

A: Hypothetically you need the distance between 2 geo locations. From the event geolocation to the the one calculated.
An identical thread from stackoverflow : Calculate distance between 2 GPS coordinates


Q: Dynamically load jade templates I'm working on a small documentation website and the content is stored in files. For instance I have two files chapter1.jade and chapter2.jade in a module1/ directory.
I'd like to read the module1/ directory and dynamically include all the chapterX.jade files in it.
I tried to have do directory = fs.readDirSync('module1/') and then in my view:
each item in directory
  include item

But jade include doesn't support dynamic values (even `include #{item}) doesn't work. Do you have any idea how I could implement this ?
EDIT: I'd like to generate some code under the each loop (anchor for easy linking) so the solution would preferabily be in the view. I could obviously manually add the anchor in the included files but it is not ideal.
Thanks

A: Here is the short version of what I've done to make it work. It uses the jade Public API.
var directory = __dirname+'/views/bla/'
  , files
  , renderedHTML = '';

if( !fs.existsSync(directory) ) {
  // directory doesn't exist, in my case I want a 404
  return res.status(404).send('404 Not found');
}

// get files in the directory
files = fs.readdirSync(directory);

files.forEach(function(file) {
  var template = jade.compile(fs.readFileSync(directory+file, 'utf8'));

  // some templating
  renderedHTML += '
 '+template()+'
';
});

// render the actual view and pass it the pre rendered views
res.render('view', {
  title: 'View',
  files: files,
  html: renderedHTML
})

And the view just renders the html variable unescaped:
div(class="component-doc-wrap")
  !{html}

A: As @user1737909 say, that's not possible using just jade.
The best way to do this (tho) is building a little Express Dynamic (view) Helpers
DEPECATED IN EXPRESS 3.XX
Check these:  Jade - way to add dynamic includes

A: in addition to kalemas answer you can also write your includes to a file which is included in jade.
in this example I write my includes to include_all.jade. This file is included in a jade file.
If it does not work, check the path ;-)
e.g.
in your app.js
var includes = "path/to/include1\n";
includes += "path/to/include2";
...
incPath = "path/to/include_all.jade";

fs.open(incPath,'w',function(err,fd){
if(err){
    throw 'error open file: ' + incPath +" "+ err;
}

var buffer = new Buffer(includes);
 fs.write(fd,buffer,0,buffer.length,null,function(err){
    if (err)
        throw 'error writing file: ' +err;
    fs.close(fd,function(){
        console.log('file written ' + incPath);
    });
 });
});

in your jade file
include path/to/include_all.jade


Q: WordPress : Form data is not displaying via echo I have created a form to which I am passing the data. When I try to echo the data it shows couple of errors saying that index is undefined.
<?php /* Template Name: Dummy Practice Page*/?>

    <form method='post' enctype='multipart/form-data'>
                <input id="name" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required>

                <input id="designation" type="text" style="height:30px; width: 350px; " maxlength="50" placeholder="Designation" required>

                <input id="description" type="text" style="height:30px; width: 350px; " maxlength="1000" placeholder="Description" required>

                <input id="pic" type="file" style="height:30px; width: 350px; ">

                <input name="insert" type='submit' style="height:40px; width: 130px; padding:10px; color:dodgerblue; background-color:black; border-radius:20px;    " name='Submit' value='Add Member' />

            </form>

<?php
if(isset($_POST['insert']))
{
    echo $namevar = isset($_POST['name']);
    echo $descriptionvar = isset($_POST['description']);
    echo $designationvar = isset($_POST['designation']);
}
?>

Following are the errors:

Notice: Undefined index: name in C:\xampp\htdocs\wordpress\wp-content\themes\twentyfifteen-child\practicepage.php
  Notice: Undefined index: description in C:\xampp\htdocs\wordpress\wp-content\themes\twentyfifteen-child\practicepage.php
  Notice: Undefined index: designation in C:\xampp\htdocs\wordpress\wp-content\themes\twentyfifteen-child\practicepage.php

A: The issue is with the names of input fields.
In PHP or any other programming language, You should use the input name="something" to get the input values.
You should give the name for each input fields.
For example,
<input name = "name" id="name" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required>

A:     <form method='post' enctype='multipart/form-data'>
                <input name="name" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required>

                <input name="designation" type="text" style="height:30px; width: 350px; " maxlength="50" placeholder="Designation" required>

                <input name="description" type="text" style="height:30px; width: 350px; " maxlength="1000" placeholder="Description" required>

                <input id="pic" type="file" style="height:30px; width: 350px; ">

                <input name="insert" type='submit' style="height:40px; width: 130px; padding:10px; color:dodgerblue; background-color:black; border-radius:20px;" value='Add Member' />

    </form>
<?php
if(isset($_POST['insert']))
{
    echo $namevar = $_POST['name'];
    echo $descriptionvar = $_POST['description'];
    echo $designationvar = $_POST['designation'];
}
?>

A: You cannot pass POST data to another page vie using ID.
You should give name to <input>
<input name="name">
<input name="description">
<input name="designation">

Edit
You are defining variables and echoing them same time
Change your code to:
<?php
if(isset($_POST["insert"])){
  echo $_POST["name"];
  echo $_POST["description"];
  echo $_POST["designation"];
}?>


Q: PyMySQL different updates in one query? So I have a python script that goes through roughly 350,000 data objects, and depending on some tests, it needs to update a row which represents each one of those objects in a MySQl db. I'm also using pymysql as I've had the least trouble with it especially when sending over large select queries (select statements with where column IN (....) clause that can contain 100,000+ values).
Since each update for each row can be different, each update statement is different. For example, for one row we might want to update first_name but for another row we want to leave first_name untouched and we want to update last_name.
This is why I don't want to use the cursor.executemany() method which takes in one generic update statement and you then feed it the values however as I mentioned, each update is different so having one generic update statement doesn't really work for my case. I also don't want to send over 350,000 update statements individually over the wire. Is there anyway I can package all of my update statements together and send them at once?
I tried having them all in one query and using the cursor.execute() method but it doesn't seem to update all the rows.

A: Your best performance will be if you can encode your "tests" into the SQL logic itself, so you can boil everything down to a handful of UPDATE statements.  Or at least get as many as possible done that way, so that fewer rows need to be updated individually.
For example:
UPDATE tablename set firstname = [some logic]
WHERE [logic that identifies which rows need the firstname updated];

You don't describe much about your tests, so it's hard to be sure.  But you can typically get quite a lot of logic into your WHERE clause with a little bit of work.
Another option would be to put your logic into a stored procedure.  You'll still be doing 350,000 updates, but at least they aren't all "going over the wire".  I would use this only as a last resort, though; business logic should be kept in the application layer whenever possible, and stored procedures make your application less portable.

A: SQL #1: CREATE TABLE t with whatever columns you might need to change.  Make all of them NULL (as opposed to NOT NULL).
SQL #2:  Do a bulk INSERT (or LOAD DATA) of all the changes needed.  Eg, if changing only first_name, fill in id and first_name, but have the other columns NULL.
SQL #3-14:
UPDATE real_table
  JOIN t  ON t.id = real_table.id
  SET real_table.first_name = t.first_name
  WHERE t.first_name IS NOT NULL;
# ditto for each other column.

All SQLs except #1 will be time-consuming.  And, since UPDATE needs to build a undo log, it could timeout or otherwise be problematical.  See a discussion of chunking if necessary.
If necessary, use functions such as COALESCE(), GREATEST(), IFNULL(), etc.
Mass UPDATEs usually imply poor schema design.
(If Ryan jumps in with an 'Answer' instead of just a 'Comment', he should probably get the 'bounty'.)


Q: Is it possible to apply dbt seed configurations to all projects that use a given package? I built a dbt package for internal use. I'd like to specify the seed configurations in the dbt_project.yml of that package, and have those configurations apply to all projects that use the package. So far, I'm not sure if there's an issue with my syntax or if this just isn't possible.
The package dbt_project.yml includes the following:
seeds:
  seed_name:
    +quote_columns: false
    +column_types:
          column_name: varchar(127)

In a project that uses this package, there is a file data/seed_name.csv. When I run dbt seed for that project, I want the configuration defined in the package to apply to this seed. Instead, it seems to be ignored. To be clear, the .csv is included in the project that uses the package, not in the package itself.
It works if I move the above code out of the package and into the project-specific dbt_project.yml. However, this would mean that anyone using my package needs to copy that code into their file, which I'd prefer to avoid.


Q: My app runs perfectly while running it on eclipse but maps disapear and it crashes on some actvitys after export Hw can this happen and be solved?
My app runs perfectly while on eclipse, I tried everything before exporting the app.
When I exported the app, the maps showed a grey area and the app crashed while loading one activity.
Running on eclipse none of this happens.
Is this because of the prograd configuration?
How can I debug an exported app?

A: To resolve the Maps grey area issue do the following:

*

*Open Google Developers Console

*Select the project you are working on (or create it if it doesn't exist)

*Select APIs & Auth

*Then Credentials

*Find the section with the title "Key for Android applications"

*Click Edit allowed Android applications

*Execute the keytool command to generate the SHA1 fingerprint for your release keystore file

*Then add the SHA1 and package name to the list of allowed Android applications

And for the crashes, try using crash reporting tool (Crashlytics for example)


Q: Using data (not METAdata) from a SSMS DB to drive biml in SSIS dtsx creation I need to be able to generate tasks in a data flow of a SSIS dtsx based on data stored in a SSMS DB table.
Basically, I have N (unknown, variable) sources and M (unknown, variable) destinations and I have a table T0 with MxN rows. Each row, using a bit B, specifies if I really need to send data from that specific source to that specific destination.
T0 is stored in a basic Database DB0 that is used for configuration.
Ideally, using BIML I want to script a dtsx that has a simple data flow (OLEDB Source -> OLEDB destination) FOR EACH row of T0 with B = 1.
This dtsx generation must be driven by the data i find in T0.
Online I can find how to read METADATA from a DB but I can't find anyone talking about the much basic "reading data from a DB" and using these data in the BIML.
Do I need to handle the DB connection in the C# code in BIMLScript? How do I use/address the connection to DB0 in the c# code? (usually I would have this connection in a config file... in this case I need to refer to the connMgr from the C# script).


Q: Unable to create table in Oracle I want to create a table in Oracle using the below syntax using %type
Create table emp_avg
(
emp_id HR.employees.emp_id%type,
dept_id HR.employees.dep_id%type
):

When I tried executing it is throwing an error.

A: The given code is not valid. Try the below code.
Create table emp_avg as
Select e.employee_id, e.department_id from HR.employees e where 1=0;

A: That's not valid syntax.  The point of an anchored type declaration (the %type syntax) in PL/SQL is that when the underlying data type changes, the PL/SQL code uses the new type automatically.  But that doesn't work when you're defining a table where Oracle has to know the actual data type when it writes a data block to disk and can't just dynamically recompile the table when the parent data type changes.  When you create a table, you have to specify actual data types.


Q: SQLSRV to Excel using php - Missing zero's in data cells I am using SQLSRV to download the data from server to excel based on requirement
When i display the data its fine, but when i try to download using
header("Content-type: application/vnd-ms-excel") the leading zero in the integer are missing.
For example '0012346' gets converted into '12346'.
In my results file i need leading zeros also like  - '0012346'.
How can i achieve it?


Q: Make checkbox.Checked = True whose corresponding PictureBox is clicked I have 28 CheckBoxes in a windows form. Each box has PictureBox above it. When the user clicks on a PictureBox, I want to change the BackColor of the PictureBox to green, and make its corresponding CheckBox.Checked = True
The code I am using:
Private Sub PictureBox1_Click
    PictureBox1.BackColor = Color. Green
    CheckBox1.Checked = true

For 28 it will be a lengthy process. Is there any easy solution?

A: Programmatically add MouseClick even handlers to all your PictureBoxes in Form_Load. The event handler will parse the sender (PictureBox) and find the CheckBox based on the fact that the corresponding controls' names end in the same index. Remove the handlers when the form closes.
Private pictureBoxPrefix As String = "PictureBox"
Private checkBoxPrefix As String = "CheckBox"

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix))
        AddHandler pb.MouseClick, AddressOf PictureBox_MouseClick
    Next
End Sub

Private Sub PictureBox_MouseClick(sender As Object, e As MouseEventArgs)
    Dim index = Integer.Parse(pb.Name.Replace(pictureBoxPrefix, ""))
    Dim pb = CType(sender, PictureBox)
    Dim cb = CType(Me.Controls.Find($"{checkBoxPrefix}{index}", True).First(), CheckBox)
    pb.BackColor = Color.Green
    cb.Checked = True
End Sub

Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
    For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix))
        RemoveHandler pb.MouseClick, AddressOf PictureBox_MouseClick
    Next
End Sub

A: In the Load() event of your form, use Controls.Find() to get a reference to both the PictureBoxes and CheckBoxes.  Store the CheckBox reference in the Tag() property of each PictureBox.  Wire up the Click() event of you PB.  In that event, change the color of the PB, then retrieve the CheckBox from the Tag() property and check the box as well:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For i As Integer = 1 To 28
        Dim PB As PictureBox = Me.Controls.Find("PictureBox" & i, True).FirstOrDefault
        Dim CB As CheckBox = Me.Controls.Find("CheckBox" & i, True).FirstOrDefault
        If Not IsNothing(PB) AndAlso Not IsNothing(CB) Then
            PB.Tag = CB
            CB.Tag = PB
            AddHandler PB.Click, AddressOf PB_Click
            AddHandler CB.CheckedChanged, AddressOf CB_CheckedChanged
        End If
    Next
End Sub

Private Sub PB_Click(sender As Object, e As EventArgs)
    Dim pb As PictureBox = DirectCast(sender, PictureBox)
    Dim cb As CheckBox = DirectCast(pb.Tag, CheckBox)
    If pb.BackColor.Equals(Color.Green) Then
        pb.BackColor = Color.Empty
        cb.Checked = False
    Else
        pb.BackColor = Color.Green
        cb.Checked = True
    End If
End Sub

Private Sub CB_CheckedChanged(sender As Object, e As EventArgs)
    Dim cb As CheckBox = DirectCast(sender, CheckBox)
    Dim pb As PictureBox = DirectCast(cb.Tag, PictureBox)
    pb.BackColor = If(cb.Checked, Color.Green, Color.Empty)
End Sub


Q: User List with Role in .Net Core 3.1 Identity Can I get a list of all the users with the associated roles in .Net Core 3.1 from Identity? I haven't found any solution that works.

A: You need to customize Identity Model and add navigation properties.
public class ApplicationUser : IdentityUser
{
    public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
}

and then add required configuration.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<ApplicationUser>(b =>
    {
        // Each User can have many entries in the UserRole join table
        b.HasMany(e => e.UserRoles)
            .WithOne(e => e.User)
            .HasForeignKey(ur => ur.UserId)
            .IsRequired();
    });

    modelBuilder.Entity<ApplicationRole>(b =>
    {
        // Each Role can have many entries in the UserRole join table
        b.HasMany(e => e.UserRoles)
            .WithOne(e => e.Role)
            .HasForeignKey(ur => ur.RoleId)
            .IsRequired();
    });
}

and then you can use joins to query users with roles. More information on adding navigation proprieties can be found here


Q: MomentJS - Intended for input validation? Is MomentJS intended for user input parsing?
I've got moderately close with the easy cases, having it accept dates in the DDMMYYYY order, and it handles some variation.
It doesn't handle invalid dates particularly well when specifying the format - Including having day values too high, or switching year values between 2 and 4 digit.
Examples of year interpretation:
var date1 = moment('30082012', 'DDMMYYYY');
var date2 = moment('30082012', 'DDMMYY'); // Gives wrong year - 2020
var date3 = moment('300812', 'DDMMYYYY'); // Gives wrong year - 1900
var date4 = moment('300812', 'DDMMYY');

Examples of what would hopefully be invalid dates:
var date5 = moment('08302012', 'DDMMYYYY'); // Gives Jun 08 2014
var date6 = moment('08302012', 'DDMMYY'); // Gives Jun 08 2022
var date7 = moment('083012', 'DDMMYYYY'); // Gives Jun 08 1902
var date8 = moment('083012', 'DDMMYY'); // Jun 08 2014

I have created a JS Fiddle with these examples: http://jsfiddle.net/cHRfg/2/
Is there a way to have moment accept a wider array of user input, and reject invalid dates? Or is the library not intended for this?

A: var parsed = moment(myStringDate, 'DD.MM.YYYY');

for Version >= 1.7.0 use:
parsed.isValid()

for Version <  1.7.0 create your own isValid() function:
function isValid(parsed) {
    return (parsed.format() != 'Invalid date');
}

checkout the docs:
http://momentjs.com/docs/#/parsing/is-valid/

A: You can try parsing multiple formats. Updated fiddle: http://jsfiddle.net/timrwood/cHRfg/3/
var formats = ['DDMMYYYY', 'DDMMYY'];
var date1 = moment('30082012', formats);
var date4 = moment('300812', formats);

Here are the relevant docs. http://momentjs.com/docs/#/parsing/string-formats/
There is development on adding moment.fn.isValid which will allow you to do validation like in examples 5-8. It will be added in the 1.7.0 release. https://github.com/timrwood/moment/pull/306


Q: All Params Not Being Passed I am using php to create a hyperlink, and pass 3 params when the hyperlink is clicked.  My issue with the syntax below is that only the 1st param is passsed, the other 2 are ignored.
What should I alter in the syntax below so that all 3 params are passed?
    if($number_of_rows > 0) {
    echo '
';
    echo '
';
    echo '  Name 	';
    echo '  User ID 	';
    echo '  Dollar Amt 	';
    echo '  Price 1 	';
    echo '  Price 2 	';
    echo '  Price 3 	';
    echo '  Price 4 	';
    echo '  Items Sold 	';
    echo '  Items On Sale	';
    echo '
';

while ($Row = mssql_fetch_assoc($result))
{
    echo '
' . $Row['Name'] . '	' . $Row['User ID'] .
    '	' . "$".round($Row['Dollar Amt']) . '	' . "$".round($Row['Price 1']) .
    '	'. "$".round($Row['Price 2']) . '	'. "$".round($Row['Price 3']) .
    '	'. "$".round($Row['Price 4']) . '	' . $Row['Items Sold'] .
    '	'.$Row['Items On Sale'].'
';
}

The above runs a sql server stored procedure and I am using echo to create a table and return to my page. That process works as it should. The only issue is that only name is passed into the url when clicked not the 2 dates that I also want to pass.
NOT a duplicate, that is pertinate to mysql and I am using mssql.  Also, the linked duplicate talks about returning rows, now passing parameters.  My issue is that only the name parameter is passed when clicked. Please remove the duplicate flag.
EDIT
The variables are defined like so:
$begin = $_GET['begin'];
$end = $_GET['end'];

A: You are mixing double-quote " and single-quote '. Replace last line of your code inside while loop with following and it should work as expected.
'	'.$Row['Items On Sale'].'
';

From your post edit, try this:
'	'.$Row['Items On Sale'].'
';


Q: Passing and accessing value in Django form I'm trying to pass info to my form and I have a bit of a struggle with that. My code looks as follows:
views.py
class ObjectUpdateView(UpdateView):

    template_name = 'manage/object_form.html'
    form_class = ObjectEditForm
    def get_success_url(self):
        #...
    def form_valid(self, form):
        return super(ObjectUpdateView, self).form_valid(form)
    def get_object(self):
        return get_object_or_404(Room, pk=self.kwargs['object_id'])
    def get_form_kwargs(self, **kwargs):
        objectid = self.kwargs['object_id']
        object = Object.objects.get(id = objectid)
        container = object.container
        kwargs['container_id'] = container.id
        return kwargs

forms.py
class ObjectEditForm(forms.ModelForm):
 class Meta:
     model = Object
     fields = ['TestField']

 def __init__(self, *args, **kwargs):
     super(ObjectEditForm, self).__init__(*args, **kwargs)
     self.Container_id = kwargs.pop('container_id')

form_page.html
{{fomr.kwarg.Container_id}}

As you can see I'd like to access Container_id value in my form_page.html. Unfortunately, nothing is there. What I also noticed, that with __init__ I had to add, now values are empty in my form. Before I added __init__ all values were properly passed (well, except Container_id).
Could you recommend how I can pass such value to be accessed in the form template?

A: You can render this with:
{{ form.Container_id }}
In your form you should first pop the container_id from the kwargs, like:
class ObjectEditForm(forms.ModelForm):

    class Meta:
        model = Object
        fields = ['TestField']

    def __init__(self, *args, **kwargs):
        # first pop from the kwargs
        self.Container_id = kwargs.pop('container_id', None)
        super(ObjectEditForm, self).__init__(*args, **kwargs)
Use the context over the form
That being said, it is a bit strange that you pass this to the form, and not add this to the context data. You can simplify your view a lot to:
class ObjectUpdateView(UpdateView):

    template_name = 'manage/object_form.html'
    pk_url_kwarg = 'object_id'
    form_class = ObjectEditForm

    def get_success_url(self):
        #...

    def get_context_data(self, **kwargs):
        objectid = self.kwargs['object_id']
        object = Object.objects.get(id = objectid)
        context = super().get_context_data()
        context.update(container_id=object.container_id)
        return context
Django automatically fetches a single element based on the pk_url_kwarg [Django-doc]. You only need to set it correctly, so here that is the object_id.
In that case, we can simply render this with:
{{ container_id }}
and you do not need to store this in the form.


Q: How do I update environment variable (System.getenv) (not Java system property) variable during runtime in Java U tried various solutions like ProcessBuilder and Runtime to update an environment variable, but none work. I have used reflection, but it does not seem to work as it's an unmodifiableMap.
private void updateEnvVars(Map<String, String> kafkaProps) {
    try {
        Class[] classes = Collections.class.getDeclaredClasses();
        System.out.println("Total Classes : " + classes.length);
        Map<String, String> env = System.getenv();
        for (Class cl : classes) {
            System.out.println("ClassName: " + cl.getFields().toString());
            if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
                Field field = null;
                field = cl.getDeclaredField("m");
                field.setAccessible(true);
                Object obj = field.get(env);
                final Map<String, String> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.putAll(System.getenv());
                objectObjectHashMap.putAll(kafkaProps);

                Map<String, String> map = (Map<String, String>) obj;
                //java.util.Collections.unmodifiableMap<String, String>
                //final Map<String, String> stringMap = Collections.unmodifiableMap(map);
                map.clear();
                map.putAll(objectObjectHashMap);
        }
    }


Q: Rewrite with proof-irrelevant equivalence relations in Agda? I am quite new to type theories and dependently typed programming and is recently experimenting with various features of Agda. The following is a very simplified example I wrote of a record type C which contains multiple component records and some constraints that we can prove things with.
open import Relation.Binary.PropositionalEquality

module Sample (α : Set) where
  record A (type : α) : Set where

  record B : Set where
    field
      type : α

  record C : Set where
    field
      b₁ : B
      b₂ : B
      eq : B.type b₁ ≡ B.type b₂

    conv : A (B.type b₁) → A (B.type b₂)
    conv a rewrite eq = a

It seems appealing to me that the constraint eq : B.type b₁ ≡ B.type b₂ should be declared irrelevant by adding a . in the front (or, in the latest dev version 2.6.0, to replace by an equivalence relation of sort Prop, e.g.
data _≡_ {ℓ} {α : Set ℓ} (x : α) : α → Prop ℓ where
  refl : x ≡ x

), so that two instances of type C with the same components can be directly unified via refl regardless of different proofs eq. However, either way, the program stops to compile because I cannot pattern match on an irrelevant value / Prop.
I would like to know whether it is possible for the same functionality to be implemented in Agda in any way, or that in general why it is impossible to rewrite with proof-irrelevant equivalence relations in Agda (technical support difficulties, or this breaks some parts of Agda's type theory, etc.)?

A: This is currently not yet possible in Agda due to technical limitations: 'rewrite' is just syntactic sugar for a pattern match on refl, and currently pattern matching on irrelevant arguments is not permitted. In our paper at POPL '19 we describe a criterion for which datatypes in Prop are 'natural' and can thus be pattern matched on. I hope to add this criterion to Agda before the release of 2.6.1, but I cannot make any promises (help on the development of Agda is always welcome).


Q: Why toast message are not show in android 4.1 operating system containing mobile I cant see the toast message in android 4.1 mobile. Upto yesterday I was able to see the toast message. From today only I can not see the message. Please help me.
Toast.makeText(getApplicationContext(), "hi", Toast.LENGTH_SHORT).show();

I have tried custom toast message also instead of toast message. But still not working.
Custom toast:
LayoutInflater inflater=getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Please fill Name");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

A: Change to this and check again.
if(first_name.length() == 0)
{
    Toast.makeText(NameOfYourActivity.this, "Please fill Name", Toast.LENGTH_SHORT).show();
    Utilities.writeIntoLog("Please fill Name");
}

A: just post the google code link here.
Since Jelly Bean, users can disable notifications for a given app via "app details" settings.
A very bad and unwanted side effect is that once notifs are disabled, Toast messages are also disabled, even when the user is running the app!
You encourage to use Toast in your design guidelines, but who will want to use it if the users have the possibility to remove them, especially if the toasted message is an important feedback to display to the user...
I understand at least that Toasts could be disabled when the app is in background, but not if it is the foreground Activity.

A: Toast was not showing with me in Android 4.1 because Show Notifications was checked off in my app's settings. I just went to Settings->Manage Applications->[My App] and toggled on Show Notifications and Toasts started to appear.

A: Toast is working fine in all the version of Android. There can be couple of issues in your code like

*

*Your context is not wrong

*You are trying to display toast in the background thread instead of worker thread.

Edit
In your custom toast don't set the parent in your layout inflater for example use like below
View layout = inflater.inflate(R.layout.toast_layout,null);

A: I had the same problem. When I invoked the code on UI thread the issue resolved for me
public void showToastMessage(final String msg) {

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(BaseActivity.this, msg, Toast.LENGTH_LONG).show();
        }
    });
}


Q: Post-request rejected by server Could anyone help to solve a problem? I'm trying to send data form from authorize user to protected controller method,   using fetch and getting  400 error. I'm using NET CORE 5 MVC  and on front-en  bootstrap 5. If I remove ValidateAntiForgeryToken from AddItemToStore method I'm getting 415 error
C# code
  [Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddItemToStore([FromBody] StoreUser itemsStore)
{
    StoreUser str = new StoreUser
    {

        Id = 1,
        UserId = itemsStore.UserId,
        CatrgoryId = itemsStore.CatrgoryId
    };

    return Ok(str);
}

JS-code

var buttonAddOrder = document.getElementById("addToOrder");

buttonAddOrder?.addEventListener("click", function () {
    var catId = document.querySelector("#formToStore input[name = 'cardId']").value;
    var userId = document.querySelector("#formToStore input[name = 'userId']").value;
    var antiForgeryToken = document.querySelector("#formToStore input[name = '__RequestVerificationToken']").value;
    var itemsStore = {
        __RequestVerificationToken: antiForgeryToken,
        UserId: userId,
        CatrgoryId: catId,
        Payed: false
    };
    var url = "/CategoriesToUser/AddItemToStore";

    var response = fetch(url, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;'
        },
        body: {

            itemsStore: itemsStore
        }
    })
        .then((response) => {
            return response.json();
        }).catch((e) => console.log(e.message));
    console.log('buttonAddOrder', response);

HTML

<form id="formToStore" method="post" enctype="multipart/form-data">
  <input type="hidden" name="cardId" id="cardId" /> @{ var getUser = await UserManager.GetUserAsync(User); }
  <input type="hidden" name="userId" asp-for="@getUser.Id" />

    <button type="button" id="buttonclose" name="buttonclose" class="buttonclose btn btn-secondary" data-bs-dismiss="modal">Close</button>

    <button type="button" id="addToOrder" name="addToOrder" class="btn btn-primary">
                        Add to Order
                    </button>

</form>

An attempt of using FormData  doesn't work, the same error.

buttonAddOrder?.addEventListener("click", function () {

    var url = "/CategoriesToUser/AddItemToStore";
    const  formToStore = document.getElementById('formToStore');
    var formOrder = new FormData(formToStore);

    let response = fetch(url, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;'
        },
        body: formOrder
    })
        .then((response) => {
            return response.json();
        }).catch((e) => console.log(e.message));
    console.log('buttonAddOrder', response);

});

But If I send data to anonymous post method without using  ValidateAntiForgeryToken on beck-end It's work.
Example:
[AllowAnonymous]
[HttpPost]
public IActionResult AddItemToStore([FromBody] StoreUser itemsStore)
{
    StoreUser str = new StoreUser
    {

        Id = 1,
        UserId = itemsStore.UserId,
        CatrgoryId = itemsStore.CatrgoryId
    };

    return Ok(str);
}

Screenshots

A: Before coding, you need be sure the following inputs contain value:
<input type="hidden" name="cardId" id="cardId" /> @{ var getUser = await UserManager.GetUserAsync(User); }
<input type="hidden" name="userId" asp-for="@getUser.Id" />

Two ways you could follow:
1.From Body:
View
<form id="formToStore" method="post" enctype="multipart/form-data">
  <input type="hidden" name="cardId" id="cardId" value="1" />
  <input type="hidden" name="userId" value="466788cb-6aab-4798-81f1-f6b05cb71e32"/>

    <button type="button" id="buttonclose" name="buttonclose" class="buttonclose btn btn-secondary" data-bs-dismiss="modal">Close</button>

    <button type="button" id="addToOrder" name="addToOrder" class="btn btn-primary">Add to Order</button>

</form>
@section Scripts
{

}

Controller
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddItemToStore([FromBody] StoreUser itemsStore)
{
    //do your stuff....
    return Ok(itemsStore);
}

Startup.cs:
services.AddAntiforgery(x => x.HeaderName = "X-ANTI-FORGERY-TOKEN");

2.From Form:
View
<form id="formToStore" method="post" enctype="multipart/form-data">

                      @*change name="cardId" to name="CatrgoryId"*@
  <input type="hidden" name="CatrgoryId" id="cardId" value="1" />
  <input type="hidden" name="userId" value="466788cb-6aab-4798-81f1-f6b05cb71e32"/>

    <button type="button" id="buttonclose" name="buttonclose" class="buttonclose btn btn-secondary" data-bs-dismiss="modal">Close</button>
    <button type="button" id="addToOrder" name="addToOrder" class="btn btn-primary">Add to Order</button>

</form>
@section Scripts
{

}

Controller
Change [FromBody] to [FromForm].
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddItemToStore([FromForm] StoreUser itemsStore)
{
    //do your stuff...
    return Ok(itemsStore);
}


Q: I can not get an image of the URL found with XmlHttpRequest Im trying to get a image url through XmlHttpRequest and use it like 'src' attribute of a 'img' tag. That is my plan:
function populaLista() {

var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://localhost:8080/artes');

ourRequest.onload = function() {
    var ourData = ourRequest.responseText.toString();
    var jsonResposta = JSON.parse(ourData);

    if (ourData.length > 0) {

        document.getElementById("paragrafo1").innerHTML = jsonResposta.url;

        var tabela = document.createElement("TABLE");
        var corpoTabela = document.createElement("TBODY");
        var tr = document.createElement("TR");
        var td = document.createElement("TD");
        var imagem = document.createElement("IMG");
        var urlImg = document.createTextNode(jsonResposta.url).toString();
    //  var urlImg = "https://mir-s3-cdn-cf.behance.net/projects/202/6310ed61231533.Y3JvcCwyNjM1LDIwNjIsMjI3LDA.jpg";

        document.getElementById("paragrafo").innerHTML = typeof urlImg;

        imagem.setAttribute("src",urlImg);
        td.appendChild(imagem);
        tr.appendChild(td);
        corpoTabela.appendChild(tr);
        tabela.appendChild(corpoTabela);

        document.getElementById("tabeladeImagens").appendChild(tabela);

    } else {
        document.getElementById("paragrafo").innerHTML = "item não encontrado";
    }

};
ourRequest.send();

The problem is: when I use the result of my request on my img tag, I can't see the image, but if I use the same url in a string var that I created I can see normally.

<meta charset="ISO-8859-1">

The json response:
{id : 38, url : "//mir-s3-cdn-cf.behance.net/projects/202/6310ed61231533.Y3JvcCwyNjM1LDIwNjIsMjI3LDA.jpg"}


Q: Retrieve all functions that called by a user mode process in kernel mode debug including kernels functions I am trying to find all the functions including both user mode functions and kernel mode functions that wmic.exe calls to execute the diskdrive command. In order to do this I opened wmic.exe in my virtual machine and set breakpoint in kernel mode windbg on WMIC!CParsedInfo::GetUser and WMIC!CExecEngine::ExecuteCommand.
As soon as I input diskdrive debugger breaks on ExecuteCommand, I am in kernel mode through COM port, but I cant use wt command, however I can run instructions line by line and step in to every call and track all function in stack call, but this will take lots of time and it’s not optimized. Is there any way to do something similar to the wt command in the kernel debugger?
Whenever I use the wt command it outputs ^ Unimplemented error in 'wt'.
Some extra info:

*

*I am running Windows 11 Enterprise Build 22000.856 on VMWare and connected to it through the COM port for kernel debugging and the host OS is the latest version of Windows 11 Enterprise.

*Windbg is also the latest version of windbg.

*Both windbg and vmware running as administrator.

*I am able to use all the usual commands I can see registers, see stack calls with single step, see threads and etc.

*wt runs normally on my main OS for user mode processes on my main OS without any problem


Q: Snowflake External Table Have a question regarding the Snowflake External Table. As we now the External Tables still a preview feature and still not a General Available. Hence have guys used External table in your production environment and you see any issue ? Snowflake do not recommend to use Preview feature in Production. Any thoughts?

A: External table feature is publicly available feature as per documentation
https://docs.snowflake.com/en/user-guide/tables-external-intro.html


Q: Azure DevOps Server 2020 - FilePath artifacts not always deleted from fileShare We are on ADS 2020.0.1
We are migrating to a new file server, we have noticed that drops on the new file server are not beeing deleted after the build run has been deleted.
I have created a test pipeline, where i drop to the old and new server.
After deleting the build, the artifacts are deleted on the old server, but not the new server.
old build path: 116 chars - new build path: 142 chars
The service account has modify permissions in both the old and new location. I am able to manually delete a file remotely while logged on as this account on one of the build servers.
I can see the cleanup job in the job history, it shows a red X, but i cannot see the details.
Question is, where can i see the logs of the delete artifacts task? i tried in the _oi page, but here it doesn't show anything.
We see this behaviour in classing and YAML pipelines


Q: positioning the child behind the parent of the parent element, ```z-index``` does not work I want the  to appear behind the #sideBar i tried z-index: -3 but that didn't work

body {
  margin: 0px;
  font-family: "Signika Negative", sans-serif;
  background-color: #252525;
  color: #f8f9fa;
  user-select: none;
}

#sideBar{
  width: 2vw;
  height: 100vh;
  background-color: rgb(15, 15, 15);
  opacity: .99;
}

.menuBtn{
  background: none;
  cursor: pointer;
  padding: .5vw;
  border: none;
  padding: none;
  color: white;
  font-weight: 600;
  font-size: 1vmax;
}

.menuBtn .label{
  transition: left .5s;
}

.label{
  position: absolute;
  font-size: .9vmax;
  opacity: 1;
  left: -2.2vw;
}

svg{
  transition: transform .5s;
}

.menuBtn:hover svg{
  transform: scale(1.2);
}

.menuBtn:hover .label{
  opacity: 1;
  left: 2.2vw;
}
<!DOCTYPE html>

    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Fira+Mono&family=Signika+Negative:wght@300&display=swap" rel="stylesheet"/>

    <meta charset="UTF-8" />
    <link rel="stylesheet" href="styles.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>OverStat</title>

Clear all games and ranks<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="lightgrey" d="M135.2 17.7C140.6 6.8 151.7 0 163.8 0H284.2c12.1 0 23.2 6.8 28.6 17.7L320 32h96c17.7 0 32 14.3 32 32s-14.3 32-32 32H32C14.3 96 0 81.7 0 64S14.3 32 32 32h96l7.2-14.3zM32 128H416V448c0 35.3-28.7 64-64 64H96c-35.3 0-64-28.7-64-64V128zm96 64c-8.8 0-16 7.2-16 16V432c0 8.8 7.2 16 16 16s16-7.2 16-16V208c0-8.8-7.2-16-16-16zm96 0c-8.8 0-16 7.2-16 16V432c0 8.8 7.2 16 16 16s16-7.2 16-16V208c0-8.8-7.2-16-16-16zm96 0c-8.8 0-16 7.2-16 16V432c0 8.8 7.2 16 16 16s16-7.2 16-16V208c0-8.8-7.2-16-16-16z"/></svg>

Prefrences<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="lightgrey" d="M0 416c0-17.7 14.3-32 32-32l54.7 0c12.3-28.3 40.5-48 73.3-48s61 19.7 73.3 48L480 384c17.7 0 32 14.3 32 32s-14.3 32-32 32l-246.7 0c-12.3 28.3-40.5 48-73.3 48s-61-19.7-73.3-48L32 448c-17.7 0-32-14.3-32-32zm192 0a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zM384 256a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zm-32-80c32.8 0 61 19.7 73.3 48l54.7 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-54.7 0c-12.3 28.3-40.5 48-73.3 48s-61-19.7-73.3-48L32 288c-17.7 0-32-14.3-32-32s14.3-32 32-32l246.7 0c12.3-28.3 40.5-48 73.3-48zM192 64a32 32 0 1 0 0 64 32 32 0 1 0 0-64zm73.3 0L480 64c17.7 0 32 14.3 32 32s-14.3 32-32 32l-214.7 0c-12.3 28.3-40.5 48-73.3 48s-61-19.7-73.3-48L32 128C14.3 128 0 113.7 0 96S14.3 64 32 64l86.7 0C131 35.7 159.2 16 192 16s61 19.7 73.3 48z"/></svg>

How to use<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="lightgrey" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336h24V272H216c-13.3 0-24-10.7-24-24s10.7-24 24-24h48c13.3 0 24 10.7 24 24v88h8c13.3 0 24 10.7 24 24s-10.7 24-24 24H216c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z"/></svg>

A: When you put opacity: .99 on the #sidebar, it forms a stacking context on #sidebar and everything inside it is stuck on it even if you put a z-index: -1000.
#sidebar {
   opacity: 1;
}
.label {
   z-index: -3;
}

Read more about the stacking context.


Q: How do I receive/send information from/to GitHub using android App I have a school project where I am supposed to create an Android application that can get notifications from a GitHub project and also be able to send comments to GitHub using the App. I don't really know where to start but I hope there is some API for Git that I can use.
I'm using Eclipse which is kinda new to me and would really appreciate some help!

A: Github has a number of apis that you can use and I'm sure there are many user created ones as well:
GitHub API
I know they recently rolled out
    Webhooks
Some developer guides


Q: React Native FlatList Object displaying I have the below object that I am retrieving from the AsyncStorage, and I want to display it in a FlatList but I am getting the following error:
Invariant Violation: Invariant Violation: Invariant Violation: Invariant Violation: Tried to get frame for out of range index NaN
My JSON format is:
Object {
  "44": Object {
    "pro_id": "44",
    "pro_img": "url",
    "pro_name": " S4 ",
  },
  "52": Object {
    "pro_id": "52",
    "pro_img": "url",
    "pro_name": " S4 ",

  },
}

The JSON above is retrieved from AsyncStorage like so:
retrieveData = async () => {

    try {
       await AsyncStorage.getItem('userFavorites')
       .then(req => JSON.parse(req))
       .then(json => this.setState({ favPro:json }))

    } catch (error) {

    }
}

My method for rendering items in the FlatList is defined like this:
 fav = ({ item }) => {
    return (
      <View>
      <Text>{item.pro_id+ item.pro_name}</Text>
      </View>
    )
}

Finally, I render the FlatList as follows:
<FlatList
          data={this.state.favPro}
          renderItem={this.fav}
          keyExtractor={item => item.pro_id}
        />

How I can display my JSON data using the FlatList component?

A: The FlatList component expects an array input for the data prop. Based on your JSON format, it appears you're passing in an object rather than an array.
Consider the following adjustment to your render method:
// Convert object to array based on it's values. If favPro not
// valid (ie during network request, default to an empty array)
const data = this.state.favPro ? Object.values(this.state.favPro) : []

<FlatList
  data={data}
  renderItem={this.fav}
  keyExtractor={item => item.pro_id}
/>

A: You're using async / await incorrectly. Instead of calling .then you assign your call to await to a variable (or don't assign it if it does not return a value) and wrap the call (or calls) to await in a try / catch block. The await keyword will automatically handle resolve and reject so you get the appropriate information.
retrieveData = async () => {
  try {
    const data = JSON.parse(await AsyncStorage.getItem("userFavorites"))
    this.setState({ favPro: data })
  } catch (error) {
    console.error(error)
    this.setState({ favPro: [] })
  }
}

You also need to pass an array, the shape of your data looks like an object, but it should be an array of objects. This is not a terribly difficult transformation and I can provide a helper function if you need it.
edit: if you need to convert an object into an array, you can use the reduce function
const data = {
  '44': { a: 2 },
  '55': { b: 3 },
}

const dataArr = Object.keys(data).reduce(
  (arr, key) => arr.concat(data[key]),
  []
)

By using Object.keys we can each object by name. Then call reduce and the array returned by Object.keys, passing a function as the first argument, and an empty array as the second argument. The second argument is automatically passed to the function as the first argument, arr, and the second argument of the function we pass is the key of the object. Then it's just a matter of adding the objects to the array using concat.
Array.reduce can seem a little overwhelming at first but it's a very powerful method and you can get a lot done with it.