text:
Q: How to move bodies with no sliding in matter.js? I am trying to create 2 boxes where 1 box B moves down and hits the other box A. I want B to move at constant speed (so I set its friction to 0 and stop it after a while). But I'm stuck on how to set A. I want A to get pushed and move out of B's way, but also at constant speed and with no sliding. Which means A gets pushed until B is not pushing A anymore, which at that point A is not sliding/moving/rotating.
Anyone know how to fix it?

   // module aliases
var Engine = Matter.Engine,
    Render = Matter.Render,
    Runner = Matter.Runner,
    Bodies = Matter.Bodies,
    Body = Matter.Body,
    Composite = Matter.Composite;

// create an engine
var engine = Engine.create();

engine.world.gravity.y = 0;

// create a renderer
var render = Render.create({
    element: document.body,
    engine: engine
});

// create two boxes and a ground
var boxA = Bodies.rectangle(400, 200, 32, 32);
var boxB = Bodies.rectangle(425, 50, 32, 32);
var ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });

console.log(boxA.friction, boxA.frictionAir, boxA.restitution);
boxA.friction = 0.75;
//boxA.frictionAir = 1;
boxA.restitution = 0.01;

boxB.friction = 0;
boxB.frictionAir = 0;
boxB.restitution = 0;

var x=425,y=50;
setTimeout(() => {
    Body.applyForce(boxB, boxB.position, {
        x: 0,
        y: 0.01
    });
    console.log("moving");
}, 1000);
setInterval(() => {
    Body.setAngularVelocity(boxB, 0);
    Body.setVelocity(boxB, {x: 0, y:0});
}, 3000);

// add all of the bodies to the world
Composite.add(engine.world, [boxA, boxB, ground]);

// run the renderer
Render.run(render);

// create runner
var runner = Runner.create();

// run the engine
Runner.run(runner, engine);
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.18.0/matter.min.js" integrity="sha512-5T245ZTH0m0RfONiFm2NF0zcYcmAuNzcGyPSQ18j8Bs5Pbfhp5HP1hosrR8XRt5M3kSRqzjNMYpm2+it/AUX/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

<body></body>

</html>


text:
Q: How to get variable from one class in another class? I have 2 classes: User and Answer
I define in the class User that the name is "Peter"
how can I get the name defined in the User instance inside the Answer instance?
$user= new User();
$user->name = "Peter";

$answer = new Answer();
echo $answer->getListAnswer(); //how can I get the name of the User (Peter) in the function getListAnswer() in the Class Answer?

A: Inject the User instance into the Answer instance. Like this, for example:
class Answer
   private $user;

   public function __construct(User $user) {
      $this->user = $user;
   }

   public function getListAnswer() {
      $userName = $this->user->name;

      // rest of your method.
      // Use $userName where you need it.
   }
}

First you create your User object as usual:
$user       = new User();
$user->name = "Peter";

In the constructor for Answer we declared that it needs (depends on) a User object. So you pass the user object you just created to instantiate a new Answer:
$answer = new Answer($user);
echo $answer->getListAnswer();

A: Well I'm not much sure of it, but if you try and define your variable scope with "global " in the Answer class,it might make some difference

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to improve this awk code to reduce processing time I have 400 tab-delimited text files with 6 million rows in each file. Below is the format of the files:
 ### input.txt
col1    col2    col3    col4    col5
ID1     str1    234     cond1   0
ID1     str2    567     cond1   0
ID1     str3    789     cond1   1
ID1     str4    123     cond1   1

### file1.txt
col1    col2    col3    col4    col5
ID2     str1    235     cond1   0
ID2     str2    567     cond2   3
ID2     str3    789     cond1   3
ID2     str4    123     cond2   0

### file2.txt
col1    col2    col3    col4    col5
ID3     str1    235     cond1   0
ID3     str2    567     cond2   4
ID3     str3    789     cond1   1

I am trying to add values in $1 from the rest of the file1..filen to $6 in input.txt file by using:
conditions:
1. columns $2 and $3 as key
2. If the key is found in files1...filen then if $5>=2 add the value from  $1 to $6 in the input file.

Code:
awk -F "\t" -v OFS="\t" '!c {
    c=$0"\tcol6";
    next
}
NR==FNR {
    a[$2$3]=$0 "\t";
    next
}
{
    if ($5>=2) {
        a[$2$3]=a[$2$3] $1 ","
    }
}
END {
     print c;
     for (i in a) {
        print a[i]
    }
}' input.txt file1..filen.txt

The output from the above code is as expected:
Output.txt
col1    col2    col3    col4    col5    col6
ID1    str2    567    cond1    0    ID2,ID3,
ID1    str4    123    cond1    1
ID1    str1    234    cond1    0
ID1    str3    789    cond1    1    ID2,

However, the problem is that the code is very slow as it has to iterate each key in input.txt through 400 files with 6 million rows in each file. This takes several hours to few days.  Could someone suggest a better way to reduce the processing time in awk or using other scripts.
Any help would really save lot of time.

A: input.txt
Sam    string    POS    Zyg    QUAL
WSS    1    125    hom    4973.77
WSS    1    810    hom    3548.77
WSS    1    389    hom    62.74
WSS    1    689    hom    4.12

file1.txt
 Sam   string    POS    Zyg    QUAL
 AC0    1    478    hom    8.64
 AC0    1    583    het    37.77
 AC0    1    588    het    37.77
 AC0    1    619    hom    92.03

 file2.txt
 Sam    string    POS    zyg    QUAL
 AC1    1    619    hom    89.03
 AC1    1    746    hom    17.86
 AC1    1    810    het    2680.77
 AC1    1    849    het    200.77

awk -F "\t" -v OFS="\t" '!c {
        c=$0"\tcol6";
        next
    }
    NR==FNR {
        a[$2$3]=$0 "\t";
        next
    }
    {
        if ( ($5>=2) && (FNR > 1) ) {
          if ( $2$3 in a ) {
             a[$2$3]=a[$2$3] $1 ",";
          } else {
             print $0 > "Errors.txt";
          }
        }
    }
    END {
         print c;
         for (i in a) {
            print a[i]
        }
    }' input.txt file*

For the above input files it prints the below output:
AC0,AC1,
WSS    1    389    hom    62.74
AC1,
WSS    1    810   hom    3548.77    AC1,
WSS    1    689   hom    4.12
WSS    1    1250      hom    4973.77

It still prints the values in $1 from file1 and file2


text:
Q: What kind of wood block is at block 0 0 0? I went to block 0 0 0 and found a wood block facing sideways.  I mined it, not realizing that my inventory was full, and it fell into a black hole. Has anyone else seen this? What kind of wood was it?

If it helps, it was an Amplify game.

A: Look like you've found one of those rare holes-in-the-void. Must be a glitch in tree generation. Also, since 1.6(?) - Layer 1 is always solid bedrock.

Here's what happened:

*

*Your terrain is generated. (The Terrain; stone, hills, ores etc.)

*Then, the world generates structures (trees, dungeons, caves, villages, etc.). Sometime at this point the game placed a tree there during world generation.
This is the point during world generation which the bug occurred.

*Because the way tree generation works, wood will override any block, while leaves will only appear if there is space for it.

