text:
Q: WPF CollectionChanged Event OldItems.Count I have an ObservableCollection and I attach to the CollectionChanged event:
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.Action == NotifyCollectionChangedAction.Add)
    {
        for (int i = 0; i < e.NewItems.Count; i++)
        {
            int id = -1 * i;
            DocumentWatchList d = (DocumentWatchList)e.NewItems[i];
            d.UID = id;
            _dataDc.DocumentWatchLists.InsertOnSubmit(d);
        }
    }
    else if (e.Action == NotifyCollectionChangedAction.Remove)
    {
        for (int i = 0; i < e.OldItems.Count; i++)
        {
            DocumentWatchList d = (DocumentWatchList)e.OldItems[i];
            _dataDc.DocumentWatchLists.DeleteOnSubmit(d);
        }
    }
    _dataDc.SubmitChanges();
}

My collection is bound to a datagrid, and the viewmodel code (above) gets called as expected.  When I select multiple rows and hit delete, I expect that the OldItems collection will contain the number of rows that I had selected (n).  however, what actually happens is that the event gets called n times, and each time the OldItems collection count is 1.  So under what conditions will the OldItems collection contain more than 1 item?  Is this behavior coming from the datagrid control, or rather is it the way ObservableCollection.CollectionChanged is meant to work?

A: For some reason, ObservableCollection doesn't support a NotifyCollectionChanged event with multiple items.
You can do this:
OnCollectionChanged(
    new NotifyCollectionChangedEventArgs(
        NotifyCollectionChangedAction.Remove, singleItem));

But not this: (you'll get a NotSupportedException)
 OnCollectionChanged(
    new NotifyCollectionChangedEventArgs(
        NotifyCollectionChangedAction.Remove, multipleItems));

I can't think of any scenario where e.OldItems.Count would be greater than 0.
Here is a good article about it, where someone actually implemented the handling of multiple items themselves, for performance purposes.

A: If you take a look at the interface that observable collection offers to you, you already know what you will get :
https://msdn.microsoft.com/en-us/library/ms668604%28v=vs.110%29.aspx
Basically it does not offer any way to insert or remove multiple items at once. So this effectively means that you can clear the whole collection, but if you need to say remove 2 items while there are 6 in the collection, you will have to remove them one by one. Which is what the datagrid will do in your case , but suppose you were to implement you own datagrid, you would be forced to do it the same way.
To make the answer complete, I must add that there is a way to get multiple items in the deleted list, but only by clearing the collection.
Replacing an item in the collection is also possible, by using the index operator, you can even replace an item with itself. I' ve tried this and this works, you will get the same item in the deleted collection and inserted collection in that case, but also here one by one.
You can of course create you own implementation of observable collection that would solve these issues. But I think you would need a different implementation of datagrid too, that would use your custom new bulk insert or bulk delete operations.


text:
Q: How to set dynamic options from API response in fluent ui react Dropdown control? I have encountered a situation where I need to display a Dropdown and want the options to dynamically fetch from an API and load on clicking the caret (maybe show a loader by the time the API response comes through). The experience I am looking for is something in the following lines -

Loading (fetching options from API)

Display options after successful response
The documentation didn't give any API surface through which this can be possible.
Is it possible to achieve this with the current APIs that are in place for this control component?

A: Good point to start is to use BasePicker Component from Pickers.
import { BasePicker } from 'office-ui-fabric-react/lib/Pickers'

Inside BasePicker you have a methods which you can use to make a "lazy" behavior. For example, when you click on component then make a call to API and populate items list.
What is inside BasePicker take a look here or from official documentation.
Codepen example

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP DateInterval: Diff between same date in two different months is not one month I am developing a subscription service where the user pays per month.
I am having two dates
1: 2012-12-05 ($today)
2: 2013-01-05 ($end_date)
For me, that is one month. But for PHP, that is only 30 days.
Here is some code (you can see the values of the dates mapped above)
$end_date_for_new_agents = clone $end_date;
$end_date_for_new_agents = $end_date_for_new_agents->add(new DateInterval("P1D"));
$agent_period_months_obj = $today->diff($end_date_for_new_agents);
echo $agent_period_months_obj->format("%y-%m-%d")

This echos 0-0-30
Why is that and how can I make PHP calculate the difference between the same dates in different months as whole months?

A: You should condider also the time, or the day can be not complete.
For example:
date_default_timezone_set("Europe/Rome");
$end='2013-01-05';
$intervalo = date_diff(date_create(), date_create($end));
echo $intervalo->format("Years:%Y,Months:%M,Days:%d,Hours:%H,Minutes:%i,Seconds:%s");

give as result:
Years:00,Months:00,Days:30,Hours:05,Minutes:59,Seconds:53

The following code
date_default_timezone_set("Europe/Rome");
$start='2012-12-05';
$end='2013-01-05';
$intervalo = date_diff(date_create($start), date_create($end));
echo $intervalo->format("Years:%Y,Months:%M,Days:%d,Hours:%H,Minutes:%i,Seconds:%s");

give the result:
Years:00,Months:01,Days:0,Hours:00,Minutes:0,Seconds:0

Check if value of$today has also the time, if so you should extract only the date and forget the time


text:
Q: Changing greeting based on screensize I was wondering how I can change my greeting based on the screensize. Currently it doesn't look nice on smaller screens.
I'm not adept at jQuery/JS so I used an if statement to check the width and change the greeting based on that. The problem with this is that it only does so when the page loads. I'd like it to change each time the size updates.
In the demo at the bottom of this website the greeting changes based on the width of the screen.
Any help?
Have a nice day,
Rover

A: The simplest way is to add onInit and echo function that will be called on each redraw that happen on resize:
term.echo(function() {
    return new Array(this.cols()).fill('-').join('');
});

this will create line that is always full width of the terminal. If you prepared multiple greetings, then you can just create function with if statements and return proper string with the greeting you want, this is how default greetings is created.
this inside the function will be the same as terminal instance and cols is method that return number of characters per line.
So the whole code (if you don't have login) should look like this:
$('body').terminal(..., {
    greetings: false, // disable default greetings
    onInit: function() {
        this.echo(function() {
            return new Array(this.cols()).fill('-').join('');
        });
    }
});

if you use login you need to use onAfterLogin instead of onInit if you want same behavior as greetings.


text:
Q: Looping over Array of objects and returning random object value without any duplicate's I am trying to loop over array of objects with dynamic length value and expecting random object value without any duplicate's
This is working but it returns duplicated values even the length is within the limit
for (let i = 0; i < test.length; i++) {
      var item1 =
        test[Math.floor(Math.random() * test.length)];
      console.log(item1);
    }

A: Store the index you plan on getting and splice it out of the main array.
for (let i = 0; i < test.length; i++) {
      const index = Math.floor(Math.random() * test.length);
      const item1 =
        test.splice(index, 1)[0];

      console.log(item1);
}


text:
Q: Serializing data from db in flat structure I have a list of objects which contains a parameter name and his value.
I want to generate serialize it in a single object with parameter name as property name and value as the value
example:
public class Parameter
{
    public string Name { get; set; }
    public string Value { get; set; }
}

I have a list of two parameters { Name = "name1", Value = "value1" }, { Name = "name2", Value = "value2" }
I want to seriliaze an object like this:
new { "name1" = "value1", "name2" = "value2"  }
any clue?

A: One way is to use a Dictionary(TKey, TValue) if the serialization library being used supports it.
For instance using Json.NET to serialize a Dictionary(string, string) to the JSON format:
var parameters = new List<Parameter>
{
    new Parameter { Name = "name1", Value = "value1" },
    new Parameter { Name = "name2", Value = "value2" }
};

var objToSerialize =
    parameters
    .ToDictionary(
        param => param.Name,
        param => param.Value);

// Use Json.NET to serialize the dictionary
var result = JsonConvert.SerializeObject(objToSerialize);

// Outputs
// result = {"name1":"value1","name2":"value2"}


text:
Q: Updating/Adding Sub-Document on Sub Document in Mongoose How to updating/adding sub-document in sub-document in mongoose,
I have sample data for Tree Json, like this:
orgchart:
 [
  {
    level: 0,
    name: Division 0,
    child: [
     {
       level: 1,
       nama: Division 1,
       child: [
        {
          level: 2,
          nama: Sub Division 2,
          child: [ here division X ]
        }
       ]
     }
  },
 ]

I tried use parent.push but only add 1 sub document, when i tried to use more sub document in sub document always failed with message "TypeError: Cannot call method 'push' of undefined"
Do you have clue for this problem,
Thanks

A: In this case you're probably best off grabbing calling .findOne() to get the document contain the sub-document that you want to update, pushing the subdocument to the array, then calling .save() on the document.
Really, if you have sub-documents with embedded sub-documents, you should consider creating a collection for the sub documents, and possibly the documents embedded in those sub-documents. You can store _id references in the parent document and invoke populate(...) with your query.
I would provide an example, though I'm not certain what you're trying to accomplish. Initially it looks like bad data modeling, but I'm not sure exactly what you're trying to accomplish.

A: Sorry to bother you mr tsturzl
I got solution from Mongodb update deeply nested subdocument
Thank You


text:
Q: Showing MapKit "Map loading error" in Objective C I am using Mapkit using objective c, i want to show "Error alert" on map.
When Internet working, its working fine but When Internet not working properly then its showing automatically on log "request time out" with out calling "mapViewDidFailLoadingMap" delegate method.
Code Here:
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    mapView.delegate=self;
    mapView.showsUserLocation = YES;
    [mapView setMapType:MKMapTypeStandard];
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];

    //[self activeCLLocation];
}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    NSLog(@"user latitude==>%f",userLocation.location.coordinate.latitude);
    NSLog(@"user longitude==>%f",userLocation.location.coordinate.longitude);
}

-(void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error
{
    NSLog(@"error map===>%@",error.description);
}

-(void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"error loc===>%@",error.description);
}

Showing Error:

2015-05-27 12:51:57.624 EventLocator[1262:160081] Could not determine
  current country code: Error Domain=NSURLErrorDomain Code=-1001 "The
  request timed out." UserInfo=0x19d80290
  {NSErrorFailingURLStringKey=http://gsp1.apple.com/pep/gcc,
  NSErrorFailingURLKey=http://gsp1.apple.com/pep/gcc,
  NSLocalizedDescription=The request timed out.,
  NSUnderlyingError=0x17e877a0 "The request timed out."}

