text:
Q: Cannot return axios promise with mongoose I've been hitting StackOverflow for the last 2 hours and I simply cannot figure out how I'm supposed to retrieve data from an API, store it in Mongo, and then transfer it to my view with express. I feel like I must have made some mistakes in how I'm manipulating the data. I'm relatively new to these concepts and I'd really appreciate some guidance about what the best practices are. I can currently store the information to my DB, but when I try to pass it back up to my route, the axios promise returns undefined. Api keys have been stripped out for this post.
Can someone please lend a helping hand?
//pull in express
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const mongoose = require('mongoose')

//Connect to mongoDB
mongoose.connect('mongodb://test:test@ds239965.mlab.com:39965/companies');
const db = mongoose.connection;

//Create Schema for the application to interact with MongoDB
const companySchema = mongoose.Schema({
    domain:{
        type: String
    },
    email:{
        type: [String]
    },
    confidence: {
        type: [Number]
    },
    create_date:{
        type: Date,
        default: Date.now
    }
}, {collection: 'companies'});

const Company = mongoose.model('Company', companySchema);

//bodyparser middleware for reading form submission
var urlencodedParser = bodyParser.urlencoded({ extended: false });

//declare router as variable for index view
const index   = express.Router();

const hunterKey = '&api_key=8bd4aaded349a5d9784d021c2767e5d23e66140f';
const hunterUrl = `https://api.hunter.io/v2/domain-search?domain=`;

const fullContactKey = `&apiKey=f71cc6c7ccaa28f1`
const fullContactUrl = 'https://api.fullcontact.com/v2/company/lookup?domain=';

function outputHunter(response, res) {
    let comp = response;
    let em = [];
    let c = [];

        for (var i = 0; i < comp.emails.length; i++) {
            //email arrays
            // console.log(comp.emails[i].value);
            em[i] = comp.emails[i].value;
            c[i] = comp.emails[i].confidence;
        }

    var data = new Company({
        domain: comp.domain,
        email: em,
        confidence: c
    });

    //console.log(data);

    var CompanyData = Company(data).save((err, data) => {
        if (err) throw err;
    });

    return data;
}

function searchHunter(searchVal, res) {
    var CompanyData;
    axios.get(hunterUrl + searchVal + hunterKey)
    .then(function (response) {
        response = outputHunter(response.data.data, res);
        CompanyData = response;
    })
    .catch(function (error) {
        console.error(error); throw error;
    });
}

//use declare router for http methods
//get request for index with request, response, next params
index.get('/', function (req, res) {
    //render response  from server using index view from declared path in app.js
    res.render('home', {
        title: "Networkerr home",
        body:
            {
                description: 'The Place to Network',
            }
    });
});

index.get('/:id', (req, res, next) => {
    CompanyData.find()
    .then(function(doc) {
      res.render('company', {company: doc});
    });
});

index.post('/submit', urlencodedParser, (req, res, next) => {
    // console.log(req.body);
    let data = searchHunter(req.body.domain, res);
    console.log('fired')
    console.log(data)
    res.redirect('/' + data._id, {company: data});
});

module.exports = index;

A: Some quick fixes:
I guess that in index.get('/:id',... you dont need the next parameter as well as in index.post('/submit',... since they are routes, not middlewares.
In the index.get('/:id',..., you need to a) fetch the right route parameter and call the right mongoose method (findById)
index.get('/:id', (req, res) => {
  CompanyData.findById(req.params.id) // <== Specify your id here
  .then((doc) => {
    ..
  });
});

the submit:
Saving the doc in the DB is an asynchronous task (fetch the data from hunter, and save it into the DB)
index.post('/submit', urlencodedParser, (req, res, next) => {
  // console.log(req.body);
  searchHunter(req.body.domain)
  .then(data => {
    // here the Promise is resolved and the doc has been fetched and saved
    console.log('doc fetched and saved');
    console.log(data)
    res.redirect('/' + data._id, {company: data});
  });
  console.log('fired but not fetched and saved');
});

Other modifications will imply that searchHuntermust return a Promise
function searchHunter(searchVal) {
  var CompanyData;
  // return the Promise, so we can know when it has finished
  return axios.get(hunterUrl + searchVal + hunterKey)
  .then(function (response) {
    return outputHunter(response.data.data);
  })
  .catch(function (error) {
    console.error(error); throw error;
  });
}

As well as outputHunter:
function outputHunter(response, res) {
  let comp = response;
  let em = [];
  let c = [];

  for (var i = 0; i < comp.emails.length; i++) {
    //email arrays
    // console.log(comp.emails[i].value);
    em[i] = comp.emails[i].value;
    c[i] = comp.emails[i].confidence;
  }

  var company = new Company({
    domain: comp.domain,
    email: em,
    confidence: c
  });

  // return the Promise so we can know when the company has been saved
  return company.save((err, data) => {
    if (err) throw err;
    return data;
  });

  // shorter, if you dont want to modify data or handle err here
  // return company.save();
}


text:
Q: i have question about asynchronous programming at flutter void main() async {
  check();
  print('end');
}

Future check() async {
  var version = lookUpVersion();
  print(version);
}

int lookUpVersion() {
  return 12;
}

void main() async {
  check();
  print('end');
}

Future check() async {
  var verion = await lookUpVersion();

  print(version);
}

int lookUpVersion() {
  return 12;
}

These two code only have one difference, await keyword.
I wonder that why not did they wait for main function code? even I used Future+async keyword at first code.
Can you explain about this?

A: The async and await keywords provide a declarative way to define asynchronous functions and use their results.
For first one - result will be
//12
//end

For second one - result will be
//end
//12

Which means if you add await it will become asynchronous.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are examples of comments that tell you WHY instead of HOW or WHAT? First of all, in this question I'd like to stay away from the polemic on whether source code commenting is good or bad. I'm just trying to understand more clearly what people mean when they talk about comments that tell you WHY, WHAT or HOW.
We often see guidelines like "Comments should tell you WHY; code itself should tell you HOW". It is easy to agree with the statement on an abstract level. However, people usually drop this like a dogma, and leave the room without further explanation. I've seen this used in so many different places and contexts, that it looks like people can agree on the catchphrase, but they seem to be talking about different things entirely.
So, back to the question: if comments should tell you WHY, what is this WHY we are talking about? Is this the reason why that piece of code exists in the first place? Is this what that piece code should be doing? I would really appreciate if someone could give a clear explanation, and then add some good examples (bad examples are not really needed, but fell free to add them for contrast).
Please do not immediately close this question as duplicate or polemic. I have tried hard to make it very objective. There are many questions on whether comments are good or bad, but no one that addresses the specific question of what are good examples of comments that tell you WHY.
Thanks,

A: Comments serve two main purposes:

*

*to summarise. Many would say "why document this method when we can just read the code?", but one line of text that describes what a method is for/what it does, can often be much faster to read and easier to understand than 30 lines of code, especially if that code calls other methods that you may need to read as well...

*to explain the things that are not obvious from the code - the WHY, or more detail on the how. Simple examples include "we must add the new XmlElement and then remove the old one, as the ReplaceChild method in .net does not work!", or "Uses an iterative Newton-Raphson approach to solve for X ", or "we must not close the port here because the reading thread may still be running", or "use this method where performance is critical, but beware that this method may provide a result that is in error by up to 5%"


text:
Q: Create Filter condition inside data-bind: foreach Is it possible to create a filter inside the foreach. My goal here is to display the specific data from my ko.obervableArray. On the sample i created on JS Fiddle my goal is to display only the type="family".
https://jsfiddle.net/zo8ygfk4/111/

name	address	Type

var people = [
    { name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "family" },
        { name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "family" },
            { name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "family" },
    { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "friend", Type: "1" },
     { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "friend", Type: "1" },
      { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "friend", Type: "1" },
       { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "friend", Type: "1" },
];

var quotesarray = function(){
var self=this;
    self.items = ko.observableArray();

      window.setInterval(function(){
      self.items.removeAll();
        ko.utils.arrayPushAll(self.items, people)
    },1000);

};

ko.applyBindings(new quotesarray()
)

A: You have a typo in your HTML code: "ko: type === 'family'" must be replaced with "ko if: type === 'family'"

var people = [
  { name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "family" },
  { name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "family" },
  { name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "family" },
  { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "friend", Type: "1" },
  { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "friend", Type: "1" },
  { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "friend", Type: "1" },
  { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "friend", Type: "1" },
];

var quotesarray = function(){
var self=this;
    self.items = ko.observableArray();

      window.setInterval(function(){
      self.items.removeAll();
        ko.utils.arrayPushAll(self.items, people)
    },1000);

};

ko.applyBindings(new quotesarray()
)

name	address	Type

A: Do not use the containerless if syntax for this little thingy, it might get the job done but you really do not need to do it, it has much poorer performance than other solutions AND its gets your dom dirty.
You can try using a computed, that will evaluate itself when the original array changes and it will return only the family items from that array each time
You may try the following:
self.familyItems = ko.pureComputed(function(){
    return self.items().filter(function(i){ return i.type === 'family'})
});

then bind your foreach against the familyItems instead of the items


text:
Q: How can I handle dynamic calculated attributes in a model in Django? In Django I calculate the breadcrumb (a list of fathers) for an geographical object. Since it is not going to change very often, I am thinking of pre calculating it once the object is saved or initialized.
1.) What would be better? Which solution would have a better performance? To calculate it at ____init____ or to calculate it when the object is saved (the object takes about 500-2000 characters in the DB)?
2.) I tried to overwrite the ____init____ or save() methods but I don't know how to use attributes of the just saved object. Accessing *args, **kwargs did not work. How can I access them? Do I have to save, access the father and then save again?
3.) If I decide to save the breadcrumb. Whats the best way to do it? I used http://www.djangosnippets.org/snippets/1694/ and have crumb = PickledObjectField().
The model:
class GeoObject(models.Model):
    name = models.CharField('Name',max_length=30)
    father = models.ForeignKey('self', related_name = 'geo_objects')
    crumb = PickledObjectField()
    # more attributes...

Thats the method to calculate the attribute crumb()
def _breadcrumb(self):
    breadcrumb = [ ]
    x = self
    while True:
        x = x.father
        try:
            if hasattr(x, 'country'):
                breadcrumb.append(x.country)
            elif hasattr(x, 'region'):
                breadcrumb.append(x.region)
            elif hasattr(x, 'city'):
                breadcrumb.append(x.city)
            else:
                break
        except:
            break
    breadcrumb.reverse()
    return breadcrumb

