text:
Q: How do i fix the function displayBal? Okay so everytime i run the code and creates an infinite loop, but within that infinite loop the balance is displaying this huge number:
Balance = $-92559631349317830736831783200707727132248687965119994463780864.00
when i need it to display
Balance = 2000
// Author:
// Source file:
// Description:
// Compiler used:

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

struct records
{
    int code;
    double amount;
};
// Function Prototypes
void displayTitle();
double getBegBal(ifstream&);
void displayBal(records);
records getData(ifstream&);
double processCheck(double, double);
double processDeposit(double, double);
double processATM(double, double);
double processSvcChg(double);

//Global Constants
const double    CHARGE = 10,
ATMFEE = 2;

int main()
{
    //Variable Declarations
    int transCode;
    double balance,
        transAmt;

    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    records trans;
    ifstream inFile;
    inFile.open("c:\\checkIn.dat");

    displayTitle();
    balance = getBegBal(inFile);
    getData(inFile);

    while (!inFile.eof())
    {
        trans = getData(inFile);

        switch (trans.code)
        {
        case 1: balance = processCheck(balance, trans.amount); break;
        case 2: balance = processDeposit(balance, trans.amount); break;
        case 3: balance = processATM(balance, trans.amount); break;
        }
        displayBal(trans);
        if (balance < 0)
            balance = processSvcChg(balance);
        getData(inFile);
    }

    return 0;
}

void displayTitle()
{
    cout << "\n       Check Register\n\n";
}

double getBegBal(ifstream& inFile)
{
    //double bal;
    records balance;
    inFile >> balance.amount;
    displayBal(balance);
    return balance.amount;
}

void displayBal(records rec)
{
    cout << "\t\tBalance = $" << setw(10) << rec.amount;
}

records getData(ifstream& inFile)
{
    records rec;
    inFile >> rec.code >> rec.amount;
    return rec;
}

double processCheck(double bal, double amt)
{
    records trans;
    trans.amount = 0;
    cout << "\n  Check =    " << setw(10) << trans.amount;
    return (bal - amt);
}

double processDeposit(double bal, double amt)
{
    records trans;
    trans.amount = 0;
    cout << "\n  Deposit =  " << setw(10) << trans.amount;
    return (bal + amt);
}
double processATM(double bal, double amt)
{
    records trans;
    trans.amount = 0;
    cout << "\n  ATM     =  " << setw(10) << trans.amount;
    bal = bal - amt;
    displayBal(trans);
    bal = bal - ATMFEE;
    cout << "\n  ATM Fee =  " << setw(10) << ATMFEE;
    return (bal);
}
double processSvcChg(double bal)
{
    records trans;
    trans.amount = 0;
    cout << "\n  Service chg =" << setw(8) << CHARGE;
    bal = bal - CHARGE;
    displayBal(trans);
    return (bal);
}

also here is the data file it is suppose to read from
2000 1 1225.72 1 463.81 3 200 1 632 2 1500 1 300 2 1800

A: You are not checking for errors. Try while (inFile) instead of while (!inFile.eof()). You might want to consider dropping some assert(inFile) after every read to make sure it actually worked.


text:
Q: Merging tesselating regions depending on size? I have the following regions marked up over map

Each region has assicated statistical data.
The problem is that sizes of these regions are very different. Some regions are very big and another ones are very small.
Obvious idea is to hierarchically merge regions so that at each zoom we will approximately same size of aggregated regions.
Are there any algorithms for this task?
The problem is that regions are not adjacing ideally, they can slightly overlap or have gaps between them.
I tried the followng approach:

I considered a grid (the same grid as web merkator use for tiles) at given zoom and assigned each region to closest grid point (closest to each centroid). Then I grouped region by grid points and joined them at some zoom.
Unfortunately, this produced bad results. A lot of regions of strange shapes and with holes appeared.
What can be suggested as better approach?

A: The approach I would take is to merge them based on an underlying grid.
The best grid would be when your regions have some parent that they would fit in (e.g. neighbourhoods fit into districts, postal codes or census blocks). If you don't have them you can take a regular grid like hexagons or squares.
Your small polygons would be merged based on their centroid falling into one of the gridcells and for every zoomlevel you would use a more coarse grid.
Personally I would use postgis to solve this problem. Once you have the grid, it shouldn't be too much work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript: JSON 'for loop' The following Javascript displays in Safari but not Mobile Safari. Can anyone see any bugs?
$("#results").append(data);

var songdata = JSON.parse(data);

var i = 0;

for (i=0;i<=songdata.total;i++)
{
    alert(i);
    var songhtml = "

" + songdata.data[i].title + "

" + songdata.data[i].artist + "

" + songdata.data[i].length + "

" + songdata.data[i].listen + "

";
    $("#results").append(songhtml);

}

Thanks in advance.

A: JSON.parse is not official Javascript, its not supported in all browsers. That could be your problem, but I don't have mobile safari to test it on.
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
Download this file and

A: I have to second MindStalkers comment. Id bet its your use of the non cross browser JSON.parse. In addition to that your loop structure looks suspicious - plus it doesnt make much sense to me to why you are using a standard loop instead of jQuery.each().

A: The for (i=0;i<=songdata.total;i++) looks suspicious to me. You're starting with zero, but continuing equal to or greater than total, so you're going to loop total + 1 times. (I take it this isn't a JavaScript/JSON array, as you're using total rather than length.)
If total tells you how many entries there are, and if the entries start at 0, then use just <. If the entries start at 1, do that. :-) But if you reference an invalid songdata[i], then songdata[i].artwork will fail because songdata[i] will be undefined.


text:
Q: Httplib2 : Processing Response String import httplib2
h = httplib2.Http(".cache")
resp, content = h.request("http://example.org/", "GET")

When I follow the examples in urllib2 to make a GET request to an API, how do I deserialize the return object?
For instance, I may have something like
'{"total_results": 1, "stat": "ok", "default_reviewers": [{"file_regex": ".*", "users": [], "links": {"self": {"href": "http://localhost:8080/api/default-reviewers/1/", "method": "GET"}, "update": {"href": "http://localhost:8080/api/default-reviewers/1/", "method": "PUT"}, "delete": {"href": "http://localhost:8080/api/default-reviewers/1/", "method": "DELETE"}}, "repositories": [], "groups": [], "id": 1, "name": "Default Reviewer"}], "links": {"self": {"href": "http://localhost:8080/api/default-reviewers/", "method": "GET"}, "create": {"href": "http://localhost:8080/api/default-reviewers/", "method": "POST"}}}'

However, the response above is a string. Is there anyway to convert it to an list for easier querying? Is this the correct idea behind making API calls (new to this) : to send a request with a HTTP API then parse the response assuming no API wrapper exists?

A: Use json.loads():
>>> import json
>>> mydict = json.loads(content)
>>> print mydict
{u'total_results': 1, u'stat': u'ok', u'default_reviewers': [{u'file_regex': u'.*', u'users': [], u'links': {u'self': {u'href': u'http://localhost:8080/api/default-reviewers/1/', u'method': u'GET'}, u'update': {u'href': u'http://localhost:8080/api/default-reviewers/1/', u'method': u'PUT'}, u'delete': {u'href': u'http://localhost:8080/api/default-reviewers/1/', u'method': u'DELETE'}}, u'repositories': [], u'groups': [], u'id': 1, u'name': u'Default Reviewer'}], u'links': {u'self': {u'href': u'http://localhost:8080/api/default-reviewers/', u'method': u'GET'}, u'create': {u'href': u'http://localhost:8080/api/default-reviewers/', u'method': u'POST'}}}

As for if it's a correct way: sure. If it works, then why not? Personally, I'd use the requests module:
>>> import requests
>>> resp = requests.get(URL)
>>> mydict = json.loads(resp.content)


text:
Q: Button can't click() on javascript if it has multiple button in one div/list I have problem that Button can't click() on javascript if it has multiple button in one div/list. In this case, "ADD" button doing nothing if i click it. But "Delete" button can. If i remove Delete function on js, add button work properly. What's wrong?
I have HTML like this

      <button class="btn btn-primary btn-sm btn-remove-coll" data-id='+data.id+'> Delete </button>
      <button class="btn btn-primary btn-sm btn-add-coll" data-id='+data.id+'> Add </button>

      <button class="btn btn-primary btn-sm btn-remove-coll" data-id='+data.id+'> Delete </button>
      <button class="btn btn-primary btn-sm btn-add-coll" data-id='+data.id+'> Add </button>

And JS function :

 var id ="";

 $('.coll-list').off('click').on('click','.btn-remove-coll', function(e) {
       id = $(this).data('id');

       // doing ajax thing
});

 $('.coll-list').off('click').on('click','.btn-add-coll', function(e) {
       id = $(this).data('id');

       // doing ajax thing
});

A: This problem happens because the second $('.coll-list').off('click') remove ALL on('click') event you have set before (i.e. on click on .btn-remove-coll, in this case).
You can try to change your off('click').on('click') order in your page and you'll see that will change the working button (or Delete or Add).
Here only remove button works

$('.coll-list').off('click').on('click','.btn-add-coll', function(e) {
  alert("add")
});

 $('.coll-list').off('click').on('click','.btn-remove-coll', function(e) {
  alert("remove")
});

      <button class="btn btn-primary btn-sm btn-remove-coll" data-id='+data.id+'> Delete </button>
      <button class="btn btn-primary btn-sm btn-add-coll" data-id='+data.id+'> Add </button>

      <button class="btn btn-primary btn-sm btn-remove-coll" data-id='+data.id+'> Delete </button>
      <button class="btn btn-primary btn-sm btn-add-coll" data-id='+data.id+'> Add </button>

And here add button only

 $('.coll-list').off('click').on('click','.btn-remove-coll', function(e) {
  alert("remove")
});

$('.coll-list').off('click').on('click','.btn-add-coll', function(e) {
  alert("add")
});

      <button class="btn btn-primary btn-sm btn-remove-coll" data-id='+data.id+'> Delete </button>
      <button class="btn btn-primary btn-sm btn-add-coll" data-id='+data.id+'> Add </button>

      <button class="btn btn-primary btn-sm btn-remove-coll" data-id='+data.id+'> Delete </button>
      <button class="btn btn-primary btn-sm btn-add-coll" data-id='+data.id+'> Add </button>

2 possible solution to make both buttons work are:

*

*Simply remove off('click')

*Combine your 2 clicks in 1 on('click')

$('.coll-list').off('click').on('click','.btn-add-coll, .btn-remove-coll', function(e) {

  if($(this).hasClass("btn-add-coll")){
    alert("add")
  } else {
    alert("remove")
  }

});

      <button class="btn btn-primary btn-sm btn-remove-coll" data-id='+data.id+'> Delete </button>
      <button class="btn btn-primary btn-sm btn-add-coll" data-id='+data.id+'> Add </button>

      <button class="btn btn-primary btn-sm btn-remove-coll" data-id='+data.id+'> Delete </button>
      <button class="btn btn-primary btn-sm btn-add-coll" data-id='+data.id+'> Add </button>

A: Try changing .coll-list from you JavaScript code with .coll_list because that is the class of you ul HTML tag.
Edit
It seems that it is impossible for some reason to have click functions for two different divs in the same
 tag. I'd sugges you to change the HTML markup a bit, and use the
 tag instead of
. Fiddle: jsfiddle.net/xpvt214o/592987


text:
Q: Can I avoid arrow keys and use any other shortcut that might be easy to access from home keys I'm using Dvorak layout, during programming or writing, it's difficult for me to move my hands from home keys to arrows key again and again, so can I create a shortcut such as Ctrl+shift+alt+h that'll alternative to left arrow key, and Ctrl+shift+alt+s alternative to right arrow?
Accessing to arrow key distract my focus from screen, and I'll have to look at the keyboard again and again, sometimes I even forget what was I about to write.