As for what kind of wood block?
It's should be one of the possible Minecraft logs. So, since you're in a desert (though it's weird for a tree to spawn there), it would most likely be Oak.

A: It seems there's a bug in world generation where sometimes the block at 0 0 0 is sideways log(Data value of 4 or 8) instead of bedrock. It is very inconsistent and glitchy and even sometimes block's data value is changed in-game naturally. It is somehow related to the seed of the world and tree generation. When tested with superflat world, this does not happen when tree generation is turned off.
See this reddit thread for more information.


text:
Q: TSL/SSL enablling in mongodb is required if my website is HTTPS enabled Our website hosted in one of AWS EC2 instance.
We have MongoDB installed in the separate EC2 instance (Note: MongoDB is not managed by AWS. We are maintaining in the EC2 server)
Our website is HTTPS enabled.
So my questions are

*

*Do we still need TSL/SSL encryption for connecting to MongoDB from our website (which is in EC2), even though both are in AWS and our website is HTTPS

*Do we see any performance issue if we enable TSL/SSL encryption for connection from the website


text:
Q: is there a way to write a boolean query with different conditions in elasticsearch? Ive setted up elasticsearch with a NodeJS Server and need a working boolean query that checks different conditions in the search. How to do that?
I am using mongoosastic(query DSL) with NodeJS and the following query to get the results
mapping Function
async function mapMongoToElastic() {
return new Promise((resolve, reject) => {
console.log("---------Mapping gets created---------");
Product.createMapping(
  {
    mappings: {
      product: {
        properties: {
          ArtNumber: { type: "text" },
          Title: {
            type: "text",
            fields: {
              keyword: {
                type: "keyword"
              }
            }
          },
          DisplayPrice: { type: "double" },
          CF_Deliverytime: { type: "text" },
          Description_Short: { type: "text" },
          MainCat: {
            type: "text",
            fields: {
              keyword: {
                type: "keyword"
              }
            }
          },
          ItemCat: {
            type: "text",
            fields: {
              keyword: {
                type: "keyword"
              }
            }
          },
          Deeplink1: { type: "text" },
          Img_url: { type: "text" },
          CF_img_url2: { type: "text" },
          CF_img_url3: { type: "text" },
          CF_Availability: { type: "text" },
          CF_Productrating: {
            type: "text",
            fields: {
              keyword: {
                type: "keyword"
              }
            }
          },
          CF_Discount: {
            type: "text",
            fields: {
              keyword: {
                type: "keyword"
              }
            }
          },
          Shop: {
            type: "text",
            fields: {
              keyword: {
                type: "keyword"
              }
            }
          }
        }
      }
    }
  },
  function(err, mapping) {
    if (err) {
      console.log("error creating mapping (you can safely ignore this)");
      console.log(err);
      resolve(err);
    } else {
      console.log("X - ElasticSearch Mapping Created");
      resolve(mapping);
    }
   }
   );
  });
 }

Query function
async function asyncSearchWithOutFilter(query, from, to) {
return new Promise((resolve, reject) => {
Product.esSearch(
  {
    from: from,
    size: to,
    query: {
      multi_match: {
        query: query.suche,
        fields: [ "Title^10", "ItemCat^5" ]
      }
    },
    aggs: {
      mainCats: {
        terms: { field: "MainCat.keyword" }
      },
      itemCats: {
        terms: { field: "ItemCat.keyword" }
      },
      itemShops: {
        terms: {
          field: "Shop.keyword"
        }
      }
    }
  },
  {},
  async (err, results) => {
    if (err) throw err;
    let res = await results;

    /*  console.log("-------------Total Hits---------------");
    console.log(res.hits.total);
    console.log("-----------------------------------------");
    console.log("-------------Shops---------------");
    console.log(res.aggregations.itemShops.buckets);
    console.log("-----------------------------------------");
    console.log("-------------Item-Categories---------------");
    console.log(res.aggregations.itemCats.buckets);
    console.log("-----------------------------------------"); */
    resolve(res);
  }
);
  });
 }

Expected results:
- Query for "TV"
Results:
Products with Title "TV" in
- if Category has "TV" also, rank it up higher.
Problem:
Smart-TV-Controller is also listed if searched for "TV", but not expected if someone is searching for a "TV"
help appreciated.

A: Seems like you are trying to get exact match. You already have keyword type sub-field for both the fields Title and ItemCat. So instead use keyword field in match query.
query: {
  multi_match: {
    query: query.suche,
    fields: [ "Title.keyword^10", "ItemCat.keyword^5" ]
  }
}

If you are not looking for exact match in Title then another way can be to set fields as below:
fields: [ "Title^10", "ItemCat.keyword^5" ]


text:
Q: Auto generate REST api documentation via RAML from Spring MVC controllers I am new to RAML. I want to auto generate my REST api documentation via RAML from my Spring MVC controllers. I know SpringFox has annotation based support for Swagger to auto generate api docs for spring mvc; Do we have a similar framework to auto generate RAML based api docs from spring controllers?
Thanks,
Lina

A: I think RAML does note have a framework like SpringFox that generates a swagger from a Spring Controller.
There is a framework that generates a HTTP from a RAML like a swagger-ui.
This the framework: https://github.com/cybertk/grunt-raml2html

A: Another alternative that was open sourced recently is https://github.com/ePages-de/restdocs-raml. It is an extension to Spring REST Docs and generates RAML out of tests for Spring MVC controller.

A: You can try the github project springmvc-raml-plugin for maven
https://github.com/phoenixnap/springmvc-raml-plugin
The plugin supports Raml 0.8, haven't found anything for RAML 1.0


text:
Q: Creating class from XML using LINQ, but TargetInvocationException when using namespace I'm not sure if this is the best way to do this, but I am following an example that worked on some other projects for importing an XML file and treating it like a class. So content like:
<Book>
   <Author>Johnny Appleseed</Author>
</Book>

Can be accessed in C# using:
Book.Author

The example I've used creates a public class that inherits XTypedElement, uses its .Load method to open an XML, and then uses LINQ to create properties. So for example,
public class Book: XTypedElement, IXMetaData
{
    private static readonly Dictionary<XName, Type> authorDictionary = new Dictionary<XName, Type>();
    private static readonly ContentModelEntity authorContent;

    static Book()
    {
        authorDictionary .Add(XName.Get("Author", ""), typeof(string));
        authorContent= new SequenceContentModelEntity(new NamedContentModelEntity(XName.Get("Author", "")));
    }

    public string Author
    {
        get
        {
            var x = Element(XName.Get("Author", ""));
            return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype);
        }
        set
        {
            SetElement(XName.Get("Author", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype);
        }
    }

    public static Book Load(string xmlFile)
    {
        return File.Exists(xmlFile) ? XTypedServices.Load<Book>(xmlFile) : null;
    }
}

This seems to work really well. Classes representing complex types can be nested using a similar structure. However, all of this breaks as soon as the root node of the XML has a namespace.
<Book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > THIS WORKS
<Book xmlns="ThisIsAValue" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > THIS DOESN'T

A TargetInvocationException is thrown, with the message "Element is not an instance of Type Book".
There is an XSD that maps to this class, maybe that isn't set up right. I'm not sure. It'd be nice to know where to start looking.
Any ideas?

A: The problem ended up being every instances of XName used throughout my class (which was a lot).
// XName.Get is overloaded. If you pass two parameters, the second one is expected to be the namespace of the XML.
XName.Get("Author", "")));

Furthermore, my effort seems to be wasted! I just found the sample I was using is based on an open source project found here, where they provide an executable to generate these classes for you. Done and done.


text:
Q: How to fix "Result undefined" in MongoDB Stitch function I'm creating Stitch Functions in MongoDB and getting result undefined instead of double.
I'm developing an iOS App, using MongoDB database. I'm creating Stitch Functions, and using callFunction(withName:withArgs:_:) method. I write a function to calculate an average morning value. I want to return the morning value to app. Here is the code below.
exports = function(DAY,MONTH){
    var total = 0.0;
    var count = 0.0;
    var morning = 0.0;

    var collection = context.services.get("mongodb-atlas").db("database_name").collection("collection_name");
    var docs = collection.find({month: { $eq: MONTH },
    day: { $eq: DAY },
    hour: { $gte: 8 },
    hour: { $lt: 13 }
    }).toArray().then((data) => {
        data.forEach((el) =>{
            total = total +  el.value;
            count = count + 1.0;
        });
        morning = total/count;
        console.log("morning");
        console.log(morning);
        return {morning};
    })
    .catch((error) => {
        console.log(error);
        return {morning};
    });
};

"""output"""
morning
869.5729166666666

result:
  {
    "$undefined": true
  }
  result (JavaScript):
  EJSON.parse('{"$undefined":true}')

"""-end of output"""
I'm trying to return morning value which is double but, it returns BSONUndefined. And when I try to reach result from iOS app, I get
"""  morning: BSONUndefined()   """
But before the return statement, it prints the morning value to stitch console correctly.

A: use the return statement before the MongoDB find() query this way
exports = function(DAY,MONTH){
    var total = 0.0;
    var count = 0.0;
    var morning = 0.0;

    var collection = context.services.get("mongodb-atlas").db("database_name").collection("collection_name");
    return collection.find({month: { $eq: MONTH },
    day: { $eq: DAY },
    hour: { $gte: 8 },
    hour: { $lt: 13 }
    }).toArray().then((data) => {
        data.forEach((el) =>{
            total = total +  el.value;
            count = count + 1.0;
        });
        morning = total/count;
        console.log("morning");
        console.log(morning);
        return {morning};
    })
    .catch((error) => {
        console.log(error);
        return {morning};
    });
};

A: you are not written the collection, {which is sending the $undefined:true}
Solution 1
Return collection.find result
return collection.find({month: { $eq: MONTH },
    day: { $eq: DAY },
    hour: { $gte: 8 },
    hour: { $lt: 13 }
    }).toArray().then((data) => {
        data.forEach((el) =>{
            total = total +  el.value;
            count = count + 1.0;
        });
        morning = total/count;
        console.log("morning");
        console.log(morning);
        return {morning};
    })
    .catch((error) => {
        console.log(error);
        return {morning};
    });

Solution 2:
Return the docs itself
var docs = collection.find({month: { $eq: MONTH },
    day: { $eq: DAY },
    hour: { $gte: 8 },
    hour: { $lt: 13 }
    }).toArray().then((data) => {
        data.forEach((el) =>{
            total = total +  el.value;
            count = count + 1.0;
        });
        morning = total/count;
        console.log("morning");
        console.log(morning);
        return {morning};
    })
    .catch((error) => {
        console.log(error);
        return {morning};
    });

return docs


text:
Q: Implementing Authentication using JSessionId Is it secure to authenticate a user using the JSessionId that the client passes to the server ?
Assume that in a Spring app, we store the jsession id for a user that provided correct credentials while logging in, in a database and we authenticate each subsequent request based on that jsession id.
Does this method provide the same security level of using Java Web Tokens ?

A: JWT tokens are cryptographically signed so they are much more difficult to forge compared to session IDs.
Session IDs are generated using a secure random number generator which may be predicable depending on the implementation.
https://news.netcraft.com/archives/2003/01/01/security_advisory_2001011_predictable_session_ids.html
Some more information on why JWT is preferable over session IDs may be found here:
https://stormpath.com/blog/beginners-guide-jwts-in-java


text:
Q: Не получается отправить полученные данные из useState в функцию prepare() - для предподготовки данных для парсинга const PageDetailMovie = () => {
    const {id} = useParams<ID>();
    const [film, setFilm] = useState<IShow | []>([]);

    useEffect(() => {
       getFilmsOnce(id).then(response => {
           setFilm(response.data)
       })
    }, [id]);

    console.log(film);

    const { routeId, nameFilm, yearFilm, countryFilm, genresFilm, imageFilm} = prepareData(film);

    return (

    )
};

** постоянно ошибка при диструктуризации const film: IShow | [] Аргумент типа "IShow | []" нельзя назначить параметру типа "IShow". Тип "[]" не может быть назначен для типа "IShow".ts(2345)**
import { IShow } from "types/API_Films/Interface/IShow";

const prepareData = (data: IShow) => {
    const apiPrepare = {
        routeId: data.id.toString(),
        nameFilm: data.name ? data.name.toUpperCase() : "информация отсутствует",
        yearFilm: data.premiered ? data.premiered.slice(0,4) : " - ",
        countryFilm: data.network?.country.name ? "("+ data.network.country.name +")" : " - ",
        genresFilm: data.genres.join(" "),
        summaryFilm: data.summary ? data.summary.replace(/<[^>]+>/g, '') : " - ",
        ratingFilm: data.rating.average ? data.rating.average.toString() + "/10" : "Рейтинг отстутствует",
        imageFilm: data.image?.medium ? data.image?.medium : data.name,
    }

    return apiPrepare;
}

export default prepareData;

import {IImage} from "./IImage";
import { IRating } from "./IRating";
import { INetwork } from "./INetwork";

export interface IShow {
    id:             number | string;
    name:           string | undefined;
    genres:         string[];
    premiered:      string | null;
    rating:         IRating;
    image:          IImage | null;
    summary:        string | null;
    network:        INetwork | null;
};


text:
Q: How to save a 'pos dictionary' type of object? (NetworkX) I am using the networkx as nx. After creating a graph object (G), I use the data = nx.spring_layout(G) method to generate a dictionary (pos). Generating this pos object is very time-consuming and I want to save it as a file, so I don't have to rerun it all whenever I want to work with this dataset.
This is what it looks like so far:
G = nx.Graph()
G.add_edges_from(tuples)
data = nx.spring_layout(G)

If I run type(data), I receive 'dict'. If I run type(G), I receive 'networkx.classes.graph.Graph'.
Since it is a 'dict' object, these are some solutions I found online that I tried and didn't work:
1. Save it as a .csv file
import csv

w = csv.writer(open("output.csv", "w"))

for key, val in data.items():
    w.writerow([key, val])

2. Save as JSON file
import json
json = json.dumps(data)

f = open("data.json","w")

f.write(json)

f.close()

3. Save as a .txt file
f = open("data.txt","w")

f.write( str(data) )

