text:
Q: JSP compilation fails on Weblogic 10.3 but works on Weblogic 10 I have below piece of code in one my JSP
<%@ page language="java" import = "import com.ecc.SiteAdmin.servlets.*" %>

This file compiles and works fine on Weblogic 10 with Sun JDK 5, but fails with below message on Weblogic 10.3 with JRockit 6

SiteAdminLogin.jsp:1:36: No type with this name could be found at this location.

<%@ page language="java" import = "import com.ecc.SiteAdmin.servlets.*" %>

SiteAdminLogin.jsp:1:36: import is a keyword and cannot be used as an identifier.

<%@ page language="java" import = "import com.ecc.SiteAdmin.servlets.*" %>

I guess its asking me to remove the word import from the code, but why it works on JDK5 and not JDK6 ? Is there something more to it ?
EDIT: It seems to work fine on my colleague machine who is using IE7, I have upgraded to IE8 sometime back and then uninstalled IE8 and switched back to IE7. It looks like its a conflict on IE side.

A: The import attribute of the page directive should contain a comma-separated list of Java packages that the JSP file should import. So the syntax you are showing here is just not correct and should fail in both cases (finding the exact difference would require more testing, providing the generated class, etc).
But unless you want to debug WebLogic appc, I wouldn't spend too much time on this problem, just write the import properly to fix it:
<%@ page language="java" import="com.ecc.SiteAdmin.servlets.*" %>

Regarding your edit, I don't think that the browser has anything to do with this problem as this is a pure server-side issue. Again, just fix it and stop spending time on it.

A: The fact the it works is strange, because putting import inside the import attribute is wrong. Perhaps they have written a (non-standard-compliant) parser that removed a leading import there.
There is nothing more - just remove the import


text:
Q: Check if item is in list (inside a directive) I have the following directive which uses two lists: listGroup and listAll.
They are JSON objects like this:
$scope.usersGroup = [
  { id: '1', name: 'User 1' },
  { id: '2', name: 'User 2' },
  { id: '3', name: 'User 3' }
]

I want to add a class to each item if item is already in userGroup:
JS:
  .directive('tableList', function() {
    return {
      restrict: 'EA',
      template: '<--SOME CODE' +
        '
' +
          '<input type="checkbox" value="0" ng-model="item.selected">	' +
          '{{item.name}}
        'MORE CODE-->',
      scope: {
        listName: "@",
        listGroup: "=",
        listAll: "=",
        submit: "&"
      },
      controller: function() {},
      link: function(scope, elem, attr, ctrl) {
        scope.checkAll = function() {
          if (scope.selectedAll) {
            scope.selectedAll = false
          } else {
            scope.selectedAll = true
          }
          angular.forEach(scope.listAll, function(item) {
            item.selected = scope.selectedAll
          })
        }
      }
    };
  })

HTML:

  </table-list

What's the AngularJS-way of doing this?

A: I don't think there is a specific angular way. I would simply set a flag in listAll
link: function(scope, elem, attr, ctrl) {
        ...
        var listGroupIds = {};
        angular.forEach(scope.listGroup, function(item) {
          listGroupIds[item.id] = true;
        });
        angular.forEach(scope.listAll, function(item) {
          item.inListGroup = item.id in listGroupIds;
        });

Then in the template
template: '<--SOME CODE' +
        '
' +
          '<input type="checkbox" value="0" ng-model="item.selected">	' +
          '{{item.name}}
        'MORE CODE-->',

A: Use ng-class in tr tag:

A: You don't even need to write anything in controller or link function. Just use Array.prototype.indexOf method, super fast and convenient:

 -1}" ng-repeat="item in listAll">