A: I use 3rd layer symbols and assign arrows to letters hjkl.

*

*Install gnome-tweaks tool

*Inside gnome-tweaks, go to Keyboard & Mouse → Additional Layout Options → Key to choose the 3rd level and choose "Caps Look".

*Then open your terminal and go to /usr/share/X11/xkb/symbols/. There are all keyboard layouts stored on your computer.

*Make a backup of your layout
cp us us_old

Modify file as root
sudo nano us

Third values in arrays are your keys:
key <AC01> {[a,A,Home]};
key <AC02> {[s,S,BackSpace]};
key <AC03> {[d,D,Delete]};
key <AC04> {[f,F,End]};
key <AC05> {[g,G]};
key <AC06> {[h,H,Left]};
key <AC07> {[j,J,Down]};
key <AC08> {[k,K,Up]};
key <AC09> {[l,L,Right]};

A: EDIT : IT DOESN'T WORK
Don't downvote, I keep it here until someone could take that workaround to work with some kind of keybinding. I'll delete it when that time has come

Take a look at xdotool and its documentation.
 $ apt show xdotool
Package: xdotool
Version: 1:3.20160805.1-4
Priority: extra
Section: universe/x11
Origin: Ubuntu
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Daniel Kahn Gillmor <dkg@fifthhorseman.net>
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Installed-Size: 125 kB
Depends: libc6 (>= 2.15), libx11-6, libxdo3 (>= 1:3.20150503.1)
Homepage: https://github.com/jordansissel/xdotool/
Task: ubuntu-budgie-desktop
Download-Size: 41.5 kB
APT-Sources: http://fr.archive.ubuntu.com/ubuntu focal/universe amd64 Packages
Description: simulate (generate) X11 keyboard/mouse input events
 xdotool lets you programmatically (or manually) simulate keyboard
 input and mouse activity, move and resize windows, etc. It does this
 using X11's XTEST extension and other Xlib functions.

sudo apt install xdotool
You can then bind xdotool commands with these commands in Setting > Keyboard shortcut.

In your case, the xdotool patterns would be :
xdotool key Left
xdotool key Right

For up and down, it's... Up and Down

A: To make things simple:

*

*Go to your system-settings(in Ubuntu) and choose Devices (i think, 'Apparaten' in Dutch) in the leftside panel, or just type 'keyboard' in Search;

*Select 'Keyboard & Mouse' and look for Keyboard 'Shortcuts' panel and make new or change old shortcuts on the fly.


text:
Q: How to loop through an object in smarty I have a script which is passing an object array to smarty like so:
$smarty->assign('results', $user->results());

The array looks like this:
Array
(
[0] => stdClass Object
    (
        [id] => 1
        [agency_name] => Agency #1
        [created_date] => 2015-03-25 20:23:44
    )

[1] => stdClass Object
    (
        [id] => 2
        [agency_name] => gggg
        [created_date] => 2015-03-25 21:26:06
    )

)

How can I loop through this object array using smarty?  I have tried something like this, with no luck..
{section name="i" loop=$result}
{$result[i]->id}
{/section}

Any ideas?
Thanks

A: // In smarty you can loop through your array like this:
{foreach from=$results item=result}
{$result->id}
{/foreach}

// You can also use "key=xx" and a "{foreachelse}" before the end of the loop in case there's nothing inside the array.

A: I managed to get it working using smarty assign_by_ref
$smarty->assign_by_ref('object', $object)


text:
Q: Union all not returning data I have this below query not returning results, but both select statements are returning results separately. Also if both where clause are removed, the union query does return the data. I can't tell what I'm missing.
select col1, col2, col3 , 'A' AS type from table1 where col4 = 'A'

union all

select col1, col2, col3, 'B' AS type from table1 where col5 = 'B'

In the above query table1 is a common table expression defined prior to this statement.

A: Or, you could simply use:
SELECT
  col1,
  col2,
  col3,
  CASE WHEN col4 = 'A' THEN col4
       WHEN col5 = 'B' THEN col5
       END as type
FROM table1
WHERE col4 = 'A' OR col5 = 'B'

This will only show each row once, whereas your query might have shown the same row multiple times if col4 = 'A' AND col5 = 'B'.


text:
Q: Variadic template function where return type depends on template argument list I am getting a "wrong number of template arguments (2, should be 1)" error that I can't really understand.
I have a class that provides some helper function for other types that want to interact with it, setting a first template parameter on which they must agree to be compatible with each other automatically on creation. In order to do this in a convenient, general way, I decided to go for a variadic template, that is intended to both be passed constructor arguments and additional template arguments the object type that is to be created takes:
template<typename INTERNAL_TYPE>
class Linker
{
  template< template<typename, typename ...> class INPUT_OBJ_TYPE, class ... TEMPLATE_ARGS, class ... CONSTRUCTOR_ARGS >
  std::shared_ptr< INPUT_OBJ_TYPE<INTERNAL_TYPE,TEMPLATE_ARGS ...> > getLinked( CONSTRUCTOR_ARGS ... args )
  {
    std::shared_ptr< INPUT_OBJ_TYPE<INTERNAL_TYPE,TEMPLATE_ARGS ...> > ptr = std::make_shared< INPUT_OBJ_TYPE<INTERNAL_TYPE,TEMPLATE_ARGS ...> >( args... );
    return ptr;
  }
};

This works for the following class:
template<typename INTERNAL_TYPE, typename SECOND_TYPE>
class TEST_CLASS_1
{};

That is, I can do the following:
Linker<int> container;
auto test_1 = container.getLinked<TEST_CLASS_1,double>();

Then I tried to do the same with another class that is only templated on one argument:
template<typename INTERNAL_TYPE>
class TEST_CLASS_2
{};
auto test_2 = container.getLinked<TEST_CLASS_2>();

But get the above mentioned error.. Why? Playing around with the code I figured as much as that it would compile for the second test (no more for the first one though) if I removed TEMPLATE_ARGS from the function declaration/definition. So I figured that the compiler at that point does not yet realize TEMPLATE_ARGS is empty for the second test and throws an error for having too many template arguments. So I thought I might need to use a trailing return type like
template< template<typename, typename ...> class INPUT_OBJ_TYPE,
          class ... TEMPLATE_ARGS, class ... CONSTRUCTOR_ARGS >
auto getLinked( CONSTRUCTOR_ARGS ... args )
    -> std::shared_ptr< INPUT_OBJ_TYPE<TREE_TYPE,TEMPLATE_ARGS ...> >

or using decltype but that didn't work either:
template< template<typename, typename ...> class INPUT_OBJ_TYPE,
          class ... TEMPLATE_ARGS, class ... CONSTRUCTOR_ARGS >
auto getLinked( CONSTRUCTOR_ARGS ... args )
    ->decltype(std::shared_ptr< INPUT_OBJ_TYPE<TREE_TYPE,TEMPLATE_ARGS ...> >())

Am I right about the problem? And how can I solve it?
Thanks a lot!

A: This might be a compiler bug.
A way to get what you want is to provide two functions, your original and another that doesn't have the non-deducible parameter pack:
template<typename INTERNAL_TYPE>
struct Linker
{
    template<
        template<typename, typename ...> class INPUT_OBJ_TYPE,
        class ... TEMPLATE_ARGS,
        class ... CONSTRUCTOR_ARGS
    >
    std::shared_ptr<
        INPUT_OBJ_TYPE<INTERNAL_TYPE,TEMPLATE_ARGS...>
    > getLinked( CONSTRUCTOR_ARGS ... args )
    {
        std::shared_ptr< INPUT_OBJ_TYPE<INTERNAL_TYPE,TEMPLATE_ARGS...> > ptr =
          std::make_shared< INPUT_OBJ_TYPE<INTERNAL_TYPE,TEMPLATE_ARGS...> >( args... );
        return ptr;
    }

    template<
        template<typename, typename ...> class INPUT_OBJ_TYPE,
        class ... CONSTRUCTOR_ARGS
    >
    std::shared_ptr<
        INPUT_OBJ_TYPE<INTERNAL_TYPE>
    > getLinked( CONSTRUCTOR_ARGS ... args )
    {
        std::shared_ptr< INPUT_OBJ_TYPE<INTERNAL_TYPE> > ptr =
          std::make_shared< INPUT_OBJ_TYPE<INTERNAL_TYPE> >( args...);
        return ptr;
    }
};

A: It appears that the initial substitution of TEST_CLASS_2 is hitting the compiler's "every valid specialization requires an empty pack" code path - that is, the following template is ill-formed, no diagnostic required:
template<class... TArgs, class... CArgs>
std::shared_ptr<TEST_CLASS_2<INTERNAL_TYPE, TArgs...>> getLinked( CArgs... args )
{
   /* ... */
}

because every valid specialization of it requires TArgs to be an empty pack. The initial substitution into getLinked will indeed result in something similar, but of course, you didn't actually write that template, so I'm not convinced that there should be an error, but whatever.
A possible workaround is to defer substitution of INPUT_OBJ_TYPE until after deduction, by taking a tag type and making everything deduced:
template< template<class, class...> class, class... > struct tag {};

template< template<class, class...> class INPUT_OBJ_TYPE,
          class... TArgs, class... CArgs >
auto getLinked(tag<INPUT_OBJ_TYPE, TArgs...>, CArgs... args )
    -> std::shared_ptr<INPUT_OBJ_TYPE<INTERNAL_TYPE,TArgs...>>
{
    /* ... */
}


text:
Q: Speeding up a large for loop using a parallel foreach I'm working on a project where I iterate over bins of the mouse genome and compute some overlaps using GenomicRanges/rtracklayer.  Bins are already computed in 150 base/position increments. For those who are not familiar, this means that for chromosomeY, which happens to be one of the shortest mouse chromosomes, there are approximately 106,000 bins and the larger chromosomes contain about 1,300,000 bins! The goal here is to iterate through the bins, expand the range of the bins 100,000 positions in both directions, then figure out which genes overlap these window. I want to compute the distance from the center of the bin to the start of the genes contained within the expanded bin window.
Okay so here's the code I've written to this point. It runs without error and computes exactly what I need. The problem here is that it is slow and will take forever to iterate through 1M+ bins.
progress <- function(w) {
  # just a function that prints out the window being processed
  cat(sprintf(paste0(as.character(Sys.time()), ": Window ", w, " completed!\n")))
}

extend <- function(x, upstream=0, downstream=0) {
# this will expand a `GenomicRanges` object range
  if (any(strand(x) == "*"))
    warning("'*' ranges were treated as '+'")
  on_plus <- strand(x) == "+" | strand(x) == "*"
  new_start <- start(x) - ifelse(on_plus, upstream, downstream)
  new_end <- end(x) + ifelse(on_plus, downstream, upstream)
  ranges(x) <- IRanges(new_start, new_end)
  trim(x)
}