f.close()

Hopefully I made it clear that (i) I don't know which type of file is the best one to save this sort of object; that (ii) I don't know how to save it in any way; and (iii) that, naturally, I don't know how to properly load this file as 'pos dict' object once it is saved in my directory.
For reference, nx.spring_layout(G) returns:
"pos: dict
A dictionary of positions keyed by node.", as described in the documentation.

A: Probably the simplest way to store a python object for later use is to use the pickle module:
import pickle

# save data
with open('positions.pickle', 'wb') as f:
    pickle.dump(data, f)

# load data
with open('positions.pickle', 'rb') as f:
    data = pickle.load(f)


text:
Q: MySQL workbench returns stored procedure with multiple rows, but from Java code, only one row is returned It is MYSQL, and the same stored procedure call in Workbench works fine, but from Java code, it always only return one row.
String sql = "{ CALL getList(?, ?, ?) }";

CallableStatement cs = conn.prepareCall(sql);
cs.setLong(1, key);
cs.setString(2, id);
cs.setInt(3, java.sql.Types.INTEGER);
ResultSet rs = cs.executeQuery();
rtn = cs.getInt(3);             // this return as 1

while (rs.next()) {
     String name = rs.getString("name");
     String age= rs.getString("age");
     //.....
}

from this while loop, always and only return one row, it is very strange, spend hours, no clue yet, please advice what may be wrong, the hint is that the MYSQL is old version 5.3, and Java is old version JDK 1.6.
Anybody have experience to deal with it, please advice, thanks.

A: In addition to what you have, you need to also implement the add() method. Try this:
String sql = "{ CALL getList(?, ?, ?) }";

CallableStatement cs = conn.prepareCall(sql);
cs.setLong(1, key);
cs.setString(2, id);
cs.setInt(3, java.sql.Types.INTEGER);
ResultSet rs = cs.executeQuery();
rtn = cs.getInt(3);

while(rs.next()) {
    String name = add(rs.getString("name"));
    String age= add(rs.getString("age"));
}


text:
Q: Webrtc server for mobile application I want to create mobile apps using webRTC APIs. My basic need is one-to-one video calling capability. Should I just use an open source webRTC server like openwebrtc? I want it to handle at least 5k clients. Is there any other option to fulfill my needs?