A: I would test for a valid internet connection before you load mapKit. Check out this thread on how to do this.
How to check for an active Internet connection on iOS or OSX?

A:
There is no issue in the code. I guess the simulator internally is not able to connect to the internet. Try connecting to some other wifi connection and test internet connection before you load MapView.

Check internet connection as :
#import <SystemConfiguration/SCNetworkReachability.h>

+(bool)isNetworkAvailable
{
   SCNetworkReachabilityFlags flags;
   SCNetworkReachabilityRef address;
   address = SCNetworkReachabilityCreateWithName(NULL, "www.apple.com" );
   Boolean success = SCNetworkReachabilityGetFlags(address, &flags);
   CFRelease(address);

bool canReach = success
                && !(flags & kSCNetworkReachabilityFlagsConnectionRequired)
                && (flags & kSCNetworkReachabilityFlagsReachable);

   return canReach;
}

You can also try resetting simulator as
iOS Simulator -> Reset Content and Settings


text:
Q: Mocking FormsAuthentication in MVC I have the code below and want to test the scenario when FormsAuthentication returns null.  How can I do this, using mocking I assume, since FormsAuthentication is a sealed class with static methods.  I am using RhinoMocks.
    public PaxiumPrincipal CreatePrincipalFromCookie(string cookieValue)
    {
        var authTicket = FormsAuthentication.Decrypt(cookieValue);

        if (authTicket == null)
        {
            return null;
        };

        var userPrincipal = new PaxiumPrincipal(new GenericIdentity(authTicket.Name), null);

        return userPrincipal;
    }

A: I see no evidence FormsAuthentication.Decrypt() ever returns null, other than a bug described here. Instead it throws an ArgumentException when the cookie is invalid. I think you should test that the cookie hasn't expired though..
But for the sake of argument, this is how you TDD a sealed class:
Create an interface for all methods you need
This goes into your production code:
public interface IFormsAuthentication
{
    FormsAuthenticationTicket Decrypt(string cookieValue);
}

Create a wrapper around the sealed class
This also goes into your production code:
public class MyFormsAuthentication : IFormsAuthentication
{
    public FormsAuthenticationTicket Decrypt(string cookieValue)
    {
        return FormsAuthentication.Decrypt(cookieValue);
    }
}

Change the method you want to test
It should use the IFormsAuthentication object it's provided with instead of the sealed class. In production this should be your wrapper.
Obviously this is in your production code...
public class PaxiumPricipalCreator
{
    IFormsAuthentication _formsAuthentication;
    public PaxiumPricipalCreator(IFormsAuthentication formsAuthentication)
    {
        _formsAuthentication = formsAuthentication;
    }

    public PaxiumPrincipal CreatePrincipalFromCookie(string cookieValue)
    {
        var authTicket = _formsAuthentication.Decrypt(cookieValue);

        if (authTicket == null)
        {
            return null;
        };

        var userPrincipal = new PaxiumPrincipal(new GenericIdentity(authTicket.Name), null);

        return userPrincipal;
    }
}

Create a unit test with a mock authenticator (This example is in MSTest)
This is your TEST code:
[TestClass]
public class PaxiumPricipalCreatorTests
{
    [TestMethod]
    public void Returns_NULL_principal_when_IFormsAuthentication_returns_null()
    {
        var mockAuthenticator = new NullReturningFormsAuthentication();
        var principalCreator = new PaxiumPricipalCreator(mockAuthenticator);

        var actual = principalCreator.CreatePrincipalFromCookie(string.Empty);

        Assert.IsNull(actual);
    }

    public class NullReturningFormsAuthentication : IFormsAuthentication
    {
        public FormsAuthenticationTicket Decrypt(string cookieValue)
        {
            return null;
        }
    }

}


text:
Q: Is a 'pace' the same as a 'step'? In the following sentence can I use either of the two? step/pace and until/til

It took exactly twenty-five paces(steps) from the office door
  until(till) her desk.

What sounds more natural to the native ear?

A: A pace usually means the stride one ordinarily takes in unimpeded walking: roughly thirty inches, or three-quarters of a meter.

But the ancient Roman military passus, usually translated 'pace', was two strides: in marching, the distance between successive strikes of the same heel. The English 'mile' of just over 5,000 feet derives from the Roman mille of one thousand paces.

A step has a broader range: it may be a step up or down, as well as a step on level ground, and even on level ground the particular footing—mud, or snow, or ice, or vegetation—may enforce steps smaller than a full stride.
Accordingly, pace is more usual for approximate measurements.
In your example, however, pace will be appropriate only if the path from the door to the desk is unimpeded—for instance, down an aisle between desks or cubicles. If there are turns or obstacles, step may be all that is enumberable.
Whichever unit of measure you use, the ordinary construction is so many X from A to B, not until or till. Until and till mark endpoints in time, and even there are used mostly for time as experienced rather than measured.

He worked until four o'clock, BUT
  He works from nine to five.

A: It depends. If you want to specify an exact number of steps, then paces sounds more natural:

My sofa is ten paces from the fridge
My sofa is ten steps from the fridge (or My sofa is ten footsteps from the fridge).

In context however, it sounds like twenty-five paces is being as a rough estimate of length, which is why it sounds a little forced. A native would much more likely use an alternative unit of length:

It is twenty-five feet from the office door to her desk.


text:
Q: Change the text from a file Data form like this:
line1
text1
text2
line2
something text1

line3

Making an output:
line1 text1 text2
line2 something text1

line3

how could I make it to delete?

A: Removing blank lines can be done as such:
with open('input') as fin, open('output', 'w') as fout:
    non_blank = (line for line in fin if line.strip())
    fout.writelines(non_blank)

A: I think your goal is to delete the blank like, right? If that's the case:
inputfile = open('example.txt', 'r')
outputfile = open('examplelines.txt', 'w')

for line in inputfile:
    if line.strip('\n') != '':
        outputfile.write(line)

inputfile.close()
outputfile.close()

A: Maybe this does what you want:
import sys

i = 2
for line in sys.stdin:
    if line.startswith('line%d' % i):
        i += 1
        sys.stdout.write('\n')
    if line == '\n':
        sys.stdout.write('\n')
    else:
        sys.stdout.write(line.rstrip() + ' ')

sys.stdout.write('\n')

This runs through the input lines and collects text until it finds an input line that says lineN. Such a line begins a new line in the input. Furthermore, a blank line in the input is passed through as a blank line in the output.


text:
Q: Update Column while checking against a column with duplicate values I'm selecting my data with the following statement:
select distinct min(revision_number) as revno,po_number
from PO_HEADER
group by PO_NUMBER
having MIN(revision_number) > 0;

I get the following data:
7   30492-SA-EH504
20  30492-PS-SO895
20  30492-RA-DD219
26  30492-SA-KK474
1   30492-BA-AT236
17  30492-RA-DD386
21  30492-PS-FS803
25  30492-PS-WM324
33  30492-SA-NS011

I want to update the MIN(REVISION_NUMBER) to ZERO without changing any other values.  For example, 30492-SA-EH504 lists with the revisions as:
30492-SA-EH504 7
30492-SA-EH504 8
30492-SA-EH504 9
30492-SA-EH504 10

I only want to update the current min revision (7) to zero.  I tried this update query but it updated all of them to zero:
update PO_HEADER
set REVISION_NUMBER = '0'
from PO_HEADER
where exists (
select min(revision_number) as revno,po_number
from PO_HEADER
group by PO_NUMBER
having MIN(revision_number) > 0
);

would select distinct help, or do I need something more intricate.

A: Here's another way of solving it. You can actually update a common table expression:
with mins as (
  select po_number, revision_number
  from (
  select po_number, revision_number,
    row_number() over (partition by po_number order by revision_number) n
  from Table1
  ) A
  where A.n = 1
)
update mins set revision_number = 0

select * from Table1

SQL Fiddle here.

A: There are multiple ways to do this.  I prefer the one using the "IN" clause:
update PO_HEADER
    set REVISION_NUMBER = '0'
    where (po_header.Revision_NUMBER, po_header.po_number) in
              (select min(revision_number) as revno, po_number
               from PO_HEADER
               group by PO_NUMBER
               having MIN(revision_number) > 0
              )

Your original query has no connection between the rows in the update table and the condition.  Hence, all evaluate to true, since the condition is true (rows exist).  I think the above syntax works in mysql -- looking for pairs using "IN".  If not, you can use the following:
update PO_HEADER
    set REVISION_NUMBER = '0'
    from (select min(revision_number) as revno, po_number
          from PO_HEADER
          group by PO_NUMBER
          having MIN(revision_number) > 0
         ) minr
    where po_header.Revision_NUMBER = minr.Revision_NUMBER and
         po_header.po_number = minr.po_number

A: Something like
UPDATE poh
  SET poh.RevisionNumber = 0
  FROM POHeader AS poh
  INNER JOIN (select distinct min(revision_number) as revno,po_number
              from PO_HEADER
              group by PO_NUMBER
              having MIN(revision_number) > 0) AS poh_rev
  ON poh.PO_Number = poh_rev.PO_Number And poh.RevisionNumber = poh_rev.revno

A: Update PO_HEADER
Set revision_number = 0
From (
      select distinct min(revision_number) as revno,po_number
      from PO_HEADER
      group by PO_NUMBER
      having MIN(revision_number) > 0
      )Z
Where PO_HEADER.revision_number = Z.revno
  and PO_HEADER.po_number = Z.po_number


text:
Q: Power of $2$ that divides $\lceil(3+\sqrt5)^{2n}\rceil$
$\lceil(3+\sqrt5)^{2n}\rceil$ is divisible by
A. $2^{n+1}$
B. $2^n$
C. $2^{n-1}$
D. not divisible by $2$

original image

A: If $f(n)=a^n+b^n,a>b$ where $a,b$ are the roots of $t^2-28t+16=0$
So,$f(m+2)-28f(m+1)+16f(m)=0,m\ge0$
As $0<b<1,$ we need the highest power of $2$ that divides $f(n)$ be $h(n)$
$h(0)=1$
$h(1)=2$
So, by strong induction, $h(n)\ge n+1$