feature.overlap <- function(x, window, genes, extend.upstream=100000, extend.downstream=100000) {

  # # test case
  # x = chrY; window = 2668 ; genes = gene; extend.upstream = 100000 ; extend.downstream = 100000

  # extend window of signal in both directions
  x.window = extend(x[window], extend.upstream, extend.downstream)
  names(x.window) <- window

  # compute signal window overlap with genes
  overlaps <- subsetByOverlaps(genes, x.window)

  if(length(overlaps) == 0){

    values <- data.frame(signal_window=names(x.window),
                         signal_start=max(0, start(x.window)),
                         signal_center=max(0, start(x.window)) + floor((width(x.window) - 1)/2),
                         signal_end=end(x.window),
                         signal_score=x.window$score,
                         symbol=NA,
                         gene_id=NA,
                         gene_chr=NA,
                         gene_start=NA,
                         gene_end=NA,
                         gene_strand=NA)

  } else {

    hits <- findOverlaps(x.window, genes)
    s.idx <- unique(subjectHits(hits))
    q.idx <- unique(queryHits(hits))

    values <- data.frame(signal_window=names(x.window)[q.idx],
                         signal_start=max(0, start(x.window)[q.idx]),
                         signal_center=max(0, start(x.window)[q.idx]) + floor((width(x.window)[q.idx] - 1)/2),
                         signal_end=end(x.window)[q.idx],
                         signal_score=x.window$score[q.idx],
                         mcols(overlaps)[,c(2,1)],
                         gene_chr=chrom(genes)[s.idx],
                         gene_start=ifelse(strand(genes)[s.idx] == '+', start(genes)[s.idx], end(genes)[s.idx]) ,
                         gene_end=end(genes)[s.idx],
                         gene_strand=strand(genes)[s.idx])

  }

  return(values)

}

# Import data
library(rtracklayer)
merged_wig <- import.wig('~/file/linked/below.wig', format='wig', genome='mm9')
merged_wig <- keepSeqlevels(merged_wig, paste0('chr', c(seq(1,19), 'X', 'Y')))
chrY <- merged_wig[seqnames(merged_wig) == 'chrY']

# Generate gene info needed for computing overlap
library(TxDb.Mmusculus.UCSC.mm9.knownGene); library(Mus.musculus)
gene <- genes(TxDb.Mmusculus.UCSC.mm9.knownGene)
values(gene) <- merge(values(gene), as.data.frame(org.Mm.egSYMBOL), by='gene_id', all.x=T)
gene <- keepSeqlevels(gene, paste0('chr', c(seq(1,19), 'X', 'Y')))

# BEGIN LOOP GENOME WINDOWS *** TIME CONSUMING ***
window.overlaps <- list()
ptm <- proc.time()
for(i in 1:100) { # ideally 1:length(chrY) but this takes very long so I've only posted a few windows
  result = feature.overlap(chrY, i, gene, extend.upstream=100000, extend.downstream=100000)
  window.overlaps[[i]] <- result
  progress(i)
}
proc.time() - ptm
all.overlaps = do.call(rbind, window.overlaps)

The code above will run right our of the box with this file (88mb).
Here is my attempt to speed up the look using a foreach with the doParallel library:
library(foreach)
library(doParallel)
cl<-makeCluster(8)
registerDoParallel(cl)
ptm <- proc.time()
ls<-foreach(i = 1:100, chrY=chrY, gene=gene, .packages=c('rtracklayer', 'GenomicRanges')) %dopar% {
  result = feature.overlap(chrY, i, gene, extend.upstream=100000, extend.downstream=100000)
  progress(i)
  result
}
proc.time() - ptm
stopCluster(cl)

But, this codes does not work. The error returned is Error: this S4 class is not subsettable and no output is produced from progress(). ERROR FIXED - SEE EDIT
Again, the goal here is to write this in a more efficient manner. Once I have values I can easily compute the metrics I need.
Any help would be much appreciated! Thank you!
EDIT: I've implement a working foreach loop with dopar, but it seems to be even slower than the above implementation.
library(foreach)
library(doParallel)
cl<-makeCluster(8)
registerDoParallel(cl)
ptm <- proc.time()
ls <- foreach(i = 1:100, .combine='rbind', .packages=c('rtracklayer', 'GenomicRanges')) %dopar% {
  result = feature.overlap(chrY, i, gene, counts, extend.upstream=100000, extend.downstream=100000)
  progress(i)
  result
}
proc.time() - ptm
stopCluster(cl)

For 100 windows this takes about 10 seconds whereas the same windows being processing with the for loop above takes 6 seconds.

A: Okay, I managed to run your code.

*

*For 100 runs, it takes

*

*6 sec with ncores = 1

*7 sec with ncores = 2

*8 sec with ncores = 3

*10 sec with ncores = 4

*For 1000 runs, it takes

*

*56 secs to run sequentially

*33 sec with 2 cores

*33 sec with 3 cores

So, basically, the 7 sec you see is due to overhead of parallelization. So the more you do, the more it will be useful to parallelize.
Then, what we can verify here, it is often inefficient to use more than half of the cores you have on your computer. So, if you have 8, you should use only 4.
Finally, if you have a very long loop, don't use the .combine parameter because it will take blocks of 100 and combine them, which is slow. If you can, just do a Reduce at the end.


text:
Q: how to create datatype to get email as input from user in java I want to accept email id from the user as an attribute like other attributes like name, id etc. What is the procedure to create custom data type to accept email id from the users?

A: *

*Store e-mail in String.

*Validate it using regex.

Ref :
http://www.regular-expressions.info/java.html
http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/
https://stackoverflow.com/a/16524798/3603806


text:
Q: Is it correct to use "insultive" in place of "insulting" So I was watching a video on youtube (https://youtu.be/hfXXbmTpkrw?t=377) where the "host" of the show (I don't know if you can call him that) is commentating on a video of a famous youtube personality being offensive to one of his fans. He uses this sentence:

(the "host" of the show): He's being incredibly insultive to the guy.

Now, why didn't he use the adjective insulting to refer to the guy, as in:

He's just being incredibly insulting to the guy.

Mind you, I wasn't able to find a definition of the word "insultive" in many well-known dictionaries online such as, Cambridge, Collins, Or Webster, but some lesser known dictionaries provid a definition, stating that it's synonymous with insulting.
Also https://en.wiktionary.org/wiki/insultive says about it:

This word (insultive) is about 0.01% as common as insulting and does not appear in most dictionaries.

I also did an Ngram look-up which confirmed the above.
is the use of "insultive" totally and utterly wrong? should it be avoided?

A: The speaker seems to be thinking too hard. He is describing the description and in doing so has built a word in the process. Rather than insulting he has come across insultive. A description of the tendency attributed to the host.
From Dictionary.com;
In using a suffix of adjectives (and nouns of adjectival origin) expressing tendency, disposition, function, connection, etc.:
active; corrective; destructive; detective; passive; sportive.
and no doubt restive.


text:
Q: Enable logging for a website via a script I'm looking for a way to enable or disable logging for an IIS 6 web site via adsutil.vbs.  Does anyone know which property I need to set?
Thanks
Neil

A: You can enable/disable logging for the entire W3SVC service using the LogType property.  Set it to 0 to disable logging.  This command would disable logging for the W3SVC web service.
cscript.exe /nologo adsutil.vbs SET W3SVC/LogType "0"

You can also exempt specific child directories or files from logging using the DontLog property.  Details for that can be found here.
Furthermore, you can specify logging at a much more granular level with the adsutil.vbs script and choose specific properties to log using the LogExtFileFlags parameter and corresponding bitmasks.  Just add the values of the bitmasks found here and set the LogExtFileFlags property.  For example, the following would enable LogExtFileDate, LogExtFileTime, and LogExtFileHttpSubStatus (1 + 2 + 2097152 = 2097155)
cscript.exe /NoLogo adsutil.vbs SET W3SVC/LogExtFileFlags "2097155"


text:
Q: Convert html special characters into numeric codes with PHP Let's say I have a string
$a = "à".
I want to convert it to html entities.
$b = htmlentities($a); // à

Instead, I want it to be converted to its numeric version: "à"
How can I do that?

A: Expanding on my comment: Look at http://php.net/manual/en/function.ord.php
$a = "à";
$b = ord($a); //224


text:
Q: If a cell is not null return the value in column 'a' in a different tab I have a list of products listed on one worksheet where you can select how many of each you want, but not every product will have a value. In a separate worksheet I want it to only pull over the product that have a amount selected.  Please Advice.
First Worksheet:
A        B

a        3

c       45

d

e

f       10

Desired Second Worksheet:
A       B

b       3

c      45

f      10

A: You can get what you want with a simple VBA subroutine:
Sub notNull()
    Dim count As Integer
    count = Application.WorksheetFunction.CountA(Range("A:A"))
    Dim i As Integer
    i = 1
    Dim rowCount As Integer
    rowCount = 1
    Do While i <= count
        If (Range("B" & i) <> "") Then
            Worksheets("Sheet2").Range("A" & rowCount) = Range("A" & i)
            Worksheets("Sheet2").Range("B" & rowCount) = Range("B" & i)
            rowCount = rowCount + 1
        End If
        i = i + 1
    Loop
End Sub

What it does is it goes through all of the rows with data in column A, checks if the associated value in column B is equal to "", and if it isn't, it copies over both values onto another sheet.  Hope this helps!

A: You could use a VBA subroutine to achieve this, if you/your end user is allowed macros.  In the example below I'm assuming you haven't renamed the worksheets and they're called "Sheet1" and "Sheet2" respectively - if you've renamed them you'll have to change them in the code to match.
1) Show the developer toolbar:
[http://www.traineetrader.com/excel-quick-tips-howto-enable-the-developer-toolbar-in-excel-20102011/][1]
2) On the developer toolbar click insert, then add a button (doesn't matter where)
3) right click the button and 'Assign Macro' then click 'New'
4) this code should do it:
Sub Button1_Click()

Dim row As Integer

row = 1
newrow = 1

Do Until Worksheets("Sheet1").Cells(row, 1).Value = ""

    If Worksheets("Sheet1").Cells(row, 2).Value <> "" Then

    Worksheets("Sheet2").Cells(newrow, 1).Value = Worksheets("Sheet1").Cells(row, 1).Value
    Worksheets("Sheet2").Cells(newrow, 2).Value = Worksheets("Sheet1").Cells(row, 2).Value

    newrow = newrow + 1

    End If

row = row + 1

Loop

End Sub

Any questions - let me know!


text:
Q: Remove SOQL query inside a loop I am coding a HttpPatch and I need help to remove the query inside the loop (line 13). Is it possible?
 @HttpPatch
global static void EstablishmentUpdateDelete(
    String actionType,
    String cuit,
    List<Establishment> establishments
){
    RestRequest req = RestContext.request;
    RestResponse res = RestContext.response;
    Account acc = [SELECT Id FROM Account WHERE CUITCUIL__c =:cuit];
    //String establishmentCode = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

    for (Establishment est : establishments) {
        List<Establishment__c> ests = [SELECT Id, Cobro_Anticipado__c, EstablishmentCode__c
                                      FROM Establishment__c
                                      WHERE EstablishmentCode__c =:est.establishmentCode AND Account__c =:acc.Id];

        if(ests.size() > 0){
            if(actionType == 'A'){
                ests.Codigo_de_Tasa__c = '67';
                ests.Cobro_Anticipado__c = true;
                if(ests.Cobro_Anticipado__c != CA){
                    ests.Alta_Baja_CobroAnticipado__c = system.today();
                }
                res.statusCode = 200;
                update ests;
            } else if(actionType == 'B'){
                ests.Codigo_de_Tasa__c = null;
                ests.Cobro_Anticipado__c = false;
                    if(ests.Cobro_Anticipado__c != CA){
                        ests.Alta_Baja_CobroAnticipado__c = date.today();
                    }
                    res.statusCode = 200;
                    update ests;
            }
        }else{
            WrapCuitNotFound accNotFound = new WrapCuitNotFound();
            accNotFound.message = 'Establecimiento no econtrado';
            res.responseBody = Blob.valueOf(JSON.serialize(accNotFound));
            res.statusCode = 200;
        }
    }
}

A: You can remove the query on the account and just use SOQL for loop, use the set or map to filter records based on your requirements -
Set<String> establishmentCodes = new Set<String>();
for(Establishment estCode : establishments) {
    establishmentCodes.add(estCode);
}