A: This question is very broad (and this isn't a proper answer), and is likely to attract very opinionated answers, and is also likely to be deemed as off-topic for Stack Overflow.
Having said that, if you can provide more information, you might get some reasonable opinions.
Please provide more information about what is important to you.
As WebRTC is a peer-to-peer system, scaling isn't a major issue. You need a signalling server of some kind to do call establishment. That work is over quite quickly, and then the two parties can continue the call without needing the server any more.
I don't have experience with openwebrtc, but I have used PeerJS, and found it to be quite good. It hasn't been updated in 2 years, but it seems to do the job pretty well, and is quite lightweight.
There are some commercial offerings around, but I question the value, as they leverage heavily from the open source components, and rely on the browsers for support. They are probably worth using if you want to do many-to-many video calling, as that is when you need a video server.
WebRTC is supposed to be easy, and it has been in the browsers for several years now (notably excluding Safari and IOS). It is a difficult area, and will take some time to master.

A: OpenWebRTC project is a reasonable option for a basic video calling native mobile app; its signalling server is only a basic demo, all written in JavaScript. As such, it should not crash on 5K simultaneous peer video connections.
But a real-world solution might require much more than this: TURN and STUN services, backup for the moments of hardware failure, load balancing, statistics and administration interfaces. Take security seriously: you should be able to cut out a spammer or other offender, in addition to protection against hackers.
Server software is that can help you will not necessarily cost much. See also https://stackoverflow.com/a/38810518/192373.


text:
Q: Get Title of clicked menu-li how can I get the title of the clicked list element? Unfortunately, the following snippet returns an 'undefined'
HTML

        Echocardiogram

        Echocardiogram

JS
$scope.menuClick = function(linkTitle) {
    var linkText = angular.element(linkTitle).data('title');
    console.log(linkText);
};

A: Here is a simple solution.  First you should angularise your code by storing your menu items in a scope variable.  You can then use ng-repeat to iterate through your items.  You can store the corresponding title as well and then reference that title through your ng-click.

                {{ item.name }}

function MyCtrl($scope) {
    $scope.listItems = [{
        "name": "Echocardiogram",
            "title": "Cardiology: Test 1"
    }, {
        "name": "Echocardiogram",
            "title": "Cardiology: Test 2"
    }];

    $scope.getTitle = function (title) {
        alert(title);
    }
}

JSFiddle

A: You could use the click event. And reference the target element () and read it's title propery.
Html:

Controller :
$scope.menuLink =function (event){
    var title = angular.element (event.target).attr ('title');
}


text:
Q: How do I use .apply(func) with a conditional function (pandas) I have the following Pd series
    count   area    volume      formula     quantity
0   1.0     22       NaN       count         1.0
1   1.0     15       NaN       count         1.0
2   1.0     1.4      NaN       area          1.4
3   1.0     0.6       10       volume        100

The quantity column is based on the value in the formula column via a lookup e.g. row(0) is "count" so it is 1, row(2) is "area" so it's 1.4
For this I have a the following formula
Merged['quantity']=Merged.apply(lambda x: x[x['QuantityFormula']] , axis=1)

However quantity for volume is a calculated field: volume * 10. I've written a function to calculate both
def func(x):
    if x[x['QuantityFormula']] == Volume:
        return volume * 10
    else:
        return x[x['QuantityFormula']]

df['Classification'] = Merged['QuantityFormula'].apply(func)

However I get the following error
Error: string indices must be integers

Any ideas? Thanks
Answer
def func(row):
    if row['QuantityFormula'] == 'Volume':
        return row['Volume'] * 10
    return row[row['quantity']]

Merged['Ans'] = Merged.apply(func, axis=1)

A: You can try something like this:
df.apply(lambda x: x['volume']*10 if x['formula'] == 'volume' else x['quantity'], axis=1)

print(df)

   count  area  volume formula  quantity    ans
0    1.0  22.0     NaN   count       1.0    1.0
1    1.0  15.0     NaN   count       1.0    1.0
2    1.0   1.4     NaN    area       1.4    1.4
3    1.0   0.6    10.0  volume     100.0  100.0

Using an explicit function, you can do:
def func(row):
    if row['formula'] == 'volume':
        return row['volume'] * 10
    return row['quantity']

df.apply(func, axis=1)

A: Use a lookup:
import numpy as np

s = df['formula'].str.lower()
m = s.eq('volume')

idx, cols = pd.factorize(s)

df['quantity'] = (df.reindex(cols, axis=1).to_numpy()[np.arange(len(df)), idx]
                  *  np.where(m, 10, 1)
                  )


text:
Q: reducing migration time of a large size postgresql database We have a postgresql 9.4 DB server that handles 2 DBs, each ~800GB. No replication is implemented yet.
We reduced pg_dump time with using -j & -Fd options to about 2 hours.
The problem is, we need to separate DBs, so we setup a fresh new server with Postgresql 9.6, but pg_restore takes a very long time (~2 days). I tried parallel pg_restore using -j (4, 8, 16, although VM has a 4 core CPU and 16GB of RAM) and tuned some parameters in posotgresql.conf like shared_buffers, effective_cache_size, work_mem, maintenance_work_mem, wal_buffers and so forth, but they didn't have any significant effect on reducing time of restore.
Even, I tried to restore data and schema separately, but same results.
I think the problem is we have many tables with 15M records that all have index and indices will increase restore time but I'm not sure of that
We thought about replication, so we do not have any significant downtime (after sync is complete, we can stop old/master server and change replica/slave to acts as a master server), but as version of postgresql servers is not same, it didn't work out! Updating main server postgresql version to 9.6 and then start replication will take such a time!
Any advice and suggestions will be greatly appreciated!

A: Bit of a FAQ.

*

*pg_upgrade with --link (but understand that you can't easily go back);

*Logical streaming replication with pglogical

*Trigger-based logical replication with Londiste etc
Search for zero or low downtime PostgreSQL major version upgrade.

A: Although pglogical seems a great tool, but I didn't take and breaking stability and reliability of Debian's Postgresql packages.
In the other hand, I figured it out I can reduce time of restore with having a good balance between hardware resources and configurations in postgresql.conf file and -j option of pg_restore command.
For example restore time with 2*2 core CPU, 32 GB of RAM and -j 32 took more than 16 hours.
Finally, pg_restore with 2*2 core CPU, 16 GB of RAM and -j 16 worked out for me. It took 5 hours 17 minutes for me!


text:
Q: How to make a grid in pygame I am trying to create a basic snake game with Python and I am not familiar with Pygame. I have created a window and I am trying to split that window up into a grid based on the size of the window and a set square size.
def get_initial_snake( snake_length, width, height, block_size ):
    window = pygame.display.set_mode((width,height))
    background_colour = (0,0,0)
    window.fill(background_colour)

    return snake_list

What should I add inside window.fill function to create a grid based on width, height, and block_size? Any info would be helpful.

A: You can draw rectangles
for y in range(height):
    for x in range(width):
        rect = pygame.Rect(x*block_size, y*block_size, block_size, block_size)
        pygame.draw.rect(window, color, rect)

I assumed that the height and width is the number of blocks.

if you need one pixel gap between rectangles then use
rect = pygame.Rect(x*(block_size+1), y*(block_size+1), block_size, block_size)

To draw snake you can use list and head_color, tail_color
snake = [(0,0), (0,1), (1,1), (1,2), (1,3)]

# head

x, y = snake[0]
rect = pygame.Rect(x*block_size, y*block_size, block_size, block_size)
pygame.draw.rect(window, head_color, rect)

# tail

for x, y in snake[1:]:
    rect = pygame.Rect(x*block_size, y*block_size, block_size, block_size)
    pygame.draw.rect(window, tail_color, rect)

A: Using the for loop as a reference from the answer: https://stackoverflow.com/a/33963521/9715289
This is what I did when I was trying to make a snake game.
BLACK = (0, 0, 0)
WHITE = (200, 200, 200)
WINDOW_HEIGHT = 400
WINDOW_WIDTH = 400

def main():
    global SCREEN, CLOCK
    pygame.init()
    SCREEN = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    CLOCK = pygame.time.Clock()
    SCREEN.fill(BLACK)

    while True:
        drawGrid()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        pygame.display.update()

def drawGrid():
    blockSize = 20 #Set the size of the grid block
    for x in range(0, WINDOW_WIDTH, blockSize):
        for y in range(0, WINDOW_HEIGHT, blockSize):
            rect = pygame.Rect(x, y, blockSize, blockSize)
            pygame.draw.rect(SCREEN, WHITE, rect, 1)

How the result looks like:


text:
Q: correct idiom for if you were me I am looking for an idiom that can be used for this like "if you were me you would have done the same thing "
 OR something like empathy , think from my sight, is there any idiom for such scenerio?
I tried to figure out but couldn't find that
I found something like, see through my eyes, but thats not appealing at all.
I thought of "be at my place" but I dont think it gives correct meaning

A: You can say:  If you were in my shoes, would you do the same thing?

A: In my place you would have done the same thing.

A: if the shoe were on the other foot


text:
Q: How to pass value to select option i want to pass the value from one page to another's option
value of array want to pass when click accSummary (direct to the desired page)which will invoke a function :
document.getElementById("1").innerHTML = ''+accSummary[0].accNo +'';
document.getElementById("2").innerHTML = ''+accSummary[0].accNo +'';

function invoked: (i try to store the value in localStorage)

getSum(no){
     localStorage.setItem("accNo",accDetail[no]);
}

i write this script to get the value

however, it turns out that the no (localStorage.accDetail[no])is undefined.
what's the problem

A: Try like this
1.function not define function getSum(no).
2.change the getSum(0) instead of getSum[0].
3.Already you have declare the local storage value.So retrieve the data like this localStorage.getItem("accNo");
 document.getElementById("1").innerHTML = ''+accSummary[0].accNo +'';
 document.getElementById("2").innerHTML = ''+accSummary[0].accNo +'';

   function getSum(no){ //its a function
         localStorage.setItem("accNo",accDetail[no]); //assign the value to local
    }


text:
Q: Integral extension/ splitting extension of rings How can I prove using integral extensions that, if $R$ is a commutative ring with $1$, and $f \in R[x]$, then there is a ring extension $R \subseteq S$ such that $S$ contains all the roots of $f$? Trying to mimic the proof for splitting field extensions, the first step would be finding an extension containing one root, and the rest would follow by induction. Problem is, the obvious injection $\iota: R \longrightarrow R[x]/(f)$ sending $r \in R$ to $r+(f) \in R[x]/(f)$ doesn't work anymore, because $R$ is not necessarily a field, and thus I can't take $R[x]/(f)$ as an extension of $R$ having a root.
I guess the proof would involve integral extensions, as this is a part of a problem involving them.


text:
Q: What's the most efficient & semantic way to display icons? Before I begin, I read this very useful question which lays out what's the pros and cons of using 's and background-images. When to use IMG vs CSS
After reading that, however I've been thinking about what's the most efficient & semantic way of displaying an icon. The other question contended that if there's semantic meaning to it such as a warning icon, then it should be displayed as an  which I think makes sense in most cases. However, what about the other times?
Here's the only other ways I've seen icons presented:

*

*Having extra padding on an element (e.g., 20px left padding on an anchor)

*As a separate element (Facebook uses the  tag, Google uses the  tag)

Using the extra padding method seems to work alright in some cases, but you might run into the problem of exposing other icons in your sprite map if the dimensions of the element don't match up with your icon.
I'm guessing the separate element icon method is probably the most fail-safe way of doing it, but I'm not 100% certain if it's always the best way to do it and what element to use (i, span, other?)
What's your thoughts?

A: It depends on the circumstance, if the icon is actually designed to give emphasis to some text, then you'd include it in the tag, i.e.
Warning!

And you would add CSS styles to display the icon as the background-image. Technically speaking, you should only be using the  tag for items which are semantically images, such as a photograph or diagram. Otherwise for things like headings or icons, stick with changing the background-image.

A: I like keeping most of my icons as background images and padding the text off from the left to adjust. When there's something that needs attention (such as a warning), you pretty much need a text-based method to convey that information for accessibility's sake, even if you find ways to hide it in the CSS.
I'm against using spans or other elements because it's just not semantic and they aren't necessary.
When I'm building sprites, I always make sure to keep all the icons on the right edge of the sprite so they never have the opportunity to expose rogue sprites (and for variable height issues, you either have to give them plenty of space to grow or put them bottom-right).

A: This article addresses well the issue. This is an adapted summary.
When using sprites and fonts for icon representation (vs img or other inline imagery insertion techniques), there are two possible scenarios:

*

*When the icon is meant to enhance the text

*When the icon is meant to stand alone and be functional or informational

Case (1) solution:
Accomplishes its goal by showing the icon on most cases, not using the i tag for the wrong purpose (semantic) and being unobtrusive for screen readers.
And you can use class instead of the data- attribute if you prefer.
/* HTML */

  Stats

/* CSS */
[data-icon]:before {
  font-family: icons; /* or use background-image instead */
  content: attr(data-icon);
  speak: none;
}

Case (2) solution:
Similar approach as before, but here the icon would have a fallback solution for screen readers.
/* HTML */

  RSS

/* CSS */
.icon-alone {
  display: inline-block;
}
.screen-reader-text { /* Reusable */
  position: absolute;
  top: -9999px;
  left: -9999px;
}

Summary:

*

*Semantically correct

*Accessibility friendly

*Future proof (you could always select uniquely down the line even if you change the character)

A: The way I would pursue this issue would be by, saving your entire icon set in one image sprite and than call each image on a per-need basis.
For example:
Stackoverlow does something similar by saving all their icons in one sprite like so:
http://sstatic.net/stackoverflow/img/sprites.png
And then it's a simple matter of defining classes for each image with the appropriate background-position that way you can also semantically set appripriate padding and sizing for each individual icon.
All this also ensures a quicker loading of icons.


text:
Q: How to add prediction intervals to describe the variability in monthly samples of data? The data analyzed here is a sample of individuals collected on a monthly basis. What would be the best way to compute "prediction intervals" for the monthly sample means, in order to indicate the natural variability that can be expected from this value month after month?
Here is an example:

*

*All individuals are sampled with replacement from the same population whose mean is expected be the same across all months;

*$y_i$ for individual $i$ is the variable of interest, with $ y_i \sim N(y,\sigma)$, both $y$ and $\sigma$ are unknown;

*$N_m$ is the sample size for month $m$;

*$\bar y_m$ is the sample mean for month $m$.

What would be the best way to compute a 95% prediction interval for $\bar y_m$?
I thought of doing the following:

*

*$\bar y $ is the sample mean across the whole sample;

*$\bar \sigma $ is the standard deviation across the whole sample;

*For each month $j$, I compute the interval as $[ \bar y - 1.96 \frac{\bar \sigma}{ \sqrt{N_m}} ; \bar y + 1.96 \frac{\bar \sigma}{ \sqrt{N_m}} ]$.

I'm afraid this is not statistically correct. Simulations I've been doing show that this interval contains the monthly value more than 95 times out of 100. I assume this is caused by the fact that I do not consider the uncertainty in the estimation of $\bar y$.
What would be the correct way to proceed?
Thanks.

A: If I understand correctly, in each month, you measure several individuals once. Then you work out the mean and standard deviation of some variable. Without knowing anything else I'd base confidence intervals on the t-distribution; the intervals would be a bit wider than those using a multiplier of 1.96, but it would take a small sample to show much difference.
However, you are saying nothing about what it is that is being measured or counted, and depending on that and what its distribution is like, the quality of a t-distribution approximation might vary a bit.
Also, nothing in your analysis addresses any dependence in time that might exist, but as you are averaging across individuals within months that is not necessarily an issue. You might want to consider whether there are dependencies between individuals that are biting.
All that said, your situation sounds good. You've checked your procedure by simulation and your coverage is a bit more than expected. Few researchers could say as much, and if it were me, I would not go further and try to correct anything. No need to fix what is not evidently broken.


text:
Q: Reshaping an array into a nested array Given an array with multiple arrays nested inside of different length, how do I reshape a separate array that has an equal amount of values?
For example:
import numpy
array1 = numpy.array([[0.1,0.2],[0.3,0.4,0.5]],dtype=object)
array2 = numpy.array([0.11,0.22,0.33,0.44,0.55])

What I am trying to get is:
finalarray = numpy.array([[0.11,0.22,], [0.33,0.44,0.55]])


text:
Q: Is there a better way to have dynamic text appear next to a combobox? I have a combobox, and based on the current selection, I would like dynamic text to appear beside the combobox.
My current solution works, but seems kludgy and fragile.  It may not work at all depending on where the combobox appears in the DOM.
Here is the crux of my current solution (called when dropdown changes):
    var child = owner.el.first().next().first().first().first().next().first();
    if (child.dom.childNodes.length == 3) {
        child.createChild({
            tag: 'span',
            html: c + Ext.id()
        });
    } else {
        child.last().replaceWith({
            tag: 'span',
            html: c + Ext.id()
        });
    }

I'm mostly concerned about the first line...this can't be a good way of finding an insertion point.
Here is a pic of the combo box with the dynamic text appearing beside:

And here is what I looked at to find where I wanted to insert the text:

Can someone suggest a better way of achieving this effect?  Thanks.

A: Have the span in the page already and grab it by its id.
Ext.get('combo-suffix').insertHTML(theText);

Or, grab the combo box element by its id and get/add its sibling.

A: Will it always be in a div called "ext-gen82"?
If so, why not use the jquery find method?
$("#ext-gen82").find("ext-gen107");

Alternatively you could give them their own class to help you find them as well:
$(".parentClass").find(".spanElement");

You could also use the children method:
$("#ext-gen82").children("span");

A: @OrangeDog pointed me the right direction, but I'll post a more detailed answer here for completeness/future reference.
var inserted = false; // need to set this up initially
...
var pos = Ext.getCmp('combo-element-id').el.next('.x-form-trigger');
if (inserted) {
    pos.next().update(c + Ext.id());
} else {
    inserted = true;
    pos.insertSibling({
        tag: 'span',
        html: c + Ext.id()
    }, 'after');
}


text:
Q: Django, haystack, elastic search and one to many relation I have problem with haystack - I do not know how to search for models A whose all foreign keys meet given condition.
My simplified models look like:
Group:
    id
Meeting:
    group = models.ForeignKey(Group)
    day_of_week = models.IntegerField()
    hour = models.IntegerField()
    length = models.IntegerField()

So basically, a group can have many meetings and users should be able to search for those groups whose all meetings are in given time range. eg:
Group(1)
    Meeting(day_of_week=Monday, hour=9, length=2)
Group(2)
    Meeting(day_of_week=Monday, hour=10, length=1)
    Meeting(day_of_week=Tuesday, hour=8, length=2)
Group(3)
    Meeting(day_of_week=Monday, hour=10, length=1)
    Meeting(day_of_week=Wednesday, hour=12, length=1)

and search: "Monday from 8 to 11", "Tuesday, from 12 to 14 (2p.m.)", "Wednesday, from 6 to 17 (5p.m.)" should return group 1 and 3, because all meetings from those groups contains in user specified ranges and group 2 is not returned, because second meeting is not in given range (tho the first one is).
If I was to write a SQL, I would probably go for something like "select count of matching meetings and count of all meetings if those numbers are equal -> then all meetings meet:
SELECT g.id,
       count(m2.id)
FROM groups g
JOIN meetings m2 ON m2.group_id = g.id
AND ((m2.day_of_week = 0  -- monday
      AND m2.hour >= 8
      AND m2.length<=3)
     OR (m2.day_of_week=1  -- tuesday
         AND m2.hour >= 12
         AND m2.length<=2)
     OR (m2.day_of_week=2 -- wednesday
         AND m2.hour >= 6
         AND m2.length<=11))
GROUP BY g.id
HAVING count(m2.id) =
  (SELECT count(*)
   FROM meetings
   WHERE meetings.group_id=g.id);

But we are using haystack + elastic search for indexing and I have completely no idea how to flatten the model to index and write a query. Can anyone help me with it?

A: You probably need to flatten your documents in such a way that all your documents must be meetings containing group information.
** Solution for ES 5 **
The mapping of your document would be:
PUT /meetings
{
    "mappings": {
       "meeting": {
          "properties": {
             "groupId": {
                "type": "integer"
             },
             "dayOfWeek": {
                "type": "integer"
             },
             "hourRange": {
                "type": "integer_range"
             }
          }
       }
    }
}

Then your five documents would look like this:
POST /meetings/meeting/_bulk
{"index": {}}
{"groupId": 1, "dayOfWeek": 0, "hourRange": {"gte": 9, "lte": 11}}
{"index": {}}
{"groupId": 2, "dayOfWeek": 0, "hourRange": {"gte": 10, "lte": 11}}
{"index": {}}
{"groupId": 2, "dayOfWeek": 1, "hourRange": {"gte": 8, "lte": 10}}
{"index": {}}
{"groupId": 3, "dayOfWeek": 0, "hourRange": {"gte": 10, "lte": 11}}
{"index": {}}
{"groupId": 3, "dayOfWeek": 2, "hourRange": {"gte": 12, "lte": 13}}

Finally, the query would look like this:
POST /meetings/meeting/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "dayOfWeek": 0
                }
              },
              {
                "range": {
                  "hourRange": {
                    "gte": "8",
                    "lte": "11",
                    "relation": "within"
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "dayOfWeek": 1
                }
              },
              {
                "range": {
                  "hourRange": {
                    "gte": "12",
                    "lte": "14",
                    "relation": "within"
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "dayOfWeek": 2
                }
              },
              {
                "range": {
                  "hourRange": {
                    "gte": "6",
                    "lte": "17",
                    "relation": "within"
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

** Solution for ES <5 **
PUT /meetings
{
    "mappings": {
       "meeting": {
          "properties": {
             "groupId": {
                "type": "integer"
             },
             "dayOfWeek": {
                "type": "integer"
             },
             "start": {
                "type": "integer"
             },
             "end": {
                "type": "integer"
             }
          }
       }
    }
}

Then your five documents would look like this:
POST /meetings/meeting/_bulk
{"index": {}}
{"groupId": 1, "dayOfWeek": 0, "start": 9,  "end": 11}
{"index": {}}
{"groupId": 2, "dayOfWeek": 0, "start": 10, "end": 11}
{"index": {}}
{"groupId": 2, "dayOfWeek": 1, "start": 8,  "end": 10}
{"index": {}}
{"groupId": 3, "dayOfWeek": 0, "start": 10, "end": 11}
{"index": {}}
{"groupId": 3, "dayOfWeek": 2, "start": 12, "end": 13}

Finally, the query would look like this:
POST /meetings/meeting/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "dayOfWeek": 0
                }
              },
              {
                "range": {
                  "start": {
                    "gte": "8"
                  }
                }
              },
              {
                "range": {
                  "end": {
                    "lte": "11"
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "dayOfWeek": 1
                }
              },
              {
                "range": {
                  "start": {
                    "gte": "12"
                  }
                }
              },
              {
                "range": {
                  "end": {
                    "lte": "14"
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "dayOfWeek": 2
                }
              },
              {
                "range": {
                  "start": {
                    "gte": "6"
                  }
                }
              },
              {
                "range": {
                  "end": {
                    "lte": "17"
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

A: ElasticSearch solution
The key to the solution is ElasticSearch feature named nested objects. Luckily this feature is present in all ES versions. Nested object is key here, because data in meeting are strictly associated.
PUT /myindex
{
  "mappings": {
    "groups": {
      "properties": {
        "meetings": {
          "type": "nested",
          "properties": {
             "dayOfWeek": { "type": "integer"},
             "start": {"type": "integer"},
             "end": {"type": "integer"}
          }
        },
        "groupId": {"type":"integer"}
      }
    }
  }
}

POST /myindex/groups/_bulk
{"index": {}}
{"groupId": 1, "meetings": [{"dayOfWeek": 0, "start": 9,  "end": 11}]}
{"index": {}}
{"groupId": 2, "meetings": [{"dayOfWeek": 0, "start": 10, "end": 11}, { "dayOfWeek": 1, "start": 8,  "end": 10}]}
{"index": {}}
{"groupId": 3, "meetings": [{"dayOfWeek": 0, "start": 10, "end": 11}, {"dayOfWeek": 2, "start": 12, "end": 13}]}

At this point it is clearly visible that meetings belong to groups and we will search in groups.
It is not possible to directly write query to get all groups whose all nested objects meet condition, but... it can be inversed easily to: get all groups where none of the meeting contains wrong time.
GET /myindex/_search
{
  "query": {
    "bool": {
      "must_not" : {
       "nested": {
          "path": "meetings",
          "filter": {
              "bool": {
                "must_not": {
                  "bool": {
                    "should": [
                        {
                          "bool": {
                            "must": [
                              {"term" : { "dayOfWeek" : 0 }},
                              {"range": {"start": {"from":8, "to":11}}},
                              {"range": {"end": {"from":8, "to":11}}}
                            ]
                          }
                        },
                        {
                          "bool": {
                            "must": [
                              {"term" : { "dayOfWeek" : 1 }},
                              {"range": {"start": {"from":12, "to":14}}},
                              {"range": {"end": {"from":12, "to":14}}}
                            ]
                          }
                        },
                        {
                          "bool": {
                            "must": [
                              {"term" : { "dayOfWeek" : 2 }},
                              {"range": {"start": {"from":6, "to":17}}},
                              {"range": {"end": {"from":6, "to":17}}}
                            ]
                          }
                        }
                      ]
                    }
                }
              }
            }
          }
       }
      }
    }
  }

This will return groups 1 and 3. Group 2 will not be returned because one of this meetings overlaps with wrong datetime.
Haystack integration
The second problem was integration with Django Haystack, because by default it doesn't support engine-specific features like nested fields in ES. Luckily I am not the only one who needs it in django app and someone has already resolved it.


text:
Q: Find all link in a string with java regex I have a String which contains some url how i can find all the href with a regular expression?
prodotto di prova

Now i have this which find all amazon links now i need to add also the href to this regex:
 String regex="(http|www\\.)(amazon|AMAZON)\\.(com|it|uk|fr|de)\\/(?:gp\\/product|gp\\/product\\/glance|[^\\/]+\\/dp|dp|[^\\/]+\\/product-reviews)\\/([^\\/]{10})";

A: This pattern works for me in Java: (IDEONE here)
String input = "prodotto di prova\"";
String pattern = "href=(?<link>['\\\"](?:https?:\\/\\/)?(?:www\\.)?(?:amazon|AMAZON)\\.(?:com|it|uk|fr|de)\\/(?<product>:gp\\/product|gp\\/product\\/glance|[^\\/]+\\/dp|dp|[^\\/]+\\/product-reviews)\\/(?<productID>[^\\/]{10})\\/(?<queryString>.*?)\\\")";

Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);

if (m.find( )) {
 System.out.println("Amazon link: " + m.group(0) );
 System.out.println("product: " + m.group("product") );
 System.out.println("productID: " + m.group("productID"));
 System.out.println("querystring: " + m.group("queryString"));
} else {
 System.out.println("NO MATCH");
}

output:

*

*Amazon link:
href="http://www.amazon.it/Die-10-Symphonien-Orchesterlieder-Sinfonie-Complete/dp/B003LQSHBO/ref=sr_1_2?ie=UTF8&qid=1440101590&sr=8-2&keywords=mahler"

*product: Die-10-Symphonien-Orchesterlieder-Sinfonie-Complete/dp

*productID: B003LQSHBO

*querystring: ref=sr_1_2?ie=UTF8&qid=1440101590&sr=8-2&keywords=mahler
Java's rules for backslashes and escapes in strings are absolutely infuriating to me and I never get it right. You may find it helpful to go to http://www.regexplanet.com/advanced/java/index.html and enter a regex, which it will convert into a java string with the proper escapes. (I couldn't get mine working until I did this!)


text:
Q: How to find the path after "cannot find module" message when I try to use grass tools in qgis I use mac and when I try to use grass modules in qgis (brighton) I get a "cannot find module" message.

A: He uses a Mac. For the procedure, look at Configuring external applications.
Check the path in Processing/Toolbox/Options/Providers/GRASS...

*

*If you use the KyngChaos version, there is a GRASS GIS 6.x version integrated in the QGIS application bundle and the path is /Applications/QGIS.app/Contents/MacOS/grass

*if you want to use another version of GRASS GIS, adapt the path, for example /Applications/GRASS-6.4.app/Contents/MacOSfor GRASS 6.x and /Applications/GRASS/GRASS-7.x.app/Contents/MacOSfor GRASS 7

If you use another version of QGIS (Homebrew, MacPorts, ...), it is the same thing


text:
Q: Django: KeyError when creating DB Table from CSV I need to create a table from a CSV file.
I think I can do it with different libraries, but in this case I've choosen to use pandas, as I'll need it more in the near future for some data analysis.
I've a script but I'm getting this error:
Traceback (most recent call last):
  File "/home/gonzales/Escritorio/virtual_envs/stickers_gallito_env/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 3078, in get_loc
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 958, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 964, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 1867

Data in Dropbox:
https://www.dropbox.com/s/o3iga509qi8suu9/ubigeo-peru-2018-12-25.csv?dl=0
script:
import pandas as pd
import csv
from shop.models import Peru
from django.core.management.base import BaseCommand

tmp_data=pd.read_csv('static/data/ubigeo-peru-2018-12-25.csv',sep=',', encoding="utf-8")

class Command(BaseCommand):
    def handle(self, **options):
        products = [
            Peru(
                departamento=tmp_data.ix[row]['departamento'],
                provincia=tmp_data.ix[row]['provincia'],
                distrito=tmp_data.ix[row]['distrito'],
            )
            for row in tmp_data['id']
        ]

        Peru.objects.bulk_create(products)

models.py
class Peru(models.Model):
    departamento = models.CharField(max_length=100, blank=False)
    provincia = models.CharField(max_length=100, blank=False)
    distrito = models.CharField(max_length=100, blank=False)

    def __str__(self):
        return self.departamento

A: The reason this doesn't work (and throws an error for the last object) is that row is actually the id of your data which begins at 1 while you're using it as an index.
Use it like this instead:
products = [
        Peru(
            departamento=tmp_data.ix[row-1]['departamento'],
            provincia=tmp_data.ix[row-1]['provincia'],
            distrito=tmp_data.ix[row-1]['distrito'],
        )
        for row in tmp_data['id']
    ]

Or you could iterate over the dataframe like the library recommends:
products = []
for i, row in tmp_data.iterrows():
    products.append(Peru(
        departamento=row]['departamento'],
        provincia=row['provincia'],
        distrito=row['distrito'],
    ))

Peru.objects.bulk_create(products)

A: The id field looks like an index but starts from 1; when you create the rows you access the dataframe by index by use the id field as the index, which yields the error as you're trying to access the 1868th row (which doesn't exist).
I would try:
import pandas as pd
import csv
from shop.models import Peru
from django.core.management.base import BaseCommand

tmp_data=pd.read_csv('static/data/ubigeo-peru-2018-12-25.csv',sep=',', encoding="utf-8")

class Command(BaseCommand):
    def handle(self, **options):
        products = [
            Peru(
                departamento=row['departamento'],
                provincia=row['provincia'],
                distrito=row['distrito'],
            )
            for index, row in tmp_data.iterrows()
        ]

        Peru.objects.bulk_create(products)


text:
Q: Is 'lamented' a dialogue tag? In these sentences,

*

*"I miss having breakfast every day," he lamented.

*"I miss having breakfast every day." He lamented.

is the first correct? I would say lamented is a dialogue tag, since if I use the verb said or responded instead, then it would be a dialogue tag:

"I miss having breakfast every day," he said.
"I miss having breakfast every day," he responded.


text:
Q: How to implement same action with transition and without transition ? Is there any solution to use same action with transition and without transition?
css
-webkit-transition: all 0.5s ease 0s;
-moz-transition: all 0.5s ease 0s;
-ms-transition: all 0.5s ease 0s;
-o-transition: all 0.5s ease 0s;
transition: all 0.5s ease 0s;

jquery
$("#transition").click(function(){
    $("#box-progress").css("left", "50%");
});
// This shoudn't show transition;
$("#no-transition").click(function(){
    $("#box-progress").css("left", "50%");
});

Demo:- http://jsfiddle.net/sweetmaanu/XcRNd/

A: Yes.
Put the transitions in a separate class, like:
.apply_transitions {
    /* .. */
    transition: all 0.5s ease 0s;
}

Then, you want the transition do:
$("#box-progress").addClass("apply_transitions").css("left", "50%");

And if you don't want the transtion, do:
$("#box-progress").removeClass("apply_transitions").css("left", "50%");

This means that by default, nothing has a transition unless you add the apply_transitions class.


text:
Q: counting matching elements of two vectors but not including repeated elements in the count I've search a lot in this forum. However, I didn't found a similar problem as the one I'm facing.
My question is:
I have two vectors
x <- c(1,1,2,2,3,3,3,4,4,4,6,7,8) and z <- c(1,1,2,4,5,5,5)
I need to count the number of times x or z appears in each other including if they are repeated or not.
The answer for this problem should be 4 because :
There are two number 1, one number 2, and one number 4 in each vector.
Functions like match() don't help since they will return the answer of repeated for non repeated numbers. Using unique() will also alter the final answer from 4 to 3
What I came up with was a loop that every time it found one number in the other, it would remove from the list so it won't be counted again.
The loop works fine for this size of this example; however, searching for larger vectors numerous times makes my loop inefficient and too slow for my purposes.
system.time({
    for(n in 1:1000){
        x <- c(1,1,2,2,3,3,3,4,4,4,6,7,8)
        z <- c(1,1,2,4,5,5,5)
        score <- 0
        for(s in spectrum){
            if(s %in% sequence){
                sequence <- sequence[-which(sequence==s)[1]]
                score <- score + 1
            }
        }
    }
})

Can someone suggest a better method?
I've tried using lapply, for short vectors it is faster, but it became slower for longer ones..

A: Use R's vectorization to your advantage here.  There's no looping necessary.
You could use a table to look at the frequencies,
table(z[z %in% x])
#
# 1 2 4
# 2 1 1

And then take the sum of the table for the total
sum(table(z[z %in% x]))
# [1] 4


text:
Q: count frequencies across a table per group in R I have a data table df, I would like to group it by the first column, 'location',
and compute the frequency of entries across all table, both columns and rows:
df

location   NN_1    NN_2   NN_3
    NYC    17      17      17
    NYC    17      16      1
    LA     1        1      10
    LA     16      10      1

which can be obtained by:
df <- structure(list(location = c("NYC", "NYC", "LA", "LA"),
                     NN_1 = c(17, 17, 1, 16),
                     NN_2 = c(17, 16, 1, 10),
                     NN_3 = c(17, 1, 10, 1)),
                     class = "data.frame",
                     row.names = c(NA, -4L))

I would like to count how many times 17 is repeated for a given location, like NYC:
output
location   NNs  freq
    NYC    17      4
    NYC    16      1
    NYC     1      1
    LA      1      3
    LA      16     1
    LA      10     2

A: Possible tidyverse solution:
df %>%
  gather("key", "NNs", 2:ncol(.)) %>%
  group_by(location, NNs) %>%
  summarize(freq = n()) %>%
  arrange(desc(location), desc(NNs))

A: Base R solution, effectively doing the same thing as the tidyverse solution. Put the first location column identifier against all the other columns, then tabulate:
as.data.frame(table(cbind(df[1], NNs=unlist(df[-1]))))
#  location NNs Freq
#1       LA   1    3
#2      NYC   1    1
#3       LA  10    2
#4      NYC  10    0
#5       LA  16    1
#6      NYC  16    1
#7       LA  17    0
#8      NYC  17    4


text:
Q: NUnit testing the application, not the environment or database I want to be better at using NUnit for testing the applications I write, but I often find that the unit tests I write have a direct link to the environment or underlying database on the development machine instead.
Let me make an example.
I'm writing a class which has the single responsibility of retriving a string, which has been stored in the registry by another application. The key is stored in HKCU\Software\CustomApplication\IniPath.
The Test I end up writing looks like this;
[Test]
public void GetIniDir()
{
    RegistryReader r = new RegistryReader();
    Assert.AreEqual(@"C:\Programfiles\CustomApplication\SomeDir", r.IniDir);
}

But the problem here is that the string @"C:\Programfiles\CustomApplication\SomeDir" is really just correct right now. Tomorrow it might have changed to @"C:\Anotherdir\SomeDir", and suddenly that breaks my unit tests, even though the code hasn't changed.
This problem is also seen when I create a class which does CRUD operations against a database. The data in the database can change all the time, and this in turn makes the tests fail. So even if my class does what it is intended to do it will fail because the database returns more customers that it had when I originally wrote the test.
[Test]
public void GetAllCustomersCount()
{
    DAL d = new DAL();
    Assert.AreEqual(249, d.GetCustomerCount());
}

Do you guys have any tips on writing Tests which do not rely on the surrounding environment as much?

A: The solution to this problem is well-known: mocking.  Refactor your code to interfaces, then develop fake classes to implement those interfaces or mock them with a mocking framework, such as RhinoMocks, easyMock, Moq, et. al.  Using fake or mock classes allow you to define what the interface returns for your test without having to actually interact with the external entity, such as a database.
For more info on mocking via SO, try this Google search: http://www.google.com/search?q=mock+site:stackoverflow.com.  You may also be interesting in the definitions at: What's the difference between faking, mocking, and stubbing?
Additionally, good development practices, such as dependency injection (as @Patrik suggests), which allows the decoupling of your classes from its dependencies, and the avoidance of static objects, which makes unit testing harder, will facilitate your testing.  Using TDD practices -- where the tests are developed first -- will help you to naturally develop applications that incorporate these design principles.

A: The easiest way is to make the dependencies explicit using dependency injection. For example, your first example has a dependency on the registry, make this dependency explicit by passing an IRegistry (an interface that you'll define) instance and then only use this passed in dependency to read from the registry. This way you can pass in an IRegistry-stub when testing that always return a known value, in production you instead use an implementation that actually reads from the registry.
public interface IRegistry
{
    string GetCurrentUserValue(string key);
}

public class RegistryReader
{
    public RegistryReader(IRegistry registry)
    {
        ...
        // make the dependency explicit in the constructor.
    }
}
[TestFixture]
public class RegistryReaderTests
{
    [Test]
    public void Foo_test()
    {
        var stub = new StubRegistry();
        stub.ReturnValue = "known value";

        RegistryReader testedReader = new RegistryReader(stub);

        // test here...
    }

    public class StubRegistry
        : IRegistry
    {
        public string ReturnValue;

        public string GetCurrentUserValue(string key)
        {
            return ReturnValue;
        }
    }
}

In this quick example i use manual stubbing, of course you could use any mocking framework for this.

A: Other way is to create separate database for tests.

A: You should read up on the inversion of control principle and how to use the dependency injection technique - that really helps you write testable code.
In your case, you should probably have an interface - e.g. IIniDirProvider - which is implemented by RegistryBasedIniDirProvider, which is resposible for providing the initial directory based off a specific key in the registry.
Then, when some other class needs to look up the initial directory, that other class should have the following ctor:
public SomeOtherClass(IIniDirProvider iniDirProvider)
{
    this.iniDirProvider = iniDirProvider;
}

-allowing you to pass in a mock IIniDirProvider when you need to unit test SomeOtherClass. That way your unit test will not depend on anything being present in the registry.


text:
Q: Moving domain name to new host but same domain needed in old host we have a website with domain name as www.abc.com the domain has one global site and 30 country sites urls will look as www.abc.com/global/index.aspx and www.abc.com/uk/index.aspx but now we are redesigning the global site and moving to new host environment, for every periodic time we going to move country sites one by one.
when we move the global site we will move the domain name to new host environment this will effect the country sites in old host. Is there any alternate way we can retain the domain name in old host ?

A: The only real way you can achieve this would be to plunk a reverse proxy down in front of your servers and make routing decisions based on the URL path requested.
There's any number of products or solutions out there that can do it, chief among the free ones are HAproxy, mod_proxy and NGinx. On the commercial side, F5's BigIP LTM products, Citrix Netscalers and any other Application Delivery Controler (aka Load balancer) can do what you need.


text:
Q: Sorting a list based on frequency of words I would need to sort a list of words based on its frequency.
My input:
Haha, hehe, haha, haha, hehe, hehe.... , Test

For example in my data structure I would have
Haha:3
Hehe:5
Test:10

I would need the data structure to be sorted at the output in this manner:
Test:10
Hehe:5
Haha:3

Such that if I pop the top of the data structure I would be able to obtain the element and its corresponding frequency.
The number of elements is unknown initially and hence, an array would not be feasible. If I would like to obtain the top few elements I would just need to access it sequentially. Is this possible in Java?

A: First, want to confirm:
Can you get all the whole words before sorting? Or these words come continuously in a stream?
(1)For the former case, you can use a Set to store the words, then put them into a PriorityQueue. If you implement the comparator function, the queue will sort the words automatically. I create a new class Pair to store the text and frequency, see the code:
import java.util.Queue;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.HashSet;
import java.util.Comparator;

public class PriorityQueueTest {

    public static class Pair {
        private String text;
        private int frequency;

        @Override
        public int hashCode() {
            return text.hashCode();
        }

        @Override
        public String toString() {
            return text + ":" + frequency;
        }

        public Pair(String text, int frequency) {
            super();
            this.text = text;
            this.frequency = frequency;
        }

        public String getText() {
            return text;
        }
        public void setText(String text) {
            this.text = text;
        }
        public int getFrequency() {
            return frequency;
        }
        public void setFrequency(int frequency) {
            this.frequency = frequency;
        }
    }

    public static Comparator<Pair> idComparator = new Comparator<Pair>(){
        @Override
        public int compare(Pair o1, Pair o2) {
            if(o1.getFrequency() > o2.getFrequency()) {
                return -1;
            }
            else if(o1.getFrequency() < o2.getFrequency()){
                return 1;
            }
            else {
                return 0;
            }
        }
    };

    public static void main(String[] args) {
        Set<Pair> data = new HashSet<Pair>();
        data.add(new Pair("haha", 3));
        data.add(new Pair("Hehe", 5));
        data.add(new Pair("Test", 10));

        Queue<Pair> queue = new PriorityQueue(16, idComparator);

        for(Pair pair : data) {
            queue.add(pair);
        }

        // Test the order
        Pair temp = null;
        while((temp = queue.poll()) != null) {
            System.out.println(temp);
        }

    }

}

(2)For the other case(the words come continuously), you may use a TreeMap to keep the order.
See ref: http://www.java-samples.com/showtutorial.php?tutorialid=370

A: To keep the information you need, you could create a class that holds your string and the count (e.g. Pair) and keep the instances of this class in a List<Pair>. This approach would make the increment of the count for a given string inefficient since you would have to look for the element that holds the string in linear time (O(N)) and then increment it.
A better approach is to use a Map<String, Integer>, that way the search is done in constant time (O(1)) and then you can sort the elements in the Set<Map.Entry<String, Integer>> returned by Map.entrySet().

A: *

*List item

I am starting with the URL below as reference and I will be building on that reference:
How can I count the occurrences of a list item in Python?
Now, the building starts:
>>> from collections import Counter
>>> word_list = ['blue', 'red', 'blue', 'yellow', 'blue', 'red','white','white']
>>> Counter(word_list)
Counter({'blue': 3, 'red': 2, 'white': 2, 'yellow': 1})

Note how Counter(word_list) displays the list of elements i.e. word/frequency pairs sorted in order of decreasing frequency for you. Unfortunately, extracting the words and compiling them in a list sorted in the same order takes a little more work:
(1) Get "size" as the number of elements in the JSON object.
(2) Apply the "most_common" method on the JSON object to get a sorted array of the elements by frequency.
(3) Apply a list comprehension to generate the list of the words extracted from the sorted array.
>>> size = len(Counter(word_list))
4
>>> word_frequency_pairs = Counter(word_list).most_common(size)
>>> word_frequency_pairs
[('blue', 3), ('white', 2), ('red', 2), ('yellow', 1)]
>>> [i[0] for i in word_frequency_pairs]
['blue', 'white', 'red', 'yellow']

There is a reason why I love Python :)


text:
Q: Why and When is a determinant of a larger matrix equal to a determinant of a smaller matrix? The following is written in the solution of my textbook.
$$|A|= \left| \begin{array} {cccc}
1 & 2& -1& 4 \\
0& 5& -1& 6 \\
0& -3& 3& -6 \\
0& 2& 2& -1\\
\end{array}
\right| = \left| \begin{array} {ccc}
5& -1& 6 \\
-3& 3& -6 \\
2& 2& -1\\
\end{array}
\right|$$
where $A=\left[ \begin{array} {cccc}
1 & 2& -1& 4 \\
0& 5& -1& 6 \\
0& -3& 3& -6 \\
0& 2& 2& -1\\
\end{array}
\right]$
I can see that we are ignoring column 1 and row 1 of $A$ to compute the determinant.
But I don't understand why this is a valid operation. Can someone please show me what are the properties of determinants/matrices that are being used to justify this?

A: The rule for a determinant is a recursive rule, namely the Laplace expansion. Thus, you can show that the determinant is equal to:
$$A_{11}\cdot|M_{11}|-A_{21}\cdot|M_{21}|+A_{31}\cdot|M_{31}|-A_{41}\cdot|M_{41}|$$
Where $|M_{ij}|$ is the determinant of the minor - the $(n–1) \times (n–1)$ matrix that results from deleting the i-th row and the j-th column of $A$.
Since $A_{21},A_{31},A_{41}$ are all zero, and $A_{11}=1$, the determinant of $A$ happens to be equal to the determinant of $M_{11}$.

A: I am going to try to sharpen your intuition a bit on this. The other answer is completely fine.
Hopefully you are familiar with the "signed sum of permutations" definition of the determinant known as the Leibniz Formula:
$$\det(A) = \sum_{\sigma \in S_n} \operatorname{sgn}(\sigma) \prod_{i = 1}^n a_{\sigma(i), i}$$
Where $\operatorname{sgn}(\sigma)$ is the sign of a permutation (+1 for even, -1 for odd) and $S_n$ is the permutation group on $n$ elements.
Think about what happens when you try to construct a permutation that doesn't include the 1 in the upper left hand corner. Try it a few times to convince yourself.
Any time you select a different column from that first row, it forces you to select a 0 from one of the other rows in order to complete the permutation. This means that these permutations will not affect the sum (multiplying by zero gives zero) and they can be safely ignored.


text:
Q: onCreateContextMenu Throws Error on API 15 & 16 only I'm having an issue with the onCreateContextMenu throwing a error only on API 15 & 16. It works perfectly fine on every other API from API 8 to API 17 (my min and max targets).
I did my best to try and solve this issue on my own by searching through Google, but after about a week I've became desperate enough to plead for help from the wonderful stack overflow community.
The onCreateContextMenu method
@Override
public void onCreateContextMenu(android.view.ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    Log.i(TAG, "Create context menu");

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu_my_time_zone, menu);

    Log.i(TAG, "Context menu created.");
}

The Containing Class
public class MyTimeZoneTActivity extends ListActivity {
    // I can post the code for the Class if required.
}

The Exception
02-14 09:38:20.828: E/AndroidRuntime(10912): FATAL EXCEPTION: main
02-14 09:38:20.828: E/AndroidRuntime(10912): java.lang.ClassCastException: com.creativitality.labs.timezoneswidget.MyTimeZonesActivity cannot be cast to android.app.Application
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.view.Window.getCompatInfo(Window.java:481)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.view.Window$LocalWindowManager.<init>(Window.java:491)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.view.Window.setWindowManager(Window.java:477)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.view.Window.setWindowManager(Window.java:460)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.app.Dialog.<init>(Dialog.java:163)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.app.AlertDialog.<init>(AlertDialog.java:114)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.app.AlertDialog$Builder.create(AlertDialog.java:913)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at com.android.internal.view.menu.MenuDialogHelper.show(MenuDialogHelper.java:79)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at com.android.internal.view.menu.ContextMenuBuilder.show(ContextMenuBuilder.java:88)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at com.android.internal.policy.impl.PhoneWindow$DecorView.showContextMenuForChild(PhoneWindow.java:2201)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.view.ViewGroup.showContextMenuForChild(ViewGroup.java:612)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.view.ViewGroup.showContextMenuForChild(ViewGroup.java:612)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.view.ViewGroup.showContextMenuForChild(ViewGroup.java:612)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.view.ViewGroup.showContextMenuForChild(ViewGroup.java:612)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.widget.AbsListView.performLongPress(AbsListView.java:2926)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.widget.AbsListView$CheckForLongPress.run(AbsListView.java:2871)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.os.Handler.handleCallback(Handler.java:615)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.os.Handler.dispatchMessage(Handler.java:92)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.os.Looper.loop(Looper.java:137)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at android.app.ActivityThread.main(ActivityThread.java:4745)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at java.lang.reflect.Method.invokeNative(Native Method)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at java.lang.reflect.Method.invoke(Method.java:511)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-14 09:38:20.828: E/AndroidRuntime(10912):    at dalvik.system.NativeStart.main(Native Method)

Anything else I can provide?
Let me know if there is any other information I can provide to help solve this issue.
Thank you all in advance!

Additional Code (as requested)
ListActivity
public class MyTimeZonesActivity extends ListActivity {

    // Define application context
    private Context applicationContext;

    //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
    List<TimeZoneData> timeZoneData = null;

    //DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
    ArrayAdapter<String> adapter;
    TimeZoneAdaptor timezoneAdaptor = null;

    public static final int INSTRUCTIONS_CODE = 0;
    private static final String TAG = "MyTimeZonesActivity";

    SharedPreferences sharedPref;
    SharedPreferencesHelper sharedPreferencesHelper;

    TimeZonesApplication timeZonesApplication;

    public Context getApplicationContext(){
        return applicationContext;
    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        Log.i(TAG, "My Time Zone Activity - onCreate called.");
        super.onCreate(savedInstanceState);

        // Get Application Globals
        timeZonesApplication = (TimeZonesApplication)getApplicationContext();

        // Set application context
        applicationContext = this;

        // Populate time zone data
        timeZoneData = new ArrayList<TimeZoneData>();
        getStoredTimeZonesData(); // Populates timeZoneData object with stored time zone data

        setContentView(R.layout.activity_my_time_zones);
        timezoneAdaptor = new TimeZoneAdaptor(this, R.layout.timezone_view_mine, timeZoneData);
        setListAdapter(timezoneAdaptor);

        registerForContextMenu(getListView());

    }

ArrayAdapter
public class TimeZoneAdaptor extends ArrayAdapter<TimeZoneData> {
    private String TAG = "TimeZoneAdaptor";
    //private ArrayList<TimeZoneData> mOrigionalValues;
    private List<TimeZoneData> mObjects;

    public TimeZoneAdaptor(Context context, int textViewResourceId, List<TimeZoneData> objects) {
        super(context, textViewResourceId, objects);
        this.mObjects = objects;
        //this.mOrigionalValues = new ArrayList<TimeZoneData>(objects);
    }

    @Override
    public int getCount() {
        return ((null != mObjects) ? mObjects.size() : 0);
    }

    @Override
    public TimeZoneData getItem(int position) {
        return ((null != mObjects) ? mObjects.get(position) : null);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

    public void add(TimeZoneData timeZone)
    {
        Log.w(TAG, "Add time zone: " + timeZone.id);
        mObjects.add(timeZone);
        notifyDataSetChanged();
    }

    public void remove(int position){
        Log.i(TAG, "Remove object from adapter at position: " + position);
        mObjects.remove(position);
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;

        if (null == view) {
            LayoutInflater vi = (LayoutInflater) MyTimeZonesActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = vi.inflate(R.layout.timezone_view_mine, null);
        }

        TimeZoneData data = mObjects.get(position);

        if (null != data) {
            TextView textCountry = (TextView) view.findViewById(R.id.timezone_country);
            TextView textName = (TextView) view.findViewById(R.id.timezone_name);
            TextView textTime = (TextView) view.findViewById(R.id.timezone_time);

            textCountry.setText(data.country.toUpperCase(Locale.getDefault()));
            textName.setText(data.city);
            textTime.setText(data.time);

            //view.setOnClickListener(new OnItemClickListener(position)); // NOT REQUIRED as we are setting in on activity level
        }

        return view;
    }
    }

A: My best guess is that you are somehow creating a widget using an Application instead of an Activity, such as by blindly using getApplicationContext() someplace. When Android goes to show the context menu, it tries to get the activity associated with the widget, runs into an Application instead, and crashes.

A: I fixed the problem.
The issue was because I overwrote an existing API method getApplicationContext() without being aware of it.
The method in question that was causing all my headaches was this:
public Context getApplicationContext(){
    return applicationContext;
}

I found this bit of code while I was searching up better ways of passing context to my methods. It turns out you shouldn't use any code until you full understand it!
Hope that someone else finds this answer useful in the future!


text:
Q: Why does Datomic yield the same temporary ID twice in a row when iterating? This will produce two different ids, which is great:
#db/id[:db.part/user]
#db/id[:db.part/user]

but anything like the following (I tried a lot of ideas so far) will produce the same id twice, which is not what I want:
(repeatedly 2 (fn [] #db/id[:db.part/user]))
(for [n [1 2]] #db/id[:db.part/user])

All yield something like
(#db/id[:db.part/user -1000774] #db/id[:db.part/user -1000774])

where the number produced is the same for each call.
What I actually want is for the calls to NOT produce a number at all, so that I can just add the produced data via a transaction.
Any ideas?
Just to be clear, the documentation says, "Each call to tempid produces a unique temporary id."
[Edited after comment by @maxthoursie that repeat would be having this problem in any case.]

A: Use
(require '[datomic.api :as d])
(repeatedly 2 #(d/tempid :db.part/user))
;; => (#db/id[:db.part/user -1000118] #db/id[:db.part/user -1000119])

Consider that #... are reader macros meaning that their value will be resolved when the expression is read which naturally happens only once. Use the #... macro only when you are writing literal transaction data (like a schema). Use datomic.api/tempid to generate tempids in runtime.

A: Because repeat is repeating the value it got from calling id once.
Use repeatedly instead.
See examples at http://clojuredocs.org/clojure_core/clojure.core/repeatedly


text:
Q: Proof verification: A group $G$ of order $p^n$ ($p$ prime) is cyclic iff it is an abelian group having a unique subgroup of order $p$. The theorems are from Rotman's book An Introduction to the Theory of Groups.

Theorem 2.19 Let $p$ be a prime. A group $G$ of order $p^n$ is cyclic if and only if it is an abelian group having a unique subgroup of order $p$.

Here is my attempt at the proof (of the "if" part):
We have already shown that

Theorem 2.17 A group $G$ of order $n$ is cyclic if and only if, for each divisor $d$ of
  $n$, there is at most one cyclic subgroup of $G$ having order $d$.

By Lagrange's theorem, if $H\leq G$, then $|H|=p^t$ for some $0\leq t\leq n$. It suffices to prove that for each $0\leq t\leq n$, there is at most one cyclic subgroup of $G$ of order $p^t$. We use induction on $t$. For $t=0$, the subgroup is trivial. For $t=1$, the uniqueness follows from the hypothesis of the theorem. Suppose $\langle a\rangle$ and $\langle b\rangle$ are two cyclic subgroups of $G$ of order $p^t$, where $2\leq t\leq n$. We see that $\langle a^{p^{t-1}}\rangle$ and $\langle b^{p^{t-1}}\rangle$ are two subgroups of order $p$, thus $\langle a^{p^{t-1}}\rangle=\langle b^{p^{t-1}}\rangle$. In particular, $b^{p^{t-1}}=a^{kp^{t-1}}$ for some $k\in\mathbb{Z}$. Since $G$ is abelian, we have $1=b^{p^{t-1}}a^{-kp^{t-1}}=(ba^{-k})^{p^{t-1}}$. Set $|ba^{-k}|=p^s$, then $0\leq s\leq t-1$. Observe that $\langle a^{p^{t-s}}\rangle$ is a subgroup of order $p^s$, and by induction hypothesis this is the unique subgroup of $G$ of this order, thus $\langle ba^{-k}\rangle=\langle a^{p^{t-s}}\rangle$ and $ba^{-k}=a^{\ell p^{t-s}}$ for some $\ell\in\mathbb{Z}$. From this it follows that $b=a^{k+\ell p^{t-s}}\in\langle a\rangle$, hence $\langle b\rangle\subseteq\langle a\rangle$. The reverse inclusion follows by symmetry, therefore $\langle b\rangle=\langle a\rangle$ and the theorem is proved.
My proof is completely different from the one in the book. Is my proof correct?


text:
Q: Tomcat app http to https redirect displays ROOT in URL Context path is set to ROOT in tomcat app because I want to access the URL without any path ex: https://URL/. AWS Loadbalancer just redirects to the app servers. It works if I directly access https site. But if I access http site, the http to https redirect takes to https://URL/ROOT and displays "page not found", then I'd to remove the ROOT to access the page. If any path is set in the context i.e https://URL/PATH/, the redirection works good but only if ROOT, http redirection is having this issue. I guess context.xml, web.xml, server.xml looks good to me. Obviously needs some tweak. Any help is appreciated please.

A: http listener rules had ROOT instead of default {path} hence why redirection happened. Right now it is fixed and I don't see ROOT in the http URL redirecting to https.


text:
Q: Power counting with a cutoff In Effective Field Theory video lectures found here, the professor explained power counting in effective field theories and the difficulties of power counting associated with loop diagrams. He then mentions that introducing a cutoff ($\Lambda_{UV}$) to regulate our divergences does not preserve power counting due to the new scale that we are introducing. To see this he uses four-fermi theory with the diagram,
$\hspace{6cm}$
We do our power counting (i.e., Taylor expansions) in powers of $m^2/M^2$ and then go on to consider the mass correction through,
$\hspace{6cm}$
Using a cutoff this gives a mass correction,
\begin{align}
a\frac{ m }{ M ^2 } \int _0^{\Lambda_{UV}}\frac{ \,d^4k _E }{ (2\pi)^4} \frac{1}{ k  _E ^2 + m ^2 } & = a\frac{  m }{ ( 4 \pi ) ^2 } \left[ \frac{ \Lambda _{ UV } ^2 }{ M ^2 } + \frac{ m ^2 }{ M ^2 } \log \frac{ m ^2 }{ \Lambda _{ UV } ^2 } - \frac{ m ^4 }{ M ^2 \Lambda _{ UV } ^2 } + ... \right]
\end{align}
If I understand correctly this breaks the power counting because even if $\Lambda_{UV} \sim M$, the first term is an order 1 correction since its not proportional to $m^2/M^2$. So far so good. However, then the professor says that you can still use power counting with a cutoff if you fix the power counting order by order and that this can be done by introducing an intermediate scale, $\Lambda$. But I don't how this fixes anything...
With an intermediate scale ($\Lambda$) we have,
\begin{equation}
a\frac{m}{M^2}\int _{ \Lambda } ^{ \Lambda _{ UV }} \frac{ \,d^4k _E }{ (2\pi)^4 } \frac{1}{ k _E ^2 + m ^2 } = \frac{a\,m}{ (4\pi)^2M^2 } \left\{ \left(\Lambda ^2 + m ^2 \log \frac{ m ^2 }{ \Lambda ^2 + m ^2 } + ... \right) + \left( \Lambda _{ UV } ^2 - \Lambda + m ^2 \log \frac{ \Lambda ^2 + m ^2 }{ \Lambda ^2 _{ UV }} \right) \right\}
\end{equation}
but how does this fix anything?
For more context see my lecture notes here under Effective Field Theory (starts around equation 4.6)

A: Before introducing any additional scales, assuming that the only relevant scale is given by $m^2$, power counting gives us the following relation for the integral in question:
$$\Delta m\sim\frac{am}{M^2}\int \frac{d^4k_E}{k_E^2+m^2}\sim \frac{am^3}{M^2},$$
which is a small mass correction.
Next, we see what happens when we introduce a regulator in the form of a UV-cutoff. In this case, the evaluated integral contains a term of the form
$$am\frac{\Lambda_{UV}^2}{M^2},$$
which is not a small correction as in the case without the regulator. Therefore, power counting fails as soon as we introduce a UV-cutoff.
Introducing an additonal scale $\Lambda$, which we assume to be small, solves this problem. Within the renormalization procedure we can absorb the $\Lambda_{UV}$-dependent terms into counterterms $\delta m(\Lambda,\Lambda_{UV})$ while still having some other terms left, i.e. something proportional to
$$am\frac{\Lambda^2}{M^2},$$
which is again a small correction. We have therefore "restored" the validity of power counting.


text: Q: Can you call an event defined in the parent window from a modal window? If I declare an event handler in a separate project, subscribe to it in the parent window constructor (after the InitializeComponent call), can I trigger the event from a modal child window?  These are WPF windows.