text:
Q: G.B. Shaw and Phonetics G.B. Shaw (the playwright) campaigned for a "universal alphabet," on and off, throughout his career. He (and some others) did have a point when they said that the English alphabet is anything but English (ancient Greek and Latin-based), is quite foreign to the language, and cannot be reformed sufficiently to reflect all the nuances of pronunciation and usage; and that it was high time someone came up with a PHONETIC version that everyone would agree on, accept, and enjoy. It is said that Shaw went so far as to invent his own version of such an alphabet which he used to write plays. Maybe he did. Who knows. My point here is that he also made it a point to spell certain words phonetically in the print versions of his plays (Shakespear rather than Shakespeare, etc).
It's mostly great fun, but the one word he used that I still find a bit puzzling is "shew" (instead of "show"). At first I thought that it was some kind of turn-of-the-century-Belle-Epoque-British thing. However, the dictionary flatly states that it is a variant of "show," and is archaic.
https://en.wiktionary.org/wiki/shew
What gives? Why would Shaw, who believed himself to be one of the most advanced, progressive, and modern people of his epoch, use an archaism (in a play about language, of all things, i.e. "Pygmalion")? What am I missing?

A: Shaw was born in 1856. At that time 'shew' was well on its way to being replaced by 'show'.
Google ngram: shew,show
However,  it's likely that 'shew' was the spelling Shaw learned in school in Dublin, Ireland -- especially if he had an old-fashioned school-master.
I also suspect that, phonetically, 'shew' was much closer to the way that Shaw pronounced the word. So it would be natural for him to spell it that way.
Here is a recording of Shaw speaking. I haven't listened to it all the way through but I wouldn't be surprised if he says, "shew" in there somewhere.


text:
Q: query this return list to show only records for a particular person. ASP.NET MVC I will like to query this return list to show only records for a particular person. Right now its show all records in the table. I am using ASP.NET MVC.
This is my code
    public ActionResult Policies()
    {

        var eList = new List<PolicyDTO>();
        using (var ctx = new RetailPlusEntities())
        {
            eList = ctx.POLICies.Select(rec => new PolicyDTO()

            {
                ID = rec.ID,
                CUSTOMERID = rec.CUSTOMERID,
                POLICYNO = rec.POLICYNO,
                PLANID = rec.PLANID,
                COMMENCEMENTDATE = rec.COMMENCEMENTDATE,
                MATURITYDATE = rec.MATURITYDATE,
                INITIALCONTRIBUTION = rec.INITIALCONTRIBUTION,
                CARDNO = rec.CARDNO,
                MARKERTERID = rec.MARKERTERID,
                COLLECTORID = rec.COLLECTORID,
                COVERID = rec.COVERID,
                STATUS = rec.STATUS,
                BRANCHID = rec.BRANCHID,
                BranchName = rec.BRANCH.NAME,
                EmployeName = rec.EMPLOYEE.FIRSTNAME,
                StatusName = rec.STATUS1.NAME,

           }).ToList();

         //   }).Where(a => a.COLLECTORID.Equals(empID)).ToList();

        }

        return View(eList);

    }

A: How about
public ActionResult Policies()
{
    using (var ctx = new RetailPlusEntities())
    {
        var eList = ctx.POLICies
            .Where(a => a.COLLECTORID == empID)
            .Select(rec => new PolicyDTO()

        {
            ID = rec.ID,
            CUSTOMERID = rec.CUSTOMERID,
            POLICYNO = rec.POLICYNO,
            PLANID = rec.PLANID,
            COMMENCEMENTDATE = rec.COMMENCEMENTDATE,
            MATURITYDATE = rec.MATURITYDATE,
            INITIALCONTRIBUTION = rec.INITIALCONTRIBUTION,
            CARDNO = rec.CARDNO,
            MARKERTERID = rec.MARKERTERID,
            COLLECTORID = rec.COLLECTORID,
            COVERID = rec.COVERID,
            STATUS = rec.STATUS,
            BRANCHID = rec.BRANCHID,
            BranchName = rec.BRANCH.NAME,
            EmployeName = rec.EMPLOYEE.FIRSTNAME,
            StatusName = rec.STATUS1.NAME,

        }).ToList();
        return View(eList);
    }
}

I removed the redundant initialization of eList that you immediately throw away, and return the result to the client. You just have to decide where you get empID from.

A: public  ActionResult  Policies()
    {
        using (var ctx = new RetailPlusEntities())
        {
            var eList = ctx.POLICies
                .Where(a => a.COLLECTORID == empID).FirstOrDefult()
                .Select(rec => new PolicyDTO()

            {
                ID = rec.ID,
                CUSTOMERID = rec.CUSTOMERID,
                POLICYNO = rec.POLICYNO,
                PLANID = rec.PLANID,
                COMMENCEMENTDATE = rec.COMMENCEMENTDATE,
                MATURITYDATE = rec.MATURITYDATE,
                INITIALCONTRIBUTION = rec.INITIALCONTRIBUTION,
                CARDNO = rec.CARDNO,
                MARKERTERID = rec.MARKERTERID,
                COLLECTORID = rec.COLLECTORID,
                COVERID = rec.COVERID,
                STATUS = rec.STATUS,
                BRANCHID = rec.BRANCHID,
                BranchName = rec.BRANCH.NAME,
                EmployeName = rec.EMPLOYEE.FIRSTNAME,
                StatusName = rec.STATUS1.NAME,

            }).ToList();
            return View(eList);
        }
    }


text:
Q: Add active class based on url is not working for submenus I have the code below to add a .active class to a link if the href is equal to the url. It is working for the menu items but for the submenu items its not working properly. For example if the link with text "Edit" is clicked i want to add the .active class to the main link with text "Item 1". But its not working tihs part, do you know how to achieve that?
html

Item 0

               Item 1

Create

Edit

Item 2

js
$("#nav a").each(function() {
        if (this.href == window.location.href) {
            $(this).addClass("active");
        }
    });

A: Note that sub-menus have 2 li elements as parents while a top menu item has only one li parent:
 $(this).parents('li').length == 2  => submenu
 $(this).parents('li').length == 1  => menu

Here is a working example:

$(document).ready(function () {

    $("#nav a").each(function() {
        // you can change here the menus href, for test purpose
        // I choose 'create' menu link: 'https://stacksnippets.net/create'
        if (this.href == 'https://stacksnippets.net/create') {

            // check if sub menu
            if ( $(this).parents('li').length == 2 ) {
              $(this).parents('ul.collapse').siblings('a').addClass('active');
            } else {
              $(this).addClass("active");
            }
        }
    });

});
a.active{
  color: red;
}

Item 0

               Item 1

Create

Edit

Item 2


text:
Q: tex4ht leaving equations unchanged - including \[...\] and \(...\) I want to let tex4ht leave the equations unchanged. Using the tip given at tex4ht leaving equations unchanged, it works for $ and $$ equations. In the case of \[...\] and \(...\) equations it does not work.
How do I have to modify the provided my.cfg  to work in the case of following document?
\documentclass {article}
\begin{document}
\[a*b^3\]
\end{document}

my.cfg:
\Preamble{html}
\newtoks\eqtoks
\def\AltMath#1${\eqtoks{$#1$}%
   \HCode{\the\eqtoks}$}
\Configure{$}{}{}{\expandafter\AltMath}
\begin{document}
\EndPreamble

\Configure{[]} seems to take only two arguments.
Using \Configure{[]}{$}{$} does not help. This leads to
Runaway argument?
a*b^3\] \end {document}
! File ended while scanning use of \AltMath.

For a complete test, the following file should work:
\documentclass {article}
\begin{document}
\begin{math}
math^3
\end{math}
\begin{displaymath}
math^3
\end{displaymath}
\begin{equation*}
equation*^3
\end{equation*}
\end{document}

A: Inspired by the mentioned answer there is a partiala, b solution of the question. The following configurations will accept \(...\) and \[...\] shorthands solely:
\Preamble{html}
    \newtoks\eqtoks
    \def\AltlMath#1\){\eqtoks{\(#1\)}%
        \HCode{\the\eqtoks}}
    \Configure{()}{\AltlMath}{}
    \def\AltlDisplay#1\]{\eqtoks{\[#1\]}%
        \HCode{\the\eqtoks}}
    \Configure{[]}{\AltlDisplay}{}
\begin{document}
\EndPreamble

a The TeX shorthand configurations and these LaTeX shorthand configurations will not work together.
b The environment configurations are missing.


text:
Q: It works using div on body. It doesn't using get Status: WORKING
Runs smoothly - click works
Jquery
 $("document").ready(function(){

    $("#test").click(function(){
        alert("abc");
    });
 });

CSS
.blue {
background-color:blue;
}

Tag Body

Testing code

Status: NOT WORKING
Succeeds to add the file and div test within it but click doesn't work
Jquery
 $("document").ready(function(){

    $.get("new.php", {
         // this math avoids IE from crashing
         nbRandom: Math.random()
         },
         function(data){
         $("body").html(data);
         });

    $("#test").click(function(){
        alert("abc");
    });
 });

CSS
.blue {
background-color:blue;
}

Tag Body

Does anybody know how to do that?

A: The method get is asynchronous which means that the stream will continue while the ajax request is still running, the best solution is to put the click handler into the get callback.
$("document").ready(function(){

$.get("new.php", {
     // this math avoids IE from crashing
     nbRandom: Math.random()
     },
     function(data){
       $("body").html(data);
       $("#test").click(function(){
         alert("abc");
       });
     });

});

A: You should delegate the event, from one of static parents of the element or document object.
$(document).on("click", "#test", function(){
    alert("abc");
})

A: use delegate or on(recommend)
$(function() {
  $('body').on('click', '#test', function() { alert('abc'); });
  // or
  // $('body').delegate('#test', function() { alert('abc'); });
});

A: problem is the the click function is called before the div with #test is appended...
call click function after the div is appended.. so that it gets that id... and the event
try this
$.get("new.php", {
       // this math avoids IE from crashing
       nbRandom: Math.random()
     },
     function(data){
        $("body").html(data);
        $("#test").click(function(){
            alert("abc");
        });
     });

OR
the on function with selector as document..(i alway prefer to go with this)
$(document).on("click", "#test", function(){
  alert("abc");
})


text:
Q: Material UI Swipable Drawer override the html style overflow to hidden I am using the Material UI SwipableDrawer component and it has an unwanted effect that makes the scrollbar disappear when the drawer is visible. That completely override the style i put on the Html tag "overflow-y: scroll" and it doesn't set it back.
How do i override this unwanted effect? thanks!

A: Problem was that i was putting overflow-y: scroll and the drawer was overriding overscoll
Setting the HTML style to overflow: scroll solved the issue
However, this will still hide the scrollbar when the drawer is open, which is still kind of undesired