OR if you need to maintain the mapping of Id to EstablishmentCode then you can create a map of Id -> EstablishmentCode__c like Map<Id,String> and filter your records by values of map and then check in your SOQL loop for existence of EstablishmentCode using the map for individual records.
for (Establishment est : [SELECT Id, Cobro_Anticipado__c, EstablishmentCode__c
                           FROM Establishment__c
                           WHERE EstablishmentCode__c IN: establishmentCodes
                           AND Account__r.CUITCUIL__c =:cuit]) {
    //Your code inside for loop
}

This will solve your problem.


text:
Q: Where should we ask questions tightly coupled with software but aren't debugging related? StackOverflow has been awesome for code related questions for me as well as my team. However, in the real world, software doesn't exist in isolation or in the context of only code - it's within the context of either a business or a higher purpose (eg: simplifying user Q&A paradigm). For many of those decisions, the question is more 'meta' than just code-questions "float or real?" but more high level; the kind of data more experienced dev / mature projects could very well share with others, in a Q&A format.
So where can one ask questions tightly coupled with software code itself? Real world, high level, software development questions that are as important (if not more) to any software project as specific questions about a few lines of code?
IMHO, StackOverflow is a great place because

*

*its "of programmers, by programmers and for programmers" approach is great for such related questions

*questions are tightly coupled, software development related (versus related-but-distant like "which software engineering role pays best?" or something)

*avoids too much fragmentation of software experts, developers and problems

However, that's my $0.02. I wanted to hear from others on what they feel is appropriate for the future.

A: Your examples, in order:

*

*https://stackoverflow.com/questions/9076462/different-ways-to-interface-with-sql-server-in-c-net
This question is "Not Constructive." I asked a Programmers.SE mod if it might be on-topic there, and he said: "'Most scalable' generally turns into 'Most favorite'. If there was a specific, observable metric he had in mind, maybe: but then I wonder if DBA would have better experts."

*https://stackoverflow.com/questions/9084856
This question is off-topic for Stack Overflow.  Programmer.SE sometimes entertains licensing questions, if they are specific.

*https://stackoverflow.com/questions/9090182/when-will-asp-net-mvc4-be-commercially-released
This question is extremely localized.  Only Microsoft possibly knows the answer, and once it's released, this question will be of no use to anyone.
From the FAQ:

What kind of questions should I not ask here?
Avoid asking questions that are subjective, argumentative, or require
extended discussion. This is not a discussion board, this is a place
for questions that can be answered!

See Also
https://blog.stackoverflow.com/2010/09/good-subjective-bad-subjective/

A: To your specific question:

Where can one ask questions tightly coupled with software code itself? Real world, high level, software development questions?

This is what Programmers.SE is for. From Introducing programmers.stackexchange.com:

In a nutshell, Stack Overflow is for when you're front of your compiler or editor working through code issues. Programmers is for when you're in front of a whiteboard working through higher level conceptual programming issues. Hence the (awesome) whiteboard inspired design!

The problem is, the examples you give are bad questions. We don't want them either, and if you had asked them on Programmers, they'd be closed for exactly the same reasons.

*

*https://stackoverflow.com/questions/9076462/different-ways-to-interface-with-sql-server-in-c-net
The meat of the question is "Which one is most scalable with increased end user traffic?" Scalable how? What specific performance metric are you looking for? What's your specific use case? If you're just looking for a broad comparison between three technologies, it's not going to go well here.

*https://stackoverflow.com/questions/9084856/gpl2-cherokee-web-server-project-setup-interestingly
The question asks, "Why on EARTH would you contribute to this project after reading that contribution agreement? Are existing contributors aware of this?" I don't know, have you asked them? Why not post your findings in the relevant discussion board or mailing list? This is more of an expression of surprise than an actual problem we can help with.

*https://stackoverflow.com/questions/9090182/when-will-asp-net-mvc4-be-commercially-released
If Microsoft isn't publishing exact dates on their roadmap, we don't know either. You'll have better luck contacting someone at Microsoft than asking random strangers on the internet for their best guess.
Real questions—or at least real questions on the Stack Exchange network—have answers: not ideas, speculation, or opinions. If you're looking for a place where people can riff about what's "most scalable", if a person was justified to use a license, or what the internal Microsoft roadmap might be, you'll likely be consistently disappointed.
But if you have a specific problem you're facing, and have specific metrics for determining the correctness of an answer, feel free to ask your high-level questions on Programmers.


text:
Q: How to write a whole LaTeX document in bf? How to write a whole LaTeX document in bold? I would like to print the pdf in bfseries. Is this possible to achieve by adding some code to the preamble or in the body of the LaTeX document?

A: pdfLaTeX answer
The optimum depends somewhat on the used font. For Computer Modern (the default font in LaTeX), there are no bold italics, only bold extended italics. So the optimum depends whether you're using \textbf to highlight things or \textit. If you're using \textbf then the best approach would be to use
\renewcommand\seriesdefault{b}

in your preamble. If however you're using \textit or \itshape in your document the usage of b as the series would result in no italics at all, as LaTeX would detect that b/it (bold italic) is not available and would use b/n (bold upright) instead. So if you want \textit and \itshape to work as expected you'd have to use
\renewcommand\seriesdefault{bx}

in your preamble.
In complete examples:
\documentclass[]{article}

\renewcommand\seriesdefault{b}

\begin{document}
Text (normal).

\textbf{Text (bold)}.

\textit{Text (italic)}.

\textit{\textbf{Text (bold italic)}}.
\end{document}

Results in

And
\documentclass[]{article}

\renewcommand\seriesdefault{bx}

\begin{document}
Text (normal).

\textbf{Text (bold)}.

\textit{Text (italic)}.

\textit{\textbf{Text (bold italic)}}.
\end{document}

Results in

However, if you by chance use a font that has both b/it and bx/it, then \renewcommand\seriesdefault{b} should be the best choice.

Using kpfonts as an example
The kpfonts family has a wide coverage of series and shape combinations (there might be others, but currently (2019-10-12) this happens to be my favourite font). The funny thing about kpfonts is that it comes in a light and a standard variant, and you can use both the light and the standard variant in combination if you specify the rmx option. So with kpfonts you have different viable combinations:

*

*Using b and bx:
\documentclass[]{article}

\usepackage{kpfonts}

\renewcommand\seriesdefault{b}
\renewcommand\bfdefault{bx} % just to make sure

\begin{document}
\begingroup
\usefont\encodingdefault\familydefault{m}\shapedefault\relax
Text (really normal), which would be used normally
\endgroup

Text (normal).

\textbf{Text (bold)}.

\textit{Text (italic)}.

\textit{\textbf{Text (bold italic)}}.
\end{document}

*Using sb and b
\documentclass[]{article}

\usepackage[rmx]{kpfonts}

\renewcommand\seriesdefault{sb}
\renewcommand\bfdefault{b}

\begin{document}
\begingroup
\usefont\encodingdefault\familydefault{m}\shapedefault\relax
Text (really normal), which would be used normally
\endgroup

Text (normal).

\textbf{Text (bold)}.

\textit{Text (italic)}.

\textit{\textbf{Text (bold italic)}}.
\end{document}

Of course you could also combine sbx and bx or sb and bx or however you like.

A: LuaLaTeX and XeLaTeX answer: Use the fontspec package
After loading the fontspec package, modify the arguments of the \setmainfont directive to specify Bold and BoldItalics as the default font shapes.
And, if needed, modify the arguments of the \setsansfont and \setmonofont instructions to obtain Bold and BoldItalics as the default font shapes for sans-serif and mono-spaced (aka "typewriter") font families.
This approach is not as challenging as it may seem like at first: If you're using the fontspec package, you may already have an instruction such as
\setmainfont{Times New Roman}[%
             ItalicFont=Times New Roman Italic,
             BoldItalicFont=Times New Roman BoldItalic]

in the preamble of your document. All you'll need to do, then, is add "Bold" in two places:
\setmainfont{Times New Roman Bold}[%
             ItalicFont=Times New Roman BoldItalic,
             BoldItalicFont=Times New Roman BoldItalic]

\documentclass{article}
\usepackage{fontspec}
%% Choose suitable font families and weights. E.g.:
\setmainfont{Times New Roman Bold}[%
             ItalicFont=Times New Roman BoldItalic,
             BoldItalicFont=Times New Roman BoldItalic]
\setsansfont{Helvetica Bold}[Scale=MatchLowercase,
             ItalicFont=Helvetica Bold Oblique]
\setmonofont{Consolas Bold}[Scale=MatchLowercase,
             ItalicFont=Consolas Bold Italic,
             BoldItalicFont=Consolas Bold Italic]

% pangram:
\newcommand\qbf{The quick brown fox jumps over the lazy dog.}

\begin{document}
\obeylines
\qbf
\textit{\qbf}
\sffamily
\qbf
\textit{\qbf}
\ttfamily
\qbf
\textit{\qbf}

\medskip
\rmfamily\bfseries
Explicit \texttt{\textbackslash bfseries} --- exactly the same as above:
\qbf
\textit{\qbf}
\sffamily
\qbf
\textit{\qbf}
\ttfamily
\qbf
\textit{\qbf}

\end{document}


text:
Q: Mail is not being delivered I am sending mail using SmtpClient. while attempting to send any-mail, I am getting success response. But mail is not getting delivered.
Dim mMailMessage As New Net.Mail.MailMessage

Dim client As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient("domain", 587)
client.EnableSsl = True
client.Timeout = 100000
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network
client.UseDefaultCredentials = False
client.Credentials = New NetworkCredential("username***", "password")

Dim msg As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
mMailMessage.[To].Add(pstrToMailid)
mMailMessage.From = New System.Net.Mail.MailAddress("frommailid")
mMailMessage.Subject = pstrSubject
mMailMessage.IsBodyHtml = True
mMailMessage.Body = text

If Not pstrfilenames Is Nothing Then
    Dim lint As Integer
    Dim larrattachment() As String
    larrattachment = Split(pstrfilenames, ",")
    For lint = 0 To larrattachment.Length - 2
        attachment = New Net.Mail.Attachment(larrattachment(lint))
        mMailMessage.Attachments.Add(attachment)
    Next
End If
client.Send(mMailMessage)


text:
Q: Determining object "type" during json deserialization While trying to de-serialize a complex JSON object (JIRA issue) into an object containing a dictionary of type string-Field I've hit a bit of a bump.
While I can de-serialize various pre-determined object types (standard), I'm having a bit of a harder time with the custom fields, which could be of various types (they all begin with customfield_ followed by a set of numbers).
The custom fields can be floats, strings, booleans, objects and arrays of objects. The latter of these is causing me issues since I can't seem to determine what the object is before I de-serialize it.
I've searched for a way to perhaps "peek" at the data in the object before de-serializing as one of the fields contains information specific to it's type. This is all so I can determine the type of the object and tell Json.Net what to de-serialize it as.
I've considered parsing the JSON string before serialization to get the information, or maybe just when hitting this particular case, but maybe there is a better way?
Thanks in advance for any advice on this.

A: You can deserialize to an object with Json.Net. Here's a quick and dirty example:
using System;
using Newtonsoft.Json;