Thats my save-Method:
def save(self,*args, **kwargs):
    # how can I access the father ob the object?
    father = self.father # does obviously not work
    father = kwargs['father'] # does not work either

    # the breadcrumb gets calculated here
    self.crumb = self._breadcrumb(father)
    super(GeoObject, self).save(*args,**kwargs)

Please help me out. I am working on this for days now. Thank you.

A: By calling both the _breadcrumb method with x.father and assigning x = x.father in the beginning of the while loop you jump over one father. Try exchanging
self.crumb = self._breadcrumb(father)

with
self.crumb = self._breadcrumb(self)

By defining _breadcrumb within the model class you can clean it up like this:
class GeoObject(models.Model):
    name = models.CharField('Name',max_length=30)
    father = models.ForeignKey('self', related_name = 'geo_objects')
    crumb = PickledObjectField()
    # more attributes...

    def _breadcrumb(self):
        ...
        return breadcrumb

    def save(self,*args, **kwargs):
        self.crumb = self._breadcrumb()
        super(GeoObject, self).save(*args,**kwargs)

For more complex hierachies I recomend django-treebeard


text:
Q: EXTJS Tab Panel Not Rending Tabs I have a new application that was created used the Sencha App create. When I am trying to add a tabpanel. It allows me to add the panel but the tabs are not being displayed as cards. They are being displayed as label's only. I can click on each label and it displays the data in the tabs but I need to have them look like tabs.
Here is the code I am using to create the panel.
{xtype: 'panel', itemId:'tpTest', region: 'west', width: 250,title: "insert form goes here",collapsible:true, items:
[
    { xtype: 'tabpanel', layout:'card', activeTab: 0, items:
        [
            { title:'Tab1', html:'Test'},
            { title:'Tab2', html:'Test 1'}
        ]
    }
]}

Here is the screen capture of what I am seeing:

I also get a strange warning stating the following:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
bootstrap,js:
xhr.open('GET', url, false);

A: It looks like your suffering from overnesting, so a tabpanel contained within another panel.
Instead try this:
{

    xtype: 'tabpanel',
    itemId:'tpTest',
    region: 'west',
    width: 250,
    activeTab: 0,
    title: 'insert form goes here',
    collapsible: true,
    items:[
        { title:'Tab1', html:'Test'},
        { title:'Tab2', html:'Test 1'}
    ]
}

So remove the parent panel item . You also dont need to specify card layout as it already uses this by default for a tab panel.

A: I was able to fix the issue by doing a sencha app refresh. Thanks everyone


text:
Q: Angular2 Dependency Injection: What's the "..." syntax I see before some injected package's name (ie 'providers = [...SomeProvider]') I'm just getting started in Angular2 and normally injecting providers looks like:
providers : [SomeProvider],

However I have been seeing some packages that include a "..." before the provider name that is being injected like:
providers : [...SomeProvider],

Why is this being done? What is the ... and what is it doing?

A: That is the spread operator. The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables  (for destructuring assignment) are expected.
You might be thinking why we need this?
A better apply
Example: it is common to use Function.prototype.apply in cases where you want to use an array as arguments to a function.
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction.apply(null, args);

With ES6 spread you can now write the above as:
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);

Any argument in the argument list can use the spread syntax and it can be used multiple times.
function myFunction(v, w, x, y, z) { }
var args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);

More information and examples can be found on it here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator


text:
Q: Exchange 2003->2010, does legacy.example.com need a public IP? I've been reading through plenty of documentation on migrating from exchange 2003 to 2010.
It doesn't seem to be overly complicated, but one part I haven't been able to wrap my brain around is how clients access the old 2003 server while we are still operating with some people on 2010 and some on 2003.
I currently have a simple setup - a single 2003 server which has all the roles on it.  It's behind NAT with ports forwarded to it for SMTP and HTTPS.  Clients access it through webmail and outlook anywhere over HTTPS to mail.example.com.
If I understand correctly, when I deploy exchange 2010, mail.example.com should point to the 2010 server (so I change the NAT port forwarding to point to the new server).  But people still on the 2003 server need to be able to access legacy.example.com.
Does legacy.example.com need a seperate public IP address with ports forwarded to the 2003 server?
We also never configured autodiscovery with 2003.  Will clients using outlook through outlook anywhere need to be reconfigured to still connect to the 2003 server?

A: First off all, before I get into, might I suggest a cut-over migration?  They're a lot easier, a lot less work, and make sense when you only have one mail server.  Downside is that there will be an email outage of however long it takes to get the data (mail) over from one server to the other (and then decommission the old server, and assign the new one to the old one's ip and hostname).  You can generally make this outage last a few minutes at most, with the right tools, if you migrate the bulk of the email over before the cutover date, and do a diff on the data, so you're only effectively migrating a day or so worth of data, instead of all of it.
Having said that... no, you wouldn't need a public IP for your new server, because you'd set up the current/old server to forward mail to it instead.  (See below.)
Typically, in co-existence migrations, you set up one mail server to forward mail to the other (if you only have 2).  The easiest way to do this would be to set up [fake] subdomains, assign one to one mail server, the other to the other mail server and configure a smarthost to handle mail routing from one to the other.  You'd leave your Exchange 2003 server as it is, and not set up a public IP or NAT for the 2010 server.
So, let's use oldmail.company.com and newmail.company.com as subdomains (to keep things simple for the example, you probably don't want to use those actual names).  The oldmail subdomain would be "assigned" to the Exchange 2003 server (internally, through the Exchange System Manager, not through DNS)  and added into the list of mail domains on which that server is authoritative, and the newmail subdomain would be added to the list of domains on which the 2010 server is authoritative.  You would then configure the smart host settings on both servers to check the other mail server if a recipient isn't found locally, and set up send and receive connectors to handle mail forwarding from one server to the other.  (So that your Exchange 2003 server will forward any mail for [recipient]@newmail.company.com to the 2010 server and the 2010 server will forward any mail for [recipient]@noldail.company.com to the 2003 server.)
In this way, users on both mail servers can send to each other internally (each mail server checks the other to see if a recipient is valid before rejecting an email), and external users can too.  Mail would arrive at the 2003 server as before, and if the recipient isn't found, it would check with the 2010 server to see if your recipient is over there.  Once everyone's over onto the Exchange 2010 server, you'd schedule a time to shut off the Exchange 2003 server, put the 2010 into its place, and remove the smarthost and mail routing rules.  This, of course, assumes that you correctly setup the 2010 mail server, and it's set up to receive mail for external, as well as having company.com as one of its mail domains.
The three main drawbacks of this are:
You have to handle the users manually - each user can only have one account, so you need to remove them from the old server once you've migrated them to the new one.
You have to handle user mail client settings - when they migrate over to the new server, they have to point their clients at it, and then point them back at the original location once you cut over.  (Also, calendaring and your other "not mail" features of the mail clients tend to be a pain to get quite right during the co-existence).
Emails sent from one server or the other will show as [sender]@[subdomain].company.com instead of [sender]@company.com unless you jump through hoops to change that.  When the co-existence is done and one or both subdomains are removed from your mail server, that will cause replies to those old emails to bounce, and probably more help desk calls than you'd like from technically illiterate users and clients.


text:
Q: ext4 jbd2 and I/O priority I want to delete a huge directory with over 6 million files across over 4000 directories, totaling about 26GB of data.  As I knew this was going to take a while I used ionice to set the I/O priority to idle, so I can continue doing other tasks while the files are deleted.
time ionice -c3 rm -vrf /tmp/huge-folder

However my entire desktop environment is now very sluggish nonetheless, Google chrome takes ages to open new tabs and load pages, sometimes it even takes a while to open a new xterm window.  In summary: I appear to get none of the benefits of reduced I/O priority on the rm process.
Inspecting the situation with iotop shows that some of the I/O time is spent in the rm process with the idle I/O priority that I want:

But then some other times the I/O time is spent in ext4's journaling process and the software raid process:

Note how they are using their own default I/O priority, which is probably the cause of the problem.  jbd2 even runs at priority be/3 which is in fact higher priority than the default be/4 of all my other desktop processes.
Many other questions ask and answer what jbd2 is and why it's consuming I/O time, that's not what I'm wondering about.  My question is: Is there a way to truly get the idle I/O scheduling priority in this specific scenario?  Obviously, applying ionice to jbd2 is a crazy idea.
Further setup info: This is on a ext4 filesystem on top of a software raid10 with 3 rotating disks.  ext4 is formatted and mounted using default options (Debian defaults, in case those differ).

A: Since I asked this I learned a lot more about how I/O works in the linux kernel and I came do the conclusion that ionice just does not work with most write operations.
Read operations are mostly synchronous and can very easily be prioritized.  Presumably this is a lot harder for write operations which are often delayed to a later time (thus asynchronous) in order to be optimized, aggregated and whatnot. I can imagine that transporting and correctly aggregating the niceness information along that way is not easy.
Source: Some notes on Linux's ionice.  Note that this source also mentions that ionice just does not work with LVM or software RAID, but I have some doubts whether that is still strue (the blog post is a bit dated).
Also see: ionice does not have any effect on un-synced writes (i.e. normal writes)?


text:
Q: C++, select function by template parameter My question is how to call one of process function by runtime-known id without using map?
#include <iostream>
#include <map>

enum id
{
    id_1,
    id_2,
    id_3
};

template <id id_>
void process();

template<>
void process<id_1>()
{
    std::cout << "1" << std::endl;
}

template<>
void process<id_2>()
{
    std::cout << "2" << std::endl;
}

template<>
void process<id_3>()
{
    std::cout << "3" << std::endl;
}

std::map<id, void(*)()> mapping =
{
    {id_1, process<id_1>},
    {id_2, process<id_2>},
    {id_3, process<id_3>}
};

int main()
{

    for (int i = 0; i < 10; ++i)
    {
        mapping[static_cast<id>(rand()%3)]();
    }

    return 0;
}

A: map is an elegant solution.
If you don't want to use map, you have to 'map' the function calls yourself.

switch-case

void mapped_process(id id_) {
    switch (id_) {
    case id_1:
        process<id_1>();
        break;
    case id_2:
        process<id_2>();
        break;
    case id_3:
        process<id_3>();
        break;
    default:
        break;
    }
}