Important: listGroup must contain references to the same objects listAll has (which is how it should be anyway).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery UI slider with multiple handles returning wrong value I made this example so you can reproduce the error:
I put some labels on top of each handle so you can see the value while moving the handles, the problem is that sometimes it behaves in a strange manner, for example if you drag one handle, say the one with the label 15, and you start moving it left and right, you will notice that sometimes when you drag to the left it adds 5 points(instead of substracting), and this behavior is the same for all handles.
I'm pretty much stuck here, and my UI wouldn't work with this bug on it :(
Thanks in advance.

A: Its not adding points, the sliderlabel gets triggered after you start sliding, so the first time you slide the function isnt triggered only the second time.


text:
Q: trying to find the correct regular expression I have the following cases that should match with a regular expression, I've tried several combinations and have read a lot of answers but still no clue on how to solve it.
the rule is, find any  combination of . inside a quoted string, atm I have the following regexp
\"\w*((..)|(.))\w*\"
that covers most of the cases:
mmmas"A.F"asdaAA
196.34.45.."asd."@
".add"
sss"a.aa"sss
".."
"a.."
"a..a"
"..A"
but still having problems with this one:
"WERA.HJJ..J"
I've been testing the regpexp in the http://regexr.com/ site
I will really appreciate any help on this

A: From the question, it seems that you need to find every occurrence of one or more dot (along with optional word characters) inside a pair of quotes. The following regex would do this:
\"\w*(\.+\w*)+\"

In "WERA.HJJ..J", you have some word characters followed by a dot which is followed by a sequence of word characters again followed by dot and word characters. Your regex would match one or two dots with a pair of optional word character blocks on either sides only.
The dots in the regex are escaped to avoid them being matched against any character, since it is a metacharacter.
Check here.

A: Change your regex to
\"\w*(\.+\w*)+\"

Update: escape . to match the dot and not any character
demo


text:
Q: remove UITableViewCell inside it's custom class I have made a custom class for my tableViewCell and there is a uibutton on the cell which removes the cell by tapping on it. How should I delete that row from UITableView inside it's custom class ?
This is the button action and custom tableviewcell :
class shopingCart_cell: UITableViewCell {
    @IBOutlet weak var img_product: mainImage_littleRounded!
    @IBOutlet weak var lbl_title: label_title!
    @IBOutlet weak var lbl_price_tak: lbl_sh_prce_kol!
    @IBOutlet weak var lbl_price_kol: lbl_sh_prce_kol!
    @IBOutlet weak var lbl_total_num: UILabel!
    @IBOutlet weak var btn_stepper: UIStepper!
    var crProduct:productMD!

    @IBAction func btn_remove_prod(sender: AnyObject) {
        dataService.instance.removeFromShopingCart(crProduct)
       //remove the cell current cell here
    }

Thanks

A: This should not be handled by the cell. Instead, you can create an IBOutlet for the UIButton and add an action where the UITableView is located.
In the cellForRowAtIndexPath:
cell.btn_remove.tag = indexPath.row
cell.btn_remove.addTarget(self, action: "removeCell:", forControlEvents: .TouchUpInside)

Then use this function:
func removeCell(sender: AnyObject) {
    myTableView.deleteRowsAtIndexPaths(NSIndexPath(forRow:sender.tag, inSection: 0), withRowAnimation: .Fade)
}


text:
Q: Defining attributes in services.xml for Ofbiz I'm encountering a problem whereby i have fields in a form that has variable naming in the name attributes that need to pass into a service, but can't do so because i can't define it in the services.xml
The scenario is that, i have a major form, and there's this sub section of fields that are added to it through ajax. These fields represent one set of data and they are not compulsory, meaning some of the fields may be empty. Example, in the added fields, i have a field of ID, amount and cheque no. The user can choose to fill in ID and amount but not the cheque no. There can be multiple rows of IDs, amounts and cheque nos added to the major form.
At first i name all these fields using the same name, and i pass them to the service as a List. It works great until i found that if i don't fill in the cheque no, the cheque no list will actually be null and not a List with an empty string. This is causing me issue to map them correctly in the service.
Then i tried to use the old school method, namely having a counter in a hidden field and have them named with a suffix that representing the counter. And then i found that i can't dynamically define the attributes in the services.xml
Does anyone encounter such issue before? Any advise or help?

A: The workaround that i used to solve this is by adding a Event Class to filter the request before calling the service to do the actual processing. This way I can get the parameters in raw form and doesn't rely on Ofbiz service definition to get the values for me.

A: You may mark all optional fields as optional in service definition ie.services.xml file
For ex  : attribute name="cheque no" type="String" mode="IN" optional="true"/>


text:
Q: JavaScript setTimeout scope issue var toogleDelay = 500;
var closeTimeout = null;

$(">ul>li", $nav).hover(function () {
    var $this = $(this);
    if(closeTimeout) {
        clearTimeout(closeTimeout);
    }
    var openMenuCallback = function() {
        $this.addClass("hover");
    };
    window.setTimeout(openMenuCallback, toogleDelay);
}, function () {
    var $this = $(this);
    var closeMenuCallback = function() {
        $this.removeClass("hover");
    };
    closeTimeout = window.setTimeout(closeMenuCallback, toogleDelay);
});

I use this snippet to open and close a multidropdown-menu and I want the menu to fade in and out with a 0.5s delay. I also added a cleartimeout to the mouseover part of the jquery hover function, so that the menu does not close if somebody (accidently) leaves the menuarea and enters it again within the 0.5s. This all works fine, but I now have the problem, because there is more than just one dropdown, that the closeTimeout of lets say the first dropdown gets cleared, if I move the mouse from the first directly to the second dropdown and I now have both dropdown-elements open. How must I rewrite the code, so that every dropdown has its own closeTimeout and at the same time I am still able to clear the timeout in the mouseover part of the hover function.
thx
sub

A: You could store the timer's id in the element's data. Something like
var $this = $(this);
var closeMenuCallback = function() {
    $this.removeClass("hover");
    $this.removeData("timerid");
};
var closeTimeout = window.setTimeout(closeMenuCallback, toogleDelay);
$this.data("timerid", closeTimeout);

and then check it with
var $this = $(this);
var closeTimeout = $this.data("timerid");
if(closeTimeout) {
    clearTimeout(closeTimeout);
    $this.removeData("timerid");
}

A: I know this isn't part of the question but I like the CSS approach to this.
http://webdesignerwall.com/tutorials/css3-dropdown-menu
there are a number of examples for this. some multilevel some not.


text:
Q: Numpy .all() ignores IndexError Lets say  we have the following array:
a = np.zeros((3,3,3))

single checks are working:
a[1,1,1] == 0 --> True
a[5,1,1] == 0 --> IndexError
checking an area  of the array  don't show the indexError
(a[0:2,0:2,0:2] == 0).all()  --> True
(a[0:20,0:2,0:2] == 0).all()  --> True  is the result, but it should be  an IndexError
In such cases  I would like to get a False  or at least the error, any hints?

A: I would suggest checking the bounds of the array beforehand. However, if you really want to, one way to accomplish this would be to pad the array with a value that will compare not equal to all numbers, such as None:
a = np.zeros((3, 3))
padded = np.pad(a.astype(object), [(0, 1), (0, 1)], 'constant', constant_values=None)

print((a[:3, :3] == 0).all())
print((a[:4, :4] == 0).all())

print((padded[:3, :3] == 0).all())
print((padded[:4, :4] == 0).all())

Output:
True
True
True
False

Note that this requires converting your array to object type.

A: By default with numpy arrays, if the index is bigger than the dimension, then it returns until the last elements it finds.
I'm not sure if you can change this behaviour though. The only solution I can think of is to check first if the indices are lower than the size of each dimension and do the comparison after.


text:
Q: Multi-touch with Famo.us I followed this example
http://famo.us/university/famous-102/input/5/
It mentioned multitouch with no example

Famo.us also has support for multitouch gestures such as rotating,
  pinching and scaling. To familiarize yourself with these, please visit
  [LINK TO EXAMPLES.GIT]

What is a simple example to get touches via array or something like that? I assume it has something to do with TouchTracker https://famo.us/docs/0.2.0/inputs/TouchTracker ?

A: This one took me a while.
First a bug..
In TouchSync.js on line 84:
payload.touch = data.identifier;

should be..
payload.touch = data.touch.identifier;

Next, if you want to keep track of all your events, you can do so manually though each of TouchSyncs start, update, and end events. TouchSync simply uses TouchTracker to manage the multitouch, but that is a class you should not need to use yourself.
Here is my example tracking multiple touch inputs. Notice I needed to clone the data objects as they came in to the event handlers to keep proper reference to them. That also took a while to figure out. Hope this helps you!
var Engine    = require("famous/core/Engine");
var TouchSync = require("famous/inputs/TouchSync");
var Surface   = require("famous/core/Surface");

var mainContext = Engine.createContext();

var touches = {};

var touchSync = new TouchSync(function() { return position; });

Engine.pipe(touchSync);

var contentTemplate = function() {

    var string = "Touches:
";

    for (var key in touches ) {
      var touch = touches[key];
      var x     = touch.clientX ? touch.clientX : "" ;
      var y     = touch.clientY ? touch.clientY : "" ;
      string += "key: "+key+", x: "+ x+", y: "+ y +"
";
    }

    return string;
};

var surface = new Surface({
    size: [undefined, undefined],
    classes: ['grey-bg'],
    content: contentTemplate(),
    properties: {
      padding:'10px'
    }
});

var clone = function(obj){
  var newObj = {};
  for ( var key in obj ) { newObj[key] = obj[key]; }
  return newObj;
}

touchSync.on("start", function(data) {
    touches[data.touch] = clone(data);
    surface.setContent(contentTemplate());
});

touchSync.on("update", function(data) {
    touches[data.touch] = clone(data);
    surface.setContent(contentTemplate());
});

touchSync.on("end", function(data) {
    delete touches[data.touch];
    surface.setContent(contentTemplate());
});

mainContext.add(surface);


text:
Q: Please recommend an optimized IP lookup algorithm and data structs I've built a geoip database with around 8,000,000 IP segments. In order to load it into memory for fast lookup, I tried to use std::map as a interval tree. The lookup speed is around 20-40us each with random IPv4 address, but far beyond the project requirement(< 10 us each).I appreciate someone can suggest a better alternative on this, thanks.
// the geoip info attach to each ip segment
struct geoip_info {
    geoip_info(const geoip_info& info);
    uint32_t country;
    uint32_t subdiv;
    uint32_t city;
    float    latitude;
    float    longitude;
};

// the ip segment definition used as the std::map key
struct ip_segment_key {
    uint32_t from;
    uint32_t to;
    ip_segment_key(uint32_t from, uint32_t to);
    ip_segment_key(const ip_segment_key& key);
    bool operator==(const ip_segment_key & data) const;
    bool operator!=(const ip_segment_key & data) const;
    bool operator>(const ip_segment_key & data) const;
    bool operator<(const ip_segment_key & data) const;
};

struct lookup_table {
    // use std::map as a interval tree here
    typedef std::map<ip_segment_key , geoip_info> ip_range_map;
    ip_range_map table;

    void load(uint32_t ip_range_from, uin32_t ip_range_to, geoip_info &info) {
        table.insert(make_pair(ip_segment_key(from, to), value));
    }

    // lookuping ip means passing a key with same 'from' and 'to' as the ip argument
    bool lookup(uint32_t ip, geoip_info &info) {
        auto it = table.find(ip_segment(ip, ip);
        if (it != table.end()) {
            info = it->second;
            return true;
        }
        return false;
    }
}

A: i'd say that's a question of available memory...
if you happen to have 4 gigs of ram for this, it can easily be a O(1) lookup in the end...
if you partition your your segments into multiple trees based on a method that can easily identify which tree to search, you can get trees with no more than 2,000,000 elements which should be in the range you are looking for ... n-bit-prefixes could be such a method ... what exactly depends on the shape of your data set

A: For your 8M IP subnets, you can create 128mb hashtable, contains 16M of uint64_t values. Each value is:

*

*bytes 0-3 - IP prefix of segment

*byte 4 - netmask (0-32)

*bytes 5-7 - 24-bit data value for your geolocation

Search/Insert into thus table can be performed by key, contains 5 lowest bytes, i.e. by IP+netmask.
For given address, just iterate masks from 0 to 31, and each time lookup your hashtable. I think, all 31 searches total would consume less than 5us. My own implementation for double hash performs each search for ~120ns, so in worst case you will spend only 4us.
Practically, you will reach result more quick, so real average lookup time I estimated is 1-2us.


text:
Q: Extracting scores from GoogleNet I would like to extract the scores from the GoogleNet network from caffe models but I don't quite understand which layers keep the scores.
I get:
Check failed: feature_extraction_net->has_blob(blob_names[i]) Unknown feature blob name loss3/top-5 in the network ./train_val.prototxt

Any suggestion?

A: The layer loss3/top5 is an Accuracy layer. I will assume that this is want you meant by scores.
By default, you will have something like this
layer {
  name: "loss3/top-5"
  type: "Accuracy"
  bottom: "loss3/classifier"
  bottom: "label"
  top: "loss3/top-5"
  include {
    phase: TEST
  }
  accuracy_param {
    top_k: 5
  }
}

If you want to have this layer in training, you can remove or comment out (#) the include section.


text:
Q: How to handle large data from wcf service I have wcf service, in one of method which returns a list.  Getting the data from oracle database, which is a large data(records in lakhs). This method when tested with wcf client works fine. When I consume the same service in silverlight application, I am getting timeout exceptions.. Pls suggest necessary steps to handle large data or avoid this issue.

A: An application I worked on a few years ago had similar requirements. If my memory serves me correctly, we created some custom WCF behaviours that compressed/decompressed the dataset and transported it as binary data. You could also stream the data but this is a little more brittle in my opinion and requires more work on the client. HTH.

A: You can do it by holding data in object collection and use silverlight datagrid pagination, so   with proper coding you can show atleast 1000 records at time because as per my view user could not look lakhs of records by scroll down and scroll up.
   If u don't want pagination then do the background threading, when user scroll up or scroll down data fetch as per index. Handle as much as data in coding level.
Above same thing i have done in my last project.


text:
Q: Number of pairs linearly independent vectors in vector space of dimension 3 Suppose V is a real vector space of dimension 3. Then what will be the number of pairs of
linearly independent vectors in V?
Cani say it should be infinity? Because there exist infinite number of basis of a vector space of dimension 3?

A: This depends on the ground field. If the ground field is infinite, this is in fact true and not all that hard to prove (just take two linearly independent vectors $v$ and $w$ and consider the pairs $(v,\lambda w)$ for any scalar $\lambda \neq 0$). If the ground field is finite, the vector space itself is finite as well, so your claim does not hold.
Edit: I missed that you specified it was a real vector space. In that case, the ground field is obviously infinite, and the argument above works. Thanks to Jonathan Taylor for noticing.

A: Since your question specifies that we are talking about a real vector space, then yes. There are an uncountably infinite number of such pairs.

A: There are only 3 linearly independent vectors e1,e2,e3 in real vector space V of dimension 3 . V is spanned by 3 L.I vectors. So pairs are only 3


text:
Q: How can I script copying files from Unix to Windows? Is there any way a script can be made that copies files from a Unix drive onto a Windows drive?

A: I do it manually all the time using secure copy (SCP).  SCP comes already installed on most Unix machines.  On my PC, I installed PuTTY which is a secure terminal app for Windows and also contains a secure copy utility.
When you do the secure copy manually from the Windows command line, you put your Unix username into the command line command, but then you have to type in your password at the prompt, so it's interactive.  But I've also thought about doing it from a script or a batch file.  In that case, you will need to create and install private and public keys on the appropriate machines.  I created the appropriate keys and installed them on both the Windows and Unix machines and then I manually performed the Windows command line secure copy again and it did not ask me for my password that time.  So this is one way you can accomplish your task.  I'm sure there are many other ways, though.

A: Yes, as long as the operating system the script is executing on can read from the Unix drive and write to the Windows drive. Since this is tagged vbscript, I'll assume you're running on Windows so you might want to look into something like this to get access to Unix filesystems for Windows (although that's a Linux ext driver). Then it's just running a standard copy function to complete your task.

A: Since you have a Samba tag, are you talking about mounting a network share from a Unix machine onto your Windows machine?
If so, it is just treated like a normal network drive and you would be able to copy anything that you had permissions via the share.

A: I would use expect tool.
Here is an example, how to upload

*

*/local/path/to/file
to

*

*\\HOST\SHARE\remote\path\to\file
authenticating with domain\user using password password:
expect <<<EOF
set timeout 10
spawn smbclient //HOST/SHARE "-Udomain\\user%password"
expect {
  "smb: \\\\\\\\>" {
    send "cd /remote/path/to\r"
    expect {
      "NT_STATUS_OBJECT_NAME_NOT_FOUND" {exit 1}
      "smb: *>"                         {
        set timeout -1
        send "put /local/path/to/file file\r"
        expect {
          "putting file " {
            expect "smb: *>" {exit 0}
          }
          "smb: *>" {exit 1}
        }
      }
    }
  }
}
# Timeout
exit 1
EOF


text:
Q: Prototyping for easier function firing So I've creating a small library of JavaScript functions that I will be using. Some are for UI functions others are to return something. Below I will post two codes, I am wondering if this method is ok and not a bad move before going any further with this library, also please do not mention jQuery as this is all JavaScript!
HTMLElement.prototype.drag = function(bool) {
var self = this;
self.classList.add('draggable');
    event.stopPropagation();
    event.preventDefault();
    var origLeft= parseInt(self.offsetLeft,10);
    var origTop = parseInt(self.offsetTop,10);
    var mdX = event.clientX;
    var mdY = event.clientY;
    var elements = [];
    if(bool === true){
      var j = window.localStorage.getItem('userSettings');
      if(j){
        self.style.left= j.left;
        self.style.top = j.top;
      }
    }
      function drag(bool) {
        self.style.position="absolute";
        self.style.zIndex=999;
        self.style.left = origLeft + event.clientX - mdX + "px";
        self.style.top = origTop + event.clientY - mdY + "px";
        event.stopPropagation();
      }
      function stop(bool){
        self.classList.remove('draggable');
        self.style.zIndex=0;
        document.removeEventListener('mousemove',drag,true);
        document.removeEventListener('mouseup',stop,true);
           if(bool === true){
            var settings = {
              left: self.style.left,
              top: self.style.top
            };
            var b = JSON.stringify(settings);
            window.localStorage.setItem('userSettings',b);
            console.log(b);
            }
        event.stopPropagation();
      }
       document.addEventListener('mousemove',drag,true);
       document.addEventListener('mouseup',stop,true);
};

The above code is of course for a draggable function, below is a getClientRects() sort of function but better.
HTMLElement.prototype.getRect = function(){
     var a = this.offsetLeft;
     var b = this.offsetTop;
     var c = this.offsetHeight + b;
     var d = this.offsetWidth + a;
     var f = this.offsetHeight;
     var g = this.offsetWidth;
     var obj = { };
     obj.left = a;
     obj.right=d;
     obj.top=b;
     obj.bottom=c;
     obj.width = g;
     obj.height=f;
  return obj;
};

Purpose of showing you all this is to get your thoughts and maybe advice about prototype or should I not do it this way. I just like the method execution like this document.getElementById('div').getRect(); instead of doing it with a function getRect('div');


text:
Q: Why do I receive foreign key conflict error when inserting value into foreign key field. Value being inserted matches primary key in reference table I insert a record into a table using autoincrement primary key.  Then I access the new primary key and try to insert it into a field that is foreign key to the new primary record.  Then receive foreign key error.  Code is:
/******************  Insert new record in session table ************************/
$insBC2020sql = "insert into session (auctionid,auctiondate,created,lastupdated,sessiondate) output inserted.*
    values ('$auctionid','$saledt','$today','$today','$today')";

$insBC2020res = odbc_exec($conn_1,$insBC2020sql);

if (!$insBC2020res) {
    exit("Request Error --" . odbc_errormsg($conn_1));
}
/*********************  Retrieve primary key from last insert **************************/
while (odbc_fetch_row($insBC2020res)) {
        $sessionid    = odbc_result($insBC2020res, 1);

    echo "\r\n".$sessionid. "  ".$customerid;
}
}
/*************************  Insert retrived value into reference table ********************/
$inssql = "insert into bidcall2020.dbo.customersession (customerid,sessionid)
       values ('$customerid','$sessionid')";
echo $inssql."\r\n";

$insres = odbc_exec($conn_1, $inssql);
if (!$insres) {
    exit("Request Error --" . odbc_errormsg($conn_1));
}

Get foreign key conflict error.  Sessionid is a foreign key.  Value retrieved does match value in primary table.

A: try
$sessionid    = odbc_result($insBC2020res, 0);

instead of
$sessionid    = odbc_result($insBC2020res, 1);


text:
Q: Fetching из сущностей, обьединенных отношениями Имею две сущности Customer и City, от Customer к City я указал many-to-one relationship с названием cities чтобы фетчить его проперти с названием name, обратно указан one-to-many relationship и они определены как inverse. Для фетча использую:
- (NSFetchedResultsController *) fetchedResultsController
{
    if (_fetchedResultsController != nil)
    {
        return _fetchedResultsController;
    }
    self.managedObjectContext = [[PTDataManager sharedManager] managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Customer"
                                              inManagedObjectContext:[self managedObjectContext]];
    [fetchRequest setEntity:entity];

    _fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;
}

Собственно все проперти Customer'ов я таким образом получаю, но значение проперти name вытягиваемое через relationship cities является (null). Для проверки наличия данных в name использую метод:

-(City )city {
    return (City )[[PTDataFetchHelper sharedInstance] entityForName:@"City"
withServerID:self.city_server_id
inContext:[self
managedObjectContext]]; }

определенный в NSManagedObject-сабклассе для сущности Customer. Таким образом данные выводятся, но это работает очень медленно, tableView в которую выводятся данные при этом начинает сильно тормозить. Да и хочется сделать это нормально, используя связи.
Таким образом вопросы:

*

*при указанном фетче из базы тянутся только Customer-объекты или и все с ним связанные отношениями?

*если нет то нужно ли указывать предикат для такого фетча (с целью вытянуть все данные из пропертей связанных сущностей)?

*Если предикат все же нужен, как он может выглядеть учитывая что мне нужно вытянуть все объекты по данной проперти никак не ограничивая фетч?

UPD:
код используемый для вывода данных в ячейку таблицы
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    .....

    customer = (Client *)[self.fetchedResultsController objectAtIndexPath:indexPath];

     // customer's full name
    cell.nameLabel.text = [NSString stringWithFormat:@"%@ %@ %@", customer.lastname, customer.firstname, client.middlename];

    // customer's city
    cell.cityLabel.text = [NSString stringWithFormat:@"%@", customer.cities.name];

     .....

    return cell;
}

A: У меня исчерпался лимит для комментирования, поэтому пишу в ответ.
1) Вы можете по-быстрому скрафтить болваночный проект, который воспроизводит вашу ситуацию, выложить его и добавить на него ссылку в ваш вопрос? Так было бы проще обсуждать, хотя и займет у вас дополнительное время.
2) Покажите ваш код - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath, или соответствующий в другом месте код, где вы обращаетесь к результатам из базы?
Мое предположение состоит в том, что в вашем случае все просто должно работать просто по точкам без всяких дополнительных предикатов в NSFetchRequest, поэтому я хочу увидеть, что именно вы делаете с результатами из базы (NSFetch results).
ФИНАЛЬНОЕ ОБНОВЛЕНИЕ
После обсуждения этого вопроса с его автором в скайпе мы совместно выяснили, что все мои основные предварительные предположения о возможных проблемах оказались верны:
Во-первых, в схеме .xcdatamodeld Xcode проекта у автора были неправильно расставлены отношения между Customer и City (точнее - не были расставлены совсем, вместо них стояли обычные геттеры и сеттеры в классах, без декларации в схеме!, с соответствующими именами вроде cities). В конечном счете оказалось, что Customer все-таки имеет один город, то есть соответствующие строки у экземпляров Customer приняли в итоге вид customer.city.name (city в единственном числе).
Во-вторых мы написали код склеивающий отношения между Customer и City (сразу же после приема соответствующего им JSON) на уровне Core Data. Вот типичная схема "склейки" - перевода JSON в Core Data:
customer создается из JSON, city создается из JSON, и, наконец, customer.city = city и после этого оказывается, что обе сущности CoreData связаны между собой.
После этих изменений весь оригинальный код заработал просто "по точкам" без всяких дополнительных предикатов, при этом, очевидно, был значительно достигнут значительный speed-up (то есть прирост в скорости) всего процесса - UI приложение перестало тормозить и начало летать. Добро восторжествовало, Ура!


text:
Q: Prerequistes for learning how to code a facebook application I am facing a really tough time doing this. I haven't done much on web development before this. I know HTML and dats it. What else do I need to learn in order to start coding a good facebook app (specifically scripting languages like JS, PHP, MySQL etc). I have already created a test application using a web hosting site. Time is of the essence here.

A: I would pick up Head First Servlets and JSP or Head First PHP & MySQL. They will be your best friends in the process of writing PHP or JSP.  Then of course you should learn what's in the Facebook API and how to use it.
You mentioned that time is off the essence, but I simply can't think of a reasonable way by which you can learn PHP or JSP without putting in the grunt work (which takes time).  You should definitely do some reading unless you want to make an app that's hacker's paradise.
If you're already familiar with Java, then JSP will feel more natural and probably easier/faster to learn.
P.S. Sorry for the multiple edits... I felt like my wording was a bit off.


text:
Q: NodeJS using 'archiver' to deploy in AWS I have a lambda that was made in Node JS. I used npm archiver to zip and deploy the files in AWS. Everything is okay except the zip includes node_modules. I then used glob
var srcFolder = './';
var ignores = ['node_modules/**/*', 'publish.js'];
archive.glob('**/*',
{
    cwd: srcFolder,
    ignore: ignores,
    nodir: true,
    dot: true,
    follow: true
});

this works.. Problem here is when a time comes to have the need to include "some" node_modules with my deployment. I would like to ask how to just include the packages that I needed for my production (not in devDependencies)? And Ignore the aws-sdk and archiver.


text:
Q: Using preg_replace to make ordinals appear in all lower case I have a column of address data that has ordinals displayed like this:
3Rd Floor, Cumbrian House
Room 223, 2Nd Floor
when I would like them to be displayed like this instead:
3rd Floor, Cumbrian House
Room 223, 2nd Floor
I'm trying to make use of the preg_replace function to swap out a capitalised letter, that directly follows a number, with a lower case letter instead. (I admit this is my first time using the preg_replace function. I am however fine with preg_match and regular expressions).
So far I have:
$string = '3Rd Floor, Cumbrian House';

$ordinalregex = '/(^.*\d+)([A-Z])/';
$correctordinal = '$1'.strtolower('$2');

echo preg_replace($ordinalregex,$correctordinal,$string)."<br>";

But its not having the desired effect and outputs the line exactly as it first appeared.
Thanks

A: I think you need to use preg_replace_callback as I'm not sure you can replace based on the part you matches in normal preg_replace. What you need to do is use a callback function that takes the matches array and processes it (you could also just use preg_match and then work with the matches seperetaly).
This example works (although it uses an anonymous function for the callback, which requires PHP 5.3.0+):
function fixOrdinals($string) {
    return preg_replace_callback("/[0-9][A-Z]/",
        function ($matches) {
            return strtolower($matches[0]);
        },
        $string
    );
}

echo fixOrdinals("3Rd Floor, Cumbrian House")."\n";
echo fixOrdinals("Room 223, 2Nd Floor")."\n";
echo fixOrdinals("4Th Room, 2Nd Floor")."\n";

Output:
3rd Floor, Cumbrian House
Room 223, 2nd Floor
4th Room, 2nd Floor

A: <?php

    $ordinalregex = '/(\d+)(st|nd|rd|th)/ei';
    $input = "Room 223, 2Nd Floor";

    $input = preg_replace($ordinalregex, "strtolower('$1$2')", $input);

    print($input);

The /e modifier tells the interpreter to use eval. Now this works, however it's NOT SECURE. If your input has a \0 (null char) due to a C bug the interpreter will execute the part of the sting after the \0.


text:
Q: What are all the possible combinations of information needed to write a linear equation? In order for someone to write a linear equation, they need some information about the line. For example, here are a few info combinations where writing a linear equation is possible:

*

*Slope + Y-intercept (solution: plug in values)

*Slope + 1 coordinate point that the line goes through (solution: increase or decrease coordinate by slope value until x = 0 to find y-intercept)

*2 coordinate points (solution: find slope and do the same as step 2 to find y-intercept)

*1 coordinate point and the equation of a line that's parallel/perpendicular to the other line (Parallel solution: plug in the slope of the other line and repeat step 2 to find y-intercept. Perpendicular Solution: get negative reciprocal of the slope of the other line and repeat step 2 to find y-intercept)

Is there any other info or info combinations that could be involved? This is a little hard to explain so if it's unclear, please tell me in the comments.


text:
Q: sed command to replace start of a line with new line, but line includes " / caused sed output errors I'm trying to replace the following line:
<inet-address value="${bind.address:IP}"/>

with a different line but I keep running into issues. There are similar lines up until the point where {bind.address: is different. IP is replaced with a random IP, so I just need to replace the entire line with a new one below.
I want to replace the entire line above with:
   <inet-address value="${bind.address:127.0.0.1}"/>

The combinations of " and / are causing me some issues and getting errors on output like:
sed: -e expression #1, char X: unknown option to `s'
Thank


text:
Q: pandas style not showing column name When I use style to format a pandas dataframe in a Jupyter notebook, the name of the columns (df.columns.name) is not displayed.
How can I fix this?
Set up:
import pandas as pd
from IPython.display import HTML, display

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]], columns = [-1,0,1], index=[-1,0,1])
df.index.name = 'A'
df.columns.name = 'B'