namespace Sandbox
{
class Program
{
    private static void Main(string[] args)
    {
       var nestDto = new Dto
        {
            customfield_1 = 20,
            customfield_2 = "Test2"
        };

        var dto = new Dto
        {
            customfield_1 = 10,
            customfield_3 = new[] { nestDto },
            customfield_2 = "Test"
        };

        var jsonString = JsonConvert.SerializeObject(dto);
        Console.WriteLine(jsonString);

        var fromJsonString = JsonConvert.DeserializeObject<Dto>(jsonString);

        Console.WriteLine(fromJsonString.customfield_3[0].customfield_2); //Outputs Test2
        Console.ReadKey();
    }
}

class Dto
{
    public int customfield_1 { get; set; }
    public string customfield_2 { get; set; }
    public Dto[] customfield_3 { get; set; }
}
}

A: Instead of peaking, you can deserialize as the same type as JSON.net uses for ExtensionData explicitly. For example:
if (reader.TokenType == JsonToken.StartArray)
{
    var values = serializer.Deserialize<List<Dictionary<string, JToken>>>(reader);
    objectContainer = ClassifyAndReturn(values);
}

private ObjectType ClassifyAndReturn(List<Dictionary<string, JToken>> values)
{
    if (values.First().ContainsKey("self"))
    {
        string self = values.First()["self"].Value<string>();
        if (self.Contains("customFieldOption"))
        //... Then go into a series of if else cases to determine the object.

The representation of the objects are given as a Dictionary of string to JToken, which can then easily be checked and assigned manually or in some cases automatically deserialized (in the case one of the fields is another object).
Here is what an object constructor could look like:
internal myobject(Dictionary<string, JToken> source)
{
    Self = source["self"].Value<string>();
    Id = source["id"].Value<string>();
    Value = source["value"].Value<string>();
}


text:
Q: Trying to convert rewriterule regex into php regex with minimal regex modification I have the following in my httpd.conf:
RewriteRule ^galleries/?([0-9]{4})?([0-9]{2})?([0-9]{2})?([a-z0-9_-]+)?/?(image|thumbnail|page)?s?/?([A-Z]+)?([0-9]+)?\.?(.+)?$ whatever [NC,L]

When someone visits any of:
http://example.com/galleries/20140630ABC/image/x1.jpg
http://example.com/galleries/20140520DEF/image/x22.jpg

The regex is processed correctly and forwards the url to "whatever".
I then tried to create the PHP version of my regex with minimal modification. This was my first attempt using the test string on the 2nd line of my code:
<?php
$is="galleries/20140630ABC/image/x1.jpg";
$p='^galleries/?([0-9]{4})?([0-9]{2})?([0-9]{2})?([a-z0-9_-]+)?/?(image|thumbnail|page)?s?/?([A-Z]+)?([0-9]+)?\.?(.+)?$';
echo preg_match($p,$is,$mat);
print_r($mat);
?>

The above code produces this error:
Warning: preg_match(): No ending delimiter '^' found in /path/to/code.php on line 4

I then surrounded my regex with slashes inside quotes. My code then is this:
    <?php
    $is="galleries/20140630ABC/image/x1.jpg";
    $p='/^galleries/?([0-9]{4})?([0-9]{2})?([0-9]{2})?([a-z0-9_-]+)?/?(image|thumbnail|page)?s?/?([A-Z]+)?([0-9]+)?\.?(.+)?$/';
    echo preg_match($p,$is,$mat);
    print_r($mat);
    ?>

I received this error:
Warning: preg_match(): Unknown modifier '?' in /path/to/code.php on line 4

I'm probably using the wrong function, but I want to modify my regex as little as possible from the one I wrote in the apache configuration file when evaluating it in PHP. How do I fix this? or is it even possible?

A: With \ to escape /, it should be better. Try this :
$re = "/^galleries\\/?([0-9]{4})?([0-9]{2})?([0-9]{2})?([a-z0-9_-]+)?\\/?(image|thumbnail|page)?s?\\/?([A-Z]+)?([0-9]+)?\\.?(.+)?$/";
$str = "galleries/20140630ABC/image/x1.jpg";

preg_match($re, $str, $matches);
print_r($str);

check it here : https://regex101.com/r/vV2vC5/1


text:
Q: Clip tool does not update polygon areas in output in ArcGIS In ArcGIS I created a buffer of 500m around a point. Then, I clipped a land use layer using the 500m buffer as the clip feature. The outcome is shown in the figure.

My problem is that the layer appears to be clipped only visually: when I open the attribute table, the polygons are not clipped, but they keep their original areas. For example, the green polygon, representing the street, has an area of 276,660,000 m2, which is clearly not possible, being the total area of the buffer only about 745,250 m2.
How can I clip the my layer in a way that it also affects the attribute table?

A: In a shapefile, there is no automatically updated area field. All the attribute values remain unchanged after clipping, including the area field.
You must compute again the area of your polygons (right click on the field, then "calculate geometry" to update the area of your polygons.
Note that if you worked with a geodatabase, the shape_area field would be updated automatically.


text:
Q: How to create case in-sensitive associative array in AWK I am trying to create associative array but it is case sensitive. Is there any command from i can create case in-sensitive associative array in Awk.

A: Use tolower() when storing into the array:
arr[tolower($1)] = $2

and when looking something up in it:
print arr[tolower($3)]


text:
Q: Database Querying from Controller Returning Query not Values Vs'12, asp.net MVC4 Internet Application, EF Code First, MySQL db
Overview
I am trying to create a report with EPPlus from a Controller level. - User clicks button program gets here, i need to query the database for some information..
Explanation
I tried this way: Where intPR=1 as a passed in variable
var pro = from p in db.Prospect
        where p.ProspectID == intPR
        select p;
var cty = from c in db.Countys
        from p in db.Prospect
        where p.ProspectID == intPR
        select c;

then I would use something like this to set it to the field
string x = pro.Select(p => p.ProspectName).ToString();
          ws.Cells["E" + LineFeed].Value = x;

string xx = cty.Select(m => m.County).ToString();
          ws.Cells["E" + LineFeed].Value = xx;

All i get is the super long query string
"SELECT
[Extent1]...... You get the hint

Question
Why am i not getting values?

A: Since you're using LINQ, the expression only gets evaluated when the results are really needed. Note that select actually returns an IEnumerable or IQueryable. It's only if actually want to use the values that it executes the query. The default ToString() method just prints the query.
You could for example call the ToList() method to make sure the query is exectuted:
var prospects = pro.Select(p => p.ProspectName).ToList();

However, this will return a list of prospects, calling the ToString()-method on that would still yield just the name of the type. If you want the first item of the list you can do the following:
var firstProspectName = pro.Select(p => p.ProspectName).First():

EDIT: Your query could be written a bit more concise, without intermediate steps:
var firstProspectName = db.Prospect.where(p => p.ProspectID == intPR)
                                   .Select(p => p.ProspectName)
                                   .First();


text:
Q: MVC3: Return a View Object from a non-Controller class In a nutshell, I would like to simplify some of my MVC pages by creating a static class to get the data from a data store of some sort then return one of multiple views based on some internal flags.
internal static class StaticPageContent
{
    internal static ViewModels.Display GetPage(string Map = null, int? ID = null) {...}
    internal static ActionResult ReturnView(ViewModels.CMS.Display vm) {...}
}

Then, in any of my controller actions I could call it something like:
public ActionResult ActionName()
{
    var vm = StaticPageContent.GetPage("/Home");
    return StaticPageContent.ReturnView(vm);
}

Where the ReturnView() method would return one of multiple (shared) views:
internal static ActionResult ReturnView(ViewModels.CMS.Display vm)
{
    if (vm.useLoremIpsum)
        return View("LoremIpsum", vm);
    else
    {
        if (vm.canEdit)
            return View("ViewReadWrite", vm);
        else
            return View("ViewReadOnly", vm);
    }
}

What is the right way of returning a View(...) object from a non-Controller class?  The above will not compile as the View(...) is part of the Controller class.

NOTE:
I believe I got something like this working but the demands on my time sent me in another direction.  I am hoping to be able to open this project back up to see what I did and post it here.  Stay tuned!

A: Simply put, the right way is to not do it in a static class. (IMO, of course). Especially if you're getting "data from a data store" - this should not be static.
In my opinion, create a protected method in a base controller, or use child actions and render them out using Html.Action.

A: Just instantiate one, though I don't think I would recommend this.
http://msdn.microsoft.com/en-us/library/system.web.mvc.viewresult.aspx
var result = new ViewResult(){
    ViewName = "ViewReadWrite"
}
result.ViewData.Model = vm; // ViewData may need to be instantiated first.

return result;


text:
Q: .csv works fine, .tsv gives 'TypeError: expected string or buffer' I'm working on a python script to parse user agent strings and reduce them down to just the 'family' (i.e., chrome, firefox, safari, etc).
I've got a script that works completely fine when run against csv files, but when I run the files against .tsv files it gives me the following error:
TypeError: expected string or buffer
Anyone else run across this problem? Sample code is below.
import pandas as pd
import numpy as np
import glob as glob
from ua_parser import user_agent_parser as uaparser

#THIS WORKS FINE:

def parse_uagent():
    ua_list = []
    uadf = pd.DataFrame()
    for datafile in glob.glob("*.csv"):
        df = pd.read_csv(datafile, sep=',')
        df = df[['user_agent','date_time','user_name']]
        ua = df[df.columns[0]].values
    for line in ua:
        uagent = uaparser.ParseUserAgent(line)
        ua_list.append(uagent)
    uadf = uadf.append(ua_list)
    print uadf

#THIS GIVES AN ERROR:

def parse_uagent():
    ua_list = []
    uadf = pd.DataFrame()
    for datafile in glob.glob("*.tsv"):
        df = pd.read_csv(datafile, sep='\t')
        df = df[['user_agent','date_time','user_name']]
        ua = df[df.columns[0]].values
    for line in ua:
        uagent = uaparser.ParseUserAgent(line)
        ua_list.append(uagent)
    uadf = uadf.append(ua_list)
    print uadf

Traceback:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-92-14c05dc8ee13> in <module>()
     29
     30
---> 31 parse_uagent()
     32

<ipython-input-92-14c05dc8ee13> in parse_uagent()
     19         ua = df[df.columns[0]].values
     20     for line in ua:
---> 21         uagent = uaparser.ParseUserAgent(line)
     22         ua_list.append(uagent)
     23     uadf = uadf.append(ua_list)

/anaconda2/lib/python2.7/site-packages/ua_parser/user_agent_parser.pyc in ParseUserAgent(user_agent_string, **jsParseBits)
    247     else:
    248         for uaParser in USER_AGENT_PARSERS:
--> 249             family, v1, v2, v3 = uaParser.Parse(user_agent_string)
    250             if family:
    251                 break

/anaconda2/lib/python2.7/site-packages/ua_parser/user_agent_parser.pyc in Parse(self, user_agent_string)
     49     def Parse(self, user_agent_string):
     50         family, v1, v2, v3 = None, None, None, None
---> 51         match = self.user_agent_re.search(user_agent_string)
     52         if match:
     53             if self.family_replacement:

TypeError: expected string or buffer

A: Figured out the issue.. the ua-parser was failing when it came across empty cells. Removing all lines with NaN prior to parsing fixed the error.


text:
Q: PhpMyAdmin search returns row but Sql returns null when I search in the PhpMyAdmin an email of the style of
something@something.com

Using
LIKE %something@something.com%

It returns a row. But whenever I search it using an sql sentence, either from php or either executing the query from PhpMyAdmin
The query I'm using is
 SELECT * FROM tblMyTable WHERE field LIKE '%something@something.com%'

Can it be because of the @?
Thanks

A: Your query is fine. There must be something else wrong.
Try and simplify the query in phpMyAdmin, and search for a specific email address which you know is in the table:
SELECT * FROM tblMyTable WHERE field = 'something@something.com'

just to make sure that you are looking in the correct table, that the value you seek is there, and that everything is working more or less like it should

A: Got it to work with
SELECT * FROM  `tblTable` WHERE  `field` LIKE  '%something@something.com%'

For some reason without the ' in the table name and field name wasn't working


text:
Q: Add custome utility JAR to Windows System Path Is it possible to add a utility jar to Window's System Path?
I have findclass.jar that is an exicutable jar located in my C:\ directory.
If I open cmd.exe, change directories to C:\, and type:
java -jar findclass.jar \path\tojar.jar nameofclass.class
it will search another jar for a given class.
How can I add findclass.jar to my Window's System Path so I don't need to change directories to C:\?
I tried  set path=C:\;%PATH% and set path=C:\findclass.jar;%PATH%
but I get Error: Unable to access jarfile findclass.jar when I try to execute it from a different directroy.
Is it not possible to add a .jar file to the path?

A: Add it to CLASSPATH environment variable.


text:
Q: задержка перед PJAX плагином Помогите пожалуйста решить проблему: использую pjax плагин для перемещения между страницами навигации.
Все работает, но есть проблема - нужно сделать задержку перед переходом на другую страницу, т.к. не видно гифки загрузки, да и нужно определенную анимацию сделать перед таким переходом
Код main.js:
$(function() {

// jQuery PJAX
$(document).pjax('.navbar-brand, .description, .placement, .around, .genplan, .ipoteque, .gallery, .documents, .contacts', '#content', { fragment: '#content' });

$.pjax.defaults.timeout = 2500;

// .pjax - класс меню навигации
$('.pjax').bind('click', function() {
    $.ajax({
        beforeSend: function() {
            $('#content').on('pjax:beforeSend', function() {
                // LOADING
                $(".loading").addClass("show");

            });

            $('#content').on('pjax:success', function() {
                // END OF LOADING
                $(".loading").removeClass("show");
            });

            // Пробую запилить анимацию перед переходом pjax
            var anim = $('.center-block img').animate({
                    'margin-left': '1000px'
                }, 1000);
        }
    })
})

// Active links after click
$('.navbar-nav li').bind('click', function() {
    $('.navbar-nav li').removeClass('active');
    $(this).addClass('active');
})
$('a.navbar-brand').bind('click', function() {
    $('.navbar-nav li').removeClass('active');
})

})

я уже пытался всевозможными способами: сначала менял опцию timeout у плагина, потом пробовал перед нажатием на ссылку меню сделать ajax-запрос, и осуществить в php с помощью sleep() задержку, но в пустую.
Пример: http://www.lisles.ru/
В общем, как новичек, буду очень признателен за помощь!


text:
Q: Too many rows when Joining to same table twice I have two tables, Product and Benchmark
A benchmark is linked to only one product. There can only be one benchmark per year per product.
I would like to retrieve every products' name for a set of years, and count how many benchmark there are for each product.
SELECT p.name,
       p.id,
       COUNT(p.id) AS nb_benchmark
FROM product p
INNER JOIN benchmark b0 ON b0.product_id = p.id
INNER JOIN benchmark b1 ON b1.product_id = p.id
WHERE p.owner = "MyCompany"
  AND b0.year = 2011
  AND b1.year = 2012
GROUP BY p.id
ORDER BY nb_trials DESC

But the count is wrong, it's way to high, it even gives me more results than there actually are in the database. I guess it's because of the JOINs, but I don't know how to build the query.

A: Remember that the basis of SQL joining is the cartesian product of rows in the referenced tables, which are then eliminated by filters and join conditions. Because you are joining TWICE to table benchmark, which from the nature of your query, we can assume has many benchmark rows per product per benchmark year.
e.g. 1 Product with 3 Benchmark rows each for 2011 and 2012
FROM product p -- 1 Product Row
INNER JOIN benchmark b0 ON b0.product_id = p.id -- 1 x 3 = 3
INNER JOIN benchmark b1 ON b1.product_id = p.id -- 1 x 3 x 3 = 9

So the multiple joins to benchmark introduces duplicate rows for product, which are then counted.
You can use COUNT(DISTINCT xx) to count distinct values, so your query should be of the form:
SELECT p.name,
       p.id,
       COUNT(DISTINCT p.id) AS distinct_products,
       COUNT(DISTINCT b.name) AS distinct_benchmark_names
       -- etc
FROM ...

Other Notes

*

*for correctness sake you should  GROUP BY both p.id and p.name. Although MySql allows this, other RDBMS are more strict.

A: Try this:
SELECT p.name,
       p.id,
       COUNT(b0.id) AS nb_benchmark
FROM product p
INNER JOIN benchmark b0 ON b0.product_id = p.id
WHERE p.owner = "MyCompany"
  AND b0.year IN (2011, 2012)
GROUP BY p.name, p.id
ORDER BY nb_trials DESC

A: I have found a way to achieve what I wanted
      SELECT p.name, p.id,  COUNT(DISTINCT(b0.id)) + COUNT(DISTINCT(b1.id))  as     nb_benchmark
      FROM product p
      INNER JOIN benchamrk b0 ON b0.product_id = p.id AND b0.year = 2011
      INNER JOIN benchamrk b1 ON b1.product_id = p.id AND b1.year = 2012
      WHERE
      p.owner = "myCompany"
      GROUP BY p.id
      ORDER BY nb_benchmark DESC

A: Try this.
SELECT p.id, p.name, b.nb_benchmark
FROM product p
JOIN (
    /* number of benchpark per product for years 2011 and 2012 */
    SELECT product_id, COUNT(*) AS nb_benchmark
    FROM benchmark
    WHERE year = 2011 OR year = 2012
    GROUP BY product_id
) b ON p.id = b.product_id
WHERE p.owner = "MyCompany"
ORDER BY nb_benchmark DESC


text:
Q: What do you call the table/counter surrounding a sushi conveyor belt? I'm referring to these kind of structures (the part where customers put their plates and eat).

At first, I thought about "group tables," but now that I think of it, they could also be called bars? Or maybe there's another more common or accurate term?

A: In AmE that is called a counter.

Would you like to sit at a table or at the counter?

The entire assemblage, including the preparation area, is "a sushi bar".
I suppose there may be some speakers who would say:

I'd like to sit at the bar.

but I've never heard that phrase used in sushi-style restaurants in the US, though it is very common in other kinds of restaurants that serve primarily alcoholic beverages at a bar but also serve food there.


text:
Q: Possible measurements of an observable described by an operator composed of two identical states Consider we have an operator $\hat{B}$ which is composed of two states i.e.
$$
\hat{B}=|\theta_1\rangle\langle\theta_1|
$$
The state $\theta_1$ is in turn composed of basis vectors
$$
|\theta_1\rangle=\alpha_1|\phi_1\rangle+\alpha_2|\phi_2\rangle
$$
where $\alpha_1,\alpha_2\in\mathbb{C}$ and $\{\phi_1,\phi_2\}$ form an orthonormal basis for the Hilbert space. If we want to find the possible measurements for this observable, we need to solve the eigenvalue equation
$$
\hat{B}|\phi_{i}\rangle=\epsilon_{i}|\phi_{i}\rangle \;\;\;\;\;\; i=1,2
$$
I tried approaching this in the manner described in jinawees answer. However, my interpretation of how it applied to this question would not work. In this case we get (for $i=1$)
\begin{align*}
\hat{B}|\phi_1\rangle&=|\theta_1\rangle\langle\theta_1|\phi_1\rangle \\
&=(\alpha_1 |\phi_1\rangle+\alpha_2 |\phi_2\rangle)(\alpha_1^*\langle\phi_1|\phi_1\rangle)\\
&=\alpha_1^{*}(\alpha_1 |\phi_1\rangle+\alpha_2 |\phi_2\rangle)
\end{align*}
which does not give us our required eigenvalue equation as both orthonormal bases are still present. Not really sure how to solve this, any help would be greatly appreciated.

A: The $\mid\phi_i\rangle$ in the eigenvalue equation are states to be determined, not some given basis states. The equation should look like this:
$$B\vert\psi\rangle=\varepsilon\vert\psi\rangle,$$
and you need to determine what the possible combinations of states $\vert\psi\rangle$ and eigenvalues $\varepsilon$ are which solve this equation. In this case you don't have to do all that much algebra, and instead notice that $\vert\theta_1\rangle$ itself is an obvious eigenstate of $B$ with eigenvalue $1$, and the state orthogonal to $\vert\theta_1\rangle$ is also an eigenstate with eigenvalue $0$. Since your Hilbert space is 2-dimensional, that's all the eigenstates you'll find.


text:
Q: why jquery click function is not working inside foreach loop My scenario is: creating button for each $newfrnd and when I click each button it insert a data in database(for example)
My question is : Button creation is happening fine. But it inserts data to database for each $newfrnd eventhough I am not clicking those $newfrnd buttons.
I think there must be some logical problem in the second part of code, I tried many changes on that but its not working . everytime its inserting data as many time as the number of $newfrnd. Why click function is not working?
Kindly help
  <?php
            $newfrnd=$_SESSION['newarr'];
            foreach ($newfrnd as &$newfriend){
          ?>
            <input type="button" id="<?php echo $newfriend; ?>" value="<?php echo $newfriend; ?>"/>
          <?php
              }
          ?>

Inside Javascript/jquery inside document.ready
<?php
$newfrnd=$_SESSION['newarr'];
foreach ($newfrnd as &$newfriend) {
?>
$("#<?php echo $newfriend; ?>").click(function(){
    <?php
    mysqli_query($con,"Insert into friendlist values ('Friend8', '') ");
    ?>
});
<?php } ?>


text: Q: How to pause and resume in pyttsx3? I am making a pdf reader and am using pyttsx3 for TTS. But i want it to have a "play and pause" like feature but i wasn't able to do this with pyttsx3.I have tried to take the location of where it stops,when "pause" button is clicked by the user, by using the Start_word() event(because it throws the name,location and length of the current word being synthesized) but then i can't start or "resume" from that point because startLoop() starts from the begining.Thanks in advance!


text:
Q: How to fetch multiple user post? I have multiple users and i want to display each image or video that they post... now the thing is that in the firebase database is only taking the last id added i have tried different methods and algorithm and nothing seen to work.
var friendsArray = [String]()
    var fetchID : String?
    for i in 0...friendsArray.count{
        friendsArray.append(fetchFriend.id!)
      let id = friendsArray[i]
        fetchID = id
    }

    print(fetchID)
    FIRDatabase.database().reference().child("users").child(fetchID!).observeEventType(.ChildAdded, withBlock: { (snapshot) in

        var videos = [Video]()
        for child in snapshot.children {
            let dictionary = snapshot.childSnapshotForPath(child.key)

            let userChannel = UserChannel()
            userChannel.profileImageName = fetchFriend.profileImage
            userChannel.username = fetchFriend.username
            let video = Video()
            video.thumbnailImageName = dictionary.value!["imageURL"] as? String
            video.userChannel = userChannel
            videos.append(video)
            videos = videos.reverse()
            dispatch_async(dispatch_get_main_queue(),{
            completion(videos)
       })
    }

  }, withCancelBlock:nil)
}


text:
Q: Recaptcha not working without referring to external page I have a recaptcha form on index.php?page=signup, which get's processed on index.php?page=process-register however it always returns the recaptcha as invalid, the data is getting sent properly and I can't work out why it doesn't work. If I set the form to submit to an external page say process.php with the same contents it works just fine. Any ideas what could be causing this? I am using the reCAPTCHA PHP class written by ShevAbam (https://github.com/shevabam/recaptcha).
edit: don't know if it's worth mentioning that I use mod_rewrite to hide file extensions and run all pages such as mysite.com/index.php?page=$ as mysite.com/$/. That shouldn't have any effect, right?
Thanks in advance.
index.php?page=register
   if($page == 'register')
  {
echo '

    <form action="index.php?page=process-register" method="POST">

Register
';

  echo getcaptcha();
    echo '
    <buttontype="submit">Register</button>
  </form>
 '; }

index.php?page=process-register
 if($page == 'process-register')
{
echo getcaptcha();
}

getcaptcha()
 function getcaptcha()
 {
     echo $_POST['g-recaptcha-response'];
     $reCAPTCHA = new reCAPTCHA('mykey', 'mykey');
      echo $reCAPTCHA->getScript();
      if (isset($_POST['g-recaptcha-response']))
      {

    if ($reCAPTCHA->isValid($_POST['g-recaptcha-response']))
    {
        echo '
-- Captcha OK ! --
';
    }
    else
    {
        echo 'captcha not okay';
    }
       }
    else
    {
     echo $reCAPTCHA->getHtml();
     }

 }


text:
Q: Inside lambda function - Blazing text algorithm invoke endpoint doesn't support the input content type Im working on sentence classification using in-build  blazing text algorithm, while invoking endpoint inside lambda function it throughs the content type mismatching error.
-- For blazing text it support only application/jsonlines or application/json but while invoking , it throughs the error like , it accepts only byte or bytearray
input format . application/json
event={
  "features": [
    "sensor_subtype Thermostats Thermal Switches product_features Hermetically sealed n Tight tolerances n Tight differentials n Logic level contacts n applications Computers n Medical electronics n Power supplies n Industrial controls n Test equipment n Infotech n description Technical Specifications technical_specs CloseTolerance 2 8 C 5 F DielectricStrength MIL STD 202 Method 301 1250 Vac 60 Hz Terminal to Case ContactResistance MIL STD"
  ]
}

and also i tried application/jsonlines
My code looks like this>>>>>>>>>>>>>>>>>>>>>>>>
def transform_data(data):
    try:
        features = data.copy()

        return features

    except Exception as err:
        print('Error when transforming: {0},{1}'.format(data,err))
        raise Exception('Error when transforming: {0},{1}'.format(data,err))

def lambda_handler(event, context):
    try:
        print("Received event: " + json.dumps(event, indent=2))

        request = json.loads(json.dumps(event))

        transformed_data = str(transform_data(request['features'])) #for instance in request['features'])
        print(ENDPOINT_NAME, "------->>>>")
        payload=transformed_data
        result = client.invoke_endpoint(EndpointName=ENDPOINT_NAME,
                              Body=(payload.encode('utf-8')),
                              ContentType='application/json')
        return result

  "statusCode": 400,
  "isBase64Encoded": false,
  "body": "Call Failed An error occurred (ModelError) when calling the InvokeEndpoint operation: Received client error (406) from model with message \"Invalid payload format\".
_______________LOGS__________________________________

11:35:22
[08/18/2019 11:35:22 ERROR 140074862942016] Customer Error: Unable to decode payload: Incorrect data format. (caused by ValueError)

11:35:22
Caused by: No JSON object could be decoded

11:35:22
Traceback (most recent call last): File "/opt/amazon/lib/python2.7/site-packages/blazingtext/serve.py", line 317, in invocations data = json.loads(payload.decode("utf-8")) File "/opt/amazon/python2.7/lib/python2.7/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/opt/amazon/python2.7/lib/python2.7/json/decoder.py", line 364, in decode obj, end = self.

11:35:22
ValueError: No JSON object could be decoded

I need to predict the sentence in realtime using invoke_endpoint option but it shows invalid payload format
I tried with byte format and apllication/jsonlines format.

A: Try to pass the following in invoke end point
Body=json.dumps(payload.encode('utf-8')

A: I encountered the same problem when trying to predict on text classification with a BlazingText container. What worked for me was simply changing the key in the payload while keeping the ContentType as application/json:
sentence = "I'm selling my PS4, practically brand new"

payload = {"instances": [sentence]}

response = client.invoke_endpoint(
        EndpointName="text_classification",
        Body=json.dumps(payload),
        ContentType='application/json'

    )

After playing around a little with the payload it seems that blazing text models only accept payloads as a dictionary with "instances" as its key and a list containing your data you want to predict on as its value.
To get to your predictions simply :
print("ResponseMetadata:", response["ResponseMetadata"])
print()
print("Body:", response['Body'].read())

A: Also make sure to get the response in Json format you need to change :
print("Body:", response['Body'].read())

TO
print("Body:", response['Body'].read().decode())


text:
Q: Google App Engine - Website closed the connection so I'm trying to host some code on a Google Cloud Platform VM. I've started with a simple 'Hello, world!' html page. But when I host it and try to connect to the IP I get:
' This Site can't be reached!
[IP Address] unexpectedly closed the connection '
Has anyone dealt with something like this before? And if so, how did you solve it?


text:
Q: Can I change this sentence into passive voice? If I have a sentence like this "We are going to join in the trip to New York", can I change it into passive voice?

A: TL;DR: You shouldn't, but you can
Very awkward and inadvisable, if technically possible
To use the passive voice, one takes a noun and puts a conjugation of to be and a past participle after it, then, optionally, "by" and whatever actually does the action.
Some examples of the passive voice are:

The question is read.
The answers are written by them.
They are viewed by us.

For your sentence, this is what the passive voice would be:

The trip to New York is going to be joined in by us.

Yikes...this is really awkward, and the normal active voice works much better. In real conversations, I would always use the active voice with this.


text:
Q: trouble with pip and easy_install to install python packages I am going to install numpy library as a *.whl file, as numpy-1.9.2rc1+mkl- cp27-none-win32, on my Windows 7 machine...
Here is my approaches to do that, are which pip and easy_install packages...
The odd thing is that both don't work in the case of either Python 3.4 or Python 2.7...
Here are the trace of the attempts in the command prompt:
pip:
"C:\Users\Matinking\Desktop\numpy-  1.9.2rc1+
mkl-cp27-none-win32.whl"    f
Exception:
Traceback (most recent call last):
File "c:\python34\lib\site-packages\pip\basecommand.py", line 122, in main
status = self.run(options, args)
File "c:\python34\lib\site-packages\pip\commands\install.py", line 257, in r
InstallRequirement.from_line(name, None))
File "c:\python34\lib\site-packages\pip\req.py", line 172, in from_line
return cls(req, comes_from, url=url, prereleases=prereleases)
File "c:\python34\lib\site-packages\pip\req.py", line 70, in __init__
req = pkg_resources.Requirement.parse(req)
File "c:\python34\lib\site-packages\pip\_vendor\pkg_resources.py", line 2667
in parse
reqs = list(parse_requirements(s))
File "c:\python34\lib\site-packages\pip\_vendor\pkg_resources.py", line 2605
in parse_requirements
line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec")
File "c:\python34\lib\site-packages\pip\_vendor\pkg_resources.py", line 2573
in scan_list
raise ValueError("Expected "+item_name+" in",line,"at",line[p:])
ValueError: ('Expected version spec in', '   C:\\Users\\Matinking\\Desktop\\numer
performance.pdf', 'at', ':\\Users\\Matinking\\Desktop\\numericperformance.pdf'

Storing debug log for failure in C:\Users\Matinking\pip\pip.log

and easy_install:
C:\Python34\Scripts>easy_install.exe "C:\Users\Matinking\Desktop\numpy-  1.9.2rc1+
mkl-cp27-none-win32.whl"
Processing numpy-1.9.2rc1+mkl-cp27-none-win32.whl
Writing C:\Users\MATINK~1\AppData\Local\Temp\easy_install-   jr2ijafr\numpy\setup.c
fg
Running numpy\setup.py -q bdist_egg --dist-dir    C:\Users\MATINK~1\AppData\Local\T
emp\easy_install-jr2ijafr\numpy\egg-dist-tmp-umy5kseg
This is the wrong setup.py file to run
No eggs found in C:\Users\MATINK~1\AppData\Local\Temp\easy_install-jr2ijafr\nump
y\egg-dist-tmp-umy5kseg (setup script problem?)

Any idea for the problem?!

A: You should upgrade your pip to version 6.0, the .whl file you're using isn't compatible with earlier versions.
To bump up your pip version on Windows :
    python -m pip install -U pip

A: pip error -> why were you running an install on a pdf?  That was never going to work.
easy_install error -> looks like you downloaded a python 2.7 binary and tried to install into a python 3.4 installation.
For scientific stack python, you are hard pressed to beat an Anaconda python distribution.


text:
Q: How do I add regex conditionals inside of an awk command Lets say I have multiple columns that may contain expressions that I want to select for if they do or do not match. How do I go about writing that awk expression?
Here is an example where I want to print columns only if certain fields get a match or not:
awk -v OFS=$'\t' -F $'t\' '($12 ~ /9\..[^b-z]/) || ($4 !~ /QA_[tT][eE][sS][tT]/) || ($4 !~ /ACC_Operator1/) || ($5 !~ /4CPP/) { print $8, $5, $4, $10, $6, $12}' filename

Running this gives me a
-bash: !~: event not found

Which I assume is a bash issue with using !

A: You have a typo, which is revealed by the syntax highlighter:
awk -v OFS=$'\t' -F $'t\' ...
                       ^ escaped single quote

This means that the opening quote of your awk command is actually closing the previous single quote.
Note that awk understands \t, so you can use -v OFS='\t', rather than using $'\t'.


text:
Q: Import geographic plots from matplotlib to plotly import mpl_toolkits
import mpl_toolkits.basemap

#
# specify the map boundaries and projection type
#
mymap = mpl_toolkits.basemap.Basemap(llcrnrlon= -120, llcrnrlat=22,
                                     urcrnrlon=-58, urcrnrlat=48,
                                     projection="tmerc", lon_0 = -95, lat_0 = 35,
                                     resolution = "l")
fig_map = plt.figure(6, figsize=(10, 8))

mymap.fillcontinents(color = "lightgray")
mymap.drawcoastlines(color = "gray", linewidth=1.2)
mymap.drawcountries(color = "gray", linewidth=2)
mymap.drawstates(color = "gray")

mymap.drawmapboundary()

plt.show()

And matplotlib gave me this beautiful plot:

Now, I want to import this to plotly intyerative plot
py.iplot_mpl(fig_map, filename='DataScience/data-visualization/geographic_map_plot_1')

/usr/local/lib/python2.7/dist-packages/plotly/matplotlylib/renderer.py:479: UserWarning:

I found a path object that I don't think is part of a bar chart. Ignoring.

And I receive several weird errors as below:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-79-561cd71f8586> in <module>()
----> 1 py.iplot_mpl(fig_map, filename='DataScience/data-visualization/geographic_map_plot_1')

/usr/local/lib/python2.7/dist-packages/plotly/plotly/plotly.pyc in iplot_mpl(fig, resize, strip_style, update, **plot_options)
    257             "object. Run 'help(plotly.graph_objs.Figure)' for more info."
    258         )
--> 259     return iplot(fig, **plot_options)
    260
    261

/usr/local/lib/python2.7/dist-packages/plotly/plotly/plotly.pyc in iplot(figure_or_data, **plot_options)
    113     if 'auto_open' not in plot_options:
    114         plot_options['auto_open'] = False
--> 115     res = plot(figure_or_data, **plot_options)
    116     urlsplit = res.split('/')
    117     username, plot_id = urlsplit[-2][1:], urlsplit[-1]  # TODO: HACKY!

/usr/local/lib/python2.7/dist-packages/plotly/plotly/plotly.pyc in plot(figure_or_data, validate, **plot_options)
    185                                          "seeing this error:\n\n{0}"
    186                                          "".format(err))
--> 187         if not figure['data']:
    188             raise exceptions.PlotlyEmptyDataError(
    189                 "Empty data list found. Make sure that you populated the "

KeyError: 'data'

I haven't seen any example for plotly on geographic maps! So, any help is much appreciated!

A: Unfortunately, Plotly does not support basemap conversions yet.
That said, there is a work-around:
http://nbviewer.ipython.org/github/etpinard/plotly-misc-nbs/blob/etienne/plotly-maps.ipynb
In brief, you need to extract the x-y coordinates from the basemap object, attached them to a Plotly trace objects and call plotly.plotly.plot().
If you have any other questions about Plotly, feel free to contact me.


text:
Q: Django formset factory ChoiceField causes is_valid to fail and return false I'm using a formset factory to generate a dynamic set of form elements. I'd like to add a set of dynamic radio buttons and dropdown menus, but when I use ChoiceField, the search.is_valid() evaluates to false. I'm sure I'm doing something obviously wrong, but I can't find it.
...
    search_formset = formset_factory(SearchForm, extra=num_extra_charts)

    # data to initialize forms
    data = {
        'form-TOTAL_FORMS': str(num_extra_charts),
        'form-INITIAL_FORMS': str(num_extra_charts),
        'form-MAX_NUM_FORMS': '',
    }
    self.search_forms = search_formset(get_request or data)
    if self.search_forms.is_valid():

...

class SearchForm(forms.Form):

    ORDERS = [('ASC', 'ASC'),
          ('DESC', 'DESC')]

    search = forms.CharField(label='',
                         max_length=250,
                         required=False,
                         widget=forms.TextInput(
                             attrs={'placeholder': 'ex. Matt Damon AND war'}),
                         )

    property = forms.CharField(label='',
                           max_length=250,
                           required=False,
                           widget=forms.TextInput(
                               attrs={'placeholder': 'Property Filter'}),
                           )

    limit = forms.CharField(label='',
                        max_length=250,
                        required=False,
                        widget=forms.TextInput(
                            attrs={'placeholder': 'Limit - Default: 25'}),
                        )

    orders = forms.CharField(widget=forms.Select(choices=ORDERS))

A: You have:
self.search_forms = search_formset(get_request or data)

This is unusual. It means that the formset is always bound.
Normally you would have
self.search_forms = search_formset(get_request or None)

Since you don not have required=False, that means that you must provide the values for the orders fields in the form data, otherwise you will get an error.


text:
Q: How to fix invisible margin parameter? for first i am really bad with css! I have strange problems... but firstly let me show you my app
Here is screen: (left sidebar expanded)

(left sidebar hidden)

Please take a look on scrollbar around that canvas covered with grid. This scrollbar look like that because it have margin-top and margin-left = 20. Look at this:

If i will delete this margin in that place, look how it will be look like:

As you can see everything look good. I needed to show you that with debbuger on my left side because if i close him then immediatly this margin come back. I needed to show that with debugger on my right side because if i close him then immediately this margin come back. Here is my code of that "grid" part:

            <canvas id="diagram" width="2100" height="2100">
                This page requires a browser that supports HTML 5 Canvas element.
            </canvas>

I am using fragments Thymeleaf, that code is fragment and it is used here:

Can anyone tell me what could be the reason for this? How is it possible that the styles in the browser show something different than what I have in the code?
Styles from browser:
element.style {
position: absolute;
width: 1600px;
height: 600px;
overflow: scroll;
margin-top: 20px;
margin-left: 20px;
}

Styles from my code:

A: It's different on other OS'.. so you should style your scrollbar
Made a quick sample:
::-webkit-scrollbar-track {
  display: none;
}

https://jsfiddle.net/p4mc70go/1/


text:
Q: open c# user control from another user control I have a c# user control.
I have a button in this control, and I want that when the user clicks on the button, another user control will be opened.
How can I do that?
Thanks

A: You have to create the control you want to add and add it.
YourCustomControl uc = null;

private void button1_Click(object sender, EventArgs e)
{
     uc = new YourCustomControl();
     this.Controls.Add(uc); // this represent the user control in which you want to add
                            // You can add it in some container like Panel or GroupBox
}

A: Take a look at RaiseBubbleEvent.  This pushes an event up to its parent.
http://msdn.microsoft.com/en-us/library/aa719644(v=vs.71).aspx


text:
Q: Moving speed like keypress event i try to explain my problem the best i can.
I have a pacman game where i move the pacman with the keyboard, the pacman moves a constant unit in every direction i check colision based on a map that i defined previously where the "-" are the obstacles, now i want to create the enemys, and i want that the enemys move randomnly without the keypress of course, the thing is that with the keypress the speed control is controlled, but with the random move i cant assure that the enemy moves like it pressed by the keyboard i want to controll the framerate here i am using requestAnimationFrame i tried the frame controll but didnt work here is my code:
   function handleKeyPressed(e) {

   var PacMan = scene.getObjectByName('PacMan');
   gameSong.play();
   switch(String.fromCharCode(e.which))
   {
     case "w": if(!detectaColisao(PacMan.position.x, PacMan.position.y + SCALE))
          PacMan.position.y += SCALE;
       break;
     case "a": if(!detectaColisao(PacMan.position.x - SCALE, PacMan.position.y))
         PacMan.position.x -= SCALE;
       break;
     case "s": if(!detectaColisao(PacMan.position.x, PacMan.position.y - SCALE))
         PacMan.position.y -= SCALE;
       break;
     case "d": if(!detectaColisao(PacMan.position.x + SCALE, PacMan.position.y))
         PacMan.position.x += SCALE;
       break;

   }
}

    function anima()
{
  var delta=clock.getDelta();
  orbitCamera.update(delta);

  requestAnimationFrame(anima);
  rendere

A:
it moves in position.x like 10 but it moves everytime

Do you mean that it moves too many times before the animation gets handled?
The reason for that is that keypressed is asyncronous from your render loop - it happens whenever a key is held down, which is constant for as long as you have a key held down.
What you have to do is to only move your pacman once per animate() cycle.
so what I would change is this-  don't move the pacman within your keypressed function, but instead trigger some booleans that will then move your pacman within the animate() cycle, like so:
var u, d, l, r;
u = d = l = r = false;

function handleKeyPressed(e) {
  switch (String.fromCharCode(e.which)) {
    case "w":
      u = true;
      break;
    case "a":
      l = true;
      break;
    case "s":
      d = true;
      break;
    case "d":
      r = true;
      break;
  }
}

function handleKeyReleased(e) {
  switch (String.fromCharCode(e.which)) {
    case "w":
      u = false;
      break;
    case "a":
      l = false;
      break;
    case "s":
      d = false;
      break;
    case "d":
      r = false;
      break;
  }
}

function moveModel(_u, _d, _l, _r, obj) {
  if (_u && !detectaColisao(obj.position.x, obj.position.y + SCALE)) {
    obj.position.y += SCALE;
  }
  if (_d && !detectaColisao(obj.position.x, obj.position.y + SCALE)) {
    obj.position.y -= SCALE;
  }
  if (_l && !detectaColisao(obj.position.x, obj.position.y + SCALE)) {
    obj.position.x -= SCALE;
  }
  if (_r && !detectaColisao(obj.position.x, obj.position.y + SCALE)) {
    obj.position.x += SCALE;
  }
}

function anima() {
  var PacMan = scene.getObjectByName('PacMan');
  moveModel(u, d, l, r, PacMan);
  var delta = clock.getDelta();
  orbitCamera.update(delta);
  requestAnimationFrame(anima);
  rendere();
}

Note that you also need to turn those booleans back off again when the key gets released, so we add another handleKeyReleased to catch when this happens. and we do the opposite of the handleKeyPressed function.
So the reason you need to add this layer of abstraction is that the keypressed event happens whenever it happens, and it doesn't care where in the animation cycle you are. But we only want to move once per animate cycle, so rather than move it directly, we create a series of flags that tell the model if and how it should move.

A: Ah okay that makes sense. So maybe you can add a value to their userData, some variable like "ghost.userData.timer" then every cycle you add 1 to it. When it goes past some coolDown variable that you define, like 60, then you give them a random move and set timer back to 0.
That way they'll take steps at regular intervals that you define.


text:
Q: Could not get unknown property 'keystoreProperties' for SigningConfig ERROR

Could not get unknown property 'keystoreProperties' for
SigningConfig$AgpDecorated_Decorated{name=release, storeFile=null,
storePassword=null, keyAlias=null, keyPassword=null, storeType=pkcs12,
v1SigningEnabled=true, v2SigningEnabled=true, enableV1Signing=null,
enableV2Signing=null, enableV3Signing=null, enableV4Signing=null} of
type com.android.build.gradle.internal.dsl.SigningConfig$AgpDecorated.

build.gradle (:app)
plugins {
        id 'com.android.application'
        id 'org.jetbrains.kotlin.android'
        id 'kotlin-android'
        id 'kotlin-kapt'
    }

    android {
        compileSdk 32

        defaultConfig {
            applicationId "com.sonkhiasinghansh.groceryapp"
            minSdk 19
            targetSdk 32
            versionCode 1
            versionName "1.0"

            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }
        signingConfigs {
            release {
                keyAlias keystoreProperties['keyAlias']
                keyPassword keystoreProperties['keyPassword']
                storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
                storePassword keystoreProperties['storePassword']
            }
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release

                minifyEnabled false

                proguardFiles(
                        getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
                )
            }
        }
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
        packagingOption {
            exclude 'META-INF/atonicfu.kotlin_module'
        }
        kotlinOptions {
            jvmTarget = '1.8'
        }
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.7.10"
        implementation 'androidx.appcompat:appcompat:1.5.0'
        implementation 'androidx.core:core-ktx:1.8.0'
        implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
        testImplementation 'junit:junit:4.13.2'
        androidTestImplementation 'androidx.test.ext:junit:1.1.3'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

        def room_version = "2.2.1"
        def lifecycle_version = "2.0.0"

        // Room and Architectural Components
        implementation "androidx.room:room-runtime:$room_version"
        implementation "androidx.legacy:legacy-support-v4:1.0.0"
        implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
        implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1'
        implementation "androidx.room:room-ktx:2.4.3"
        kapt "androidx.room:room-compiler:$room_version"

        // Coroutines
        implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1'
        implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1"

        // New Material Design
        implementation "com.google.android.material:material:1.6.1"

        // ViewModel
        implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
        implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
        //noinspection LifecycleAnnotationProcessorWithJava8
        kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

    }


text: Q: How to handle multiple smart home devices asynchronously using node.js application? I'm developing a node.js application for IOT project where the application needs to receive stream of sensor data through messaging library like zeromq and does pattern matching and anomaly detection. The challenge here is that  how to perform pattern matching and anomaly detection for multiple devices asynchronously without blocking using node.js? Node.js being event-driven, can it handle this scenario smartly by default or we need to explicitly incorporate the technique?


text:
Q: How to integrate ruby in Visual Studio 2010 Currently I'm started to learn Ruby in Steel 2.
I installed Ruby from the link and also I installed the Interpreters from the same link, rubyinstaller-1.9.2-p290.exe, but while running in Visual Studio 2010 it's showing
**Error  :-**

'RunRuby Exception : unsupported Interpreter Type : Not Supported'

How do I resolve this issue? If anybody has some idea of correct interpreter for Ruby in Steel 2 please share your views.

A: I guess it is because of wrong version of Interpreter selected by visual studio.I mean the path may be wrong or version mismatch.
You uninstall all and install Ruby in Steel setup and then ruby Interpreter from the  same link you used earlier.
And just follow this to get visual studio to select the right path of ruby installed.
Follow this link here
It should work and i got the same problem and it worked for me.