text:
Q: Cockpit using Nginx - with private ip only Context:
I have an ec2 ubnutu 20.04.5 LTS instance - which sits in a vpc with no public ip.
On that, I have nginx:1.23.2 running in a container and cockpit installed directly on the host.
The way it is currently configured, if I visit my private ip in the browser while on vpn, I am able to reach the login screen for cockpit.  For example http://10.235.66.23/ leads me to login.
When I attempt to login with the correct credentials (both for root and sudo users,) it leads to the exact same page I started with: login.
inspecting the browser:
GENERAL
Request URL: http://10.235.66.23/cockpit/login
Request Method: GET
Status Code: 401 Authentication failed
Remote Address: 10.235.66.22:80
Referrer Policy: no-referrer

RESPONSE HEADERS
Connection: keep-alive
Content-Type: text/html; charset=utf8
Cross-Origin-Resource-Policy: same-origin
Date: Sun, 25 Dec 2022 23:42:41 GMT
Referrer-Policy: no-referrer
Server: nginx/1.23.2
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-DNS-Prefetch-Control: off

REQUEST HEADERS
X-Frame-Options: sameorigin
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cache-Control: no-cache
Connection: keep-alive
DNT: 1
Host: 10.235.66.23
Pragma: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36

The status code Status Code: 401 Authentication failed doesn't add up, because these credentials are good.  I've also made sure to have /etc/ssh/sshd_config allow password use.
the nginx container is configured to listen on ports 8080 and 4430 - and firewalld has the ports forwarding:
my_zone (active)
  target: DROP
  icmp-block-inversion: no
  interfaces:
  sources: 10.0.0.0/8
  services: cockpit
  ports: 22/tcp 8081/tcp 4431/tcp 80/tcp 443/tcp 8080/tcp
  protocols:
  masquerade: yes
  forward-ports: port=80:proto=tcp:toport=8081:toaddr=
        port=443:proto=tcp:toport=4431:toaddr=
  source-ports:
  icmp-blocks:
  rich rules:

NGINX configuration:
server {
    listen         8081;
    listen         4431;

    server_name    10.235.66.23;

    location / {
        # Required to proxy the connection to Cockpit
        proxy_pass https://127.0.0.1:9091;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;

        # Required for web sockets to function
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        # Pass ETag header from Cockpit to clients.
        # See: https://github.com/cockpit-project/cockpit/issues/5239
        gzip off;
    }

        location = /testapp {
                proxy_pass https://127.0.0.1:8082;
        }
}

you might have noticed the port is 9091, i have changed it here:
/usr/lib/systemd/system/cockpit.socket and here: /usr/share/cockpit/motd/update-motd
and when I check the cockpit and cockpit.socket status with systemctl:
● cockpit.service - Cockpit Web Service
     Loaded: loaded (/lib/systemd/system/cockpit.service; static; vendor preset: enabled)
     Active: inactive (dead) since Sun 2022-12-25 18:44:12 EST; 7min ago
TriggeredBy: ● cockpit.socket
       Docs: man:cockpit-ws(8)
    Process: 1106981 ExecStartPre=/usr/lib/cockpit/cockpit-certificate-ensure --for-cockpit-tls (code=exited, status=0/SUCCESS)
    Process: 1106982 ExecStart=/usr/lib/cockpit/cockpit-tls (code=exited, status=0/SUCCESS)
   Main PID: 1106982 (code=exited, status=0/SUCCESS)

Dec 25 18:42:39 ip-10-235-66-23 systemd[1]: Starting Cockpit Web Service...
Dec 25 18:42:39 ip-10-235-66-23 systemd[1]: Started Cockpit Web Service.
Dec 25 18:44:12 ip-10-235-66-23 systemd[1]: cockpit.service: Succeeded.

everything is good.
when i run sudo journalctl -xe, i have no issues.  when i look at the nginx output:
10.118.46.12 - admin[25/Dec/2022:23:53:47 +0000] "GET /cockpit/login HTTP/1.1" 200 81 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" "-"
10.118.46.12 - - [25/Dec/2022:23:53:47 +0000] "GET / HTTP/1.1" 200 11105 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" "-"
10.118.46.12 - - [25/Dec/2022:23:53:47 +0000] "GET /cockpit/static/login.js HTTP/1.1" 200 15897 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" "-"
10.118.46.12 - - [25/Dec/2022:23:53:47 +0000] "GET /cockpit/static/login.css HTTP/1.1" 200 12201 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" "-"
10.118.46.12 - - [25/Dec/2022:23:53:48 +0000] "GET /cockpit/static/branding.css HTTP/1.1" 200 500 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" "-"
10.118.46.12 - - [25/Dec/2022:23:53:49 +0000] "GET /cockpit/static/logo.png HTTP/1.1" 200 2971 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" "-"
10.118.46.12 - - [25/Dec/2022:23:53:49 +0000] "GET /cockpit/static/bg-plain.jpg HTTP/1.1" 200 81737 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" "-"
10.118.46.12 - - [25/Dec/2022:23:53:49 +0000] "GET /cockpit/login HTTP/1.1" 401 3464 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" "-"
10.118.46.12 - - [25/Dec/2022:23:53:49 +0000] "GET /cockpit/static/fonts/RedHatText-Regular.woff2 HTTP/1.1" 200 28396 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" "-"
10.118.46.12 - - [25/Dec/2022:23:53:49 +0000] "GET /cockpit/static/fonts/RedHatText-Medium.woff2 HTTP/1.1" 200 29312 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" "-"

So, i am really not understanding what is happening.  is the authentication not passing through?
/run/cockpit/tls/server has cert.source and key.source - i am assuming the self-certificates are working.
if i create the /etc/cockpit/cockpit.conf file with:
[WebService]
Origins = https://10.235.66.23 127.0.0.1:9091
ProtocolHeader = X-Forwarded-Proto

[Log]
Fatal = /var/log/cockpit.log

[Session]
IdleTimeout=15

same issue.
not sure how to route without a public ip - i don't think you can do a combination like cockpit.<private_ip> since I have tried.
My assumption is, the nginx configuration is not done well.


text:
Q: Hardware RAID 0 without OS re-installation
*

*I have Ubuntu & Windows 7 installed on my hdd. Can I mirror the image of the hdd to the second identical drive?  Is this not recommended (i.e have to re-install every OS)? If it is okay to mirror, is there anything else to do to make hw RAID 0 work?

*Does RAID 0 have the same risk as a single drive?

*What sector size would you recommend for read/write/extract video files (mostly each around 2 GB)?

A: *

*No.  You cannot do this without reinstalling (or moving your data temporarily, setting up RAID, then moving it back).  If you were doing RAID 1, you might be able to do it, if you have a fancy enough RAID controller, but even then it's doubtful.

*No, RAID 0 has higher risk than a single drive, and for pretty obvious reasons.  Suppose that one drive has a 10% chance of failure over the course of a year (that's an unrealistically high failure rate, but it's a convenient number).  That means that in a given year 1/10 drives will fail.  Now, if you add a second drive to a RAID 0 configuration, then you have a 2/10 chance that at least one drive will fail in that year--so you've effectively doubled your failure rate.  A third drive brings that up to 3/10, and so on.

*For video files, I wouldn't recommend RAID 0 at all, because speed is not important and, as explained above, you double your failure rate. Instead, I would just use two drives.  (I might use LVM if I were only using Linux, but that's not much of an option with Windows).


text:
Q: trouble recursively building a binary tree I have this file(the file): the first word is the illness and the following words are its symptoms
i need to build a binary tree recursively from this data,
however I dont know how to do so. if someone knows - i'd like help


text:
Q: One time migration of VSAM files from Mainframe to Cloud Azure Want to migrate bulk files (e.g VSAM) from Mainframe to Azure in the beginning of the Project, how that can be achieved ?
Any utility or do we need to write own scripts?

A: I suspect there are some utilities out there but I suspect they are most / all priced products.  Since VSAM datasets are not defined using a language construct like DDL you will likely have to do most of the heavy lifting.  Either writing your own programs or custom scripts.    You didn't mention operating system but I assume you're working on z/OS.
Here are some things to consider:

*

*The structure of the VSAM dataset is basically record oriented.  There are three basic types you'll run into that host application data:

*

*Key Sequenced Datasets (KSDS)

*Entry Sequenced Datasets (ESDS)

*Relative Record datasets (RRDS)

*Familiarize yourself with the means of defining the datasets as it will give you some insight into the dataset specifics.  DFSMS Access Method Services Commands will show the utilities used to create them and get information like Keylength and offest of the key.   DEFINE CLUSTER is the command to create the dataset.  You mentioned you are moving the data toi Azure but this will help you understand  the characteristics of the data you are moving.

*Since there is no DDL for VSAM datasets you will generally find the structure in the programs that manipulate them like COBOL Copybooks, HLASM DSECTs and similar constructs.  This is the long pole in the tent for you.

*Consider what are the semantics of accessing the data.   VSAM as an access method does have some ability to control read/write access on a macro level using a DEFINE CLUSTER option called SHAREOPTIONS.   The SHAREOPTIONS instruct the operating system how to handle the VSAM buffers in terms of reading and writing so that multiple processes can access the same data.  Its primitive if compared to sahred files systems like NFS.  VSAM allows the application to control access (or serialization) using ENQ / DEQ functions.  These enable applications to express intent in the cluster about a VSAM file and coordinate their own activities.

*You might find that converting a VSAM file to a relational form like Db2 is better for you.  Again, you'll have to create the DDL to describe the tables, data formats and the like.

*Another consideration is data conversion.  You'll find there is character data that is most likely in EBCDIC and needs to be converted to a new code page.  Numeric data can be in Packed Decimal, Binary, or even text and will need to be converted.
The short answer is there isn't an "Easy Button" to do what you want.   Consider the data is only one of the questions that needs to be answered.  Serialization and access to the data, codepage conversion, if you are moving some data but not others will you need to be able to map some of the converted data back to data on the mainframe.

A: Consider exploring IBM CDC classic replication. You can achieve it with click of buttons.
I have not done for Azure. So not sure about support.


text:
Q: codeigniter database calls from view Hey guys was hoping you could help me out.
basically i'm working on a website created using codeigniter by someone else. The site has two instances, one for development and one for live. The site is still under construction which means files are constantly being changed and moved from the development site (after being tested) to the live site.
Now the thing is, the person who initially created the site made some database calls from a few views. And to access the database from the view, he manually connected to the database from the view, i.e using
$db=mysql_connect(...);
mysql_select_db(...);