This is how the data look like:
display(df)   # Has name of columns 'B'

Now, I want to add percentage formatting to all columns:
display(df.style.format("{:.1%}"))

but I have lost the name of columns!

A: I try your code, not find your problems, I get this:

I think you update your pandas or jupyter version will fix it.


text:
Q: How to sign out of a Google Drive account? How do I log out of the Google Drive service? I do not want to switch accounts but to log out definitively.
I am working on an app that will use the user's Google Drive storage among other storage services. Therefore I need to allow the user to sign out of Google Drive.

A: I found that this works. These are the same sign in options I use. Replace with your own.
I put this right before my sign in code so the user chooses an account each time.
    val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestScopes(Drive.SCOPE_FILE).requestScopes(Drive.SCOPE_APPFOLDER).build()
    val googleSignInClient = GoogleSignIn.getClient(this, signInOptions)
    googleSignInClient.signOut()

A: Leaving aside I think this is a poor API implementation, this is how you log out.
mGoogleApiClient.unregisterConnectionCallbacks(mConnectionCallbacksListener);
mGoogleApiClient.unregisterConnectionFailedListener(mOnConnectionFailedListener);
mGoogleApiClient.clearDefaultAccountAndReconnect();

The unregistration of the callbacks is to avoid the API showing the Google Account picker, in other words, to avoid reconnecting. Remember to set the callbacks again if you are going to sign in to any Google service later!
Optionally, you can get the operation's result:
mGoogleApiClient.clearDefaultAccountAndReconnect().setResultCallback(new ResultCallback<Status>() {
        @Override
        public void onResult(Status status) {
            // Optional
        }
    });