mapped_process(static_cast<id>(rand()%3);

map by index

Just as one of the comment mentioned, you can use array or vector to replace map with some constraint: the enums have unique values.
std::array<void(*)(), 3> procs = {process<id_1>, process<id_2>, process<id_3>};

procs[rand() % 3]();


text:
Q: EF 4.0 and stored procedures: return business objects or complex types? I'm new to EF4 and I'd like to know what the best approach when using EF with stored procedures as part of the DAL. So far I have these two options:
Option 1
Using EF4, I can create a complex type that the EF will map my results from stored procedures. I can then return this complex type from the DAL layer and then convert it again into custom BLL object in the main application layer. This strategy is appealing to me since I would rely on EF4 designer to build the plumbing without me building parameters by hand. It also makes DAL stand alone without referencing the assembly that contains the business objects. The major issue that I see with this approach is the fact I have to sort of hydrate DAL complex type to BLL business object again. Not sure how it would affect the performance.
Option 2
Have DAL reference assembly that contains BLL object and then return BLL objects from DAL layer. I'm not really sure if this is the right approach for me. I would have to manually create stored procedure parameters and then iterate of DataReader to build business objects to return. It's doable, but I would rather let EF4 designer build me stored procedure plumbing. Also, it would seem to couple DAL with BLL assembly, which I'm not sure is appropriate.
Would appreciate some comments on this and suggestions.
Thanks!

A: There is a third option - make your business objects entities. EF is tool to persist and retrieve business objects from the database but you make it just data access layer with need to manually convert its results to business objects. That is whole source of your problems.


text:
Q: Flexbox, scrolling elements I have a flexbox horizontally aligned with 62 items in it. I would like
the items to scroll to the left and when complete loop back to the start.
I started trying a lot of things, but since I am new to flexbox I dont think I have a firm enough understanding of its interactions with other content to yet even attempt a solution that may work.

function GetAcceptances(value) {
  var acceptances = value;
  $("#tempAcceptanceLoader").remove();
  for (var x = 0; x < acceptances.length; x++) {
    //console.log(acceptances[x].Name);
    $("#recentAcceptances").append(`<div class="slidingText">${acceptances[x].Name}</div>`);
  }
};
#recentAcceptances {
  width: 60%;
  background-color: white;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  overflow: hidden;
}

.slidingText {
  flex: 1;
  padding: 0px 5px 0px 5px;
  white-space: nowrap;
  color: black;
  font-size: 18px;
  font-family: 'Oxygen', sans-serif;
  animation: example1 20s infinite linear;
}

@keyframes example1 {
  0% {
    padding-left: 0px;
  }
  100% {
    padding-left: -1000px;
  }
}

Currently loading the list of acceptances...

A: Calculation of actual padding can be different from the specified padding value, especially with flex layouts. Try using transform with translateX instead; that applies the transform after the elements' layout is done:
@keyframes example1 {
  0% {
    transform: translateX(0px);
  }
  100% {
    transform: translateX(-1000px)
  }
}


text:
Q: Analog of subset for lists I'd like to subset a list of sublists, based on the contents of one of the sublist elements, in a manner similar to the way subset works on data frames:
sublist1 <- list(data=rnorm(10), name="name1", keepMe=2)
sublist2 <- list(data=rnorm(10), name="name2", keepMe=2)
sublist3 <- list(data=rnorm(10), name="name3", keepMe=3)
myList <- list(s1=sublist1, s2=sublist2, s3=sublist3)

I'd like to do something like keepers <- subset[myList, keepMe==2] which would return a list of length 2.
The following is almost what I want:
require(plyr)
selector <- function(x) {
  if (x$keepMe==2) {return(x)}
  else {return(NULL)}
}
keepers <- llply(myList, selector)

except that in that case the undesirable list elements don't get thrown out, they just get replaced with NULL.
Note that in all cases the sublists will have the same components, only the values of the components change.

A: This will give you the two lists with TRUE in the keepMe position:
myList[ unlist( sapply(myList, "[", "keepMe") ) ]

@ttmaccer solution omitting the i=
myList[ sapply(myList, "[[", "keepMe")  ]

(Which succeeds because sapply will try to deliver a vector or matrix if it can, but "[" returns a list, while "[[" returns an atomic logical.)

A: This works but I don't know if there is a more direct way:
keepers = myList[-(which(sapply(1:length(myList),
                                function(x) myList[[x]]$keepMe == FALSE)))]

Here's the str() of the resulting list:
str(keepers)
# List of 2
# $ s1:List of 3
#  ..$ data  : num [1:10] -0.82 0.487 0.738 0.576 -0.305 ...
#  ..$ name  : chr "name1"
#  ..$ keepMe: logi TRUE
# $ s2:List of 3
#  ..$ data  : num [1:10] -0.0449 -0.0162 0.9438 0.8212 0.5939 ...
#  ..$ name  : chr "name2"
#  ..$ keepMe: logi TRUE


text:
Q: PHP code formatter with Drupal coding style We do our Drupal programming mostly with simple text editors like Vim. Now, after several years of development and many different people working on the project, the coding conventions have diverged a bit :-)
Drupal itself has a clear code style and a script exists to identify violations of the coding conventions. However, fixing everything by hand is too much effort and could possibly introduce errors.
I wonder if there is any customizable non-commercial PHP code formatter, which can process all PHP files of a project in a batch run. I only found a closed solution, which doesn't seem to be customizable.

A: As for Drupal, we have Coder module.

A: You can try our PHP Formatter.
It is scriptable, and using a project file, it can
be run on as large a batch of PHP files as one desires.
Because it uses a language accurate parser and prettyprinter, it will not break your code when reformatting.
I don't know if has a "Drupal" style, but it has some configurability.
(This seemed pretty easy to find with Google using "PHP Formatter").


text:
Q: Is "pushing at an open door" a common expression in English? I'm not sure if the expression "pushing at an open door" is used and understood by a native English speaker.

A: Vivid idiom meaning that an action/initiative/task can be achieved easily because there is minimal resistance.
Apparently it's usage is on the up in both British and American English.