This means that each time a view is changed, before copying the files from the dev site to the live site, we need to change the variables inside these views.
moving all queries to models, and then calling them through controllers would take too long, so was wondering if there was a way through which i could access the database variables in the database.php file and pass them as the variable for mysql_connect.
i tried $this->db->database but get the error "Undefined property: CI_Loader::$db"
thanks in advance

A: There is no way to access database object from view. And you should also not do
$db=mysql_connect(...);
mysql_select_db(...);

in view. Try to remove those calls from view. And call it from model.
That is what MVC in codeigniter  used for. Othervise what is use of using codeigniter framework.
See also:

*

*access model from view in codeigniter?

*CodeIgniter - Calling a function from inside a view

A: First of all don't be eager about moving database calls to views, than take a look at this answer: https://stackoverflow.com/a/5835321/1444604

A: Define constants in constant.php assign them database username , password , host name etc and use them anywhere you want

A: If this site is under construction yet, it shall be much better fix all this programing issues now than later.
Remembering that mysql_* codes are deprecated and won´t go much longer be accepted by hosts.
A hint that you could use what sometimes we forget, are those options of replacing texts presents in som many text editors and IDE´s, normally with a shortcut ctrl + H, you can rewrite a lot of code in many files, but be careful, or this can get all worse.
Well... said that, what you´ve tried to do in the view $this->db->database() maybe can work if you use this code before load database. I think it should
work just like as when creating libraries.
$CI =& get_instance();
Give a look on, but even if it works, avoid it as much as you can:
https://www.codeigniter.com/user_guide/general/creating_libraries.html
Good Luck!


text:
Q: marshalling from py to c and from c to py In cython the marshalling of the types like int or char is done automatically,
but if I use a
       cdef struct MyClass_Tag:
            pass
      ctypedef MyClass_Tag* MyClass_ptr
      ....
      cdef class MyClass:
           cdef MyClass_ptr obj
           ....

Now for wrapping any function like for example in c is some function foo that takes
      foo(char* , MyClass_ptr self)
           #return stuff

To wrap this function I do:
       def py_foo(char* n, self):
            return foo(n,self.obj)

So from py to c:
       char is done automatically
       but self is of type MyClass so to call the foo i have to write self.obj ,
       so i pass the same obj

in here is where happen the marshalling from py to c
The problem is that I don't understand where happen the marshalling from c to py,
I mean at which point does it happen?
Even in this case or even if you give me some other example it will be ok.
Thank you!

A: I didn't completly understood your question, but you might want to use the command:
cython -a <yourfile.pyx>

Then, open the generated  with your webbrowser. You'll see how cython have translated your code into C, and then, found your answers :)

A: As the parameter name self suggests the C foo() function might make more sense as a method in Python:
cdef extern void c_foo "foo" (char* n, MyClass_ptr)

cdef class MyClass:
   cdef MyClass_ptr this

   def foo(self, unicode n not None):
       b = n.encode('ascii')
       cdef char* p = b
       c_foo(p, self.this)

See also Wrapping C library.
Cython translates your code to C (or C++). At this point you can forget it exists. Generated C code is an ordinary C extension for Python. This code contains ordinary Python C API calls such as PyBytes_AsString() (convert Python bytes to char*) or PyInt_FromLong() (convert C int to Python integer).
MyClass_ptr is used as is:
struct __pyx_obj_3foo_MyClass {
  PyObject_HEAD
  MyClass_ptr this; /* <-- using MyClass_ptr as is */
};

i.e., pure Python code never sees it so there is no conversion from/to Python objects.


text:
Q: Unicode string (in @variable) doesn't match in LIKE? In my SQL  "N" function in where clause  doesn't work properly.
This is my SQL Code
SELECT
    [11 Lab Data Detail].LineDesc,
    [11 Lab Data Detail].ProductSample,
    [11 Lab Data Detail].LotNo,
    [11 Lab Data Detail].TestDesc,
    Avg([11 Lab Data Detail].TestRes) AS [TestRes]
into
    [21 Test Result]
FROM
    [11 Lab Data Detail]
GROUP BY
    [11 Lab Data Detail].LineDesc,
    [11 Lab Data Detail].ProductSample,
    [11 Lab Data Detail].LotNo,
    [11 Lab Data Detail].TestDesc
HAVING
    [11 Lab Data Detail].LineDesc=@LineDesc AND
    [11 Lab Data Detail].ProductSample=@ProductSample AND
    [11 Lab Data Detail].LotNo=@LotNo AND
    [11 Lab Data Detail].TestDesc like N'%' + @TestDesc + '%'

Here if i use constant value for @testDesc - like
like N'SP (C)' then it works properly.

A: Is the column [11 Lab Data Detail].TestDesc a varchar or nvarchar data type or something else?


text:
Q: In Doctor Who "The Tsuranga Conundrum" what are they looking for in the junkyard? In Doctor Who "The Tsuranga Conundrum" what are they looking for on the junkyard planet? Did I miss where they said what they were looking for? It seemed important as all of them were looking for it.

A: Thanks to @RemyLebeau for the Episode transcript we can see that the item is never named however it is actually shown on screen :-
Approximately 1 minute into the episode (based on BBC iPlayer timings) the Doctor says the line "Maybe 59's the one with a big pile of these."
She is holding a cylindrical object (see image)


text:
Q: Center Storyboard Views in autolayout So basically, I have a UITextView that I want centered in my UIView.  Here's my view controller code below:
import UIKit

class OpeningScreenViewController: UIViewController {

    @IBOutlet weak var topBarUIView: UIView!
    @IBOutlet weak var topViewTextView: UITextView!

    override func viewDidAppear(animated: Bool) {
        let superViewWidth = view.frame.size.width
        let superViewHeight = view.frame.size.height

    //creating the top bar
        topBarUIView.frame = CGRect(x: 0, y: 0, width: superViewWidth, height: superViewHeight * 0.1)
        topBarUIView.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.5)

    //adding text to the top bar
        topViewTextView.frame = CGRectMake(0, 0, superViewWidth, superViewHeight * 0.1)
        topViewTextView.backgroundColor = UIColor.blueColor()
        topViewTextView.text = "Hello World"
        topViewTextView.textAlignment = NSTextAlignment.Center
        topViewTextView.font = UIFont(name: "Arial", size: 24)
    }
}

I change the opacity of my background view to 50 % and the textView to a background color of blue, but when I run this, the blue background is well within the UIView, like 10 ish pixels on one side, and 20 on the other.  I'm not sure why.
I set it up in storyboard, and cnt-dragged it on, and then changed the properties of the views in viewDidAppear to override the storyboard.
Also I tried doing things like:
  override func viewDidAppear(animated: Bool) {
    // Get the superview's layout
    let margins = view.layoutMarginsGuide

    // Pin the leading edge of myView to the margin's leading edge
    topBarUIView.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true

    // Pin the trailing edge of myView to the margin's trailing edge
    topBarUIView.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor).active = true

    // Give myView a 1:2 aspect ratio
    topBarUIView.heightAnchor.constraintEqualToAnchor(topBarUIView.widthAnchor, multiplier: 2.0)
}

And got a weird error saying that the layout constraints were having a problem.
Would it be easier to set the view's height and width and starting point separately? If so how can I do something like this pseudocode:
topBar.startingPoint = (x,y)
topBar.height = this
topBar.width = this

etc.

A: In a modern application you should never be setting .frame directly. Especially not in viewDidAppear -- your layout changes on rotate and in Slide Over or Split View multitasking whilst remaining visible.
The correct thing to do is always to use Auto Layout, and generally to apply all your Auto Layout constraints in Interface Builder, customizing by size class where necessary, and preview them there. Any misspecifications can be corrected much more easily that way. Excellent tutorials can be found at raywenderlich.com:

*

*Auto Layout Tutorial in iOS 9 Part 1: Getting Started

*Auto Layout Tutorial in iOS 9 Part 2: Constraints

*Easier Auto Layout: Coding Constraints in iOS 9


text:
Q: Redirect page with passing value I have a real problem and it's syntax problem. Normally when I need redirect any page I just use header function. Sometimes I use a variable when I need like below:
if(condition) header("Location: home.php?wrong=1");

Sometimes it could be:
if(condition) header("Location: home.php?wrong=1&&success=2");

There is no problem with direct use of variable(wrong or success). And when I need redirect a value from html form via post method, I use this code and it works:
if (condition) header("Location: home.php?id=".$_POST['topic_id']);

But I need more, I need pass another value too. So I use:
if (condition) header("Location: home.php?id=".$_POST['topic_id']&&wrong=1);

And this time I become a dumb. Can anyone help me out by providing proper syntax? I just need pass the WRONG=1 part too.

A: you need:
if (condition) header("Location: home.php?id=" . $_POST['topic_id'] . "&wrong=1");

or
if (condition) header("Location: home.php?id={$_POST['topic_id']}&wrong=1");

A: some times it could be
if (condition) {
  $_SESSION['error']['topicId'] = $_POST['topic_id'];
  $_SESSION['error']['otherData'] = array('sadfasdfasdfasd' => 'adsfasdf');
  header("Location: home.php?wrong=1");
  exit;
}

and then:
//home.php
if (!empty($_SESSION['error'])) {
  $topicId = $_SESSION['error']['topicId'];
  //... do someth ...
}

A: If there is any problem with PHP header function, you may keep in mind that you are able to printout the refresh meta tag in your script HTML output.
<meta http-equiv="refresh" content="0;url=http://yoursite.com/thepath/you/want/file.php?parames=anything">

This is a resource about meta refresh tag:
http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm


text:
Q: Why I get TransactionRequired exception even method saving entity is annotated with @Transactional? I get an exception when I upload picture
Methods
 public ServiceResult uploadPortrait( MultipartFile file,int userId){
    if (file.getSize()>ConfigurationHolder.getPictureSize()) {
        return ServiceResult.getErrorResult("exceed 2M!");
    }else{
        String filename=file.getOriginalFilename();
        String subfix=FileType.getSuffixByFilename(filename);
        if(ConfigurationHolder.getPortraitFileType().contains(subfix)){
            String inLibPath=ConfigurationHolder.getUserPortraitInLibPath(userId, subfix);
            try {
                savePortraitToDataBase(inLibPath, userId);
            } catch (Exception e) {
                e.printStackTrace();
                return ServiceResult.getErrorResult("saveError!");
            }
            ServiceResult result=ServiceResult.getSuccessResult("changeSuccess!");
            result.putProperty("portraitPath", inLibPath);
            return result;
        }else{
            return ServiceResult.getErrorResult("file type must be one of jpg,png,jpeg or gif!");
        }
    }
}
@Transactional(value="account",rollbackFor=Exception.class)
public void savePortraitToDataBase(String inLibPath, int userId){
    userOthersRepos.updatePortait(userId,inLibPath);
    userOthersdao.savePortraitToRedis(inLibPath, userId);
}