text:
Q: Correct usage of os.NewFile in Go I'm attempting to compose an image in memory and send it out through http.ResponseWriter without ever touching the file system.
I use the following to create a new file:
file := os.NewFile(0, "temp_destination.png")

However, I don't seem to be able to do anything at all with this file. Here is the function I'm using (which is being called within an http.HandleFunc, which just sends the file's bytes to the browser), which is intended to draw a blue rectangle on a temporary file and encode it as a PNG:
func ComposeImage() ([]byte) {
    img := image.NewRGBA(image.Rect(0, 0, 640, 480))
    blue := color.RGBA{0, 0, 255, 255}
    draw.Draw(img, img.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)

    // in memory destination file, instead of going to the file sys
    file := os.NewFile(0, "temp_destination.png")

    // write the image to the destination io.Writer
    png.Encode(file, img)

    bytes, err := ioutil.ReadAll(file)
    if err != nil {
        log.Fatal("Couldn't read temporary file as bytes.")
    }

    return bytes
}

If I remove the png.Encode call, and just return the file bytes, the server just hangs and does nothing forever.
Leaving the png.Encode call in results in the file bytes (encoded, includes some of the PNG chunks I'd expect to see) being vomited out to stderr/stdout (I can't tell which) and server hanging indefinitely.
I assume I'm just not using os.NewFile correctly. Can anyone point me in the right direction? Alternative suggestions on how to properly perform in-memory file manipulations are welcome.

A: os.NewFile is a low level function that most people will never use directly. It takes an already existing file descriptor (system representation of a file) and converts it to an *os.File (Go's representation).
If you never want the picture to touch your filesystem, stay out of the os package entirely. Just treat your ResponseWriter as an io.Writer and pass it to png.Encode.
png.Encode(yourResponseWriter, img)

If you insist on writing to an "in memory file", I suggest using bytes.Buffer:
buf := new(bytes.Buffer)
png.Encode(buf, img)
return buf.Bytes()

A: Please have a detailed read of the NewFile documentation. NewFile does not create a new file, not at all! It sets up a Go os.File which wraps around an existing file with the given file descriptor (0 in your case which is stdin I think).
Serving images without files is much easier: Just Encode your image to your ResponseWriter. That's what interfaces are there for. No need to write to ome magic "in memory file", no need to read it back with ReadAll, plain and simple: Write to your response.


text:
Q: Contour integration with absolute value I am trying to use contour integration to evaluate the integral
$$
\int_\mathbb{R}\frac{|x|e^{i\omega x}}{x^2+ a}dx \,,
$$
where $a>0$ and $\omega$ can take any real value. I am worried about the existence of the absolute value and I am not sure how to proceed.
Any help appreciated.
EDIT: Contour integration might not be the way to go here (see comments). In any case, it is easy to see that the integral in question is also equal to
$$
2\int_0^\infty \frac{x \cos(\omega x)}{x^2+ a}dx \,,
$$
and I am wondering whether anyone can produce a solution regardless of the method used.

A: Let's treat it like a Fourier Transform, and use a number of table lookups and theorems.
Set $\omega = -2\pi s$,
$$\begin{align*}\int_{-\infty}^\infty{\dfrac{|x|e^{i\omega x}}{x^2+a}}dx &= \int_{-\infty}^\infty{\dfrac{|x|e^{-2\pi is x}}{x^2+a}}dx \\
\\
&= \mathscr{F}\left\{\dfrac{|x|}{x^2+a}\right\} \\
\\
&= \mathscr{F}\left\{\dfrac{x\space\mathrm{sgn}(x)}{x^2+a}\right\}\\
\\
&= \mathscr{F}\left\{\dfrac{1}{x^2+a}\right\}*\mathscr{F}\left\{x\space\mathrm{sgn}(x)\right\} \\
\\
&= \dfrac{(2\pi)^2}{2\left(2\pi\sqrt{a}\right)}\mathscr{F}\left\{\dfrac{2\left(2\pi\sqrt{a}\right)}{(2\pi x)^2+\left(2\pi\sqrt{a}\right)^2}\right\}*-\dfrac{1}{2\pi i}\mathscr{F}\left\{-2\pi i x\space\mathrm{sgn}(x)\right\} \\
\\
&= \dfrac{2\pi}{2\sqrt{a}}e^{-2\pi\sqrt{a}|s|}*-\dfrac{1}{2\pi i}\dfrac{d}{ds}\dfrac{1}{i\pi s} \\
\\
&= \dfrac{1}{2\sqrt{a}}e^{-2\pi\sqrt{a}|s|}*\dfrac{d}{ds}\dfrac{1}{\pi s} \\
\\
&= \dfrac{1}{2\sqrt{a}}e^{-2\pi\sqrt{a}|s|}*-\dfrac{1}{\pi s^2} \\
\\
&= -\dfrac{1}{2\pi\sqrt{a}}\int_{-\infty}^{\infty} {\dfrac{e^{-2\pi\sqrt{a}|\tau|}}{(s-\tau)^2}}d\tau \\
\\
&= -\dfrac{1}{2\pi\sqrt{a}}\left[\int_{-\infty}^{0} {\dfrac{e^{2\pi\sqrt{a}\tau}}{(s-\tau)^2}}d\tau +\int_{0}^{\infty} {\dfrac{e^{-2\pi\sqrt{a}\tau}}{(s-\tau)^2}}d\tau\right] \\
\\
&= -\dfrac{1}{2\pi\sqrt{a}}\left[\int_{-\infty}^{-s} {\dfrac{e^{2\pi\sqrt{a}(t+s)}}{t^2}}dt +\int_{-s}^{\infty} {\dfrac{e^{-2\pi\sqrt{a}(t+s)}}{t^2}}dt\right] \\
\\
&= -\dfrac{1}{2\pi\sqrt{a}}\left[e^{2\pi\sqrt{a}s}\int_{-\infty}^{-s} {\dfrac{e^{2\pi\sqrt{a}t}}{t^2}}dt +e^{-2\pi\sqrt{a}s}\int_{-s}^{\infty} {\dfrac{e^{-2\pi\sqrt{a}t}}{t^2}}dt\right] \\
\\
&= -\dfrac{1}{2\pi\sqrt{a}}\left[e^{-\sqrt{a}\omega}\int_{-\infty}^{\frac{\omega}{2\pi}} {\dfrac{1}{t}\dfrac{e^{2\pi\sqrt{a}t}}{t}}dt +e^{\sqrt{a}\omega}\int_{\frac{\omega}{2\pi}}^{\infty} {\dfrac{1}{t}\dfrac{e^{-2\pi\sqrt{a}t}}{t}}dt\right] \\
\\
&= -\dfrac{1}{2\pi\sqrt{a}}\left[e^{-\sqrt{a}\omega}\int_{-\frac{\omega}{2\pi}}^\infty {\dfrac{1}{t}\dfrac{e^{-2\pi\sqrt{a}t}}{t}}dt +e^{\sqrt{a}\omega}\int_{\frac{\omega}{2\pi}}^{\infty} {\dfrac{1}{t}\dfrac{e^{-2\pi\sqrt{a}t}}{t}}dt\right] \\
\\
\end{align*}$$
So those integrals are looking really close to being an integration by parts resulting in an expression involving the Exponential Integral function, and Wolfram Alpha confirms the indefinite integral results include the Exponential Integral function.
I think getting to the final result from here is straightforward, but tedious.


text:
Q: Proof that $\left(\lim_{N\to \infty}\sum_{n=-N}^N \frac{(-1)^n}{z-n\pi}\right)^2=\lim_{N\to \infty}\sum_{n=-N}^N \left(\frac{(-1)^n}{z-n\pi}\right)^2$ How would I prove the following identity? $$\left(\lim_{N\to \infty}\sum_{n=-N}^N\frac{(-1)^n}{z-n\pi}\right)^2=\lim_{N\to\infty}\sum_{n=-N}^N \left(\frac{(-1)^n}{z-n\pi}\right)^2$$
Can this be proved algebraically?

A: $$f(z)=\left(\sum_{n\in\mathbb{Z}}\frac{(-1)^n}{z-n\pi}\right)^2-\sum_{n\in\mathbb{Z}}\left(\frac{(-1)^n}{z-n\pi}\right)^2$$ It is $2\pi$-periodic, entire (because $\left(\sum_{n\in\mathbb{Z}}\frac{(-1)^n}{z-n\pi}\right)^2$ is even), grouping the terms of the first series by two shows it is $O(|z|)$ on $\Re(z)\in [-\pi,\pi]$ thus it is $O(z)$ on the whole complex plane and $g(z)=\frac{f(z)-f(0)}{z}$ is entire and bounded thus constant. Since $zg(z)$ is periodic then $g(z)=0$ and $f(z)=f(0)$.
To find $f(0)$ : the second series is absolutely convergent thus it vanishes at $i\infty$, not sure how to deal with the first series, anyway since we know it is bounded away from its poles, it is immediate that it is $= \frac{1}{\sin( z)}+C$ and $C=0$ because it is odd.


text:
Q: API call function with completion handler crashes when accessed from different VC Can someone fix my function code because I have created a API call function which will get the imageURL for the specific object in my class and display the results in the second view controller. I have created custom completion handler so that the code from second VC is only executed when dowloading of the imageURL is completed.
However, when I am testing this function in the second view controller to print me data that it has arrived I am getting a crash on the print statement line.
Here is the code for my API call function located in Model class file:
func parseImageData(finished: () -> Void) {

    let urlPath = _exerciseURL
    let url = URL(string: urlPath!)

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in

        if error != nil {
            print("Error while parsing JSON")
        }
        else {

            do {
                if let data = data,
                    let fetchedImageData = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String:Any],
                    let images = fetchedImageData["results"] as? [[String: Any]] {

                    for eachImage in images {
                        let imageUrl = eachImage["image"] as! String
                        self._imageUrl = URL(string: imageUrl)
                    }

                    print(self._imageUrl)

                }
            }
            catch {
                print("Error while parsing data.")
            }
        }

    }
    task.resume()
    finished()
}