text:
Q: "Message: Expected ')' " but that doesn't seem right i have this code :
function createTable(tabletop, tableside, gridbutton, tabletype){
var spinner = createSpinner();
var table = '

   	';

for(var j = 0; j < tabletop.length; j++){
table +='' + tabletop[j]+ '	'; // creates tableheader horizontally
}
table+='
';

for(var i = 0; i < tableside.length; i++) {
table+='
' + tableside[i]  + '	' ; // creates table header vertically
for(var j = 0; j < tabletop.length; j++){    // inserts tablecell
table +='';

function createButtons(tabletop[j], tableside[i], tabletype){
var rolebuttons = new Array();
var phasebuttons = new Array();
var systembuttons = new Array();

for(var i = 0; i < Articles.length; i++){
if(tabletype == 'role'){
 if(contains(Article[i].System, tabletop[j] && Article[i].Phase, tableside[i])){
  $.each(rolebuttons, function(i, a){
  if($.inArray(a, rolebuttons) === -1) rolebuttons.push(a);
  )};

table += '<input type="button" value="'+ rolebuttons[i] + '" class="'+ tabletype  +'button" onclick="createListView(\'' + rolebuttons[i] + '\', \'' + tabletop[j] +'\', \''+ tableside[i] +'\', \'role\');"/>';

}
}else if(tabletype == 'phase'){
 if(contains(Article[i].System, tabletop[j] && Article[i].Role, tableside[i])){
 $.each(phasebuttons, function(i, a){
 if($.inArray(a, phasebuttons) === -1) phasebuttons.push(a);
 )};
 }else if(tabletype == 'system'){
  if(contains(Articles[i].Role, tabletop[j] && Article[i].Phase, tableside[i])){
  $.each(systembuttons, function(i, a){¨
  if($.inArray(a, systembuttons) === -1) systembuttons.push(a);
  )};
 }
  }
   }
    }
 table += '	';
 }
 table += '
';
     }
 table+=('
');
 $('body').html('
' + table + spinner + '
');
 return table;
 }

and I keep getting the message : Expected ')' at line xxx char xxx (in the middle of the tabletop variable):
this line:
 function createButtons(tabletop[j], tableside[i], tabletype){

but I really cant see what the problem is?
did I go blind? :)
hop you can help me out :)

A: Firstly, you have some syntax mistakes in your code; I'm assuming you accidentally included some other characters in your code.
For example, the speech mark shouldn't appear here:
$.each(systembuttons, function(i, a){¨

Regarding your problem, parameter names cannot contain brackets. I can understand what you are trying to do in regards to running your original loop and then you are thinking that you can get the current loop iteration however this isn't how it works.
I think that you need not create a function called "createButtons". I would simply include your function's contents within your original loop.
Also, just a tip - try not to take directness as an insult, I'm sure the commentator didn't mean to come across as rude, he/she simply keeps things direct to get straight to the point. It enables us all to get the correct answer for you quicker :)


text:
Q: Add list of objects to List> if not contain I have List<List<Vertex>> , Vertex has a property id. I need to add List<Vertex>> into this list, but not duplicate lists.
 public void AddComponent(List<Vertex> list)
{
    List<List<Vertex>> components = new List<List<Vertex>>;

    //I need something like
      if (!components.Contain(list)) components.Add(list);
}

A: You can use SequenceEqual - (this means the order must also be the same):
if (!components.Any(l => l.SequenceEqual(list)))
    components.Add(list);

A: You could do something like:
public void AddComponent(List<Vertex> list)
{
    var isInList = components.Any(componentList =>
    {
        // Check for equality
        if (componentList.Count != list.Count)
            return false;

        for (var i = 0; i < componentList.Count; i++) {
            if (componentList[i] != list[i])
                return false;
        }

        return true;
    });

    if (!isInList)
        components.Add(list);
}


text:
Q: Can we update a radock without updating the full radock zone..? Can a ajax update panel be placed inside a Radock control? I don't need to update the complete radock zone , only the dock need to be updated..Can somebody help me with this matter..?

A: There is an example on demos.telerik.com with RadDocks containing UpdatePanel controls. Here is a link to it: "My Portal demo". For example if you add the "ExchangeRates.ascx" dock to the page and press the "Calculate Rate" button, only this dock will be updated.


text:
Q: Remove empty Strings after splitting a StringBuilder into Array Java Sorry if this question has already been asked, but I could only find results of c#.
So I have this StringBuilder:
 StringBuilder sb = new StringBuilder(" 111     11 ");

and I want to split it into an array using this method:
String[] ar = sb.toString().split(" ");

As expected the result array has some empty entries. My question is if I can remove these empty spaces directly when I split the StringBuilder or I have to do it afterwards.

A: split takes a regex. So:
String[] ar = sb.toString().split("\\s+");

The string \\s is regexp-ese for 'any whitespace', and the + is: 1 or more of it. If you want to split on spaces only (and not on newlines, tabs, etc), try: String[] ar = sb.toString().split(" +"); which is literally: "split on one or more spaces".
This trick works for just about any separator. For example, split on commas? Try: .split("\\s*,\\s*"), which is: 0 or more whitespace, a comma, followed by 0 or more whitespace (and regexes take as much as they can).
Note that this trick does NOT get rid of leading and trailing whitespace. But to do that, use trim. Putting it all together:
String[] ar = sb.toString().trim().split("\\s+");

and for commas:
String[] ar = sb.toString().trim().split("\\s*,\\s*");

A: I would use guava for this:
    String t = " 111     11 ";
    Splitter.on(Pattern.compile("\\s+"))
            .omitEmptyStrings()
            .split(t)
            .forEach(System.out::println);

A: If you do not want to depend on any third party dependencies and do not want to regex filtering,
You can do it in one line with Java 8 Streams API:
Arrays.stream(sb.toString().trim().split(" ")).filter(s-> !s.equals("")).map(s -> s.trim()).toArray();

For a detailed multiline version of the previous:
Arrays.stream(sb.toString()
    .trim() // Trim the starting and ending whitespaces from string
    .split(" ")) // Split the regarding to spaces
    .filter(s-> !s.equals("")) // Filter the non-empty elements from the stream
    .map(s -> s.trim()) // Trim the starting and ending whitespaces from element
    .toArray(); // Collect the elements to object array

Here is the working code for demonstration:
StringBuilder sb = new StringBuilder(" 111     11 ");
Object[] array = Arrays.stream(sb.toString().trim().split(" ")).filter(s-> !s.equals("")).map(s -> s.trim()).toArray();

System.out.println("(" + array[0] + ")");
System.out.println("(" + array[1] + ")");

A: There is couple of regex to deal with it, i would also prefer @rzwitserloot method,
but if you would like to see more.
Check it here : How do I split a string with any whitespace chars as delimiters?
glenatron has explained it :

In most regex dialects there are a set of convenient character summaries you can use for this kind of thing - these are good ones to remember:
\w - Matches any word character.
\W - Matches any nonword character.
\s - Matches any white-space character.
\S - Matches anything but white-space characters.
\d - Matches any digit.
\D - Matches anything except digits.
A search for "Regex Cheatsheets" should reward you with a whole lot of useful summaries.

Thanks to glenatron

A: You can use turnkey solution from Apache Commons.
Here is an example:
StringBuilder sb = new StringBuilder(" 111     11 ");
String trimmedString = StringUtils.normalizeSpace(sb.toString());
String[] trimmedAr = trimmedString.split(" ");
System.out.println(Arrays.toString(trimmedAr));

Output: [111, 11].


text:
Q: Python Path Not Read Correctly in Selenium When trying to create a filepath in Python with Selenium to run.
I tried running the code line by lane and for this code:
path = os.path.expanduser("~\Anaconda2\selenium\webdriver\firefox\amd64\geckodriver.exe")

In the variable explorer it shows as below:
C:\Users\username\Anaconda2\selenium\webdriverirefox(bullet character)md64\geckodriver.exe

Thus running into an error [Error 267] The directory name is invalid.
Can someone help me?
Thanks!

A: You need to escape (\) your backslashes, or put an r before your string, which string2 below demonstrates.
>>> string1 = "~\Anaconda2\selenium\webdriver\firefox\amd64\geckodriver.exe"
>>> string1
'~\\Anaconda2\\selenium\\webdriver\x0cirefox\x07md64\\geckodriver.exe'

>>> string2 = r"~\Anaconda2\selenium\webdriver\firefox\amd64\geckodriver.exe"
>>> string2
'~\\Anaconda2\\selenium\\webdriver\\firefox\\amd64\\geckodriver.exe'


text:
Q: Exporting Dataframe into Microsoft Azure SQL Database in R Studio I have a list of 19 dataframes named list_dfs. I recently created a SQL database in Microsoft Azure, and I am trying to create SQL tables from R studio and export these data frames into those tables. An example of one of these dataframes is as follows:
                          Item avg_price
1  15 Gal Texas Mountain Laurel       135
2        24" Box Texas Mountain       165
3 24" Box Texas Mountain Laurel       300
4 36" Box Texas Mountain Laurel       550
5     36" Texas Mountain Laurel       300

I have established a connection to the SQL database already, and I have this saved to an object named my_connection. I have searched through many proposed solutions, like this one, with no success.
I do not have existing tables in the SQL server, and I am wondering if there is a way to create those tables from R Studio and insert the dataframes into those SQL tables from R Studio as well.
I have tried to do this through a loop, using the DBI library like so:
for(i in 1:length(list_dfs)){
dbWriteTable(conn = my_connection,
             name = paste(names(list_dfs)[i]),
             value = list_dfs[i],
             row.names = F)
}

Unfortunately, I get this error message:
Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function 'dbWriteTable' for signature '"Microsoft SQL Server", "character", "list"'

I have tried searching the error message and got to other posts like this, and I still cannot find an answer. I am new to how SQL databases work, but I cannot find any solutions to my specific issue.
More Information
I connected to my database using this code:
my_connection <- dbConnect(drv = odbc::odbc(),
Driver = "ODBC Driver 18 for SQL Server",
server = "servername.database.windows.net",                          database = "database",
uid = "user",
pwd = "pwd")

It shows up on my connections tab. I see my databases, but it still gives me the error above. I still do not know why I am getting this error.

A: The issue is that you are passing a list with a frame, not the frame itself. The clue:
... for signature '"Microsoft SQL Server", "character", "list"'

None of the db* functions use a list in their signature determination, that should have clued me in right away (but didn't).
To verify this, looking at your code,
for(i in 1:length(list_dfs)){
dbWriteTable(conn = my_connection,
             name = paste(names(list_dfs)[i]),
             value = list_dfs[i],              # <-- single-bracket yields list
             row.names = F)
}

Change that to:
for(i in 1:length(list_dfs)){
dbWriteTable(conn = my_connection,
             name = paste(names(list_dfs)[i]),
             value = list_dfs[[i]],            # <-- double-brackets yields a frame
             row.names = F)
}


text:
Q: Copy one table to another except the id filed I want to copy table1 to table2 except for the 'id' field because i want the 'id' in table2 to increment automatically.
Here is one of the solution i have tried... but not working:
"INSERT INTO table2 SELECT field1, field2, field3 FROM table1 WHERE member_id = '53'"

A: You can select NULL in place of the id, if you don't (for whatever reason) want to name the columns.
Assuming both of your tables have the columns member_id, field1, field1, field3, in that order, you can do:
insert into table2 select NULL, field1, field2, field3 from table1 where member_id = '53';
NOTE: you must provide a value for ALL columns, using this format.

A: If you don't want to fill all columns of the destination table, then you need to name the columns you want to fill
INSERT INTO table2 (table2_f1, table2_f2, table2_f3)
SELECT field1, field2, field3
FROM table1
WHERE member_id = '53'

A: INSERT INTO table2 (table2_f1, table2_f2, table2_f3)
SELECT field1, field2, field3
FROM table1
You don't need to specify id if you set it auto_increment

A: The best answer........
USE TEMPORARY TABLE!
example table a and table b
a have 3 column
b have 6 column
both table has first column id.(but we do not wish column id copy to  table b)

CREATE TEMPORARY TABLE temp AS SELECT * FROM a WHERE id=5;
UPDATE temp
SET id = NULL;
INSERT INTO b
SELECT *,'EFG',33,'ABCD' FROM temp;
DROP TEMPORARY TABLE temp;


text:
Q: Matplotlib ColorbarBase: delete color separators I'd like to delete the back line-separators (dividers?) in the drawn colormap, using ColorbarBase:
cm    = get_cmap('RdBu')
Ncol  = 501
cccol = cm(1.*arange(Ncol)/Ncol)
cax     = fig.add_axes([0.15,0.15,0.05,0.4])
fig.add_axes([0.5,0.15,0.3,0.03])
norm    = mpl.colors.Normalize(vmin=valmin, vmax=valmax)
cb1     = mpl.colorbar.ColorbarBase(cax, cmap=cm, norm=norm, orientation='vertical')

It always gives me too many black lines in between.. is there a way to eliminate them? I already tried stuff like:
del cb1.lines
del cb1.dividers

or
cb1.lines.remove()
cb1.lines = []

as seen in the ColorbarBase methods in http://fossies.org/dox/matplotlib-1.2.0/matplotlib_2colorbar_8py_source.html#l00281.

A: That works for me, without any lines.  I see two obvious possibilities:
1) You have a buggy version.  If I do matplotlib.__version__ at the python prompt, I see 1.2.0.  I'm using OS X 10.6.8 with python 2.7.3, and everything installed from macports.  How about you?
2) It's something in the code you haven't shown us.  With questions like this, you should always show a minimal working example.  (Which can sometimes help you to figure out your problem before you even ask it.)  For example, I can start ipython --pylab, and the following works:
fig    = figure()
valmin =-1.0
valmax =1.0
cm     = get_cmap('RdBu')
Ncol   = 501
cccol  = cm(1.*arange(Ncol)/Ncol)
cax    = fig.add_axes([0.15,0.15,0.05,0.4])
norm   = mpl.colors.Normalize(vmin=valmin, vmax=valmax)
cb1    = mpl.colorbar.ColorbarBase(cax, cmap=cm, norm=norm, orientation='vertical')
draw()
savefig('/tmp/bla.png')

Both the GUI that pops up and the PNG that gets saved show the following:

Does that work for you?  Have you done something significantly different in the rest of your code?

A: I found out that it WAS indeed the matplotlib backend!
mpl.use('WXAgg')

solved it!


text:
Q: Python sqlite => reportlab data what is difference between [1,2,3] and [[1],[2],[3]] I apologize in advance, but I just cannot figure it out....
I am attempting to read data from a sqlite database and populate data to a reportlab bar chart. The sample data that I have is a snippet from http://www.reportlab.com/snippets/3/
The sqlite3 code is:
def arrData():
    conn = sqlite3.connect('alarmdb.sqlite')
    ccursor = conn.cursor()
    strSQL = "Select distinct ErrorMsg, count(*) as Amt from tmpTable where cast(source as int)<20 group by ErrorMsg Order by count(*) desc limit 10"
    ccursor.execute(strSQL)
    arrResult = ccursor.fetchall()
    arrErrAmt = [int(element[1]) for element in arrResult]
    return arrErrAmt

but that returns [200, 100, 50, 40,..], but in the reportlab sample they show:
self.bar.data = [[4.22], [4.12], [3.65], [3.56], ...]
How do I do that with my arrData function?

A: Each element of the list [[4.22], [4.12], [3.65], [3.56], ...] is itself a list (containing one float).
Each element of the list [200, 100, 50, 40,..] is an int. So you need to create lots of lists instead of merely lots of ints.
You could change your code to:
[[int(element[1])] for element in arrResult]

or perhaps:
[[float(element[1])] for element in arrResult]

if you want it to look even more like the example data.


text:
Q: Один блок наезжает на другой при изменение размера Подскажите как исправить наезжание одного блока на другой.
Есть раздел на сайте "Товары", если кликать на табы, то количество товаров меняется и нижний блок наезжает. Как это можно поправить?
Стилей , отступов вроде бы нет никаких. Как это можно поправить?

A: Проблема не с padding / margin, а с flow:left у элементов #portfoliolist .portfolio
Добавьте в ваш div#portfoliolist класс clearfix


text:
Q: rewrite lighthttpd QSA Help rewrite flag apache - QSA for lighttpd.
Now available:
RewriteRule ^([^?]*) index.php?_route_=$1 [L, QSA]

Try the case, but is not functioning properly:
url.rewrite-if-not-file = ("^/(?:\?(.*))?" => "/index.php?_route_=$1")

A: From what I understand of lighttpd:
url.rewrite-if-not-file = ("^/([^\?]*)$" => "/index.php?_route_=$1")

.. should work.  If not, then the following will:
url.rewrite-if-not-file = ("^([^\?]*)$" => "/index.php?_route_=$1")


text:
Q: Javascript client side ssh / ping / scp I'm trying to build a web app that has the capability to scp, ssh, and ping devices on the local network from Javascript client-side. I'm very familiar with Django, but that's all server side code and won't be able to communicate with a device on the local area network.
Is there any way to do this in Javascript? I know that packages like scp2 in NodeJS do exactly what I want, but NodeJS is a server-side framework too. I'm looking for something that does what scp2 does, but client-side.

A: There is no browser-independent way to do this. You would have to write browser-specific extensions to be able to get access to TCP sockets and the like. Even then if you browserify ssh2 or any of its dependents, you may run into other issues, such as missing node.js functionality not supported by browserify or the browser's extension API.
Alternatively, you could use something like Electron, but that's only if you don't mind the client being a separate application (but still web/JavaScript-based). That would also have the added benefit of having the ssh2 or related code being completely compatible (since Electron uses node.js).


text:
Q: twitter bootstrap: what files to include OK. I am a little confused.  I downloaded the bootstrap v2 and noticed that the .css file does not contain "topbar" or "fill" classes. but I see several examples using these classes.
Also,  What is the required files to include to have the framework working?  Do I just need th one bootstrap.css file?
What about the bootstrap.js file? Do I need to include that too?

 Product

Create Account

Forgot Password

Contact Us

My menu is on the left side. I want it in the middle so it lines up with the main body content. I thought wrapping a "container" would do this...

A: Most parts of Twitter bootstrap only require that you include the CSS-file. There are however some additional things that might be required.
If you want to use the glyph-icons, you need upload the image-sprites for those.
If you want to use any of the jQuery-plugins (carousel, tooltip, dropdown etc.), you need to include the JS-file as well.

A: "topbar" or "fill" are not standard classes in bootstrap. You should use some kinds of modified version or just use class "navbar" "navbar-fixed-top" "navbar-fixed-bottom" ...

A: in projects which rely on a lot javascript i always use RequireJS to load my dependencies for only what i need. you also can easily turn the JS plugins of bootstrap into AMD modules so you don't miss any dependencies after you configured them once.


text:
Q: Extracting Several Files contents Within a folder into one file with Visual Basic and userform to chose the folder I want to create a macro in Visual Basic that will select all  of the Excel files from a folder and put them into a single file. I used a form with a button that will open a window to select the folders.
Here's the button code, here I can only choose the file instead of the folders:
Private Sub importer_Click()
    Dim file As String
    file = Application.GetOpenFilename("excel (*.xlsx),*.xlsx", , "Chose", , True)

    If (LCase(file) <> "Faux" And file <> "0") Then

        liste_elements.AddItem (file)

    End If
End Sub

A: In order to select more than one file you should set the MultiSelect parameter to true.
Read more about it here: Application.GetOpenFilename Method (Excel)


text:
Q: \how to retrieve table data in drop down list with first option manual using PHP I want to add in drop down list first option manual and after all from my "game table".
In my code everything works fine but my manual option "select" repeat every time after the result from game table.
Here is my code
<!DOCTYPE HTML>

 <title>Update Result</title>

 <?php
    //Connect to Database Server
    include 'secure.php';
    //Select a Table from Database
    $query = "SELECT * FROM game";
    //Get Result from Table (all)
    $result = mysqli_query($connect,$query);
 ?>

 Update Result

 <form action="rsave.php" method="post">
    Date:<input type="date" name="ResultDate" tabindex="1" min="1899-12-31"  max="2100-12-31" title="Please Enter Correct Date" required >

    Game:<select id="Select1" name="ResultName" tabindex="2"  title="Select a GameName" required >
    <?php
        // PHP Again
        while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) {
    ?>
    <option value="">SELECT</option>
    <option value="<?php echo $line['GameID'];?>"><?php echo $line['name'];?></option>
    <?php
    }
    ?>
    </select>

    ReNO:<input type="number" name="ResultNo" min="0" max="100" tabindex="3" pattern="[0-9]{2,3}" title="Add a Number Between 0 to 100"required >

    <input type="submit" value="Update" tabindex="4">
    <input type="reset" value="Reset" tabindex="5">

</form>

A: pull this line:
<option value="">SELECT</option>

above your while loop, like this:
Game:
<select id="Select1" name="ResultName" tabindex="2"  title="Select a GameName" required >
<option value="">SELECT</option>
<?php
     // PHP Again
      while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) {
 ?>

 <option value="<?php echo $line['GameID'];?>"><?php echo $line['name'];?></option>
 <?php
 ....


text:
Q: datatable to Excel in c# While exporting Datatable to Excel some columns to fall into a new line. I don't know what the problem is. My code is below:
string attachment = "attachment; filename=Test.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in transposedTable.Columns)
{
    Response.Write(tab + dc.ColumnName);
    //tab = "\t";
}
Response.Write("\t");
int i;
foreach (DataRow dr in transposedTable.Rows)
{
    Response.Write("\n");
    tab = "";
    for (i = 0; i < transposedTable.Columns.Count; i++)
    {
        Response.Write(tab + dr[i].ToString());
        tab = "\t";
    }
    Response.Write("\t");
}
Response.End();

I have tried many ways, but didn't get the exact issue. Is the issue with excel in machine or with my code?

A: It seems possible that your DataRow data contains newline characters, that is one reason why newlines might be appearing in your data.
Swapping:
    Response.Write(tab + dr[i].ToString());

For:
    string replacement = Regex.Replace(dr[i].ToString(), @"\t|\n|\r", "");
    Response.Write(tab + replacement);

May fix the problem if I did diagnose it correctly.


text:
Q: Problem with session security feature of JBoss 6 using servlet 3.0 We migrated our application from JBoss 5 to JBoss6 and one of the main reasons for this is to make use of the new features of servlet 3.0. Everything works fine apart from one new feature of JBoss 6 and servlet 3.0: setting the session cookie to only be transferred through secure channel even if the request was made through plain HTTP. This is a very important security feature for us and is achieved by adding
<secure>true</secure>

in web.xml. This is part of our web.xml:
<session-config>
<session-timeout>25</session-timeout>
<cookie-config>
    <http-only>true</http-only>
    <secure>true</secure>
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>

When we remove the
<secure>true</secure>

everything works fine. When it is there, there is a new jsessionid generated for each request even when being on a secure page (HTTPS) or in an unsecured page (HTTP). Also, the login does not work since after login with secure credentials the user is redirected back to the login page.
I suppose this might be also an issue with Tomcat 7 since it also uses the servlet 3.0 spec. Any advice would be much appreciated.
Regards

A: According to the HTTP Specification:

Secure
Optional.  The Secure attribute (with no value) directs the user
  agent to use only (unspecified) secure means to contact the origin
  server whenever it sends back this cookie.
The user agent (possibly under the user's control) may determine
  what level of security it considers appropriate for "secure"
  cookies.  The Secure attribute should be considered security
  advice from the server to the user agent, indicating that it is in
  the session's interest to protect the cookie contents.

It means that specification leaves it open to the browser (user agent) to defined what is "secure".
The Secure element in the web.xml is a reference for the HTTP Cookie Secure property, and you can track that value with your browser's debug tool.
If the communication is not "secure", the browser won't send the received cookie to the server on the following requests.
The problem is not JBoss always returning new cookies, but the browser that is not sending it back because communiation is unsecure. JBoss then creates a new session for every request.
It is very clear that for non-encrypted communication (not HTTPS) the browser won't send the cookie, this is expected since you are marking the cookie as secure = true.
But, even if you are using HTTPS, the "secure" is relative to the browser concept of security, for example:

*

*Certificate can be expired

*Certificate is self-signed

*You are using a hostname different from the one who signed the certificate

These and other security problems can happen using TLS, meaning the communication is not secure.
The problem must be with your SSL/TLS or Cookie configuration, which means you have to check what you have done and isole the problem. I don't think there is any bug in JBoss or JBossWeb (Tomcat 6 fork) causing it, and for sure it is not a specification error.
I was able to configure a JBoss 6.1.0 Final with TLS and with your web.xml configuration, and everything worked as expected.
I suggest you to double-check your configuration, browser debug and alerts.


text:
Q: TypeError: Cannot filter a non-Node argument; received False I am getting TypeError: Cannot filter a non-Node argument; received False on the second line of the following code (query1 = ...).
def checkExits(EVname,EVmanufacturer,EVyear):
    query1 = EVModel.query(EVModel.name == EVname).fetch()
    query2 = EVModel.query(EVModel.manufacturer == EVmanufacturer).fetch()
    query3 = EVModel.query(EVModel.year == EVyear).fetch()
    query = ndb.get_multi(set(query1).intersection(query2.intersection(query3)))
    if len(query) == 0:
        return True
    else:
        return False


text:
Q: Removing expired certificates from LDS (new ver of ADAM) This is my situation:
We are in the process of replacing a certificate store currently hosted on Sun's iPlanet with Microsoft's Lightweight Directory Services (new version of ADAM with Server 2008).
These certificates have been imported into LDS into an application partition (say o=myorg, C=AU).  Under this structure I have around 40,000 OU's each one representing a customer under each customers OU are one or more user (iNetOrg) objects (around 60,000 in all).  In each user are one or more certificates in the UserCertificate attribute.
A combination of in-house written application code and proprietory PKI code reads and publishes these certficates to validate financial transactions.
As the LDAP path of the certificates is stored within the customer certificates (and within the application code) and there is zero appetite for changing any of the code, I have had to pick up the iPlanet directory as a whole and dump it in LDS in the same structure.
(I will not be using or hosting a Microsoft CA, just implementing an LDAP compliant directory to host these certificates)
We have fully tested the application using the data in LDS and everything works fine - here is my dilema and question (finally, phew!)
There was no process put in place for removing revoked or expired certificates, consequently the vast majority of the data is completely useless, the system has been running for about 8 years!  I have done a quick analysis and I estimate that at least 80% of the data is no longer valid.
As I am taking on responsibility for managing the directory I would like to start with a clean directory.  Does anyone have any idea how I can cleanup these expired certificates.  I am not a highly experienced scripter but have some background in VB.  I have been researching the use of CAPICOM and have a feeling this may be able to be used but in exactly what way I am not sure??
I would prefer to write a script that I could specify an expiration date (say any certs that expired prior to 2010) then run against the LDS paritition.  This way I can reuse the script periodically to cleanup the directory (as mentioned above - I have no way to adjust the applications that are writing the certs, this is with a third party).
Another, less attractive, alternative is to massage the LDIF file (2.7 million lines!) to rip the certs out prior to the import
Any help and advice MUCH appreciated.
Cheers
Jon


text:
Q: Importing Go packages locally rather than remotely In a node.js project, I'm using Go for a critical part of it that node isn't adequate enough to handle. I want to split the Go code into a sockets package and a main package, with sockets containing required structs/interfaces for the main package to run. The problem I'm having is that from what I can gather from Go's documentation, I can only use external packages like sockets remotely from github/gopkg. I don't want to split the repository for the project into one containing the Go code and one containing node's. How can I make the sockets package available for main to import locally while making it possible to rebuild the binaries for the two packages if any updates to their source code are made?
Edit: importing the packages is no longer an issue, but rebuilding packages on update still remains

A: It happens the same to my team too and we end up using vendor it's pretty easy to manage all the external packages. So, whoever checkout your repo will have all the packages inside vendor.
Understanding and using the vendor folder
And Please refer this site lots of other option out there too:
Golang Package Management Tools


text:
Q: Does every topological group embed as a closed subgroup in an amenable group? It is a standard result that closed subgroups of locally compact amenable groups are themselves amenable, so for example $F_2$, the free group on two generators, cannot be embedded as a closed subgroup of a locally compact amenable group. However, by a result of Pestov, $F_2$ embeds as a closed subgroup of $\mathrm{Aut}(\Bbb Q,\leq)$ and the latter group is (extremely) amenable.
Are there topological groups that cannot be embedded as a closed subgroup of any amenable group?

A: At least for Polish groups, which was the case I was most interested in, the answer is positive.
I mentioned this question to Ola Kwiatkowska yesterday and she immediately pointed out that one of the standard universal Polish groups, the group $\mathrm{Iso}(\Bbb U)$ of isometries of the Urysohn space, is in fact not only amenable, but even extremely amenable (and Polish subgroups of Polish groups are closed).
For arbitrary groups I still expect the answer to be positive, but I have no meaningful comments to make about that case, apart from the fact that if a group embeds as a closed subgroup into an amenable group $G$, then it also embeds as a closed subgroup into an extremely amenable group, namely $L^0(G,X,\mu)$.


text:
Q: Firefox developer edition won't accept cookies I'm trying to switch over from Firebug to Firefox Developer Edition. I have a website that starts with a login page. The user enters his credentials, these are sent to a perl backend server, which sets a number of cookies with which the user can log in. In production this happens all over a secure connection, in my personal development environment that connection is not secure, since I'm testing toward a vm I'm running on my own pc. This has always worked with every browser. However with developer edition these cookies aren't set.
Do more people have this problem? Is there a way to fix this? Isn't the Firefox developer edition supposed to be exact a representation of Firefox? Because I don't want to have yet another browser to test my website for.

A: Same problem here.
Based on this thread:
https://bugzilla.mozilla.org/show_bug.cgi?id=1042859
I decided it is likely a problem with using "localhost". So I added an alias to me /etc/hosts file:
/etc/hosts
127.0.0.1 bb
Now instead of going to localhost:5000, I go to bb:5000. And so far the cookies are working.
Ubuntu 16.04
Firefox Developer Edition version 54.0a2


text:
Q: How do I append rows with dependent dropdown Whenevr I append the row and try to use the dependent dropdown. The value of the apppended rows is change based on the first row.
 $(document).ready(function() {

           $('#addmoretable').click(function(){

            $('#coursetable').append(
                                  '
'+
                                        ''+
                                            '
'+
                                                '<select class="form-control" name="program_id" id="program_id">'+
                                                    '<?php if($programs): ?>'+
                                                        '<?php foreach($programs as $key => $value): ?>'+
                                                            '<option value="<?= $value -> program_id ?>"><?= $value -> programs ?></option>'+
                                                       ' <?php endforeach; ?>'+
                                                   ' <?php endif; ?>'+
                                                '</select>'+
                                            '
'+
                                        '	'+
                                        ''+
                                            '
'+
                                                '<select class="form-control" name="collegeyear_id"></select>'+
                                           '
'+
                                       ' 	'+
                                      '  '+
                                            '
'+
                                               ' <input type="text" class="form-control" placeholder="COURSE...">'+
                                            '
'+
                                        '	'+
                                        ''+
                                            '
<input type="text" class="form-control" placeholder="COURSE CODE">
'+
                                        '	'+
                                        ''+
                                            '
'+
                                                '<input type="text" class="form-control" placeholder="UNITS">'+
                                            '
'+
                                        '	'+
                                        ''+
                                            '
<select class="form-control"></select>'+
                                            '
'+
                                        '	'+
                                        ''+
                                            '<button class="btn btn-danger" id="remove" type="button"></button>'+
                                        '	'+
                                   '
'
            );
        });$('select[name="program_id"]').on('change', function() {
            var programID = $(this).val();
            if(programID) {
                $.ajax({
                    url: '<?= base_url('/Admin/Dashboard/getcollegeyear/') ?>'+programID,
                    type: "GET",
                    dataType: "json",
                    success:function(data) {
                        $('select[name="collegeyear_id"]').empty();
                        $.each(data, function(key, value) {
                            $('select[name="collegeyear_id"]').append('<option value="'+ value.collegeyear_id +'">'+ value.collegeyear +'</option>');
                        });
                    }
                });
            }else{
                $('select[name="collegeyear_id"]').empty();
            }
        });
    });

<?= form_open('', 'class=""') ?>

                                        PROGRAM
                                        YEAR LEVEL
                                        COURSE NAME
                                        COURSE CODE
                                        UNITS
                                        SEMESTER OFFERED

                                                <select class="form-control" name="program_id" id="program_id">
                                                    <?php if($programs): ?>
                                                        <?php foreach($programs as $key => $value): ?>
                                                            <option value="<?= $value -> program_id ?>"><?= $value -> programs ?></option>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </select>

                                                <select class="form-control" name="collegeyear_id"></select>

                                                <input type="text" class="form-control" placeholder="COURSE...">

                                                <input type="text" class="form-control" placeholder="COURSE CODE">

                                                <input type="text" class="form-control" placeholder="UNITS">

                                                <select class="form-control">

                                                </select>

                                            <button class="btn btn-success" id="addmoretable" type="button"></button>

                        <?= form_close(); ?>

A: you can make the id unique by appending the length of row to the id and use that id to the events.
var rowCount = $('#coursetable tr').length; // count the row
id="program_id'+rowCount+'" // change this id="program_id" and append rowCount
$("#program_id"+rowCount) //use this instead of this $('select[name="program_id"]') on the events

hope this helps.


text:
Q: Custom key for a HashMap I need to map a [Integer, List<Integer>] key to an Integer. I have considered the following approaches and am struggling to figure which is most beneficial, given that speed is key.
WHY I NEED THIS?
There is a 2D array. Each row is the number of lines going out of a station. Each row contains the lines originating from a subway. So, subway stations are numbered 0,1,... All rows have the same number of elements (same number of lines originating from all stations). 0th index of a row gives the destination on taking the 0th line. 1th index of a row gives the destination on taking the 1th line,... The rth element of the list for station k, gives the station directly reachable by taking line r from station k. Now, suppose you are lost at one of the stations. Independent of which station you are at, if you take a certain combination of paths, you will arrive at a common station. This is called a meeting path. I need to find if, for a given subway configuration, there is a meeting path possible. Eg. For subway = [[2, 1], [2, 0], [3, 1], [1, 0]], taking line1 then line0 from any station, results in ending up at station2. So [1,0] would be a meeting path.
I have generated a set of paths, that would look like [[0],[1],[0,0],[0,1],[1,0],[1,1],[0,0,0],[0,0,1],...]. I have to traverse the path from each station to see if I end up at the same station for all the stations. Say, we consider station0, and am considering path[0,0,1]. I would already have traversed the path [0,0]. Instead of traversing that portion again, I can use whatever result I had after traversing [0,0] and take line1 from that point, to end up at my new destination. This is why I need to cache ([startStation, pathList], destination). Moreover, if this way of searching for a meeting path doesn't work for say, 8 degrees of paths, we need to check if closing down a certain station will result in a meeting path. This is more so, why I want to use a [startStation, pathList] as a key. Link to full problem statement is at the end of the post.
First approach: Create a new unmodifiableList with the value at the 0th index as the aforementioned Integer and the rest as the List<Integer>. I would use this unmodifiableList as the key.
Second approach: Create a new unmodifiableList with the value at the 0th index as the aforementioned Integer and the 1st index as the hashCode for an unmodifiable copy of List<Integer>. I would use this unmodifiableList as the key. [Thilo correctly noted in the comments that this approach would cause collisions].
Third approach: [Nested Map] Create a mapping from an Integer to another HashMap that maps from List<Integer> to Integer. [Similar to the accepted answer here]
Fourth approach: Make an object with Integer and List<Integer> as fields, and override the equals and hashCode methods. This would serve as the key.
I feel the third approach is the simplest, and would make for the most readable code. I am struggling to weigh the pros and cons with respect to all 4 designs. Speed is key here.
This is with reference to a question on the Google Foobar challenge [problem]

A: I would favour using a custom class, you can make it more readable by using your IDE to generate getters, setter, equals, hashCode and toString() methods.
Note: using a HashMap instead of an object has a much higher overhead and make your program more difficult to profile later.


text:
Q: How to modify bundle env variables enter image description here
how to change the value of these variables I tried by setting env variables in .profile and .bashsrc file .but nothing worked. I have uninstalled the ruby 2.7.0 also but this env variable still shows some entries with ruby 2.7.0.
I just want to update them with ruby 2.7.1.


text:
Q: Find remaining line from rectangle in OpenCV I'm detecting a rectangle with known dimensions in OpenCV. I've written code - which works - for detecting all four lines, but the furthest line is difficult to detect and usually causes problems when it comes time for warp the perspective.
My question (which I've looked into, but haven't found an answer for), is whether, theoretically, having 3 lines (angles and intercept) is enough to approximate the final line.
EDIT: I was asked to include my current code. Here it is:
import numpy as np
import cv2
from sklearn.cluster import AgglomerativeClustering

# find intersection of lines
def line_intersect(m1, b1, m2, b2):

    if m1 == m2:
        print ("These lines are parallel!!!")
        return None

    x = int((b2 - b1) / (m1 - m2))

    y = int(m1 * x + b1)

    return [x,y]

# method specs
width_error = 10
height_error = 10
kernel_size = 7
kernel_dilate = np.ones((1, 1), 'uint8')
kernel = np.ones((5, 5), 'uint8')

# read and process image
img = cv2.imread('assets/game-frames/hard-m-2019-124-1200.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
blur_gray = cv2.GaussianBlur(gray,(kernel_size, kernel_size),0)
edges = cv2.Canny(blur_gray, 0, 100, apertureSize = 3)
dilate_img = cv2.dilate(edges, kernel_dilate, iterations=3)
closing = cv2.morphologyEx(dilate_img, cv2.MORPH_CLOSE, kernel)

# find hough lines
lines = cv2.HoughLinesP(closing, 2, np.pi/180, 100, minLineLength=20, maxLineGap=10)
lines_np = np.reshape(lines, (np.int32(lines.size/4), 4))
lines_np = lines_np[(lines_np[:, 2] - lines_np[:, 0]) != 0]
lines_np = np.c_[lines_np, (lines_np[:, 3] - lines_np[:, 1])/(lines_np[:, 2] - lines_np[:, 0])]
lines_np = np.c_[lines_np, np.sqrt((lines_np[:, 3] - lines_np[:, 1])**2 + (lines_np[:, 2] - lines_np[:, 0])**2)]

# find lengthwise lines
lengthwise_lines = lines_np[(abs(lines_np[:, 4]) < 3.5) & (abs(lines_np[:, 4]) > 1.20) & (lines_np[:, 5] > 100)]
if lengthwise_lines[:, 4].size < 2: print('No lengthwise lines!')
ward_length = AgglomerativeClustering(n_clusters = None, distance_threshold = 0.50, linkage = "ward").fit(abs(lengthwise_lines[:, 4].reshape(-1,1)))
lengthwise_lines = np.c_[lengthwise_lines, ward_length.labels_]
length_clusts = np.bincount(ward_length.labels_).argsort()[-2:]
lengthwise_lines = lengthwise_lines[np.isin(ward_length.labels_, length_clusts)]

# find extremities
x_max = np.max(lengthwise_lines[:,[0,2]].reshape(-1,1))
x_min = np.amin(lengthwise_lines[:,[0,2]])
y_coords = lengthwise_lines[:, [1, 3]].reshape(-1,1)
ward = AgglomerativeClustering(n_clusters = None, distance_threshold = 10, linkage = "ward").fit(y_coords)
want_clusts = np.bincount(ward.labels_).argsort()[-2:]
y_ext1 = np.median(y_coords[np.isin(ward.labels_, want_clusts[0])])
y_ext2 = np.median(y_coords[np.isin(ward.labels_, want_clusts[1])])
y_max = max(y_ext1, y_ext2)
y_min = min(y_ext1, y_ext2)

# find outer lengthwise lines
length_want = ward_length.labels_[np.isin(ward_length.labels_, length_clusts)][np.argmin(abs(lengthwise_lines[:,4]))]
lengthwise_lines = lengthwise_lines[lengthwise_lines[:, 6] == length_want]
lengthwise_lines = np.c_[lengthwise_lines, (lengthwise_lines[:,1] - (lengthwise_lines[:,4]*lengthwise_lines[:,0]))]
lengthwise_lines = np.c_[lengthwise_lines, ((np.max(lengthwise_lines[:,1]) - lengthwise_lines[:,5])/lengthwise_lines[:,4])]

# subset left and right outer lengthwise lines
l_left = lengthwise_lines[lengthwise_lines[:,4] < 0]
l_right = lengthwise_lines[lengthwise_lines[:,4] > 0]

# find top and bottom lines
widthwise_lines = lines_np[(abs(lines_np[:, 4]) < 0.10)]
widthwise_lines = np.c_[widthwise_lines, (widthwise_lines[:,1] - (widthwise_lines[:,4]*widthwise_lines[:,0]))]
bottom_lines = widthwise_lines[np.where((np.amin(widthwise_lines[:,[1,3]], axis = 1) >= y_min - height_error) & (np.amin(widthwise_lines[:,[1,3]], axis = 1) <= y_min + height_error) & (np.amin(widthwise_lines[:,[0,2]], axis = 1) >= x_min - width_error) & (np.amax(widthwise_lines[:,[0,2]], axis = 1) <= x_max + width_error))[0]]
top_lines = widthwise_lines[np.where((np.amax(widthwise_lines[:,[1,3]], axis = 1) >= y_max - height_error) & (np.amax(widthwise_lines[:,[1,3]], axis = 1) <= y_max + height_error) & (np.amin(widthwise_lines[:,[0,2]], axis = 1) >= x_min - width_error) & (np.amax(widthwise_lines[:,[0,2]], axis = 1) <= x_max + width_error))[0]]

# if no lines found for any border, stop
if top_lines.size == 0 or bottom_lines.size == 0 or l_left.size == 0 or l_right.size == 0: print('No Lengthwise lines!')

# take median of left outer lengthwise lines
l_left_b = np.median(l_left[:,7])
l_left_m = np.median(l_left[:,4])

# take median of right outer lengthwise lines
l_right_b = np.median(l_right[:,7])
l_right_m = np.median(l_right[:,4])

# take median of top widthwise lines
top_lines_b = np.median(top_lines[:,6])
top_lines_m = np.median(top_lines[:,4])

# take median of bottom widthwise lines
bottom_lines_b = np.median(bottom_lines[:,6])
bottom_lines_m = np.median(bottom_lines[:,4])

# find interesction of lines
int_pt1 = line_intersect(l_left_m, l_left_b, bottom_lines_m, bottom_lines_b)
int_pt2 = line_intersect(l_right_m, l_right_b, bottom_lines_m, bottom_lines_b)
int_pt3 = line_intersect(l_left_m, l_left_b, top_lines_m, top_lines_b)
int_pt4 = line_intersect(l_right_m, l_right_b, top_lines_m, top_lines_b)

# draw intersections
cv2.circle(img, int_pt1, 3, (0, 255, 0), -1)
cv2.circle(img, int_pt3, 3, (255, 255, 0), -1)
cv2.circle(img, int_pt2, 3, (0, 255, 0), -1)
cv2.circle(img, int_pt4, 3, (255, 255, 0), -1)

# show image
cv2.imshow('frame diff ', img)
cv2.waitKey(0)

Original image:


text:
Q: Network install of cytoscape Cytoscape appears to expect it can write to its installation directory. On Linux, we do shared installs of software such the installation directories are root-owned and read-only.
Upon launch, the message:
Unable to update instance pid: Unable to create directory /usr/software/cytoscape/framework/instances

is displayed. Is this something to be concerned about? Is there an option to specify a different, usable writable directory for the instance data?

A: Good news. This is not a critical error message. You can ignore it.
The Cytoscape dev team now has this as a bug to fix in future versions (thanks). We'll write that properties file to the CytoscapeConfiguration folder (where all other properties are written).


text:
Q: Share an attribute or method between components I am trying to share a method between multiple components and this method should access an attribute from the parent component.
I am using VUE3, with script setup.
I tried with "extend" but I couldn't find how to extend a component with script setup.
I don't want to pass any parameter because in my real case I have many of them, too many.
Thank you very much for the support
//TheComponent.vue
<template>

</template>

//Common.js
const common={
    print: function() {
        alert(x);
    }
  }
};
export default common;


text:
Q: Does opencv have Savitzky Golay or Polynomial fit? I can't find anything similar to Savitzky Golay Polynomial Fit on opencv. This is a standard smoothing operation though, so it seems like something they should have. Does anybody know of anything they have? Using C++ for what its worth.
Thanks!
-Tim

A: It is not clear what you need to do: fit or smooth, you mentioned both. But if you need to smooth using OpenCV you can try Kalman filter (fit in its way and smooth), smooth-2D (using your 1D-data) or your own convolution smooth kernel 1D+1D using 1D-data for kernelX only convolution (the fastest way to smooth).
OpenCV is near to real time image and video processing library, and it contains most common task solvers for this, where is no polynomial fitting among them yet. But if you really need fitting (not just smoothing) you can use polynomial fitting matrix equation and calculate your answer by yourself in a simple way thanks to Mat objects in OpenCV which has inv()(inverse) and t()(transpose) functions.


text:
Q: create InfoWindow for clustered markers using Google Maps v3 I m developing a map that will cluster pins to prevent over crowded pin, but I wanted to create an infoWindow that will list all the marker when I click on the marker, I tried to get some help around and found out i can do it using marker.getTitle() but this is not helping me because I m using makrewithLable object and not using title, my question is there any why to add title to the marker or as I prefer to use the label instead to list them in the infowindow.
here is a copy of my work.
google.setOnLoadCallback(initialize);
var globalMarker = [];
var map;

  function initialize() {
    var center = new google.maps.LatLng(45.4214, -75.6919);

    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 3,
      center: center,
      disableDoubleClickZoom: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var markers = [];
    var infowindow = new google.maps.InfoWindow();
    for(i=0; i<50; i++) {
    var latLng = new google.maps.LatLng(center.lat() + Math.random() - 0.5, center.lng() + Math.random() - 0.5);
    //var latLng = new google.maps.LatLng(45.4214, -75.6919)
     markers[i] = new MarkerWithLabel({
       position: latLng,
       draggable: true,
       raiseOnDrag: true,
       map: map,
       labelContent: "Marker ID = "+i,
       labelAnchor: new google.maps.Point(30, 0),
       labelClass: "labels", // the CSS class for the label
       labelStyle: {opacity: 0.75}
     });
      markers.push(markers);
    makeDiv(i, 15, "Marker #");
     google.maps.event.addListener(markers[i], 'click', function(e) {
    infowindow.setContent('Marker postion: '  + this.getPosition());
    infowindow.open(map, this);});
    }
    var clusterOptions = { zoomOnClick: false }
    var markerCluster = new MarkerClusterer(map, markers, clusterOptions);
    globalMarker = markers.slice();
    google.maps.event.addListener(markerCluster, 'clusterclick', function(cluster) {
var content = '';

// Convert lat/long from cluster object to a usable MVCObject
var info = new google.maps.MVCObject;
info.set('position', cluster.center_);

//----
//Get markers
var markers = cluster.getMarkers();

var titles = "";
//Get all the titles
for(var i = 0; i < markers.length; i++) {
    titles += markers[i].getTitle() + "\n";
}
//----

infowindow.close();
infowindow.setContent(titles); //set infowindow content to titles
infowindow.open(map, info);
});
  }

  function makeDiv(index, zoomLevel, content) {
    document.getElementById("sidebar").innerHTML += '
' + content + ' ' + index + '
';
  }

  function zoomIn(index, zoomLevel) {
    map.setCenter(globalMarker[index].getPosition());
    map.setZoom(zoomLevel);
  }
  google.maps.event.addDomListener(window, 'load', initialize);

Thank you

A: The key change was titles += markers[i].labelContent + "\n";. (You can use the dot notation or markers[i]["labelContent"] to refer back to any property you set). I also changed the part markers.push(markers), and that when zoom is changed the window disappears (because cluster number is likely to change)  Everything else looked great!
http://jsfiddle.net/ErYub/
<!DOCTYPE html>


text:
Q: How would a native speaker formulate this request? We went to a pet hospital because my dog was scratching her ears and they looked infected. I got a pill for my dog to take every day. And it worked.
So we continued to give her the pills until gone. I then returned for more pills.
They were out so we got a creme instead. But we had paid for the pill first and that was more expensive than the creme we got so they told me that I would get the money back the next time I come. And I went to that hospital again and wanted to ask for the money back.
But as you can see above my English is very childish and informal.
How would you make such a request clearly, simply and formally?

A: You could say:
The person who helped me here last time told me to come back and ask for a refund for some medication.
If you just say that, and wait, they will probably ask you some questions and try to find some information on your account.
If that didn't work, you could probably tell the whole story again, slowly and calmly.

A: You need to ask them either to refund the amount you overpaid or to credit that amount towards your current bill.
You overpaid the last time you were in.  You had attempted to refill a prescription and had paid for it, but the pills you requested were out of stock; so they gave you instead a less expensive alternative, a topical ointment, and told you that they would make the necessary adjustments the next time you came in.


text:
Q: Problem on installing new software on Eclipse Galileo Platform I want to install a subversion on my eclipse.
So I went to Help < Install New Software and when I pick the "Galileo - http://download.eclipse.org/releases/galileo" in the "Work with" dropdown, it tells me in the main box "No repository found at http://...".
It is appearing in my available software sites and when I test the connection it returns me an error saying Unknown host.
Can someone please help me, I really need to install that subversion :).
Anna

A: As mention in this thread, this could be a proxy issue:

I assume you mean you used a web browser to get that - if so, is it
  configured to use a web proxy? If your browser is using a proxy then
  you need to configure Eclipse to use one too (see the General/Network
  Connections preference page).

Since 3.5 Galileo, The Network Connection page has been changed to better show the current proxy configuration.

Now if you go to Preferences > General > Network Connections, you are able to see and change Eclipse proxy settings as well as see settings provided by the operating system.
  If you want to use your browser or Gnome settings, or you have your proxy configured using environmental variables on Linux, you can see them all in this new UI

So to set your proxy, you can follow this tutorial (How to configure Proxy Settings in Eclipse)

A: The severity of the bug is downgraded, since there is a workaround. Open the eclipse.ini file and add the following
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient
In a few words the above command says that Eclipse can access the web via the *.pac files of the HTTP clients (eg Internet Explorer or Firefox).
To summarize:
Add the above line at the ini file
ensure that your default system http client (eg Internet Explorer) has proxy settings configured
Go to Eclipse Window->Preferences->Network Connection and enter the proxy setting here as well
It should work with this workaround

A: I'm not sure which Subversion client you use but neither of them can be installed from the main Galileo site. Follow the instructions on the web page of the Subversion plug-in how to install it.


text:
Q: Is it necessary to know ASP.NET before learning ASP.NET MVC 2? I've begun reading an excellent book on ASP.NET MVC 2 by Manning Press.  In the early part of the book, the authors imply understanding ASP.NET 3.5/4.0 is good for building ASP.NET MVC 2 concepts on top.  I am an intermediate developer - should I cover ASP.NET first or can I get by ?
Thanks,
Scott

A: Knowing HTML, JavaScript, CSS and obviously C# or VB is all you need to be a kickass MVC developer. It also helps to know some stuff about how a webserver works internally when you want to do some more advanced stuff.
But ASP.NET Webforms on it's own? No you don't need that knowledge AT ALL to start developing in MVC.

A: No doubt, You can directly go for MVC but if you have knowledge of general asp.net then it will be very help full to you in MVC. because availability of help and tuts for general asp.net application is much higher than MVC.

A: Go for it as you are now. Yes, it would help to have a background in ASP.NET WebForms, but you'll do fine just keeping in mind that there is this other 'thing' out there which is going to be referenced a lot as you read about ASP.NET MVC.

A: The biggest advantage would be knowing C# or VB.NET. ASP.Net and MVC are yet very different in how to use it. but also have similarities. if you want to study MVC, you don't need to learn asp.net at first, because it'll only confuse you. and it is not very nescesary.
The things you'll learn or should learn to make a good/great MVC application are C#, Linq and jQuery.
ofcourse this is just my opinion.

A: You'll pick plenty of some bad habits if you learn asp.net by itself. Some devs have trouble unlearning those when moving to asp.net MVC.
imho learning it in the context of asp.net MVC should reduce those. Can't really tell for sure, since I worked with asp.net since 1.0, so I knew it pretty well before moving to asp.net MVC.

@eglasius: well i dont agree on the long run. if you want to be a decent developer you need to know the underling technologies. and asp.net is not rocket science ;-) – Yves M