Exception
Caused by:exception'stacktrace:Caused by:javax.persistence.TransactionRequiredException: Executing an update/delete query
        at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:96)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:601)
        at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:372)
        at $Proxy118.executeUpdate(Unknown Source)
        at org.springframework.data.jpa.repository.query.JpaQueryExecution$ModifyingExecution.doExecute(JpaQueryExecution.java:174)
        at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:61)
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:95)
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:85)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:323)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
        ... 79 more

When I add the @Transactional annotation to uploadPortrait() and remove it from savePortraitToDataBase() , it works.
Can somebody tell me why?

A: In the above code fragment you are invoking "savePortraitToDataBase" method from "uploadPortrait" and before this invocation you invoke  "userOthersdao.savePortrait". It seems to me that the exception which you are getting is because of the invocation of userOthersdao.savePortrait(as it might also be doing insert/update operation and transaction is missing in case @Transactional is placed over savePortraitToDataBase this method).
But in the other way around when you place @Transactional over "uploadPortrait" function, transaction is available to both the methods.

A: To elborate on @chrylis's comment, the "Transactional" annotation is a Spring decorator - it only applies when something calls from outside the class to your function via an injected (or "autowired", in spring terminology) bean. Calling from inside the same class doesn't have the same effect


text:
Q: Error munmap_chunk(): Invalid Pointer C programming Dynamic Memory Allocation Unable to figure out this issue that is causing my program to throw this error, i'm reading from 3 files and have to make a dynamic array to store all the values of the text file(which are INTs). Then sort and print out to a new file.
This is my updated code
#include <stdio.h>
#include <stdlib.h>

//Jeffrey Hennen

int cmpfunc (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

void main(){
     //printf("hello\n");
     int counter = 0;

     FILE *fp;
     fp = fopen("list0.txt", "r");

     int ch;
     while((ch = fgetc(fp)) != EOF){
          //counter++;
          if(ch == '\n'){
              counter++;
          }
     }
     //printf("%d\n", counter);
     //printf("hello1\n");

     fclose(fp);
     fp = fopen("list1.txt", "r");

     while((ch = fgetc(fp)) != EOF){

          //counter++;
          if(ch == '\n'){
              counter++;
          }
     }
     //printf("%d\n", counter);
     //printf("hello1\n");
     fclose(fp);
     fp = fopen("list2.txt", "r");

     while((ch = fgetc(fp)) != EOF){
          //counter++;
          if(ch == '\n'){
              counter++;
          }
     }
     //printf("%d\n", counter);
     fclose(fp);
     //printf("hello2\n");
     int size = counter;
     int * sizeOfFile = (int*) malloc(size * sizeof(int));

     //int z = 0;
     //for (z = 1; z<= size; z++){
     //     printf("%d %d\n", z, sizeOfFile[z]);
     //}

     char ch1[sizeof(int)];
     int counter1 = 0;
     int y = 0;
     fp = fopen("list0.txt", "r");
     while ((ch = fgetc(fp)) != EOF){
          fgets(ch1, sizeof(int), fp);
          y = atoi(ch1);
          printf("%s\n", ch1);
          sizeOfFile[counter1] =  y;
          counter1++;
     }
     fclose(fp);

     fp = fopen("list1.txt", "r");
     while ((ch = fgetc(fp)) != EOF){
          fgets(ch1, sizeof(int), fp);
          y = atoi(ch1);
          printf("%s\n", ch1);
          sizeOfFile[counter1] =  y;
          counter1++;
     }
     fclose(fp);

     fp = fopen("list1.txt", "r");
     while ((ch = fgetc(fp)) != EOF){
          fgets(ch1, sizeof(int), fp);
          y = atoi(ch1);
          printf("%s\n", ch1);
          sizeOfFile[counter1] =  y;
          counter1++;
     }
     fclose(fp);

     qsort(sizeOfFile, size, sizeof(int), cmpfunc);
     fp = fopen("Hw3.out", "w");
     int x = 0;
     for(x; x < size; x = x + 1){
          fprintf(fp, "%d\n", sizeOfFile[x]);
     }
     fclose(fp);

     free(sizeOfFile);

}


text:
Q: SQLite Cordova - Error processing SQL: 5 var db = window.openDatabase("Database", "1.0", "userData", 200000);
console.log(db);
db.transaction(populateDB, errorCB, successCB);

function populateDB(tx) {
   tx.executeSql('CREATE TABLE IF NOT EXISTS USER (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, api_key TEXT NOT NULL, username TEXT NOT NULL)');
   tx.executeSql('INSERT INTO USER (api_key, username) VALUES ( "asd", row")');
}

function errorCB(err) {
    console.log("Error processing SQL: "+err.message);
}

function successCB() {
    console.log("success!");
}

First SQL statements executes, but then the second one returns:
could not prepare statement (1 unrecognized token: "")")  //with error code 5

. Any ideas why?
I am following the PhoneGap Docs at here

A: You forge the opening quote of the row string.


text:
Q: Can't make Curl POST request from web app A server I am working on appears to be denying outbound HTTP requests. The reason I think this is because I've tried both Guzzle and curl requests to the API.
The API lives on the same domain as the web server (this is temporary at clients request). I can make requests to the API server via Postman (Chrome plugin), but when I run that same request on the server, it doesn't return anything.
Here are the headers from the 'Postman' request:
POST /api2/user/session HTTP/1.1
Host: example.com
Connection: keep-alive
Content-Length: 49
Cache-Control: no-cache
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: PHPSESSID=d9ad79c4c0822fc5c86f4d8799307f1b; _ga=GA1.2.1674422587.1425409444

Post data:
token=a559d5bba5a9e9517d5c3ed7aeb62db6&user=30972

This works. It returns the data. But when I call the same endpoint from within my web app, I get nothing.
$data = urlencode("token=a559d5bba5a9e9517d5c3ed7aeb62db6&user=30972");

$ch = curl_init('http://example.com/api2/user/session');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded',
    'Content-Length: ' . strlen($data))
);

$result = curl_exec($ch);

What I don't understand is I can run the following, and it returns the content:
print file_get_contents("http://www.google.com");

When I var_dump the $_POST fields on the endpoint user/session it returns the array of postdata using Postman but $_POST fields are blank when sending via the web app. Even before it makes any request to the database, the post fields should be set right?
Via SSH this also works:
curl -F token=a559d5bba5a9e9517d5c3ed7aeb62db6 -F user=30972 http://example.com/api2/user/session

As suggested in comments I've tried:
var_dump(function_exists('curl_version'));

// bool(true)

I can't figure out what's going on.
Edit: This works ... but I don't want to use sockets. Must be a curl issue.
$fp = fsockopen('example.com', 80);

$vars = array(
    'token' => 'a559d5bba5a9e9517d5c3ed7aeb62db6',
    'user' => '30972'
);
$content = http_build_query($vars);

fwrite($fp, "POST /api2/user/session HTTP/1.1\r\n");
fwrite($fp, "Host: example.com\r\n");
fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fwrite($fp, "Content-Length: ".strlen($content)."\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");

fwrite($fp, $content);

header('Content-type: text/plain');
while (!feof($fp)) {
    echo fgets($fp, 1024);
}

Edit:
curl_error() also returns no error.

A: It turns out I needed to use http_build_query.
$vars = array(
    'token' => 'a559d5bba5a9e9517d5c3ed7aeb62db6',
    'user' => '30972'
);

$content = http_build_query($vars);

$ch = curl_init('http://example.com/api2/user/session');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded',
    'Content-Length: ' . strlen($content))
);

$result = curl_exec($ch);

A: This can be caused by a session lock... If you use curl to access the same server, the same session is used. While the script is running, the session is locked by default, this means that the current request has to finish before another is handled for the same session. This would explain a timeout of the request in curl, as your first request is not completed and another is made...
Using session_write_close() before the curl_exec will unlock the session and correct the problem.

A: To better understand the differences between the PHP code and cURL, I created a RequestBin instance and tried both on it. They yielded drastically different results:

It seemed like the POST data from the PHP script yielded an incorrect result for what was sent. This can be fixed by using a built-in PHP function http_build_query.
It will yield a more apt result:


text:
Q: FirebaseRecyclerAdapter populateViewHolder NullPointerException I am trying to populate RecyclerViews using FirebaseRecyclerAdapter. I am using FragmnetPagerAdapter to populate and have a three tabs layout using my ListFragment which contains the RecyclerView. I have catered for all the usual issues such as no empty constructor in the Model Class, Setting the layout manager using context e.t.c. but I am still getting a null pointer exception when the protected void populateViewHolder() function is called.
08-31 13:19:42.681 21993-21993/com.momskitchen.momskitchen V/MealListFragment:: mealname :Pakore
08-31 13:19:42.682 21993-21993/com.momskitchen.momskitchen E/UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.momskitchen.momskitchen.MealListFragment$3.populateViewHolder(MealListFragment.java:114)
at com.momskitchen.momskitchen.MealListFragment$3.populateViewHolder(MealListFragment.java:110)
at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:177)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5822)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5855)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5091)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4967)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3315)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3124)
at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1549)
at android.support.v7.widget.RecyclerView.access$400(RecyclerView.java:150)
at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:305)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

here is my Model Class
public class MealItem{
    public String id;
    public String name;
    public Long pricePerUnit;

    public MealItem() {
    }

    public MealItem(String id, String name, Long pricePerUnit) {
        this.id = id;
        this.name = name;
        this.pricePerUnit = pricePerUnit;
    }
}

here is my ViewHolder Class
public class MealHolder extends RecyclerView.ViewHolder {
    View mView;
    public final TextView mNameTV;
    public final TextView mPriceTV;