And here in the second view controller I am just testing if I can access the code block:
override func viewDidLoad() {
    super.viewDidLoad()

    exercise.parseImageData() {
        print("Arrived Here?") // I am getting crash on this line moving to debug navigator.

    }

}

A: If the crash says something about force unwrapping nil then it's probably because let task = URLSession.shared.dataTask(with: url!) is unwrapping url which is a nil optional variable here.
But your completion handler is called in the wrong place anyway, try putting your finished() callback into the do statement instead. Because finished was executed the moment you called exercise.parseImageData()
if error != nil {
   print("Error while parsing JSON")
}
else {

    do {
        if let data = data,
            let fetchedImageData = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String:Any],
            let images = fetchedImageData["results"] as? [[String: Any]] {

            for eachImage in images {
                let imageUrl = eachImage["image"] as! String
                self._imageUrl = URL(string: imageUrl)
            }

            print(self._imageUrl)

            finished()
        }
    }
    catch {
        print("Error while parsing data.")
    }
}


text:
Q: For loop in the csv module I was using the csv module to do some parsing, but I have been confounded by a problem that I couldn't really put my hands on. I think the for-loop for the csv.reader() eliminates the row that has been looped through. For example:
import csv

f = open('example.csv', 'rb')
r = csv.reader(f)

for row in r:
    print(row[0])

for row in r:
    print(row[1])

While the first for-loop prints out some stuff, the second does not. It would be great if someone could explain what is going on here behind the scenes.

A: It's late so sorry about any mistake, I need to do some brush up on my python skills, but I will try to solve your problem.
From the documentation:

csv.reader(csvfile, dialect='excel', **fmtparams)
Return a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called

Usually a reader is positioned in the beginning of the target file and begin reading it line by line every time the user calls next(), so you should not expect the reader to iterate again over the same file, because it has already iterated over it.
In this example, we read the first 2 lines of a csv file:
import csv
with open('example.csv', 'rb') as csvfile:
    r = csv.reader(csvfile)
    line = r.next()
    line2 = r.next()
print line
print line2

The result is:
['name', 'lastname', 'number']
['name1', 'lastname1', '99999999']

So, from this you can assume that the next() method from the reader returns a list of tokens as strings for each line read from the csv.
From the documentation: For Loops

...any object with an iterable method can be used in a for loop in Python...
...Having an iterable method basically means that the data can be presented in list form, where there's multiple values in an orderly fashion. You can define your own iterables by creating an object with next() and iter() methods...

See this example:
import csv
csvList = []
with open('example.csv', 'rb') as csvfile:
    r = csv.reader(csvfile)
    for row in r:
        csvList.append(row)
print csvList

This outputs the values as a list of strings, including the headers:
[['name', 'lastname', 'number'], ['name1', 'lastname1', '99999999'], ['name2', 'lastname2', '88888888']]
There are some utility methods you can make good use if you intend to parse a csv, like the DictReader().
import csv
with open('example.csv', 'rb') as csvfile:
    r = csv.DictReader(csvfile)
    for row in r:
        print(row['name'], row['lastname'], row['number'])

This will print:
('name1', 'lastname1', '99999999')
('name2', 'lastname2', '88888888')

From the documentation:

csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds): Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the optional fieldnames parameter.

So if you want to have a list of the different values for each field of your csv file, you could create a dictionary and append each value of the row in each iteration.
import csv
nameDict = {'name':[], 'lastname':[], 'number':[]}
with open('example.csv', 'rb') as csvfile:
    r = csv.DictReader(csvfile)
    for row in r:
        nameDict['name'].append(row['name'])
        nameDict['lastname'].append(row['lastname'])
        nameDict['number'].append(row['number'])
print nameDict

This produces something like this:
{'lastname': ['lastname1', 'lastname2', 'lastname3', 'lastname4', 'lastname5', 'lastname6', 'lastname7', 'lastname8', 'lastname9', 'lastname10'], 'name': ['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8', 'name9', 'name10'], 'number': ['99999999', '88888888', '88888888', '88888888', '88888888', '88888888', '88888888', '88888888', '88888888', '88888888']}

Refer to the module documentation for better ways to parse csv.
Hope this helps you.


text:
Q: Android App crashes after proguard obfuscation (Google plus people search) I added some code to my app to search people on Google Plus. This code works well without Proguard. After running proguard to obfuscate the code, my app crashes when searching for people on google plus.
09-14 10:21:51.346: E/AndroidRuntime(12527): FATAL EXCEPTION: AsyncTask #4
09-14 10:21:51.346: E/AndroidRuntime(12527): Process: com.mapegames.sudokukings, PID: 12527
 java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:300)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:864)
 Caused by: java.lang.NullPointerException
    at com.google.api.client.util.Types.getActualParameterAtPosition(SourceFile:327)
    at com.google.api.client.util.Types.getIterableParameter(SourceFile:307)
    at com.google.api.client.http.HttpHeaders.parseHeader(SourceFile:1158)
    at com.google.api.client.http.HttpHeaders.fromHttpResponse(SourceFile:989)
    at com.google.api.client.http.HttpResponse.<init>(SourceFile:148)
    at com.google.api.client.http.HttpRequest.execute(SourceFile:969)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(SourceFile:410)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(SourceFile:343)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(SourceFile:460)
    at com.mapegames.sudokukings.PlayersActivity$getPeople.doInBackground(SourceFile:904)
    at com.mapegames.sudokukings.PlayersActivity$getPeople.doInBackground(SourceFile:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)

... 4 more

I have tried to keep the classes in the proguard config-file which are related to the google.api.sevices.plus, but this doesn't work.
-keep class com.mapegames.sudokukings.** { *; }
-keep class com.google.api.client.** { *; }
-keep class com.google.api.services.plus.** { *; }
-keep class com.google.api.services.plus.model.** { *; }
-keep class java.lang.** { *; }
-keep class android.os.** { *; }

It seems that the error occurs at the following execute "src[0].execute()" in the code below.
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.model.PeopleFeed;

private Plus.People.Search searchPeople;

private void searchPeople(String name) throws IOException {
    searchPeople = plusSvc.people().search(name);
    searchPeople.setMaxResults(5L);
    status.setText(getString(R.string.searching) + " 10%");
    Log.i(TAG, "searchPeople: " + searchPeople);

    new getPeople().execute(searchPeople);
}

private class getPeople extends AsyncTask<Plus.People.Search, Void, PeopleFeed> {

     public PeopleFeed doInBackground(Plus.People.Search... src) {
         Log.i(TAG, "Start PeopleSearch");
         try {
             Log.i(TAG, "Try PeopleSearch: " + src[0]);
             return src[0].execute();
         } catch (IOException e) {
             Log.i(TAG, "Catch PeopleSearch");
             e.printStackTrace();
             return null;
         }
     }

     protected void onPostExecute(PeopleFeed feed) {
         Log.i(TAG, "Set PeopleSearch");
         setPeople(feed);
     }
 }

The last lines of my Log-file below show the error occurs at "src[0].execute()".
09-13 13:17:14.170: I/PL(2881): searchPeople: {b=yhb, f=5, key=AIzaSyAfaXmYlCopeZuV-Rk5rdwGOBP3Pdkp24o}
09-13 13:17:14.170: I/PL(2881): Start PeopleSearch
09-13 13:17:14.170: I/PL(2881): Try PeopleSearch: {b=yhb, f=5, key=AIzaSyAfaXmYlCopeZuV-Rk5rdwGOBP3Pdkp24o}

Im not sure this information above is sufficient enough, so please let me know when additional information is required.

A: Can you try:
-keep class com.google.api.services.plus.** { *; }

You can also check what gets taken away by looking at the proguard output files.
EDIT - Your problem might be similar to these:

*

*http://softwyer.wordpress.com/2012/10/20/android-google-drive-sdk-and-proguard/

*Google Drive API doesn't play well with ProGuard (NPE)
These are for Drive, but the location of the NPE is similar, and they provide a working proguard config you can start with.