I think that's actually an argument for not learning asp.net by itself. I've seen devs learn asp.net and not knowing much of the underlying technologies, and imho asp.net MVC makes a much better job at encouraging you to know about http, html, css, ajax, etc.
Dig into the pieces of asp.net that you work with in asp.net / Session, Cache, anything that you end up using. Not much point in learning about aspx syntax and controls, if you will go with a different View Engine. Also there are some parts of the control lifecycle that's just noise when you are just working with aspx/ascx in asp.net MVC.

Gathering prior knowledge for LINQ, WCF and ADO.NET data services, JSON, Entity Framework, etc. (part of .NET 3.5/4.0 framework) can help you tremendously when you advance towards the ASP.NET MVC development path. At least that is my opinion. – Dick Lampard

Definitely. You are more likely to learn JSON by going into asp.net MVC than by going web forms. When learning asp.net you risk further obscuring data access in the learning experience by using the Data Source controls (we didn't had those in asp.net 1.0 :)). As for the rest, those are more neutral pieces of the framework, you could be developing desktop applications and be learning those. I agree with the thinking that knowing those are skills that transfer very well, but you don't need to go to asp.net to learn those / doing so in the context of asp.net MVC is perfectly ok.

A: Do you need to know ASP.NET WebForms? No, because you'll be using MVC for your presentation.
Would it be useful to know all the other bits that are in ASP.NET? Absolutely.
You should think of ASP.NET as a whole platform - WebForms and MVC are only two pieces, there's lots of other pieces of functionality built into the platform that are useful regardless of your presentation technology - membership, caching etc. Those presentation-agnostic pices are what you should concentrate on.


text:
Q: WPF: Listbox custom items unable to auto size I have a listbox with dynamically added items which are custom user controls (PriceGroupControl).
I am trying to resize that custom user control based on the size of the parent, but it always has a fixed size not related to the size of the listboxitem as far as I can see and resizing just clips the control.
I am using a similar control in a grid and that resizes perfectly.
My page has a grid, the first row has a combobox, the second has the custom control that resizes and the third row has a scrollviewer with a listbox in it. Since the listbox items are quite large and dynamically added, I use the scrollviewer.
The reason why I use a listbox is that, because based on the selected item, the content of the custom control on the second row of the grid is updated.
In XAML:
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="2*"/>
            <RowDefinition Height="5*"/>
        </Grid.RowDefinitions>
            <StackPanel Margin="12" Grid.Row="0">
                <ComboBox Name="comboBoxPriceGroups" ItemsSource="{Binding Groups}"
                   SelectedValuePath="GroupName"
                 Width="250" SelectionChanged="comboBoxPriceGroups_SelectionChanged">
                    <ComboBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding GroupDescription}" />
                            </StackPanel>
                        </DataTemplate>
                    </ComboBox.ItemTemplate>
                </ComboBox>
            </StackPanel>
            <Frame x:Name="ModPriceFrame" NavigationUIVisibility="Hidden" Grid.Row="1" Margin="10"/>
        <ScrollViewer Grid.Row="2" VerticalScrollBarVisibility="Auto">
            <ListBox x:Name="PriceListBox" Margin="10" Background="{StaticResource BackgroundLightBrush}" BorderThickness="0" SelectionChanged="PriceList_SelectionChanged"/>
        </ScrollViewer>
</Grid>

The way I bound my listbox content to the listbox is the following:
List<PriceGroupControl> priceGroupControls = new List<PriceGroupControl>();
foreach (GroupDetail detail in groupDetails)
 {
      priceGroupControls.Add(new PriceGroupControl(detail.GroupName, detail.GroupDetailDescription));
 }

 PriceListBox.ItemsSource = priceGroupControls;

I have tried the following:

*

*listbox: width set to auto in XAML, width = double.NaN code behind

*my custom control: horizontalAlignment = stretch, horizontalContentAlignment = stretch, width = double.NaN.

*bind a list of listboxitems with each listboxitem having a pricegroupcontrol.

If I put an actual number e.g. 1000 as the minimum width of pricegroupcontrol, it sizes to this width and looks more normal (now everything is cramped together in the minimum space needed), but obviously doesn't resize with the screen.
I am fairly new to WPF, so maybe I am missing the obvious.
I have used the live visual tree to get an idea which part is causing the issue and this seems to indicate that it is the PriceGroupControl that is too small, while the listbox is the size of the screen.
Any help would be appreciated.