    public MealHolder(View itemView) {
        super(itemView);
        mView = itemView;
        this.mNameTV = (TextView) mView.findViewById(R.id.meal_name_edit_text);
        this.mPriceTV = (TextView) mView.findViewById(R.id.meal_price_text_view);
    }

    @Override
    public String toString() {
        return super.toString() + " '" + mNameTV.getText() + "'";
    }
}

and this is where I try to populate the RecyclerView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_meal_list, container, false);

    int position = getArguments().getInt(ARG_POSITON);
    // Set the adapter
    if (view instanceof RecyclerView) {

        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list);
        if (mColumnCount <= 1) {
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(getActivity().getApplicationContext(), mColumnCount));
        }
        recyclerView.setHasFixedSize(true);
        if(position == 0){
            lunchListAdapter = new FirebaseRecyclerAdapter<MealItem, MealHolder>(MealItem.class,R.layout.meal_item_layout_admin,MealHolder.class, FirebaseDatabase.getInstance().getReference().child("Meals").child("lunch")) {
                @Override
                protected void populateViewHolder(MealHolder viewHolder, MealItem model, int position) {
                    Log.v(TAG, "mealname :"+model.name);
                    viewHolder.mPriceTV.setText(model.name);
                    viewHolder.mNameTV.setText(""+model.pricePerUnit);
                }

            };
            recyclerView.setAdapter(lunchListAdapter);
        }else if(position == 1){
            dessertListAdapter = new FirebaseRecyclerAdapter<MealItem, MealHolder>(MealItem.class,R.layout.meal_item_layout_admin,MealHolder.class, FirebaseDatabase.getInstance().getReference().child("Meals").child("dessert")) {
                @Override
                protected void populateViewHolder(MealHolder viewHolder, MealItem model, int position) {
                    Log.v(TAG, "mealname :"+model.name);
                    viewHolder.mNameTV.setText(model.name);
                    viewHolder.mPriceTV.setText(""+model.pricePerUnit);
                }

            };

            recyclerView.setAdapter(dessertListAdapter);
        }else if(position == 2){
            complimentListAdapter = new FirebaseRecyclerAdapter<MealItem, MealHolder>(MealItem.class,R.layout.meal_item_layout_admin,MealHolder.class, FirebaseDatabase.getInstance().getReference().child("Meals").child("compliment")) {
                @Override
                protected void populateViewHolder(MealHolder viewHolder, MealItem model, int position) {
                    Log.v(TAG, "mealname :"+model.name);
                    viewHolder.mNameTV.setText(model.name);
                    viewHolder.mPriceTV.setText(""+model.pricePerUnit);
                }
            };
            recyclerView.setAdapter(complimentListAdapter);
        }
    }
    return view;
}

Also here is my RecyclerView xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView     xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:name="com.momskitchen.momskitchen.MealListFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager"
    tools:context="com.momskitchen.momskitchen.MealListFragment"
    tools:listitem="@layout/meal_item_layout_admin" />

And here is my list item layout xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/meal_name_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/meal_price_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>


text:
Q: How can i update my jLabel through another Thread? So, I have made a socket connection which runs on another thread. Now I want to update the number of connections each time a connection is accepted. But a change in a public variable is reflected but not in the GUI of the label. Here is a piece of my code:
while(flag){
    try{
        s = ss2.accept();
        ob.inc();
        System.out.print(ob.counter.getText());
        String x = ob.counter.getText();
        System.out.println(x);
        System.out.println("connection Established");

    }

catch(Exception e){
    e.printStackTrace();
    System.out.println("Connection Error");

}

}
    }
The code in the GUI section is:
public void inc()
{
    ctr++;
       counter.setText(String.valueOf(ctr));
    counter.repaint();
}

Can anyone tell how I can dynamically change the jLabel values?

A: If inc() is called from a worker thread (not the main or UI thread) then you would want to wrap that call inside of SwingUtilities.invokeLater().


text:
Q: the weights in Logistic Regression As I am studying Logistic regression, I just wanted to confirm that I understand it correctly,
my main concern is the equation wx+b.
here is my understanding :
(logistic regression is an algorithm used to classify things. The goal is to classify.
So let's assume that we are classifying if something belongs to class 0 or class 1 .
We use a function that gives us a probability  of it belonging to a class 0 or 1.
We set a threshold such as 0.5, if the prob above 0.5 it belongs to class 1 and vice versa.
The function that gives us values between 0 and 1 is called sigmoid.
the logistic regression uses decision boundary to decide to which class the data belong to, this decision boundary has the weights w and has the formula of : wx + b or w1x1+w2x2+ b )
or are the weights for the sigmoid and not for the decision boundary ?


text:
Q: Angular 6 firebase deploy can not dist/server I've been experiencing the following error when I want to deploy my Angular 6 project firebase, please help please
Error: Error parsing triggers: Cannot find module './dist/server'

Try running "npm install" in your functions directory before deploying.


text:
Q: Kafka Consumer: Pros and cons of using auto commit I am building a consumer and I want to ensure that every message, from a Kafka topic, is read and processed accordingly. While the auto commit feature is appealing, I would want to have full control of the offsets -- meaning, I want to only commit the offsets if the processing went well.
However, I'm not sure about the downsides of turning auto commit to false. What are the PROs and CONs of turning auto commit off? Is it gonna perform slower? Will multiple consumers, with the same consumer name have a problem with this implementation?

A: Performance really depends on how you implement it - you can commit offsets synchronously, or asynchronously, having different guarantees about how sure you want to be about the fact that offsets are committed.  Usually when you don't commit offsets manually, you have more control about it - like you want.  But there are some caveats, like, commitSync or commitAsync are committing offsets that are obtained by poll, so if you commit in the middle of the processing loop, and application crashes, then you'll lose data.
"Kafka. The Definitive Guide" has big section about commits & offsets - I recommend to read it - Confluent distributes the PDF of the book for free.


text:
Q: Birthday problem: By symmetry, the variance is $\text{Var}(X) = 365 \text{Var}(I_1) + 2 {365 \choose 2} \text{Cov}(I_1, I_2)$. I have the following problem:

Let $X$ be the number of distinct birthdays in a group of 110 people (i.e., the number of days in a year such that at least one person in the group has that birthday). Under the usual assumptions (no February 29, all the other 365 days of the year are equally likely, and the day when one person is born is independent of the days when the other people are born), find the mean and variance of $X$.

The solution proceeds as follows:

Let $I_j$ be the indicator r.v. for the event that at least one of the people was born on the $j$th day of the year, so $X = \sum_{j = 1}^{365}$ with $I_j \sim \text{Bern}(p)$, where $p = 1−(364/365)^{110}$. The $I_j$'s are dependent but by linearity, we still have $\mathbb{E}(X) = 365p \approx 95.083$. By symmetry, the variance is $\text{Var}(X) = 365 \text{Var}(I_1) + 2 {365 \choose 2} \text{Cov}(I_1, I_2)$.

I don't understand how the author got the following fact:

By symmetry, the variance is $\text{Var}(X) = 365 \text{Var}(I_1) + 2 {365 \choose 2} \text{Cov}(I_1, I_2)$.

I also searched for this "variance symmetry" formula, but I was unable to find it.
I would greatly appreciate it if people could please take the time to explain this.

A: You are looking for $\text{Var}(X)=\text{Cov}(X, X) = \text{Cov}\left(\sum\limits_{i=1}^{365} I_i, \sum\limits_{j=1}^{365} I_j\right) = \sum\limits_{i=1}^{365}\sum\limits_{j=1}^{365}\text{Cov}\left( I_i,  I_j\right)$
There are $365^2$ terms in the double sum

*

*$365$ of the terms are $\text{Cov}\left( I_i,  I_j\right)$ where $i=j$, and are equal to each other by symmetry, being $\text{Cov}\left( I_1,  I_1\right)=\text{Var}(I_1)$

*$365^2-365= 2{365 \choose 2}$ of the terms are $\text{Cov}\left( I_i,  I_j\right)$ where $i\not=j$, and are equal to each other by symmetry, being $\text{Cov}\left( I_1,  I_2\right)$
so $\text{Var}(X)=365\text{Var}(I_1)+2{365 \choose 2}\text{Cov}\left( I_1,  I_2\right)$


text:
Q: A boundary for integrals of eigenfunctions over geodesics? Let $X$ be a compact hyperbolic surface, and $\gamma$ a closed geodesic on it.
Consider the  integral
$$\int_\gamma f(x)\, dl(x)$$
where $f$ is a (normalized)  Laplace eigenfunction on $X$.  Intuitively, if  the length $l$ of $\gamma$ is large while  the eigenvalue $\lambda$ is moderate, then one would  expect  this integral to be small.  Did anyone found bounds for  this integral (in terms of $l$  and $\lambda$)?


text:
Q: Who is the Grand Inquisitor? I just watched the Star Wars Rebels episode "Shroud of Darkness". In it, Kanan, Ezra, and Ashoka go to the Jedi temple on Lothal and meditate so that they can contact Yoda.

During Kanan's vision, he fights three temple guards. When he finally realizes that he has to submit and accept his fate, the lead guard dubs him a Knight of the Jedi Order and then reveals that he is the Grand Inquisitor and that he was once a Jedi himself.

Is there any canonical proof of who the Grand Inquisitor was before he was the Grand Inquisitor and, if so, did he serve in the Clone Wars?

A: In "Shroud of Darkness" we learn not only that the Grand Inquisitor was a Jedi, as you have pointed out, but furthermore that he was a Temple Guard at the Jedi Temple on Coruscant.
That is, however, the extent of what is confirmed in canon.  As indicated in the entry concerning the Grand Inquisitor in the official StarWars.com databank:

Not much is known about the Empire's Grand Inquisitor. A Pau'an male, he was tasked by Darth Vader to hunt down any surviving Jedi Knights. The Inquistor was an intimidating figure, dressed in all black and wielding a red, double-bladed lightsaber. After several encounters with Kanan Jarrus and his Padawan Ezra Bridger, the Inquisitor died in a lightsaber duel with Kanan — but warned the rogue Jedi that his victory had unleashed something terrible.

(Source)
In particular, we know nothing of his record during the Clone Wars.
One further thing to add is that the credits for "Shroud of Darkness" refer to the Inquisitor as Sentinel, although it is unclear if this is a proper name or simply a description.


text:
Q: Using custom selectors in Jquery My code programmically creates  nodes with a custom ID. I am trying to access a specific one using Jquery but it doesn't want to work for me.
the html:

the jquery:
$(document).ready(function () {
    $("a").click(function () {
        var post = $(this).data('postid'); //this works and returns the postID selected.
        $('#list').slideUp(); //this hides all the anchor tags
        $('#' + 'post' + post).show(); //This is what is not working
    });
});

the .net c#
    foreach (SyndicationItem item in feed.Items)
    {
        subject[count] = item.Title.Text;
        date[count] = item.PublishDate.DateTime.ToString();

        summary[count] = item.Summary.Text;
        list.InnerHtml += "
" + subject[count] + "
" +
           "Posted on: " + date[count] + "
";
        article.InnerHtml += "" + summary[count] + "
";
        count++;
    }

Pretty much when I click one of the anchor nodes, it grabs the postID and hides the list of anchor tags I have and is suppose to display(un-hide) the post that has the postID.
Please let me know if u need any more information.

A: Your ids aren't unique.
You've got
 and ". Which will return something like
 and
 where an id is used twice.
Make sure to use unique ids and the show() method will work.

A: You can't duplicate element id's. Your  and
 elements both use the id "post" + count, when you call .show() it'll only grab the first element matching this id, in this case the

A:
Pretty much when I click one of the anchor nodes, it grabs the postID
  and hides the list of anchor tags I have and is suppose to
  display(un-hide) the post that has the postID.

Assuming the posts links are ordered the same as the posts themselves, do you really need the post ID? how about the following refactoring:
// The posts links

Post Number 1 title

Post Number 2 title

Post Number 3 title

Post Number 4 title

// the full posts

Post number 1. bla bla bla

Post number 2. bla bla bla

Post number 3. bla bla bla

Post number 4. bla bla bla

JQuery:
posts = $(".posts>li");

$(".posts_list").find("li").click(function(){

index = $("li").index(this);

posts.hide();
posts.eq(index).show();

});

JS Bin


text:
Q: How to set Priority level for ISR I am performing small test application in C, I want to add new ISR routine for my custom task. I read some part of it to insert new ISR. Also i got few articles to generate interrupt (int 3 windbg DbgBreak interrupt).
The part of I am not able find is how to define PRIORITY for my interrupt, whether its at raising interrupt or while new ISR entry
Any help appreciated.


text:
Q: Given a standard playing card deck of 52 cards. The probability of being dealt a 2 pair 5 card hand consisting exactly two pair of NOT face cards Homework. A face card is a king, Queen or Jack. Four of a kind is not considered two pair

A: Two pairs is the trickiest of the standard "poker hand" problems, the easiest one to get wrong. As usual we note that there are $\binom{52}{5}$ possible hands, all equally likely. We need to count the "favourables."
The two kinds we have $2$ each of can be chosen in $\binom{10}{2}$ ways. For there are $3$ kinds of face cards, and hence $10$ kinds of non-face cards.
For each of the $2$ kinds we have chosen, there are $\binom{4}{2}$ ways to choose the actual cards of the higher-ranking kind, and for each of these there are $\binom{4}{2}$ ways to choose the actual cards of the lower-ranking kind.
For each way of doing these things, there are $\binom{44}{1}$ ways to choose the useless fifth card, since we must avoid the $2$ kinds we have pairs in.
Thus the number of favourables is $\binom{10}{2}\binom{4}{2}\binom{4}{2}\binom{44}{1}$.
Remark: It is all too easy to decide that there are (in this problem) $(10)(9)$ ways to choose the kinds. That would be double-counting, since two $7$'s and two Aces is the same as two Aces and two $7$'s. But we could deliberately double-count, and then divide by $2$.


text:
Q: Expanding my singleton class I have use a singleton class that contained just one passed value. I then tried to add another one.
#import <Foundation/Foundation.h>

@interface GlobalValueContainer : NSObject {

    NSString *passedText;
    NSString *myPassedPictureName;
}

@property (nonatomic, strong) NSString* passedText;
@property (nonatomic, strong) NSString* myPassedPictureName;

+ (GlobalValueContainer *) sharedStore;

@end

#import "GlobalValueContainer.h"

@implementation GlobalValueContainer;

@synthesize passedText;
@synthesize myPassedPictureName;

static GlobalValueContainer *sharedStore = nil;

+ (GlobalValueContainer *) sharedStore {
    @synchronized(self){
        if (sharedStore == nil){
            sharedStore = [[self alloc] init];
        }
    }

    return sharedStore;
}

@end

From the first view I then try to set the myPassedPictureName
-(IBAction)setPicture:(id)sender{

    myPicture = @"Hus";
    GlobalValueContainer* localContainer = [GlobalValueContainer sharedStore];
    localContainer.myPassedPictureName = myPicture;

}

and on the second view I want to set an imageview with that name (+png that is)
- (void)viewDidLoad
{
    [super viewDidLoad];
    //Store* myStore = [Store sharedStore];

    GlobalValueContainer* localContainer = [GlobalValueContainer sharedStore];
    myPassedPictureName = localContainer.myPassedPictureName;
    myPicture.image = [UIImage imageNamed:myPassedPictureName];
    whatFile.text = myPassedPictureName;

   //object.imageView.image = [UIImage imageNamed:@"downloadedimage.png"];

}

the picture doesnt show. I have also tried to add a UIlabel and set the string that should have been passed. But it also turns out blank.
When I pass text using the "passedText" it works fine. When I added the second NSString, nothing happens?.
First things first. Can anyone see what´s wrong (still learning obj c here :)  and, is it the correct way I try  to manipulate an UIImageView. I want to use the myPassedPictureName to set a picture on a number of UIViews depending on the button being pressed.
Looking forward to your input.

A: I'm quite sure using singleton for passing value like this is not a good idea.Singleton is not designed for passing value,but for doing something.So you can not use Property like
sharedManager.passValue
Here has some good discussion about singleton.
When should you use the singleton pattern instead of a static class?
and
What should my Objective-C singleton look like?

So I suggest write it like this:

#import <Foundation/Foundation.h>

@interface GlobalValueContainer : NSObject {

}

+ (id) sharedManager;
-(NSString*)myText;
-(NSString*)myPictureName;

@end

#import "GlobalValueContainer.h"

@implementation GlobalValueContainer;

static GlobalValueContainer *sharedManager = nil;

+ (id) sharedManager {
    @synchronized(self){
        if (sharedManager == nil){
            sharedManager = [[self alloc] init];
        }
    }

    return sharedManager;
}

-(NSString*)myText
{
    return @"your text";
}
-(NSString*)myPictureName
{
    return @"yourPictureName.png";
}
@end

A: If variable "myPassedPictureName" is URL to file then you cannot use this method for it:
 [UIImage imageNamed:myPassedPictureName];

you should use
NSData *data = [[NSData alloc] initWithContentsOfURL:myPassedPictureName];
UIImage *image = [[UIImage alloc] initWithData:data];


text:
Q: Why isn't the serialVersionUID automatically generated? Why isn't the serialVersionUID automatically generated? I was running into an issue on an application server where apparently an old class was being cached.

A: It is automatically generated, based on the structure of the class. If the structure changes, the id is regenerated (according to the serialization specification it is a hashof the class).
So you'd better define an explicit serialVersionUID.

A: serialversionuid is not automatically generated because it is dangerous.  When serialversionuid is set, it implies that two versions of a class are compatible with respect to serialization.
Imagine you have a class called Foo, and it has no serialversionuid (the default), and you serialize an instance of Foo to a file.  Later, you add some new members to the Foo class.  If you try to deserialize the Foo object from the file, you will get a serialization failure stating that the objects are incompatible.  They are incompatible, this is what you want and is the default.  They are incompatible because new members in the Foo class cannot be initialized from the old serialized instance of Foo.
Now, you might say, "I don't care, in my application it is acceptable for those fields to be uninitialized".  If that really is the case, you can set the serialversionuid of the new Foo class to be the same as the old Foo class.  This will tell Java that the objects are compatible with respect to serializablity, and Java will not complain when you deserialize the old Foo instance into the new Foo class (but the new fields will still be uninitialized).
If you are creating a new class for the first time, and you set the serialversionuid, you are entering a contract.  That contract is, "For all future versions of this class with the same serialversionuid, I will guarantee they are compatible with respect to state and serialization".
If you change a class, and you explicitly want to disallow deserialization of old versions, you can change the serialversionuid to a new value.  This will cause an exception to be thrown if an old object is attempted to be deserialized into a new class instance.

A: If you're using Eclipse as your IDE, you can right-click on the warning about the missing serialVersionUID and you'll get two options:
1) Define the Eclipse default, which has the value 1L; or
2) Define a randomly generated long value
If you care about versioning of serialized objects, you'll need to manually regenerate a new value each time you modify the class. The Javadoc for the Serializable interface has this to say about what happens if you don't declare a serialVersionUID at all:

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value.

In practice, I've found that even if you start with identical source code on two or more machines (checked out of Subversion, for example) where serialVersionUID was undefined in a class, the compiler-generated value in the class is different on each machine when the code is compiled. This can cause confusing errors during development.
If you are sure that you'll never have a situation where you have stale serialized objects that are out-of-sync with a newer version of the class (or two JVMs sending out-of-sync serialized objects to each other, perhaps across a network or socket connection) then just set a value of 1L for serialVersionUID and leave it that way forever.
http://download-llnw.oracle.com/javase/6/docs/api/java/io/Serializable.html


text:
Q: sandbox error credentialas? I am new to paypal and use sanbox.
I'm trying to implement the paypal payment platform on an online sales page and I get an error; When creating an app in developer paypal (generates my client id and its normal secret) and use it on the page I get the following error;

PayPalConnectionException in PayPalHttpConnection.php line 154:
  Got Http response code 401 when accessing
  https://api.sandbox.paypal.com/v1/oauth2/token.

But if I use a public credentials (taken from the internet) if it works and I redirect to paypal correctly ..
What am I doing wrong? I need something to check
Thanks in advance

A: Use a package like anouar/paypalpayment or omnipay/paypal and it will be much easier for you to implement it.

A: You need to create sandbox account, your regular account not work on sandbox, search on google for sandbox account for test, you can even create buyers with money on the account to simplify your tests.

A: yes friends, I understand that I had to create a Sandbox account and so I did and still does not work when creating my app.
I am creating an application in laravel and I need the cliend id and the secret of a sandbox api that is why I am trying to implement this method. I hope to see if anyone can come up with a way to solve this problem.
Why does not my account generate a valid client id? Why does any other internet work?