text:
Q: Everything except index.html gets 404 in Github Pages This is the Github page for my project.
https://bootsoon.github.io/ng-circle-progress/
Everything except index.html gives a 404 error and can't be loaded. I've tried locally and it works perfectly.
And it worked fine before I updated my gh-pages branch yesterday.
These files are indeed in repository: https://github.com/bootsoon/ng-circle-progress/blob/gh-pages/inline.073c4f038407ccd2fce1.bundle.js
But cannot be visited (404 error): https://bootsoon.github.io/inline.073c4f038407ccd2fce1.bundle.js
What am I suppose to do ?

A: You need to go to https://bootsoon.github.io/ng-circle-progress/inline.073c4f038407ccd2fce1.bundle.js, where bootsoon is your username (or organization name), ng-circle-progress is your repo name, and inline.073c4f038407ccd2fce1.bundle.js is your file name. :)


text:
Q: Calculating marginal effects from predicted probabilities of zeroinfl() model object This plot, which I previously created, shows predicted probabilities of claim onset based on two variables, PIB (scaled across the x-axis) and W, presented as its 75th and 25th percentiles. Confidence intervals for the predictions are presented alongside the two lines.
Probability of Claim Onset
As I theorize that W and PIB have an interactive effect on claim onset, I'd like to see if there is any significance in the marginal effect of W on PIB. Confidence intervals of the predicted probabilities alone cannot confirm that this effect is insignificant, per my reading here (https://www.sociologicalscience.com/download/vol-6/february/SocSci_v6_81to117.pdf).
I know that you can calculate marginal effect easily from predicted probabilities by subtracting one from the other. Yet, I don't understand how I can get the confidence intervals for the marginal effect -- obviously needed to determine when and where my two sets of probabilities are indeed significantly different from one another.
The function that I used for calculating predicted probabilities of the zeroinfl() model object and the confidence intervals of those predicted probabilities is derived from an online posting (https://stat.ethz.ch/pipermail/r-help/2008-December/182806.html). I'm happy to provide more code if needed, but as this is not a question about an error, I am not sure it is needed.

A: So, I'm not entirely sure this is the correct answer, but to anyone who might come across the same problem I did:
Assuming that the two prediction lines maintain the same variance, you can pool SE before then calculating. See the wikipedia for Pooled Variance to confirm.
SEpooled <- ((pred_1_OR_pred_2$SE * sqrt(simulation_n))^2) * (sqrt((1/simulation_n)+(1/simulation_n)))
low_conf <- (pred_1$PP - pred_2$PP) - (1.96*SEpooled)
high_conf <- (pred_1$PP - pred_2$PP) + (1.96*SEpooled)

##Add this to the plot
lines(pred_1$x_val, low_conf, lty=2)
lines(pred_1$x_val, high_conf, lty=2)


text:
Q: Prove x(t) is bounded given a integral inequality I want to answer the following question:
$x=x(t)$ is defined and continuous on $[0,T)$ and satisfies an integral inequality
$$1 \leq x(t) \leq A_1 + A_2\int_0^t x(s)\big(1+\log x(s)\big) ds$$
for $0 \leq t < T$, where $C_1$ and $C_2$ are constants. Prove $x(t)$ is bounded on $[0,T]$.

A: We'll prove it without directly using the Gronwall's inequality.
By introducing $u(s):= \log(ex(s)),$ we see that $u$ satisfies
\begin{equation}
e \leq u(t) \leq eA_1 + A_2\int_0^t ue^u\,du =: v(t).
\end{equation}
Then, we observe $v'(t) = A_2 u(t)e^{u(t)}.$ Furthermore, since $t \mapsto te^t = \alpha(t)$ is strictly increasing on $t \geq 0,$ and $u \leq v,$ we see $ \alpha(u) \leq \alpha(v),$ or equivalently,
$$
A_2 \frac{ue^u}{ve^v} \leq A_2 \Leftrightarrow \frac{v'(t)}{ve^v} \leq A_2.
$$
Define $g(t) := \int_a^t \frac{\,dt}{te^t},$ where $a>0$ is any real number.
Then we see,
$$
\frac{\,dg(v)}{\,dx} \leq A_2,
$$
and hence integrating, we see with $k = v(a),$
$$
g(v(t)) \leq  g(k) + A_2(t-a).
$$
Since $g$ is increasing, we see
$$
v(t) \leq g^{-1} \left( g(k) + A_2(t-a) \right),
$$
and we are done if we by recalling that $y(t) \leq v(t),$ except a remark in order, namely that the above estimate doesn't depend on the choice of $a.$ Indeed,
setting $\tilde{g(t)} = \int_{\tilde a}^t \frac{\,dt}{\alpha(t)},$ we see
$
\tilde{g(v)} = g(v) - \int_a^{\tilde{a}} \frac{\,dt}{\alpha(t)},
$
and $\tilde{g}^{-1}(v) = g^{-1}(v + \int_a^{\tilde{a}} \frac{\,dt}{\alpha(t)}).$


text:
Q: How can I return an image as the output of a google sheet custom function? I have a custom function in a google sheet. How can I return an image instead of normal data(for example number) as the output of this custom function ?
In fact I am going to read this image from image-charts.com site, which means that image-charts.com creates this image for us and gives us its url, and I actually want to be able to use this image that was created in a Google Sheet cell.
Can google sheet custom functions support image as the return value of the function?
Thanks in advance

A: Update
Found an answer to what you actually wanted. There is IMAGE (see reference), a function that adds an URL as an image into a cell (didn't know it existed). So you could do something like:
=IMAGE(GETCHARTURL(...))

Original workaround
You cannot add an image in a cell. You cannot show an image as the result of a formula either. The best What you can do is having a button that calls a Google Apps Script function that adds the images on top of the cells using Sheet.insertImage (reference).
I've made this little script that automatically adds the image on top of the cells that have the value img+ followed by the image url (eg. img+https://example.com/image.png):
const IMAGE_HEIGHT = 100 // Image height in pixels
function sameRange(a, b) {
  return a.getGridId() === b.getGridId()
    && a.getA1Notation() === b.getA1Notation()
}
function addImages() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet()
  const toChange = sheet
    .createTextFinder(/^img\+https?:\/\//.source)
    .useRegularExpression(true)
    .findAll()

  // Remove old image(s)
  for (let img of sheet.getImages()) {
    const range = img.getAnchorCell()
    if (toChange.some(r => sameRange(r, range))) {
      img.remove()
    }
  }

  // Create new ones
  for (let range of toChange) {
    const url = range.getValue().toString().split(/\+(.*)$/, 2)[1]
    const image = range.getSheet()
      .insertImage(url, range.getColumn(), range.getRow(), 0, 0)

    image.setAltTextTitle("Chart")

    const w = image.getWidth()
    const h = image.getHeight()
    image.setWidth(IMAGE_HEIGHT*w/h) // Keep aspect ratio
    image.setHeight(IMAGE_HEIGHT)
  }
}

Then simply make a new button (a drawing with text) and set addImages as the assigned script.
I don't know your exact use case so you will probably need to modify the script to better fit your needs.
References

*

*IMAGE function (Docs Editor Help)

*Sheet.insertImage(url, column, row, offsetX, offsetY) (Google Apps Script reference)

*Class OverGridImage (Google Apps Script reference)

*Sheet.createTextFinder(findText) (Google Apps Script reference)

*Class TextFinder (Google Apps Script reference)

*Class Range (Google Apps Script reference)


text:
Q: Numberpart of a string in specific range I'm using a SqlServe and I need to get all rows where a part of the string is within a specific numberRange.
As example I've got in the column uniqueStringID:

*

*BE09 Mytest

*BE10 Mytest

*CE101 Mytest

*CE300 Mytest

and I want to get all rows where the number within uniqueStringID (the number has to be located before the space) is between (including) 10 and 101
So result would be:

*

*BE10 Mytest

*CE101 Mytest

My question here is this possible with just SQL or would I need a stored procedure for that? And if the former how would the SQL be?

A: drop table #t
create table #t(id varchar(100))
insert into #t values('BE09 Mytest'),
('BE10 Mytest'),
('CE101 Mytest'),
('CE300 Mytest'),
('CE450595 Mytest')

select id,cast(substring(id,patindex('%[0-9]%',id),patindex('%[a-z0-9] [a-z]%',id)-1) as int) from #t where cast(substring(id,patindex('%[0-9]%',id),patindex('%[a-z0-9] [a-z]%',id)-1) as int) between 10 and 101

FIDDLE DEMO
FIDDLE DEMO WITH FEW MORE TEST CASES

A: Hi first Create function in sql server
CREATE FUNCTION dbo.udf_GetNumeric (@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
END
END
RETURN ISNULL(@strAlphaNumeric,0)
END

and then use below query to get result
SELECT * FROM
(
SELECT uniqueStringID,dbo.udf_GetNumeric(uniqueStringID) AS NumuniqueStringID
 FROM YourTableName
) a
WHERE NumuniqueStringID >=10 and NumuniqueStringID<=101

A: You can use substring to get part with your number for filtering  (in all your examples string in the end is always the same length):
select cast(substring(uniqueStringID, 3, len(uniqueStringID)-9) as int)


text:
Q: Is the subgroup of orthogonal matrices in $GL_3(\mathbb R)$ cyclic? What's generating it?
Is the subgroup of $GL_3(\mathbb R)$ denoted by $Q=\{A \in GL_3(\mathbb R)\mid AA^t=I_3\}$ cyclic? What's generating it?

I showed $Q$ is a group, and realized it's the group of all orthogonal matrices. My conjecture is that the generating element is some sort of rotation matrix, however it seems that rotation around the x-axis, for instance:
        \begin{bmatrix}
        \cos x & -\sin x & 0 \\
        \sin x & \cos x & 0 \\
        0 & 0 & 1 \\
        \end{bmatrix}
Seems to be like it doesn't generate some orthogonal matrices, actually all those that don't have the element 1 in the (3,3) entry...
Thanks in advance for any assistance!


text:
Q: Сжатие CSS файлов средствами php Есть функция сжатия css файлов.
 Как можно удалить все пробелы после знака ,,  :,  ;,  )
function compression_files($files_css, $new_file) {
        // получаем содержимое всех css файлов
        $content_css = "";
        foreach($files_css as $one_file){
            $content_css .= @file_get_contents($one_file);
            if(!$content_css) return false; // если какой-то из файлов не получилось прочитать
        }

        // удаляем комментарии
        $content_css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!','', $content_css);
        // удаляем табуляции и переходы на новую строку
        $content_css = str_replace(array("\r\n","\r","\n","\t"),'', $content_css);
        // удаляем повторяющиеся пробелы
        $content_css = preg_replace('/ {2,}/','', $content_css);

        // сохраняем результат в файл
        $css_file = fopen ($new_file, "w+");
        fwrite($css_file, $content_css);
        $result_save = fclose($css_file);

        // вернем результат сохранения
        return $result_save;
    }
    ////  Пример использования этой функции:  ////

    // массив с путями до css файлов
    //$css_array = array('style.css','main.css');
    $css_array = array('style.css');

    // путь, куда будет сохранен сжатый файл
    $new_file = "compression.css";
    // вызываем функцию сжатия
    $result = compression_files($css_array, $new_file);

    if(file_exists($new_file)){
       echo "Файл успешно создан";
    }else{
       echo "Ошибка";
    }

A: $content_css = preg_replace('/([,:;)]) /','$1', $content_css);
В этом выражении все что в круглых скобках, так называемая группа захвата, каждая такая группа может быть использована в выражении на что менять и там обозначена как $1, если бы были еще круглые скобки были бы $2 и т.д.
Квадрантные скобки - перечисление символов, т.е. в этом месте строки ожидается любой из перечисленных в скобках символов. Ну и пробел поле скобок обозначает сам себя. preg_replace заменяет найденное выражение целиком на то, что после запятой, мы в данном случае нашли, например ,, но запятую нам удалять не надо, а только пробел после нее. поэтому в правой части и стоит $1. В итоге получаем заменить запятую с пробелом на запятую.
И мне $content_css = preg_replace('/ {2,}/','', $content_css); не нравится, она удаляет все двойные пробелы, вообще удаляет. т.е. если в строке 3 пробела, то все ok, а если четное кол-во - то ни одного не останется. Если такое поведение и задумывалось то ok, просто не знаю на сколько привередлив css.
Если один пробел от любых строк пробелов оставить то
$content_css = preg_replace('/ + /',' ', $content_css);
В последнем выражении все элементарно, + обозначает повтор предыдущего символа 1 и более раз. Т.е. заменить один и более пробелов и еще один пробел на один пробел


text:
Q: PowerShell dynamic menu from xml I'm drawing a blank here and I'm sure the answer is right in front of me. I'm trying to build a dynamic menu to launch small apps in a WinPE image. I'm using an XML file for the data (it seemed the most appropriate)
Now my xml file looks like this
<Programs>
    <!-- Programs -->
    <Program Name="7-Zip" Path="\7-Zip\7zFM.exe" Type="Addin"/>
    <Program Name="HwMonitor" Path="\HwMonitor\HwMonitor.exe" Type="Addin"/>
    <!-- HDTools -->
    <Program Name="Defraggler" Path="\Defraggler64\Defraggler64.exe" Type="Hdtools"/>
</Programs>

where I'm running into a problem, is the function I wrote to take a $Type parameter so I can filter based on the type. The filter itself works fine, it's the part just below for building the menu....it only works if there's more than one item matching that criteria.
Function Select-Program($Type)
{
    clear; MenuHeader
    Write-Host " ----------------------------------------------------------------------- "

    $List = $null # set the list to null, for some reason there was duplication when re-entering the menu

    try
    {
        $AddinPath = switch([System.IntPtr]::Size)
        {
            8 {Join-Path (Get-PEDrive).DriveLetter "Programs64"}
            4 {Join-Path (Get-PEDrive).DriveLetter "Programs"}
        }

        $ListFile = Join-Path $AddinPath "Programs.xml"

        [xml]$Programs = Get-Content $ListFile
        Write-Host " "
        $List = $Programs.DocumentElement.Program | Where-Object {$_.Type -eq $Type}

    }
    catch [exception]
    {
    $_.Exception
    }

    # if there's no items in the list, then write a message
    if ($List.Count -eq 0)
    {
        Write-Host "  No Programs Found" -ForegroundColor Red
        Write-Host " "
    }

    $menu = @{}

    # build menu item list dynamically from the imported data

    for ($i=1;$i -le $List.count; $i++)
    {
        Write-Host "  $i. $($List[$i-1].Name)" -foregroundcolor White
        $menu.Add($i,($List[$i-1].Name))
    }

    # add one last item to return to main menu
    Write-Host "  $i. Return to main menu" -foregroundcolor White
    $menu.Add($i,"return")

    #prompt for selection
    Write-Host " "
    [int]$ans = Read-Host ' Enter selection'
    $selection = $menu.Item($ans)

    if ($selection -eq "return")
    {
        MainMenu
    }

    # launch the selected application
    $Launch = Join-Path $AddinPath ($List | Where-Object {$_.Name -eq $selection}).Path
    Start-Process $Launch

    Select-Program -Type $Type # reload the program menu
}

If I run "Select-Program -Type Addin" with the above XML, I get a menu with 2 items, plus the return to main menu. However, if I run "Select-Program -Type Hdtools" I get nothing because there's only one item with this type in the XML file.
I tried this morning with a CSV file and I get the same thing, so I don't think it has anything to do with where the data is coming from or what format I pull it from.
What am I missing here? I tohught the less than operator was messing me up so I tried less than or equal but that bombed on me too and leaves me scratching my head at the moment

A: I'm going to suggest a different approach that I think will simplify the whole process.
First, generate objects that represent what you're storing in XML, then export them as CliXML or JSON:
$objects = @()
$objects += [PSCustomObject]@{
    Name = "7-Zip"
    Path = "\7-Zip\7zFM.exe"
    Type = "Addin"
}
$objects += [PSCustomObject]@{
    Name = "Defraggler"
    Path ="\Defraggler64\Defraggler64.exe"
    Type = "Hdtools"
}
# etc.
$objects | Export-CliXml -Path C:\my.xml
$objects | ConvertTo-Json | Set-Content -Path C:\my.json

Now, when you want to bring them back in:
# from xml
$List = Import-CliXml -Path C:\my.xml

# or from JSON
$List = Get-Content -Path C:\my.json -Raw | ConvertFrom-Json

$List = $List | Where-Object { $_.Type -eq $Type }

$menu = @{}
for ($i=1;$i -le $List.count; $i++)
{
    Write-Host "  $i. $($List[$i-1].Name)" -foregroundcolor White
    $menu.Add($i,($List[$i-1].Name))
}

I think this simplifies the process of exporting and importing objects in a consistent way. The array should be serialized as part of the export process and deserialized as part of the import, so you won't have to worry about a method or cmdlet returning a single object.

A: I solved it. The problem was that PowerShell handles the array differently when there's only a single item. I experienced the same behavior importing from CSV. This appears to result specifically from piping the data through the Where-Object cmdlet
When only one item was pulled from the XML $List variable being piped through Where-Object, $List[0].Name returned a blank string, where $List.Name returned the desired value.
The solution was to change this
$menu = @{}
for ($i=1;$i -lt $List.count; $i++)
{
    Write-Host "  $i. $($List[$i-1].Name)" -foregroundcolor White
    $menu.Add($i,($List[$i-1].Name))
}

To this
$menu = @{}
for ($i=1;$i -le $List.Name.count; $i++)
{
    $DisplayName = switch([string]::IsNullOrEmpty($List[$i-1].Name))
    {
        $true {$List.Name}
        $false {$List[$i-1].Name}
    }

    Write-Host ([string]::Format("  {0}. {1}", $i, $DisplayName)) -foregroundcolor White
    $menu.Add($i,($DisplayName))
}

The main items of focus are the following
-change $List.count to $List.Name.count as $List.Count returned a null or empty value when only was item was in the XML data
-change -lt (less than) to -le (less or equal) because with only one item and the $i value starting at one a less than would never meet the criteria
-added a switch variable to check if $List[$i-1].Name returned a null as it did with only a single item. in this case, use $List.Name
-used string.Format method for the output line, not necessary, but I find it to be a more predictable method of joining strings in some cases


text:
Q: Open connections with Hibernate + Spring + C3P0 + Multithreading I have the next abstract configuration class:
@Configuration
@ComponentScan("my.app")
@EnableTransactionManagement
public abstract class AbstractApplicationConfig {
protected HibernateTransactionManager newHibernateTransactionManager(final LocalSessionFactoryBean localSessionFactoryBean) {
    final HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
    hibernateTransactionManager.setSessionFactory(localSessionFactoryBean.getObject());
    return hibernateTransactionManager;
}

protected LocalSessionFactoryBean newLocalSessionFactoryBean(final DataSource dataSource, final String packagesToScan) {
    final LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
    localSessionFactoryBean.setPackagesToScan(packagesToScan);
    localSessionFactoryBean.setDataSource(dataSource);

    final Properties properties = new Properties();
    properties.setProperty("hibernate.dialect", env.getRequiredProperty("databasePlatform"));
    properties.setProperty("hibernate.show_sql", env.getRequiredProperty("showSql"));
    properties.setProperty("hibernate.jdbc.batch_size", 10);
    properties.setProperty("hibernate.order_inserts", true);
    properties.setProperty("hibernate.order_updates", true);
    properties.setProperty("hibernate.jdbc.batch_versioned_data", true);

    properties.setProperty("hibernate.c3p0.min_size", 10);
    properties.setProperty("hibernate.c3p0.max_size", 50);
    properties.setProperty("hibernate.c3p0.timeout","300");
    properties.setProperty("hibernate.c3p0.max_statements", 50);
    properties.setProperty("hibernate.c3p0.idle_test_period", "3000");

    localSessionFactoryBean.setHibernateProperties(properties);
    return localSessionFactoryBean;
}

protected DataSource newDataSource() {
    final ComboPooledDataSource dataSource = new ComboPooledDataSource();
    try {
        dataSource.setDriverClass(env.getRequiredProperty("dataSource.driverClassName"));
        dataSource.setJdbcUrl(env.getRequiredProperty("dataSource.url"));
        dataSource.setUser(env.getRequiredProperty("dataSource.username"));
        dataSource.setPassword(env.getRequiredProperty("dataSource.password"));
        dataSource.setPreferredTestQuery("SELECT 1 FROM DUAL");
        dataSource.setMaxPoolSize(Integer.valueOf(50));
        dataSource.setMinPoolSize(Integer.valueOf(10));
        dataSource.setMaxStatements(Integer.valueOf(50));
    } catch (final IllegalStateException e) {
        e.printStackTrace();
    } catch (final PropertyVetoException e) {
        e.printStackTrace();
    }
    return dataSource;
}
}

And I'm using it like this:
@Configuration
public class SchemaApplicationConfig extends AbstractApplicationConfig {

/** DATASOURCES **/

@Bean
public DataSource dsSchema() {
    final DataSource dataSource = newDataSource(DataSourcesNames.SCHEMA1);
    return dataSource;
}

/** SESIONFACTORIES **/

@Bean
public LocalSessionFactoryBean sfSchema() {
    final LocalSessionFactoryBean localSessionFactoryBean = newLocalSessionFactoryBean(dsSchema(), "es.miapp.schema");
    return localSessionFactoryBean;
}

/** TRANSACTIONMANAGERS **/

@Bean
public HibernateTransactionManager txSchema() {
    final HibernateTransactionManager hibernateTransactionManager = newHibernateTransactionManager(sfSchema());
    return hibernateTransactionManager;
}
}

In my application, I run a process with several Threads:
public static void main(String... args) {
    AbstractApplicationContext context =  new AnnotationConfigApplicationContext(SchemaApplicationConfig.class);
    MainProcess mainProcess = context.getBean(MainProcess.class)
    mainProcess.execute();
    context.close();
    System.out.println("ENDS");
}

@Service
@Scope("prototype")
public class MainProcessImpl implements MainProcess{

    @Autowired
    protected ApplicationContext applicationContext;

    public void execute() {
        final ExecutorService executorService = Executors.newFixedThreadPool(5);
        final List<Future<?>> futures = new ArrayList<Future<?>>();
        for (int i = 0; i < 5; i++) {
            final MyService runnable = (MyService) applicationContext.getBean(MyServiceBean.class);
            final Future<?> future = executorService.submit(runnable);
            futures.add(future);
        }

        for (final Future<?> future : futures) {
            try {
                future.get();
            } catch (final InterruptedException e) {
                e.printStackTrace();
            } catch (final ExecutionException e) {
                e.printStackTrace();
            }
        }

        executorService.shutdown();
        try {
            executorService.awaitTermination(2, TimeUnit.MINUTES);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    }
}

MyServiceBean looks like this:
@Service
@Scope("prototype")
public class MyServiceBean implements Runnable {

    @Autowired
    private MyDao myDao;

    @Override
    public void run() {
        // Do Stuff and create entity
        myDao.insert(entity);
    }
}

And my Dao looks like this:
@Repository
public class MyDaoImpl implements MyDao {

    @Autowired
    @Qualifier("sfSchema")
    private SessionFactory sessionFactory;

    @Override
    @Transactional("txSchema")
    public void insert(Entity entity) {
        sessionFactory.getCurrentSession().persist(entity);
        sessionFactory.getCurrentSession().flush();
    }
}

The problem here is that Hibernate doesn't close all the connections, and after a  couple of runs of this process, I get the next error:
Caused by: java.net.BindException: Address already in use: connect

If I keep executing instances, there is a moment where the program hangs trying to do the insert:
[09-08-2018] [11:15:43,961] [DEBUG] [TEST] checkoutStatement: com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache stats -- total size: 18; checked out: 6; num connections: 6; num keys: 18
[09-08-2018] [11:15:43,961] [DEBUG] [TEST] insert into ENTITY... COMPLETE SQL
[09-08-2018] [11:15:43,961] [DEBUG] [TEST] Executing batch size: 1

Checking on Oracle, I can see that my user has already 46 connections opened and they keep increasing with every run...
Ideas?


text:
Q: Facebook like button causing page to jump when loading I have tried implementing the facebook like button on my website but it causes the content that comes after  to jump when loading. Any ideas as to why this is happening?

    Home
    >
    {{ collection.title }}

    {% if current_tags %}
      {% for tag in current_tags %}
        >
        {{ tag }}
      {% endfor %}
    {% endif %}

    {% if paginate.pages != 0 %}
      > Page {{ paginate.current_page }} of {{ paginate.pages }}
    {% endif %}

And here is the css (hopefully I have picked out the relevant part..)
.clearfix:after, .row:after { clear:both; }
.clearfix, .row { zoom:1; }

.breadcrumb { font-size: 12px; margin: 0 0 30px 0; }
.breadcrumb .arrow-space { margin: -2px 6px 0; font-size: 10px; opacity: .5; filter:alpha(opacity=50); }
.breadcrumb a { color: {{ settings.body_font_color }}; }

If you look at the home page http://festrags.com/ (password="cheaye")
The button doesn't cause a jump but on the product and collection pages it does http://festrags.com/collections/all
I have tried adding a width and height but it is just cutting off the frame and when I make it big enough it just pushes the content down.

A: The like Button is loading an iframe to your page, which is too Large for the desired viewport. Try to add this:
.hide-fb
{
    Overflow:hidden;
}

If that should Not work like that. You will have to add a certain width and height also.
To prevent the content of your list view to jump, you can add this css:
.breadcrumb .hide-fb {
    height: 34px;
    overflow: hidden;
}

The FB container has a height of 34px max (in this case), so when it's loaded your container (.hide-fb) will already have the correct height.
Update: Since the implemention above is cutting off the fb Share modal, we just Need to prevent the overflow until the iframe is loaded completly.
Try to remove every implementation of .hide-fb, that contains overflow:hidden; then just add this to your css:
.hide-fb:empty {
    height: 34px;
    overflow: hidden;
}

The Containers from the fb like plugin should Not be Cut off
Update 3:
This is beginning to get silly...
I've created a fiddle of your page and all I did was this:
.hide-fb {
    height: 34px;
}

your float: right is also applyed to that element. Now when i load the page the element is not jumping, when FB is loaded. Also I can use all controls without having them cut off. It Could be the german Facebook behaves differently or uses different controls. But the Share Window is opened in a new browser popup. When you click "like" a dialog appears that says: "Say more about this..." this look like it could have been cut off, but it is not. It seems to have to look like that.

A: I had a similar problem. The solution was to force the button to be of particular dimensions, rather than unstyled:
.fb-like {
    height: 30px;
    width: 78px;
    overflow: hidden;
    display: inline-block;
}

But this would mean that the "Like" popup could not appear. My subsequent solution was to add a new class fb-like-not-fixed-yet, which would have the fixes above - and set a window.setTimeout to remove the class once the Like button had loaded. Yuck.


text:
Q: How to get Dictionary from Database by using Linq to entity? I use something like this but some exception was occured. here is info about exception.
EXCEPTION:
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.Collections.Generic.Dictionary2[System.String,System.Collections.Generic.List1[System.Nullable1[System.Int64]]] ToDictionary[<>f__AnonymousType5a2,String,List1](System.Collections.Generic.IEnumerable1[<>f__AnonymousType5a2[System.String,System.Collections.Generic.List1[System.Nullable1[System.Int64]]]], System.Func2[<>f__AnonymousType5a2[System.String,System.Collections.Generic.List1[System.Nullable1[System.Int64]]],System.String], System.Func2[<>f__AnonymousType5a2[System.String,System.Collections.Generic.List1[System.Nullable1[System.Int64]]],System.Collections.Generic.List1[System.Nullable`1[System.Int64]]])' method, and this method cannot be translated into a store expression.
My code is here :
            List<Match> matches = new List<Match>();
        using (var en = new LiveOddsEntities())
        {
            matches = (from m in en.Matches
                       join mi in en.MatchInfoes on m.match_id equals mi.match_id
                       join to in en.Tournaments on mi.tournament_id equals to.id
                       join ca in en.Categories on mi.category_id equals ca.id
                       join sp in en.Sports on mi.sport_id equals sp.id
                       join ht in en.Teams on mi.home_team_id equals ht.id
                       join at in en.Teams on mi.away_team_id equals at.id
                       where mi.DateOfMatch > ticks
                       orderby mi.DateOfMatch ascending
                       select new Match { MatchId = m.match_id, DateOfMatch = mi.DateOfMatch, Tournament = to.name, Category = ca.name, Sport = sp.name, HomeTeam = ht.name, AwayTeam = at.name, BetTypes = (from mat in en.Matches
                                                                                join odd in en.Odds on mat.match_id equals odd.match_id
                                                                                select new { odd.type, proba = (from matc in en.Matches
                                                                                join odds in en.Odds on matc.match_id equals odds.match_id
                                                                                where odd.type ==odds.type
                                                                                select odds.subtype).ToList()}
                                                                                ).AsEnumerable().ToDictionary(k => k.type, k => k.proba) }).Skip(skip).Take(pageSize).ToList();
        }
        return matches;


text:
Q: Sharepoint Web Part restrict to zone Is there any way to restrict a web part to a certain zone? I know I can restrict it by using the AllowZoneChange flag, but is it possible to make sure the web part can only be added to certain zones? I have some web parts which are only viable in a wide column (zones), so I want to make sure that no one tries to add the web parts to narrow columns (zones). Is there any way of accomplishing this?

A: If you stick in a Quick Add Group with the same name as your "wide" one, it'll show up at the top of the list by default when someone tries to add a web part in that zone.
However, it will show up as normal further odwn the list when someone tries to add to another zone.
However, I don't think it's actually possible to do this at all - the only method I can think of, off the top of my head is to (somehow, maybe through modifyin the page layout directly) add some code to an event handler for SPWebPartManager.WebPartAdded to check the webpart and the zone, and to remove it if it was added in the wrong zone.
However, I've never tried to do this, nor know if it would work - feel free to give it a try though. Blog about it if you do get it to work!
Have a look at this for info on the event itself.
http://msdn.microsoft.com/EN-US/library/ms157584


text:
Q: Mysql select all rows except ones which are in another table
Possible Duplicate:
Need SQL Query to find Parent records without child records

I have a table one and two,
select name from one

let say i have 3 rows a, b, c
select name from table two;

and let say I have 3 rows in table two which are contains a, d , f
I want to select * from table one where name are not in table two so i should end up with
b,c and not a because a is in the table two
Please advice thanks

A: Use a NOT EXISTS clause
SELECT name from one
WHERE NOT EXISTS (
    SELECT 1 FROM two
    WHERE two.name = one.name
)

Update
Alternatively, you can use a LEFT JOIN with a NULL qualifier
SELECT one.name FROM one
LEFT JOIN two on one.name = two.name
WHERE two.name IS NULL

A: You can make a subquery to get the names from table two and use them to exlude rows from table one
SELECT * FROM table1 WHERE name NOT IN (SELECT name FROM table2)


text:
Q: InternalServerError when calling the synchronization API's I'm looking for a way to automate the process of updating admin credentials inside an enterprise app in AAD. Looking at the Microsoft docs e.g. here this should be possible via the graph api. Whenever I attempt these steps I'm running into "InternalServerError" along with "Microsoft.Graph.ServiceException: Code: UnknownError".
My dotnet code for validating existing credentials is the following.
await graphServiceClient.ServicePrincipals[$"{servicePrincipalId}"].Synchronization.Jobs[$"{jobsId}"]
                .ValidateCredentials(null,null,null,credentials)
                .Request()
                .PostAsync();

The result is the error above with the same error for any other synchonization method. I've considered it could be a permissions issue but I've found that the api does a reasonable job of sending permission issues back so I'm stumped at this point.
Does anybody have any advice on this?

A: I see that you're updated that "The result is the error above with the same error for any other synchronization method".  In such scenario, I would do the basic sanity checks

*

*Validate the credentials that
you're using

*Make sure the user context has necessary scopes/roles
defined too

*Make sure the template and the parameters that you're
is correct.

*Once you assigned app role to the user that you're using for delegating permissions, it worked for you.