Q:

Java, Inheritance, Generics - using parameters of subtypes in template method implementations

I am building an application that is generating PDF documents for sales orders and sales invoices. For simplicity I have exluded redundant logic and fields.
Here is my class structure:
public class SalesEntity {
    public String name;
    public String createdDate;
}

public class SalesOrder extends SalesEntity {
}

public class SalesInvoice extends SalesEntity {
    public String invoiceSpecificField;
}

and similar scturcure for wrapper and list items:
public class SalesEntityItem {
    public String name;
    public String price;
}

public class SalesOrderItem extends SalesEntityItem {
}

public class SalesInvoiceItem extends SalesEntityItem {
    public String invoiceItemSpecificField;
}

public class SalesEntityResponse {
    public SalesEntity salesEntity;
    public List<SalesEntityItem> salesEntityItems;
}

and here is first part of the problem.
public class SalesOrderEntityResponse extends SalesEntityResponse {
//    public SalesOrder salesEntity; <-- say somehow to java that in this subclass the property type should also be subclass
//    public List<SalesOrderItem> salesEntityItems;
}

For building mechanism I am using template method:
public class PDFBuilder extends AbstractPDFBuilder {
    protected void buildPdfDocument(Map<String, Object> model /*...*/) throws Exception {
        /*...*/
        addEntityNumber(document, salesEntityResponse);
        addItems(document, salesEntityResponse);
    }
}

public class OrderPDFBuilder extends PDFBuilder {
    /*...*/
    @Override
    protected void addEntityNumber(Document document, SalesEntityResponse entityResponse) throws DocumentException {
        /*...*/
        PdfPTable documentNameTable = new PdfPTable(1);
        Phrase documentNamePhrase = new Phrase(entityResponse.labels.account_number, timesFont);
        PdfPCell documentNameCell = new PdfPCell(documentNamePhrase);
        documentNameTable.addCell(documentNameCell);
        document.add(documentNameTable);
    }

    @Override
    protected void addItems(Document document, SalesEntityResponse entityResponse) throws DocumentException {
        /*...*/
        for (SalesEntityItem salesEntityItem : entityResponse.salesEntityItems) {
            /* Items adding specific logic */
        }
    }
}

And if first part of somwhow solveable, here comes main part:
Question: How can I make specific template method implementations (OrderPDFBuilder, InvoicePDFBuilder)
receive parameters of subtype SalesEntityResponse (SalesOrderResponse and SalesInvoiceResponse) respectively? So that in specific implementations I can use specific fields of those entities. Does it make sense? I assume here is something related to bounded types, but I am not sure how to use it properly.

A:

As you've established generics are how you achieve this. So firstly you'll need to stick your generics decleration on the SalesEntityResponse:
public class SalesEntityResponse<T extends SalesEntity, U extends SalesEntityItem> {
    public T salesEntity;
    public List<U> salesEntityItems;
}

Then in the declaration of your subtypes you tell it what concrete types they hold:
public class SalesOrderEntityResponse extends SalesEntityResponse<SalesOrder, SalesOrderItem> {

}

To make the "magic" work in your addItems method you'll have to also have to add generics to which ever class/interface declares the addItems method, this is presumably AbstractPDFBuilder? So something like:
public abstract class AbstractPDFBuilder<T extends SalesEntity, U extends SalesEntityItem, V extends SalesEntityResponse<T, U>> {
    protected abstract void addItems(Document document, V entityResponse) throws DocumentException;
    }
}

And then your concrete PDFBuilder types need to supply the relavant generics:
public class SalesOrderPDFBuilder extends AbstractPDFBuilder<SalesOrder, SalesOrderItem, SalesOrderEntityResponse> {
    protected void addItems(Document document, SalesOrderEntityResponse entityResponse) {
    }
}


Q:

svn changes my files names

I'm using command line SVN 1.6.5 on my Ubuntu 9.10. This is my first time using it on the latest Ubuntu, I found svn confused about file names. The problem was as follow:
I firstly used
sudo svn co http://my-repository/h2m h2m
after successfully checkout these files, I immediately used
svn st and found
dean@notebook:~/FAT32/h2m$ svn st
?       license
?       readme
?       cnt/readme
!       cnt/README
?       doc/changes
!       doc/CHANGES
?       data/readme
!       data/README
?       octave/readme
!       octave/README
!       LICENSE
!       README

Looks like
I find checked my \h2m\data\ folder and find there is a file called README.
I also checked my server repository:
dean@notebook:~/FAT32/h2m/data$ svn list http://my-repository/h2m/data
README
digits.m
digits.mat
digits.sig

This is strange,I'm looking forward to hearing from your.
BTW: I'm using dualboot, I found the files are working perfectly on my Windows 7 which was using Tortoise SVN.
Thanks again.

A:

The first thing that looks wrong is that you've checked out as root (sudo) and then used normal user account.
Another thing is filesystem case sensitivity. I would expect weirdness like that when working with fat32 partition. Maybe checking mount options will help.


Q:

Creating PPT table runs intolerably SLOW

I am using Excel vba to create a table in a powerpoint slide and export data to said table. It's a basic calendar of events. The table builds so slow. It's 25 rows (header + 24 hours) and 9 (for a M-F) or 11 (including weekends) columns depending on whether the user clicks a 5-day button or a 7-day button.
I have separate subs for the 9 column version and the 11 column version. Both tables are building incredibly slow. It takes so long to adjust the row heights specifically. Once the row heights are set the table populates fast enough. The 9 column version code is below abbreviated not to include every row of time. Is there any way to speed things up?
Sub BuildFiveDayTable()

Dim BREtable as PowerPoint.Shape

Set BREtable = NewBREslide.Shapes.AddTable(25, 9, 1, 15, 719.25, 486)       'BREtable and NewBREslide are public variables decalred as Powerpoint shape and slide respectively.
BREtable.Name = "BREtable"

BREtable.Table.ApplyStyle ("5940675A-B579-460E-94D1-54222C63F5DA")     'No Fill, Table Style

BREtable.Table.Rows(1).Height = 14.4

For i = 2 to BREtable.Table.Rows.count         'steps through each row setting height. This is what runs slow.
     BREtable.Table.Rows(i).Height = 19.44
Next i

For i = 1 To BREtable.Table.Rows.count
     For j = 1 to BREtable.Table.Columns.count
          With BREtable.Table.Cell(i,j).Shape.TextFrame
               .TextRange.ParagraphFormat.Alignment = ppAlignCenter
               .TextRange.Font.Name = "Calibri"
               .TextRange.Font.Size = 10
               .TextRange.Bold = msoTrue
               .MarginBottom = 0
               .MarginLeft = 0
               .MarginTop = 0
               .MarginRight = 0
          End With
      Next j
Next i

With BREtable.Table
     .Columns(1).Width = 28.8
     .Cell(1,1).Shape.TextFrame.TextRange.Text = "KWT"
     .Cell(1,1).Shape.Fill.Forecolor.RGB = RGB(0,0,0)
     .Cell(1,1).Shape.TextFrame.TextRange.Font.Color = RGB(255,192,0)
     .Cell(2,1).Shape.TextFrame.TextRange.Text = "0600"
     .Cell(3,1).Shape.TextFrame.TextRange.Text = "0700"
     ...
     .Cell(25,1).Shape.TextFrame.TextRange.Text = "0500"

     .Columns(2).Width = 28.8
     .Cell(1,2).Shape.TextFrame.TextRange.Text = "GMT"
     .Cell(1,2).Shape.Fill.Forecolor.RGB = RGB(255,192,0)
     .Cell(1,2).Shape.TextFrame.TextRange.Font.Color = RGB(0,0,0)
     .Cell(2,2).Shape.TextFrame.TextRange.Text = "0400"
     .Cell(3,2).Shape.TextFrame.TextRange.Text = "0500"
     ...
     .Cell(25,2).Shape.TextFrame.TextRange.Text = "0300"

     .Columns(3).Width = 28.8
     .Cell(1,3).Shape.TextFrame.TextRange.Text = "EDT"
     .Cell(1,3).Shape.Fill.Forecolor.RGB = RGB(0,0,0)
     .Cell(1,3).Shape.TextFrame.TextRange.Font.Color = RGB(255,192,0)
     .Cell(2,3).Shape.TextFrame.TextRange.Text = "2300"
     .Cell(3,3).Shape.TextFrame.TextRange.Text = "0000"
     ...
     .Cell(25,3).Shape.TextFrame.TextRange.Text = "2200"

     .Columns(4).Width = 120.6
     .Cell(1,4).Shape.TextFrame.TextRange.Text = "Mon"
     .Cell(1,4).Shape.Fill.ForeColor.RGB = RGB(242,242,242)
     .Cell(1,4).Shape.TextFrame.TextRange.Fond.Color = RGB(0,0,0)

     .Columns(5).Width = 120.6
     .Cell(1,5).Shape.TextFrame.TextRange.Text = "Tues"
     .Cell(1,5).Shape.Fill.ForeColor.RGB = RGB(242,242,242)
     .Cell(1,5).Shape.TextFrame.TextRange.Fond.Color = RGB(0,0,0)

     .Columns(6).Width = 120.6
     .Cell(1,6).Shape.TextFrame.TextRange.Text = "Wed"
     .Cell(1,6).Shape.Fill.ForeColor.RGB = RGB(242,242,242)
     .Cell(1,6).Shape.TextFrame.TextRange.Fond.Color = RGB(0,0,0)

     .Columns(7).Width = 120.6
     .Cell(1,7).Shape.TextFrame.TextRange.Text = "Thurs"
     .Cell(1,7).Shape.Fill.ForeColor.RGB = RGB(242,242,242)
     .Cell(1,7).Shape.TextFrame.TextRange.Fond.Color = RGB(0,0,0)

     .Columns(8).Width = 120.6
     .Cell(1,8).Shape.TextFrame.TextRange.Text = "Fri"
     .Cell(1,8).Shape.Fill.ForeColor.RGB = RGB(242,242,242)
     .Cell(1,8).Shape.TextFrame.TextRange.Fond.Color = RGB(0,0,0)

     .Columns(9).Width = 28.8
     'Repeat Column 3
End With
End Sub

A:

Try hiding the table
Dim t
'.....
BREtable.Visible = False
t = Timer
For i = 2 To BREtable.Table.Rows.Count
     BREtable.Table.Rows(i).Height = 19.44
Next i
BREtable.Visible = True
Debug.Print Timer - t
'.....

In my quick tests, that change cut execution of the block from ~1.3 sec to ~0.3-0.4 sec


Q:

AJP Connector Apache-Tomcat with php and java application

I have a question about proxy and ajp module.
On my machine I have a Apache web server and a Tomcat servlet container.
On Tomcat is running a my java webapplication.
On Apache I have some services and I can call these in this way:
http://myhos/service1
http://myhos/service2
http://myhos/service3

I would configurate a ajp connector to call my tomcat webapplication from Apache.
I would somethin as http://myhost  to call the Tomcat webapp.
So, I configurated my apache in this way..and I have what I wanted: I can use http://myHost to visualize the Tomcat webApp by Apache.
<VirtualHost *:80>

    ProxyRequests off
    ProxyPreserveHost On

    ServerAlias myserveralias
    ErrorLog logs/error.log
    CustomLog logs/access.log common

    <Proxy *>
      Order deny,allow
      Allow from all
    </Proxy>

     ProxyPass /server-status !
     ProxyPass /balancer-manager !

    ProxyPass / balancer://mycluster/ stickysession=JSESSIONID nofailover=Off maxattempts=1

    <Proxy balancer://mycluster>
       BalancerMember ajp://myIp:8009  min=10 max=100 route=portale loadfactor=1
       ProxySet lbmethod=bytraffic
    </Proxy>

    <Location /balancer-manager>
        SetHandler balancer-manager
        Order deny,allow
        Allow from localhost
    </Location>

    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
    LogFormat "%{Referer}i -> %U" referer
    LogFormat "%{User-agent}i" agent

</VirtualHost>

But, now I can't use the apache services:
If I use http://myhos/service1 I have an error because apache  try to search service1 on  my tomcatWebApp.
Is there a way to fix it?

A:

You can prevent your Apache services from being proxied to Tomcat by using the ! exclusion syntax, just like you're already doing for server-status and balancer-manager:
ProxyPass /service1 !
ProxyPass /service2 !
ProxyPass /service3 !


Q:

Name suggestions for OpenSource organisation and MVC CMS Project

Hey guys, a couple of us are looking for a collaborative name to work under when developing OpenSource products. The first of which will be an MVC CMS which is designed to be as usable as possible (no admin system all editing done inline).
So can you help us name the two:

OpenSource Organisation - mainly dealing with .net and mvc solutions
MVC CMS - which is highly usable and intuiative

Thanks our efforts have failed us so far. We may even give a prize to the winner.
Update: We settled on OpenQuarters for our organisation and WebQuarters for our CMS more information at: http://www.openquarters.org

A:

OpenSource Organisation: PeopleFlow. Because it's always about people, workflows and flow ("usable and intuiative")
MVC CMS: PeopleFlow Web Headquarters (HQ): Web Headquarters (HQ) because CMS it too technical and because you need a concept that covers all of the functionality and business aspects of a CMS. You need the PeopleFlow because Web HQ is too generic and because it's better branding.


Q:

Service class and logging design Scala with Futures

I have a service class that gets some data from a database (for context, I'm using Play! Framework). Here's an example method:
  def getAccessToken(id: BSONObjectID): Future[Option[String]] = {
    userDAO.find(id).map {
      case Some(user) =>
        user.settings flatMap (_.accessToken)
      case _ => None
    }
  }

I'm trying to improve the error handling (new to Scala) on this thing as there are a couple things that can go wrong:

User might not be found
User might be found but accessToken might not be set (accessToken is an Option[String])

As it stands right now, I can't differentiate between the two. My natural inclination to fix this is to use \/ from Scalaz and have the return type be Future[ErrorType \/ String] and this seems like a reasonable approach. In my controller method, I can for comprehension a bunch of different service methods like this by lifting into a wrapper monad.
But I have the following questions:

Should my ErrorType extend Exception, or should I just use the sealed trait style and just extend from that. I've heard that it is not good practice to use exceptions in Scala, so I'm not sure what the right approach is.
How can I handle logging without polluting the controller class with excessive log statements? If a controller class calls a bunch of these service methods, the controller will have to handle several different ErrorTypes in the for comprehension. Assuming I'm lifting all the monads to a wrapper monad with ?|, I want to avoid this:
accessToken <- service.getAccessToken(id) ?| { error => error match { case Error1 =>
               logger.error(
                 "Unable to find access token for user: " + id
                   .toString())
               InternalServerError(
                 ApiResponse("internal_server_error",
                             "Unable to get token."))
               case Error2 => ...
             }

Thanks!

A:

I think Future[ErrorType / String] is a bit overkill as Future[T] already can hold either an object of type T or an Exception derived one (see Future.successful(...)/ Future.failed(...))

Should my ErrorType extend Exception, or should I just use the sealed trait style and just extend from that. I've heard that it is not good practice to use exceptions in Scala, so I'm not sure what the right approach is.

I would recommend to use a class (or a set of classes, one per particular error type), say YourAppException derived from Exception, as you need to handle low level exceptions one way or another anyway.
I agree that throwing/catching exceptions is not going very well with functional code and it is better to use Try[T] or Future[T] to return errors in a more explicit way instead. On the other hand there is nothing wrong with using an Exception derived class to hold some error info. It is often useful to wrap the original non-application (say IO) exception in an application one and keep a reference to the initial one in Exception's 'cause' for troubleshooting. It gives an opportunity to provide a more context specific error message.

How can I handle logging without polluting the controller class with excessive log statements?

Consider encapsulating error messages in Exception derived case classes, representing application errors so you can access the error messsages uniformly using exception.getMessage. It is easy to add some method to YourAppException to construct ApiResponse as well.
def getAccessToken(id: BSONObjectID): Future[String] = {
    userDAO.find(id).flatMap {
      case Some(user) =>
        val optToken = user.settings.flatMap (_.accessToken)
        optToken.map(Future.successful).getOrElse(Future.failed(AccessTokenIsInvalid(user)))
      case _ => Future.failed(UserNotFoundError(user))
    }
  }

case class AccessTokenIsInvalid(user: String)
  extends YourAppException(s"Access token is invalid for user $user") {
}

accessToken <- service.getAccessToken(id) ?| { error =>
           logger.error(error.getMessage)
           InternalServerError(
             ApiResponse("internal_server_error", error.getMessage))
         }


Q:

Concatenate Rows at different levels of a datatable

Click Image to View
In Above Image link is a datatable and with rows highlighted in blue border needs to be concatenate , as we can see the Project Ids are same but present at different levels in datatable
How to concatenate these 2 levels and aggregate it or bring the down 2 rows and append it with above rows with same project ID.

A:

You might be missing a Order By ProjectID based on how the table shows. Apparently it is only ordering by MODDATE.


Q:

MVC 4 oAuth With Facebook does not return email address

I am experimenting witht he MVC 4 oAuth that was released this month.
Can anyone point me to where I can add eMail address so that I can store that with user properties?
I need to be able to send a welcome email but don't know where to start with the out of the box MVC 4 oAuth.
Ideally, after successful login, I want to receive the User Info from Facebook in my controller and drop it in a table so an offline process can send the welcome email.
Thanks,
Victor

A:

It is because Facebook allows its users to specify what data is shared with 3rd party authentication services, such as you website Victor.  And by default, I believe the Email addresses (yes, there are multiple you can add to a facebook account) are not shared byd default.  A user has to go in and explicitly share their email addresses with 3rd parties - something I don't think anyone ever uses.
The only "mandatory" shared data that Facebook forces shared is the FullName (e.g. "Eric Duncan").  Everything else is optional for the user to share.
For example, I have my Facebook setup to share only my birthdate, but not the birthyear.  I also have my Facebook setup to share my interests but not my email.
Therefore, you have to code for what is guaranteed - the display name in Facebook's case (which is called the "UserName" in the MVC 4.0 OAuth).  Everything else is not guaranteed.
What I do in my OAuth applications, including Facebook connect, is after a successful authentication with the 3rd party, on the callback url page (e.g. ExternalLoginConfirmation.cshtml in MVC 4.0), I will ask the user to enter their Display Name, email address, birthdate, etc.  And make those fields required using standard data annotations on your custom view model.

A:

In order for Facebook to return an e-mail you must specify it in the scope. For example with the JS SDK you would do something like....
return FB.login(function(response) {
    if (response.authResponse) {
      return window.location = '/auth/facebook/callback';
    }
  }, {scope: 'email,user_likes'}
);


Q:

Do we support Ubuntu MATE?

I saw this question, GTK disappears while in sudo mode, which appeared to be about a derivative Ubuntu release.
Do we support derivatives of Ubuntu? Or have I misidentified the question?

A:

It's funny the difference a week makes.
Ubuntu MATE is official now; it is supported on Ask Ubuntu.
Standard rules apply though so bugs and major pre-release issues should primarily be reported through the bug tracking tools on Launchpad.

A:

I think that is in the air right now, as they are on the way to be official and they have number releases corresponding with Ubuntu and still have "Ubuntu" in the title, as it seems the legal team is diligent in having derivatives remove that.
Since their goal is close compatibility, aka as pure as possible Ubuntu + Mate for the desktop - which can be added via ppa as well, it would be reasonable to let some through, till it's official.
However some still apply rules hard and fast without grey areas, and will still close until the day that happens.
This however isn't on the scale of mint, so I wouldn't be so fast to burn these questions.
So... tl;dr:

Official? No.
A recognized flavor? No.
Is it Mint? NO.
Will it be a flavor? Maybe.
Should it be burned on sight? I'm willing to wait until they request them to stop using the word "Ubuntu" before we do that.


Q:

Formula field in Opportunity to populate Opportunity Line Items

I have given a requirement of populating the Opportunity Line Items in a formula field in Opportunity Object. But i find it unable to write the formula for this as Opportunity Line Items And Opportunity shares a LookUp Relationship ...
Is there anything i am missing here. Kindly suggest any approach.

A:

This cannot be achieved by formula.
Through formula, we can only traverse from child to Parent. Reverse is not possible.
Salesforce maintains special kind of relationship for Account-Contact and Opportunity-OpportunityLineItems.
Though those relationships are defined as lookup but behave as Master-Detail. That's why they are special.
You could create a field and write a trigger to populate the field.


Q:

How can I check PHP version if phpinfo() is disabled?

What are some workarounds for checking what version of PHP when phpinfo() is disabled?

A:

phpversion() will return a full version string.
The PHP_VERSION constant also contains the version information.
Since PHP 5.2.7, there are also constants containing "sub-info" like PHP_MAJOR_VERSION, PHP_MINOR_VERSION....

A:

You can check the PHP_VERSION constant (this is a string) or PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION for their respective integer values.


Q:

Cisco administrative distance 255

On Cisco gear the maximum administrative distance for a route is 255. This makes the route unusable.

If the administrative distance is 255, the router does not believe the source of that route and does not install the route in the routing table.

Is there any practical use in configuring a route with an administrative distance of 255?

A:

I suppose the following link states it usage
http://www.cisco.com/c/en/us/support/docs/ip/open-shortest-path-first-ospf/4170-ospfprocesses.html
As per the link it helps in preventing routing loops by denying the routes to installed within the routing table..(In case of redistribution in OSPF)
Please have a look at the link, it has an illustrated example.
Hope it helps Thanks


Q:

How to set SplitMasterWorker value as false in giraph

I try to execute the giraph custom code from eclipse IDE, and when i try to run the code its showing Exception in thread “main” java.lang.IllegalArgumentException: checkLocalJobRunnerConfiguration: When using LocalJobRunner, must have only one worker since only 1 task at a time!
So i want to set the giraph.SplitMasterWorker=false.How to set it and where to set it?

A:

pass -ca giraph.SplitMasterWorker=false to your application as an argument.


Q:

How does NSURLRequestReturnCacheDataElseLoad work in iOS?

In my application I am using Webview and loading a data which I am getting from the webserver. In this it's working fine but issue is I used NSURLRequest object for sending request to the server. And I wrote the code as such below
NSMutableURLRequest * webPageRequest=[NSMutableURLRequest requestWithURL:webPageUrl cachePolicy:2 timeoutInterval:60.0];

Here the data is caching in memory successfully. But issue is when ever I open app it is always giving old data. It's not sending a request to the server for new data and even the app data is also not updating. I am supporting both IOS6 & IOS7.
So can you please let me know how to resolve this issue. And may I know how long the data will be available in Cache memory. And how NSURLRequestReturnCacheDataElseLoad will work means at what situation this method will execute.

A:

The issue you can see the old data is because the NSURLRequestReturnCacheDataElseLoad, see this (it has been taken from NSHister:

NSURLRequestReturnCacheDataElseLoad: Existing cached data should be
  used, regardless of its age or expiration date. If there is no
  existing data in the cache corresponding to the request, the data is
  loaded from the originating source.

Check out this link you should find the way to use right policy for your purpose.


Q:

Why is sqlite db database locked when there's no other python process writing to it at the same time?

In here Python sqlite3 doc, I see that the default timeout is 5 seconds.
I do connect without specifying the timeout. python 3.7.
I have 2 python processes that write to the same DB. This file.db is in WAL mode. I see the 2 files -shm and -wal there.
I get this exception sqlite3.Error:  'database is locked'
At the time of this exception, the other process had finished its transaction (got out of the with context manager) and had gone to sleep with signal.pause
The file is on a locally mounted regular hard drive.
How can i investigate what's happening besides doing:

I can check fuser -v on myfile.db

I do assume that any other writing process only locks the database while it is executing a transaction. Once it's finished, it releases the lock.
Besides, in WAL mode, are things supposed to work differently?

A:

From the docs:
The sqlite3 module opens transactions implicitly before a Data Modification Language (DML) statement (i.e. INSERT/UPDATE/DELETE/REPLACE), and commits transactions implicitly before a non-DML, non-query statement (i. e. anything other than SELECT or the aforementioned).
In my case, I only had a UPDATE, which means a BEGIN was inserted by sqlite3 before that, followed but the signal.pause(), which means I hadn't encountered a non DML stmt, and the transaction was still active right before sleeping
The other process tried to run a UPDATE while the 1st was still asleep ( and the transact active).
I've added a  conn.commit() before signal.pause()


Q:

getting string from resource strings.xml

When I get the string from the strings.xml , I don't get an error right away, but I can't run the program :
String myButtonText = getString(R.string.ButtonText);

(when I remove this line and this variable from my program it works perfectly)
I'll put up my program, in case you'd need it:
public class MainActivity extends AppCompatActivity {

    private Button button;
    String myButtonText = getString(R.string.ButtonText);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

           if(myButtonText.equals("Red")){//the button's text is "red" already
               button.setText("Blue");
           }
            }//I'm changing the text on the button to "blue" when it says"red"
        });
    }
}

A:

You should call getString(...) within the activity lifecycle to ensure that all the components under the hood are initialized.
In your example, you should call myButtonText = getString(R.string.ButtonText); in onCreate(...)


Q:

Angular 7 navigation forcibly returning to root

I'm having an issue with routing since I've upgraded from Angular 5 to Angular 7. I've googled the hell out of this to no avail.
Essentially the problem lays in navigating from one page to the other. If on the navbar, I select 'Plans' (as in payment plans), it brings me to the payment plans list (a list from Stripe). Then once I select a plan, I use router.navigate to go to a Stripe payment form page (Template driven form). I can see it navigate to the payment form page for a moment when I debug, but then it goes back to /.
My routes:
const appRoutes = [
{ path: 'home', component: HomeComponent },
{ path: 'accounts/login', component: LoginFormComponent },
{ path: 'accounts/register', component: RegistrationFormComponent },
{ path: 'plans', component: StripePlansComponent },
//{ path: 'pay', component: StripeFormComponent, canActivate: [IsLoggedinGuardService, HasSelectedPlanGuardService] },
{ path: 'pay', component: StripeFormComponent },
{ path: 'privacy', component: PrivacyStatementComponent },
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }

];
I have my Pay route commented out at the moment to make sure that Gaurds are not to blame.
My navmenu component:

         Pay

My plans component:
import { Component, Inject, OnInit, OnDestroy, ElementRef, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { PaymentService } from '../../shared/services/payment.service';

@Component({
    templateUrl: 'stripe-plans.component.html',
    styleUrls: ['stripe-plans.component.css'],
})

export class StripePlansComponent implements OnInit {

    public plans: Observable<StripePlan[]>;
    selectedPlan: StripePlan | undefined = undefined;

constructor(private _paymentService: PaymentService, private _router: Router) {

}

    ngOnInit() {
        this.plans = this.GetAllPlans();
    }

    GetAllPlans()  {
        return this._paymentService.getAvailablePlans();
    };

    ClickHandler(plan: StripePlan) {
        this._paymentService.setSelectedPlan(plan);
        this._router.navigate(['pay']);
    }
}

My plans HTML (I'm using the async pipe to handle subscribing/unsubscribing):

Payment Plans

                        Buy
                        {{ plan.Amount / 100 | currency: plan.Currency:'symbol-narrow':'1.2-2' }}
                        Now

{{ plan.PlanId }}

{{ plan.Amount / 100 | currency: plan.Currency:'symbol-narrow':'1.2-2' }} per {{ plan.Interval }}

                Select

As you can see in the javascript above, I'm navigating from within a click handler.
My form component:
import { Component, NgZone, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from '../../shared/services/user.service';
import { PaymentService } from '../../shared/services/payment.service';
import { NgxSpinnerService } from 'ngx-spinner';
import * as moment from 'moment';

@Component({
    templateUrl: 'stripe-form.component.html',
    styleUrls: ['stripe-form.component.css']
})

export class StripeFormComponent implements OnInit {

    Stripe: any;
    model: any = {};

   message: string | undefined = undefined;
   errorMessage: string | undefined = undefined;

   selectedPlan: StripePlan | undefined;
   submitted: boolean = false;
   valuesMonth: any[];
   valuesYear: any[];

  constructor(private paymentService: PaymentService, private _zone: NgZone, private _router: Router, private _userService: UserService, private spinner: NgxSpinnerService) {
      this.Stripe = ( < any > window).Stripe;
  }

  ngOnInit() {
       this.selectedPlan = this.paymentService.getSelectedPlan();
  }

Router output:
> VM41 vendor.js:66038 Router Event: NavigationStart
> VM41 vendor.js:66033 NavigationStart(id: 2, url: '/plans')
VM41 vendor.js:66033 NavigationStart {id: 2, url: "/plans", navigationTrigger: "imperative", restoredState: null}
VM41 vendor.js:66038 Router Event: RoutesRecognized
VM41 vendor.js:66033 RoutesRecognized(id: 2, url: '/plans', urlAfterRedirects: '/plans', state: Route(url:'', path:'') { Route(url:'plans', path:'plans') } )
VM41 vendor.js:66033 RoutesRecognized {id: 2, url: "/plans", urlAfterRedirects: "/plans", state: RouterStateSnapshot}
VM41 vendor.js:66038 Router Event: GuardsCheckStart
VM41 vendor.js:66033 GuardsCheckStart(id: 2, url: '/plans', urlAfterRedirects: '/plans', state: Route(url:'', path:'') { Route(url:'plans', path:'plans') } )
VM41 vendor.js:66033 GuardsCheckStart {id: 2, url: "/plans", urlAfterRedirects: "/plans", state: RouterStateSnapshot}
VM41 vendor.js:66038 Router Event: ChildActivationStart
VM41 vendor.js:66033 ChildActivationStart(path: '')
VM41 vendor.js:66033 ChildActivationStart {snapshot: ActivatedRouteSnapshot}
VM41 vendor.js:66038 Router Event: ActivationStart
VM41 vendor.js:66033 ActivationStart(path: 'plans')
VM41 vendor.js:66033 ActivationStart {snapshot: ActivatedRouteSnapshot}
VM41 vendor.js:66038 Router Event: GuardsCheckEnd
VM41 vendor.js:66033 GuardsCheckEnd(id: 2, url: '/plans', urlAfterRedirects: '/plans', state: Route(url:'', path:'') { Route(url:'plans', path:'plans') } , shouldActivate: true)
VM41 vendor.js:66033 GuardsCheckEnd {id: 2, url: "/plans", urlAfterRedirects: "/plans", state: RouterStateSnapshot, shouldActivate: true}
VM41 vendor.js:66038 Router Event: ResolveStart
VM41 vendor.js:66033 ResolveStart(id: 2, url: '/plans', urlAfterRedirects: '/plans', state: Route(url:'', path:'') { Route(url:'plans', path:'plans') } )
VM41 vendor.js:66033 ResolveStart {id: 2, url: "/plans", urlAfterRedirects: "/plans", state: RouterStateSnapshot}
VM41 vendor.js:66038 Router Event: ResolveEnd
VM41 vendor.js:66033 ResolveEnd(id: 2, url: '/plans', urlAfterRedirects: '/plans', state: Route(url:'', path:'') { Route(url:'plans', path:'plans') } )
VM41 vendor.js:66033 ResolveEnd {id: 2, url: "/plans", urlAfterRedirects: "/plans", state: RouterStateSnapshot}
VM41 vendor.js:66038 Router Event: ActivationEnd
VM41 vendor.js:66033 ActivationEnd(path: 'plans')
VM41 vendor.js:66033 ActivationEnd {snapshot: ActivatedRouteSnapshot}
VM41 vendor.js:66038 Router Event: ChildActivationEnd
VM41 vendor.js:66033 ChildActivationEnd(path: '')
VM41 vendor.js:66033 ChildActivationEnd {snapshot: ActivatedRouteSnapshot}
VM41 vendor.js:66038 Router Event: NavigationEnd
VM41 vendor.js:66033 NavigationEnd(id: 2, url: '/plans', urlAfterRedirects: '/plans')
vendor.js:66033 NavigationEnd {id: 2, url: "/plans", urlAfterRedirects: "/plans"}
vendor.js:66038 Router Event: Scroll
vendor.js:66033 Scroll(anchor: 'null', position: 'null')
vendor.js:66033 Scroll {routerEvent: NavigationEnd, position: null, anchor: null}
vendor.js:66038 Router Event: NavigationStart
vendor.js:66033 NavigationStart(id: 3, url: '/pay')
vendor.js:66033 NavigationStart {id: 3, url: "/pay", navigationTrigger: "imperative", restoredState: null}
vendor.js:66038 Router Event: RoutesRecognized
vendor.js:66033 RoutesRecognized(id: 3, url: '/pay', urlAfterRedirects: '/pay', state: Route(url:'', path:'') { Route(url:'pay', path:'pay') } )
vendor.js:66033 RoutesRecognized {id: 3, url: "/pay", urlAfterRedirects: "/pay", state: RouterStateSnapshot}
vendor.js:66038 Router Event: GuardsCheckStart
vendor.js:66033 GuardsCheckStart(id: 3, url: '/pay', urlAfterRedirects: '/pay', state: Route(url:'', path:'') { Route(url:'pay', path:'pay') } )
vendor.js:66033 GuardsCheckStart {id: 3, url: "/pay", urlAfterRedirects: "/pay", state: RouterStateSnapshot}
vendor.js:66038 Router Event: ChildActivationStart
vendor.js:66033 ChildActivationStart(path: '')
vendor.js:66033 ChildActivationStart {snapshot: ActivatedRouteSnapshot}
vendor.js:66038 Router Event: ActivationStart
vendor.js:66033 ActivationStart(path: 'pay')
vendor.js:66033 ActivationStart {snapshot: ActivatedRouteSnapshot}
vendor.js:66038 Router Event: GuardsCheckEnd
vendor.js:66033 GuardsCheckEnd(id: 3, url: '/pay', urlAfterRedirects: '/pay', state: Route(url:'', path:'') { Route(url:'pay', path:'pay') } , shouldActivate: true)
vendor.js:66033 GuardsCheckEnd {id: 3, url: "/pay", urlAfterRedirects: "/pay", state: RouterStateSnapshot, shouldActivate: true}
vendor.js:66038 Router Event: ResolveStart
vendor.js:66033 ResolveStart(id: 3, url: '/pay', urlAfterRedirects: '/pay', state: Route(url:'', path:'') { Route(url:'pay', path:'pay') } )
vendor.js:66033 ResolveStart {id: 3, url: "/pay", urlAfterRedirects: "/pay", state: RouterStateSnapshot}
vendor.js:66038 Router Event: ResolveEnd
vendor.js:66033 ResolveEnd(id: 3, url: '/pay', urlAfterRedirects: '/pay', state: Route(url:'', path:'') { Route(url:'pay', path:'pay') } )
vendor.js:66033 ResolveEnd {id: 3, url: "/pay", urlAfterRedirects: "/pay", state: RouterStateSnapshot}
vendor.js:66038 Router Event: ActivationEnd
vendor.js:66033 ActivationEnd(path: 'pay')
vendor.js:66033 ActivationEnd {snapshot: ActivatedRouteSnapshot}
vendor.js:66038 Router Event: ChildActivationEnd
vendor.js:66033 ChildActivationEnd(path: '')
vendor.js:66033 ChildActivationEnd {snapshot: ActivatedRouteSnapshot}
vendor.js:66038 Router Event: NavigationEnd
vendor.js:66033 NavigationEnd(id: 3, url: '/pay', urlAfterRedirects: '/pay')
vendor.js:66033 NavigationEnd {id: 3, url: "/pay", urlAfterRedirects: "/pay"}
vendor.js:66038 Router Event: Scroll
vendor.js:66033 Scroll(anchor: 'null', position: 'null')
vendor.js:66033 Scroll {routerEvent: NavigationEnd, position: null, anchor: null}
Navigated to https://localhost:5001/
platform-browser.js:216 Router Event: NavigationStart
platform-browser.js:211 NavigationStart(id: 1, url: '/')
platform-browser.js:211 NavigationStart {id: 1, url: "/", navigationTrigger: "imperative", restoredState: null}
core.js:15702 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
platform-browser.js:216 Router Event: RoutesRecognized
platform-browser.js:211 RoutesRecognized(id: 1, url: '/', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
platform-browser.js:211 RoutesRecognized {id: 1, url: "/", urlAfterRedirects: "/home", state: RouterStateSnapshot}
platform-browser.js:216 Router Event: GuardsCheckStart
platform-browser.js:211 GuardsCheckStart(id: 1, url: '/', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
platform-browser.js:211 GuardsCheckStart {id: 1, url: "/", urlAfterRedirects: "/home", state: RouterStateSnapshot}
platform-browser.js:216 Router Event: ChildActivationStart
platform-browser.js:211 ChildActivationStart(path: '')
platform-browser.js:211 ChildActivationStart {snapshot: ActivatedRouteSnapshot}
platform-browser.js:216 Router Event: ActivationStart
platform-browser.js:211 ActivationStart(path: 'home')
platform-browser.js:211 ActivationStart {snapshot: ActivatedRouteSnapshot}
platform-browser.js:216 Router Event: GuardsCheckEnd
platform-browser.js:211 GuardsCheckEnd(id: 1, url: '/', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } , shouldActivate: true)
platform-browser.js:211 GuardsCheckEnd {id: 1, url: "/", urlAfterRedirects: "/home", state: RouterStateSnapshot, shouldActivate: true}
platform-browser.js:216 Router Event: ResolveStart
platform-browser.js:211 ResolveStart(id: 1, url: '/', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
platform-browser.js:211 ResolveStart {id: 1, url: "/", urlAfterRedirects: "/home", state: RouterStateSnapshot}
platform-browser.js:216 Router Event: ResolveEnd
platform-browser.js:211 ResolveEnd(id: 1, url: '/', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
platform-browser.js:211 ResolveEnd {id: 1, url: "/", urlAfterRedirects: "/home", state: RouterStateSnapshot}
platform-browser.js:216 Router Event: ActivationEnd
platform-browser.js:211 ActivationEnd(path: 'home')
platform-browser.js:211 ActivationEnd {snapshot: ActivatedRouteSnapshot}
platform-browser.js:216 Router Event: ChildActivationEnd
platform-browser.js:211 ChildActivationEnd(path: '')
platform-browser.js:211 ChildActivationEnd {snapshot: ActivatedRouteSnapshot}
platform-browser.js:216 Router Event: NavigationEnd
platform-browser.js:211 NavigationEnd(id: 1, url: '/', urlAfterRedirects: '/home')
platform-browser.js:211 NavigationEnd {id: 1, url: "/", urlAfterRedirects: "/home"}
platform-browser.js:216 Router Event: Scroll
platform-browser.js:211 Scroll(anchor: 'null', position: 'null')
platform-browser.js:211 Scroll {routerEvent: NavigationEnd, position: null, anchor: null}

Also, nothing unusual shows up in the route output except for the "Navigated to https://localhost:5001/".
I'd appreciate any help. This is really confusing me.

A:

Have you tried to remove the href attribute from the link: Select sometimes it could affect the routers behavior.


Q:

"Cette affaire l'est pour une autre raison." - what's that "l" there supposed to mean?

This is a short dialogue from a podcast for students of French. It's just two people talking:

Wal-Mart est le plus grand employeur dans le secteur privé aux États-Unis. Cette entreprise emploie plus de 1,4 millions de personnes aux États-Unis. Elle possède 8500 magasins dans 15 pays.
Oh, cette affaire est extrêmement importante. Potentiellement, l'obligation d'indemnisation pourrait atteindre des milliards de dollars.
C'est juste ! Mais en plus, elle n'implique pas seulement Wal-Mart. Cette affaire, « extrêmement importante », comme tu dis, l'est pour une autre raison. La défaite de Wal-Wart pourrait rendre n'importe quelle grande société vulnérable à des allégations similaires.

Why is there an l before est? Is it the pronoun le? Why do we need it there? That's something I really don't understand.

A:

The "l'" is indeed the elided form of "le". It is a pronoun that replaces "extrêmement important".
Let us imagine the sentence without this pronoun:

Cette affaire, extrêmement importante, est extrêmement importante pour une autre raison.

Repeating "extrêmement importante" is awkward and should be avoided. Hence, it is replaced by a pronoun.
A similar example:

Sa voiture est-elle grande ? Oui, elle l'est (= elle est grande)


Q:

Understanding Spring mvc produces/consumes and Jackson

I am running a Spring MVC 3 maven app with embedded jetty with configuration below:
    <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.14</version>
        <configuration>
            <scanIntervalSeconds>10</scanIntervalSeconds>
            <testClassesDirectory>/Users/mydownloads/Downloads/jackson-all-1.8.10.jar</testClassesDirectory>
            <useTestClasspath>true</useTestClasspath>
        </configuration>
    </plugin>

As seen above, I have jackson-all-1.8.10 jar in the test classpath.
I have mappings like below which are working fine when I produce json from my controller:
@RequestMapping(value="/getSomething",produces="application/json",method=RequestMethod.GET)
However, when I try to have a POST mapping so then I get an error: 415: Unsupported Media Type
the annotation I am using for POST is:
@RequestMapping(value="/postSomething", consumes="application/json", method= RequestMethod.POST)
How can I fix this so that the jackson jar sitting in the classpath takes care of the media type?
On the client when I am making a request to POST the data the request has following headers:
Request URL:http://localhost:8080/myapp/postSomething
Request Method:POST
Status Code:415 Unsupported Media Type
**Request Headersview source**
  Accept:*/*
  Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
  Accept-Encoding:gzip,deflate,sdch
  Accept-Language:en-US,en;q=0.8
  Connection:keep-alive
  Content-Length:23
  Content-Type:application/x-www-form-urlencoded
  Cookie:JSESSIONID=1f0mox1qw67zl
  Host:localhost:8080
  Origin:http://localhost:8080
  Referer:http://localhost:8080/myapp/
  X-Requested-With:XMLHttpRequest

I have datatype: 'json' on jQuery

A:

You don't set the request Content-Type correctly.
As you can see in the headers you posted, the Content-Type header value is  application/x-www-form-urlencoded, which is jquery default.
Use contentType: 'application/json'  attribute in jquery ajax call.
The dataType attribute tells jquery what content type is to be expected in the response.


Q:

Appending to empty element does not work

I want to display the characters of a string, stored in an array, one by one.
When I call threadsleep(a) using the following code: http://jsfiddle.net/thefiddler99/re3qpuoo/, it appears all at once.
The problem lies somewhere here I presume
for (var i = 0; i < str.length; i++) {
        $('#hello').append(str[i])
        alert("foo")
        sleep(500)
};

The alert shows that everything is working properly except that the interval between each is not present.
I cannot figure out why.
Note: Sleep is a function I have defined that works for the set amount of time

A:

JavaScript is single threaded. It is too busy running round and round your while loop to perform a repaint of the page.
Don't try to write a sleep function. The language isn't suited to it and it just chomps CPU. Rewrite your code to use setInterval or setTimeout instead.
var i = 0;

next();

function next() {
    $('#hello').append(str[i]);
    i++;
    if (i < str.length) {
        setTimeout(next, 500);
    }
}


Q:

Watir. Select multiple radio button options

The issue I'm dealing with, and unable to solve due to my ignorance, is that I have a page on a browser with different education requirements which each have four radio buttons. I want to be able to select a certain radio button for each education requirement.
The code I have is like this:
radios = browser.radios
radios.each do |radio|
  radio.input(:value => "very").set
end

However this keep giving me an error message saying: "undefined method 'set' for #Watir::Input:0x103a5d508"
I did something similar for select_lists where I changed the option of all select_lists on a page to the 2nd option which worked:
lists = browser.select_lists
lists.each do |list|
  list.option(:index, 1).select
end

For my code for the radio buttons I tried using radio.option but it gave me a similar error: "NoMethodError: undefined method `set' for #Watir::Option:0x103a466a0"

A:

Problem
The code
radios = browser.radios
radios.each do |radio|
  radio.input(:value => "very").set
end

Says that for each radio button on the page, set the first input element with value "very". This suggests that you are looking for html like:
<radio>
  <input value="very" />
</radio>

This is probably not what the html looks like.
Solution
I assume the html you really want to set is like:
<input type="radio" value="very" />

To set each radio button with value "very", the code should be:
# Get a collection of all radios with value "very"
radios = browser.radios(:value => "very")

# Iterate through each radio button in the collection and set it
radios.each do |radio|
  radio.set
end

This can be shortened to simply:
browser.radios(:value => "very").each(&:set)


Q:

Is there a more secure way to store sensitive string in an Android project?

In my Android project, I want to keep my web service address unknown.
I store the link as follows:
private final String SERVICE_LINK = "mywebservicelink..."

But since I saw that APK's can be decompiled, I wonder if this link can be known.
How can I store it securely?
Thanks.

A:

You can set sensitive string in your gradle.properties
https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_properties_and_system_properties
For example:
in your gradle.properties (usually located in your root project), you can define:
SERVICE_LINK = "mywebservicelink"

Then in your application's build.gradle
android {
   ...
   defaultConfig {
       resValue "string", "service_link", SERVICE_LINK
   }
   ...
}

Then, this service link will be ready in your resource as R.string.service_link. That is, you can simply get the value by doing:
getString(R.string.service_link);

EDIT 1:
If you're asking about how to hide your strings in your APK, then you can use ProGuard.
However, be advised. Whatever you put into your source code, there's no 100% guarantee that it cannot be reverse-engineered.
ProGuard will obfuscate your code, which will make reverse-engineering harder significantly.
For more information, this thread is awesome:
How to avoid reverse engineering of an APK file?


Q:

Add summary row in Gridview for one column

I have this GridView, and I want to add in the footer summation of PremiseScore score (third column).
How I can do this?

            <asp:BoundField DataField="PremiseUno" HeaderText='<%$ Resources:Language, grdPremiseUno %>' ReadOnly="True" SortExpression="PremiseUno"  >
                        <HeaderStyle CssClass="gHeaderStyle" />
                        <ItemStyle CssClass="gControlStyle" />
                        </asp:BoundField>

                         <asp:BoundField DataField="PremiseName" HeaderText='<%$ Resources:Language, grdPremisesName %>'
                            ReadOnly="True" SortExpression="grdPremisesName" >
                            <HeaderStyle CssClass="gHeaderStyle" />
                        <ItemStyle CssClass="gControlStyle" />
                        </asp:BoundField>

                        <asp:BoundField DataField="PremiseScore" HeaderText='<%$ Resources:Language, grdPremiseScore %>' ReadOnly="True" SortExpression="PremiseScore"  >
                        <HeaderStyle CssClass="gHeaderStyle" />
                        <ItemStyle CssClass="gControlStyle" />
                        </asp:BoundField>

                <asp:TemplateField ShowHeader="False" HeaderText= '<%$ Resources:Language, btnDelete %>'>
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
                            CommandName="Delete" Text="Delete" CommandArgument='<%# Eval("PremiseUno") %>'  onclick="LinkButton1_Click"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>

            </Columns>

A:

If you convert the bound field to a template field, you can access the control holding the value of premise score:
<asp:TemplateField HeaderText="test">
     <ItemTemplate>
         <asp:Label runat="server" ID="testLabel" Text='<%# Eval("PremiseScore") %>'></asp:Label>
     </ItemTemplate>
</asp:TemplateField>

You can then do the following to compute the sum in the Databound-event of the gridview:
protected void Grid_DataBound(Object sender, EventArgs e)
{
    GridViewRow footerRow = grid.FooterRow;
    var sum = (from GridViewRow row in grid.Rows select ((Label)row.FindControl("testLabel")).Text).Sum(d => Convert.ToInt16(d));

    footerRow.Cells[0].Text = sum.ToString();
}

I assume here that all values are ints, but it´s easily convertible to other value types.


Q:

reading fortran binary file in c++

The problem of reading (with c++ program) binary file generated by fortran code has been asked many times and the satisfactory description of conventions in fortran records has been given (e.g. http://local.wasp.uwa.edu.au/~pbourke/dataformats/fortran/ )
However when I try to implement c++ program, keeping in mind fortran conventions it still does not work. Here I assume we that the binary file "test.bin" contains 1 integer and is written in binary format by fortran routines.
Here is how I try to read it in c++:
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ifstream file;
  file.open("test.bin", ios::in|ios::binary);
  if (file.is_open())
  {
    int ival;
    file >> ival >> ival;  cout<< ival<<endl;
   }
   return 0;
}

Here the double >>ival construction first reads the header of the fortran record (which contains the size of the record in bytes) and the second >>ival supposed to extract the value. The integer written in file is 8, but the program outputs 0, so it does not read the data properly.
Here is a content of the binary file:
    ^D^@^@^@^@^@^@^@^H^@^@^@^D^@^@^@^@^@^@^@
So my question - what am I doing wrong?
Here is what hex editor shows:
0000000: 0400 0000 0000 0000 0800 0000 0400 0000  ................
0000010: 0000 0000 0a                             .....

Any idea what that means?

A:

operator>> is the formatted input operator. It is used to read text files, converting the textual representation to binary.
You should be reading using unformatted input operations. Try this:
file.read(reinterpret_cast<char*>(&ival), sizeof ival);

Of course, after you read it, you may need to byte swap for correct endian representation.


Q:

PHP, Sort Multidimensional Array by Child Array

I need to sort my multidimensional array by a value in the child array. In the array example below, I need to sort the parent arrays by child value "revenue_certificate".
function custom_sort($a, $b) {
    return strcmp($a['revenue_certificate'], $b['revenue_certificate']);
}

usort($data_array, 'custom_sort');

I feel like I'm almost there, but where I simply don't understand is how to reference the child array value of "revenue_certificate".
Array
(
    [0] => Array
        (
            [company_id] => 130
            [company_name] => Eureka / Brookings
            [revenue_certificate] => 3
            [revenue_cash] => 33
            [average_sale] => 0
            [total_orders] => 0
            [certificates_per_order] => -1
            [revenue_per_certificate] => -1
            [visible_items] => 25
            [retail_value] => -1
            [average_discount] => -1
            [new_advertisers] => 1
            [emails_harvested] => 1
            [new_customers] => 1
        )

    [1] => Array
        (
            [company_id] => 82
            [company_name] => Big Deals Across America
            [revenue_certificate] => 1
            [revenue_cash] => 0
            [average_sale] => 0
            [total_orders] => 0
            [certificates_per_order] => -1
            [revenue_per_certificate] => -1
            [visible_items] => 1
            [retail_value] => -1
            [average_discount] => -1
            [new_advertisers] => 0
            [emails_harvested] => 0
            [new_customers] => 0
        )

    [2] => Array
        (
            [company_id] => 134
            [company_name] => Fergus Falls, MN
            [revenue_certificate] => 2
            [revenue_cash] => 20
            [average_sale] => 0
            [total_orders] => 0
            [certificates_per_order] => -1
            [revenue_per_certificate] => -1
            [visible_items] => 128
            [retail_value] => -1
            [average_discount] => -1
            [new_advertisers] => 129
            [emails_harvested] => 2
            [new_customers] => 1
        )

)

Thanks for any help.

A:

Don't use strcmp :)
function custom_sort($a, $b) {
    return $a['revenue_certificate'] - $b['revenue_certificate'];
}

usort($data_array, 'custom_sort');

custom_sort should return a negative, 0, positive value when $a < $b, $a == $b, $a < $b respectively (just as strcmp does BTW).


Q:

PHP CheckStyle: Can't configure indentation

I am trying to use phpcheckstyle. I can't figure out how to configure it for functional brackets on a new line (using 4 spaces for indentation):
1. class MyClass
2. {
3.     public function __construct()
4.     {
5.         // do something
6.     }
7. }

It always gives the error "The indentation level must be 8 but was 4." for line 4 and 6. It only allows one of the following:
1. class MyClass
2. {
3.     public function __construct() {
4.         // do something
5.     }
6. }

or
1. class MyClass
2. {
3.     public function __construct()
4.         {
5.         // do something
6.         }
7. }

If there a way to get around this or another PHP style checker than can understand this?

A:

Sorry for that, it was a bug.
It should be corrected with the latest version.
I personally only use tabs for indentation and I haven't tested enough. Please feel free to report any problem on the project page.


Q:

When does $P(a-b)=0$ for $a\ne b$ ensure $P(0)=0$?

Let $n$ be a positive integer. How large must be a set $A\subset F_2^n$ to ensure that if $P$ is a quadratic polynomial in $n$ variables, vanishing at all non-zero points of the sumset $2A:=\{a_1+a_2\colon a_1,a_2\in A\}$, then also $P(0)=0$?
Considering the situation where $P(x_1,\ldots,x_n)=\sum x_ix_j+\sum x_i+1$, and $A$ consists of $0$ and the elements of the standard basis, we see that having $|A|>n$ is not enough. On the other hand, if $|A|>C2^{3n/4}$ with an appropriate absolute constant $C$, then $A$ contains a $3$-dimensional affine subspace, whence $2A$ contains a $3$-dimensional linear subspace, and the assertion is easy to deduce. Where exactly between $n$ and $2^{3n/4}$ lies the truth?

A:

Let $A$ be a maximal subset of $F^n_2$ with $P(A+A)\equiv 0$ but $P(0)\neq 0$. By finding a maximal linearly independent subset of $A$, and applying an appropriate linear transformation, we may assume $A$ contains the basis elements $e_1,\ldots,e_k$ and that all other elements of $A$ are linear combinations of these. We may further assume that $P$ is a polynomial in $x_1,\ldots,x_k,$ since we can throw out the other terms without changing our hypotheses. Then using that $P(e_i)=P(e_j)=P(e_i+e_j)=0$ and $P(0)=1$, one can deduce
$P=\sum_{\leq k} x_ix_j+\sum_{\leq k} x_i + 1$.
Finally, if $A$ contained anything besides the basis elements $e_i$ (and possibly zero*), $A+A$ would necessarily contain a non-zero element with either 3 or 0(mod 4) non-zero coordinates, for which $P$ does not vanish. So in fact, $|A|>n+1$ suffices.
*Actually, if $n\equiv 2 (\text{mod }4)$, we need $|A|>n+2$, since we can take the $e_i$'s, $0$, and $(1,1,\ldots,1)$.


Q:

Make a sad unicorn happy!

I am here to propose that a % of all unicoin's earned for the rest of the day count towards a donation to "Make a sad unicorn happy!" the group prevents any and all unhappy unicorns from becoming specialty in several different restaurants around the world where people specifically seek for unicorns as well as other cruelties such as skinning and others.
I've been able to see first hand what kind of cruelty they do such as:

Unicorns on a stick

Canned unicorn meat

unicorn pet disguise
And several other cruelties.
I hope StackOverflow will join the cause and if possible add a donation counter below the unicoin's widget...
If you support this act, post an answer with what sort of cruelty against unicorns have you seen!

A:

I'm very sad that my spell checker doesn't recognize the word "Unicoin".


Q:

Disable the use of CD drive (VB.NET)

I have a task and no idea how to tackle it!
Basically, I want to disable the CD drive on a PC so our users can't use them.
That's how I want to start anyway - ultimately I'd like an icon in the system tray that allows the CD drive(s) to be locked and unlocked providing you know a password.
I need somewhere to start though - does anyone know how to disable the use of a CD drive in VB.net?
Any help would be appreciated.
Andrew

A:

I found a way to do this.
Basically I needed to loop through all the items in the device manager like this:
search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                ' Go through each device detected.
            Next

I then took the DeviceID and ClassGuid sections.
If the Guid matched {4D36E965-E325-11CE-BFC1-08002BE10318} which is the GUID for a CD/DVD player, I told it to disable/enable the device dependent on what the user wanted to do.
To enable or disable them, I found this handy program all ready to go from here .
I then simply edited Form1.vb this:
Imports System.Management

Public Class Form1
Private Sub btnEnable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnable.Click
    getCdDrives("Enable")
End Sub

Private Sub btnDisable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisable.Click
    getCdDrives("Diable")
End Sub

Public Function getCdDrives(ByVal EnableOrDisable As String) As Boolean
    If InputBox("password") = "password" Then
        Try
            Dim info As System.Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            Dim deviceGuid As String
            Dim deviceType As String
            Dim cameraIsSeenByWindows As Boolean = False
            Dim showDebugPrompts As Boolean = False
            Dim actualGuid As Guid

            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                ' Go through each device detected.
                deviceType = CType(info("DeviceID"), String)
                deviceGuid = CType(info("ClassGuid"), String)
                If deviceGuid = "{4D36E965-E325-11CE-BFC1-08002BE10318}" Then
                    actualGuid = New Guid(deviceGuid)
                    If EnableOrDisable = "Enable" Then
                        DeviceHelper.SetDeviceEnabled(actualGuid, deviceType, True)
                    Else
                        DeviceHelper.SetDeviceEnabled(actualGuid, deviceType, False)
                    End If
                End If
            Next
            If EnableOrDisable = "Enable" Then
                btnDisable.Enabled = True
                btnEnable.Enabled = False
            Else
                btnDisable.Enabled = False
                btnEnable.Enabled = True
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    Else
        MsgBox("Oooh Va Vu!!")
    End If
End Function

End Class
That will then loop through the CD/DVD drives in device manager and disable/enable them.
I have yet to tidy the code up - and I need to run the script as a thread because it hangs at the moment while it's doing it's thing.
I also intend to get the program to work out what state the CD drives are in using a timer event - and then report back accordingly... I then need to get it to run in the system tray with no form and finally get it to run as the LSA with desktop interaction enabled.
I'll finish it when I get a moment - but everything you need should be here.
Hope this helps someone out a bit!


Q:

how can I clean a prefinished door?

I have a prefinished bedroom door and it appears to have developed a grey patch that looks like grease.  The patch isn't grease, however it just appeared by itself. Any help as to how I can get clean it off?

A:

I would try, in order of escalating cleaning function, these series of things until a suitable result has been obtained:

Wiping with a clean dry cloth.
Apply a little (15 ml/1 Tbsp) white vinegar to a paper towel and wipe.  Rinse with a wet (water) paper towel.
Combined with vinegar or dish detergent (for hand washing), use a rough cloth or mild scrub brush (pink or white Scotch brite).
Green Scotch bright and soap.  Repainting might be necessary afterward.
220 grit sandpaper
150 grit sandpaper
100 grit sandpaper
woodworking plane
replace the door


Q:

problem when accessing sharepoint site externally

i have created a sharepoint site urls:
 internal url : http://orbsp:2323
 external url : http://orbsp.com:2323.
when i am trying to access from other computers,its not opening.
plesae help me regarding this issue.

A:

1) try pinging it
2) if ping works, look further into IIS settings.
3) if ping doesn't work, try nslookup from the command line
4) if it doesn't resolve, check your DNS settings.
5) if it resolves, but you cannot ping it, check your firewall settings on the server network.


Q:

Url redirection issue with redirect 301

I am trying to redirect url using this condition
RewriteCond %{HTTP_HOST} ^www.example.com/xyz/Pianos-212--0$
RewriteRule ^(.*)$ http://www.example.com/xyz/Pianos-212/ [R=301,L]

the output i get is this
www.example.com/xyz/Pianos-212/?getCategory=$1&getBrand=$2

I need output URL to look like this
http://www.example.com/xyz/Pianos-212/

I am sure there is one line written above my condition that looks like this
RewriteRule ".*-([0-9]+)-.*-([0-9]+)" category.php?getCategory=$1&getBrand=$2 [L]

It is automatically appending query string after rewritten url

A:

Try adding a ? to the end of your RewriteRule:
RewriteRule ^(.*)$ http://www.example.com/xyz/Pianos-212? [R=301,L]

See this answer for more information:
htaccess 301 redirect - Remove query string (QSA)


Q:

How to use boost::bind to create a function wrapper

I want to use boost::bind (I'm not sure if it is really the right solution to my problem) to create a wrapper to a function that takes one or two arguments, while the wrapper takes only one argument and fixes the other to some constant value. My functions look like
double f(double a, double b)
{
  return a/b;
}

or
double g(double b)
{
  return 2*b; // b+b?
}

In my code I have a typedef for a function with one argument:
typedef boost::function<double (double)> callback;

and my idea was to create the function wrapper with this:
callback cb;
cb = boost::bind(f, _1, 2)(x);

so that I could call a third function that uses a wrapped function passed in the arguments:
double use(callback cb, double x, double y)
{
  return cb(x0) - y0;
}

I have about 30 functions with one or two arguments, and the first or the second must be a constant. This constant is not known to use(), but the algorithm implemented in use works with every function.
When I try to compile my code, I get an error for the line cb = boost::bind(f, _1, 2)(x);:
'* f' cannot be used as a function

When I try to use the bind directly, as in cout << boost::bind(f, _1, 2)(x);, I don't get an error.
What have I done wrong here?

A:

Why add the (x)?
cb = boost::bind(f, _1, 2);

This already defines a wrapper of f which the second argument is 2, and you can call
cb(x0)

to get f(x0, 2).


Q:

What is the probability that a point chosen randomly from inside an equilateral triangle is closer to the center than to any of the edges?

My friend gave me this puzzle:

What is the probability that a point chosen at random from the interior of an equilateral triangle is closer to the center than any of its edges?

I tried to draw the picture and I drew a smaller (concentric) equilateral triangle with half the side length. Since area is proportional to the square of side length, this would mean that the smaller triangle had $1/4$ the area of the bigger one. My friend tells me this is wrong. He says I am allowed to use calculus but I don't understand how geometry would need calculus. Thanks for help.

A:

You are right to think of the probabilities as areas, but the set of points closer to the center is not a triangle. It's actually a weird shape with three curved edges, and the curves are parabolas.

The set of points equidistant from a line $D$ and a fixed point $F$ is a parabola. The point $F$ is called the focus of the parabola, and the line $D$ is called the directrix. You can read more about that here.
In your problem, if we think of the center of the triangle $T$ as the focus, then we can extend each of the three edges to give three lines that correspond to the directrices of three parabolas.
Any point inside the area enclosed by the three parabolas will be closer to the center of $T$ than to any of the edges of $T$. The answer to your question is therefore the area enclosed by the three parabolas, divided by the area of the triangle.

Let's call $F$ the center of $T$. Let $A$, $B$, $C$, $D$, $G$, and $H$ be points as labeled in this diagram:

The probability you're looking for is the same as the probability that a point chosen at random from $\triangle CFD$ is closer to $F$ than to edge $CD$. The green parabola is the set of points that are the same distance to $F$ as to edge $CD$.
Without loss of generality, we may assume that point $C$ is the origin $(0,0)$ and that the triangle has side length $1$. Let $f(x)$ be equation describing the parabola in green.

By similarity, we see that $$\overline{CG}=\overline{GH}=\overline{HD}=1/3$$
An equilateral triangle with side length $1$ has area $\sqrt{3}/4$, so that means $\triangle CFD$ has area $\sqrt{3}/12$. The sum of the areas of $\triangle CAG$ and $\triangle DBH$ must be four ninths of that, or $\sqrt{3}/27$.
$$P\left(\text{point is closer to center}\right) = \displaystyle\frac{\frac{\sqrt{3}}{12} - \frac{\sqrt{3}}{27} - \displaystyle\int_{1/3}^{2/3} f(x) \,\mathrm{d}x}{\sqrt{3}/12}$$
We know three points that the parabola $f(x)$ passes through. This lets us create a system of equations with three variables (the coefficients of $f(x)$) and three equations. This gives
$$f(x) = \sqrt{3}x^2 - \sqrt{3}x + \frac{\sqrt{3}}{3}$$
The integral of this function from $1/3$ to $2/3$ is $$\int_{1/3}^{2/3} \left(\sqrt{3}x^2 - \sqrt{3}x + \frac{\sqrt{3}}{3}\right) \,\mathrm{d}x = \frac{5}{54\sqrt{3}}$$

This gives our final answer of $$P\left(\text{point is closer to center}\right) = \boxed{\frac{5}{27}}$$

A:

In response to Benjamin Dickman's request for a solution without calculus, referring to dtldarek's nice diagram in Zubin Mukerjee's answer (with all areas relative to that of the triangle $FCD$):
The points $A$ and $B$ are one third along the bisectors from $F$, so the triangle $FAB$ has area $\frac19$. The vertex $V$ of the parabola is half-way between $F$ and the side $CD$, so the triangle $VAB$ has width $\frac13$ of $FCD$ and height $\frac16$ of $FCD$ and thus area $\frac1{18}$. By Archimedes' quadrature of the parabola (long predating the advent of calculus), the area between $AB$ and the parabola is $\frac43$ of the area of $VAB$. Thus the total area in $FCD$ closer to $F$ than to $CD$ is
$$
\frac19+\frac43\cdot\frac1{18}=\frac5{27}\;.
$$
P.S.: Like Dominic108's solution, this is readily generalized to a regular $n$-gon. Let $\phi=\frac\pi n$. Then the condition $FB=BH$, expressed in terms of the height $h$ of triangle $FAB$ relative to that of $FCD$, is
$$
\frac h{\cos\phi}=1-h\;,\\
h=\frac{\cos\phi}{1+\cos\phi}\;.
$$
This is also the width of $FAB$ relative to that of $FCD$. The height of the arc of the parabola between $A$ and $B$ is $\frac12-h$. Thus, the proportion of the area of triangle $FCD$ that's closer to $F$ than to $CD$ is
$$
h^2+\frac43h\left(\frac12-h\right)=\frac23h-\frac13h^2=\frac{2\cos\phi(1+\cos\phi)-\cos^2\phi}{3(1+\cos\phi)^2}=\frac13-\frac1{12\cos^4\frac\phi2}\;.
$$
This doesn't seem to take rational values except for $n=3$ and for $n\to\infty$, where the limit is $\frac13-\frac1{12}=\frac14$, the value for the circle.

A:

The problem can be solved without calculus by using Archimedes Quadrature of the Parabola. To prove this Archimedes did, however, use techniques that are closely related to modern calculus.

According to Archimedes Quadrature of the Parabola the area between the parabola and the edge EF is $4\over3$ the area of triangle EFG.
Let's assume that EK has length x, then due to similarity DI has length ${3\over2}x$ and DH has length ${1\over2}x$. Because point G is on the parabola we have that the length of DG is half the length of DI, hence the length of DG is ${3\over4}x$. Now the length of HG is ${3\over4}x-{1\over2}x={1\over4}x$. So the length of DH is twice the length of HG
From this it follows that the area of triangle EFG is half the area of triangle EFD.
The area between EF and the parabola is ${4\over3}\cdot{1\over2}={2\over3}$ times the area of triangle EFD.
As the area of triangle EFD is equal to ${1\over27}$ the area of triangle ABC we now find that the area of points closer to the middle then to the edges is equal to $3\cdot1{2\over3}\cdot{1\over27}={5\over27}$ the area of triangle ABC.
Hence P(point is closer to the center)=${5\over27}$.


Q:

CodeIgniter loading a view

A function in the controller User loads the signup form, eg:
public function signup()
    {
        $this->load->view('form_view');
    }

So the signup form url will be like root/user/signup  (ignore index.php)
The form_view has a form, which is submitted to another method in the same controller, lets say process(), eg.
<? echo form_open('user/process') ?>

Once the form is submitted, it goes to the user/process, which contains the validation code. If there is any validation error, It would load the form_view again and pass the error data to display on the form.
if ( $this -> form_validation -> run() === FALSE )
{
    //$this -> load -> vars( $data );
    $this -> load -> view( 'form_view' );

}

Everything works fine. But now since the same form_view is loaded from the user/process function, the url of the form will change from:
root/user/signup

to
root/user/process

Because the form was submitted to the url user/process and the form_view is being called from the process(). Is it possible to somehow redirect or maintain the original form url(root/user/signup) when the form_view is loaded from the process function in case of errors?
Thanks.

A:

Using the same method to for and validation you can try something like
if( count($this->input->post()) > 0 )
{ // do validation
   if ($this->form_validation->run())
   {
       // initilize and
       redirect('logged');
   }
}
$this->load->view( 'form_view' );

you always get the same method, as you asked


Q:

Google JSON/Ajax API - how do you get the next page of results?

According to : http://code.google.com/apis/ajaxsearch/documentation/#fonje
I get back a cursor result, but stupidly, the moreResultsUrl returns a URL NOT to the JSON service but to the main site - how do instead fetch the next page of results into JSON?

A:

Well, that's because moreResultsUrl is pointing to http://www.google.com/search instead of http://ajax.googleapis.com/ajax/services/search/web.
What you need are just the parameters of the moreResultUrl which you can pass to http://ajax.googleapis.com/ajax/services/search/web for the JSON result.
For example:
http://www.google.com/search?v=1.0&q=Luca
is translated in JSON with
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Luca
Google is just showing you their RESTful api, it's up to you to use the pages JSON value with whatever interface you want.


Q:

How do I read in a Csv file full of numbers into seperate arrays so I then process them

I'm trying to read a list of numbers into an array from a csv file as I then want to be able to output to a file all possible combinations of those numbers.
For example here is a list of the numbers in a CSV File
-8,-13,-8,-2,-4,6,4
-6,-12,-5,3,3,12,5
-5,-9,-4,5,10,13,10
-4,-8,-2,7,13,17,11
-3,-6,0,8,14,18,13
-2,-5,2,9,15,22,17
-1,-3,5,10,16,23,18

How can I read the first number in the list in a separate array to the next number in the list and so forth?
This is using visual basic
Thanks

A:

If your file is composed of rows each of 7 numbers then you need to 7 different collection variables. Because you don't specify how many rows are present I assume a unknown number of rows and thus the preferred type of collection to use is a List(Of Integer) instead of an array. This because the List doesn't need to know in advance how many elements do you need to store in it
Dim col1 As List(Of Integer) = new List(Of Integer)
Dim col2 As List(Of Integer) = new List(Of Integer)
Dim col3 As List(Of Integer) = new List(Of Integer)
Dim col4 As List(Of Integer) = new List(Of Integer)
Dim col5 As List(Of Integer) = new List(Of Integer)
Dim col6 As List(Of Integer) = new List(Of Integer)
Dim col7 As List(Of Integer) = new List(Of Integer)

for each line in File.ReadLines("c:\temp\this_is_your_file_to_read.csv")
    Dim parts = line.Split(","c)
    if parts.Length = 7 Then
        Col1.Add(Convert.ToInt32(parts(0)))
        Col2.Add(Convert.ToInt32(parts(1)))
        Col3.Add(Convert.ToInt32(parts(2)))
        Col4.Add(Convert.ToInt32(parts(3)))
        Col5.Add(Convert.ToInt32(parts(4)))
        Col6.Add(Convert.ToInt32(parts(5)))
        Col7.Add(Convert.ToInt32(parts(6)))
    Else
        MessageBox.Show("Line not matching the expected pattern")
    End If
Next


Q:

custom keybinding on find and Reg replace in sublime text?

Am thinking whether it's achievable to make shortcut key-bindings on user
sublime key-map, so that one-key-triggered "find reg expression and replace-all"
if can assign custom keybinding will save a lot of work.
For example can be applied to make below answer into shortcut:
Sublime Text 2: How to delete blank/empty lines
Thanks to Joyas's answer, Below is the usage that could achieve the above task.
1.install RegReplace plugin for sublime 2/3
2.configure user reg replace function
      {
            "replacements": {
                "remove_blank_lines": {
                    "find" : "(^\n)",
                "replace": "",
                "greedy_replace": true
               }
            }
     }

3.configure key bindings
  {
    "keys": ["ctrl+shift+y"],
    "command": "reg_replace",
    "args": {"replacements": ["remove_blank_lines"]}
  }

go to font-end press shortcut and it works so good!

A:

There is already a post here about custom shortcut in sublime text.
In order to change the default shortcut for find and replace, you just have to edit de the line

{ "keys": ["super+shift+f"], "command": "show_panel", "args":
  {"panel": "find_in_files"} }

in you preferences.
Furthermore, if you want to create a keybinding in order to "find and replace" a specific sequence of character, it seems that there is the plugin RegReplace to do so.


Q:

reverse returning an empty string in get_absolute_url

I am trying to use reverse for get_absolute_url in one of my models. However, it's returning blank string.
url.py
url(
    regex=r'^$',
    view=SocietyView.as_view(),
    name='society',
),
url(
    regex=r'^(?P<tagname>[\w ]+)/?$',
    view=SocietyView.as_view(),
    name='society_with_tag',
),

model.py
class Tag(models.Model):
    name = models.CharField(max_length=64, unique=True)
    posts = models.ManyToManyField(Post, related_name='tags', null=True, blank=True)

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("society_with_tag", kwargs={"tagname": self.name})

template.html

    {{ tag.name }}

result.html

    tag

A:

I have no idea why but removing ',' in the end solved this problem.
Both catherine and caio gave me great answers but since I am not using 1.5, that wasn't it.
I changed
def get_absolute_url(self):
    return reverse("society_with_tag", args=[self.name,])

into
def get_absolute_url(self):
    return reverse("society_with_tag", args=[self.name])


Q:

How can I disable Active Record Query Caching in Tests? Or use reload smarter?

I have had a lot of headaches in testing recently with what seems to be query caching.
A lot of variables didn't seem to have to values I thought they would, and I discovered that I have to use 'reload'. Now I'm using 'reload' way too often to make sure I have the most recent data from the db.
When exactly should I be using 'reload', or should I just disable caching altogether?
For example this line in one of my tests, won't work without the 'reload' bits:
assert_equal @fl1.reload.orig_price, @fl1.lesson.reload.price #price is reset in previous
I'm starting to lose faith in passing tests because of this as well, thinking, yeah, but what if it's passing because of stale values.
Can anyone shed some light on this?

A:

Basically, if you're working just in memory, you don't need to use reload. If you're going straight to the database, you will need to.
So, in general, something like:
@user = User.create!(:name => "John Doe", :age => 100, :login => "jdoe")
assert_equal "John Doe", @user.name

That will work just fine because everything about that object is in memory.
Now, let's say you did something like:
@user.pictures << Picture.create!(:locn => "/images/my_image.jpg")
assert @user.contains_picture(/images/"my_image.jpg")

and that method, contains_picture, was defined in user.rb as:
def contains_picture(path)
    User.includes(:picture).where("pictures.locn = ?", path)
end

Because that method goes directly to the database, it will fail because it will not find that picture. Instead, after adding the picture to the .pictures collection, you would need to do @user.save!
So, it depends on what is happening to the object and what the methods being used look like, and that will tell you if you need reloador not.


Q:

Changing VMContext attributes during tests

I want to write tests that require the ability to change predecessor accounts mid-test. But I couldn't find a way to change the VMContext dynamically.
fn get_context(value: u128) -> VMContext {
        VMContext {
            current_account_id: "alice.near".to_string(),
            signer_account_id: "bob.near".to_string(),
            signer_account_pk: vec![0, 1, 2],
            predecessor_account_id: "carol.near".to_string(),
            input: vec![],
            block_index: 0,
            account_balance: 0,
            is_view: false,
            storage_usage: 0,
            block_timestamp: 123789,
            attached_deposit: value,
            prepaid_gas: 10u64.pow(9),
            random_seed: vec![0, 1, 2],
            output_data_receivers: vec![],
        }
    }

    #[test]
    fn test_market_creation() {
        let mut context = get_context(500000000);
        let config = Config::default();
        testing_env!(context, config);
        let mut contract = MyContract::default();
        contract.do_something(); // Fire method with "carol.near" as predecessor
        // Switch account to "bob.near"
        contract.do_something(); // Fire method with "bob.near" as predecessor
    }

A:

When you call ‘testing_env!‘ again with a new context within the same test, it will keep the old storage, but use the new context.
Take a look at tests for fungible token example https://github.com/nearprotocol/near-bindgen/blob/75a62c7c1fd46feda614c4e7776d02eeea054ef8/examples/fun-token/src/lib.rs#L395

A:

Fields in VMContext are public. It should be possible to change any of its fields:
#[test]
    fn test_market_creation() {
        let mut context = get_context(500000000);
        context.predecessor_account_id = "carol.near".to_string();
        let config = Config::default();
        testing_env!(context, config);
        let mut contract = MyContract::default();
        contract.do_something(); // Fire method with "carol.near" as predecessor
        // Switch account to "bob.near"
        contract.do_something(); // Fire method with "bob.near" as predecessor
    }


Q:

Ruby: Hash Array of Column Name and Value pair from YAML

I have this YAML entries;
table:
  - name: table_a
select:
  - id: source.id
  - code: source.code
  - name: source.name
  - is_active: TRUE

I need to read this into a HASH array and construct a SELECT SQL statement like this;
SELECT
  source.id as id,
  source.code as code,
  source.name as name,
  TRUE as is_active
FROM table_a

I'm struggling to access HASH |key,value| pairs dynamically.
I used this code;
yml = YAML.load_file("file.yml")
yml.each_pair { |key, value| puts "#{key} = #{value}"}

But when I use yml['select'].each_pair I get "undefined method `each_pair'" error.

A:

Based on the YAML, here's how to parse it:
asdf = YAML.load('table:
  - name: table_a
select:
  - id: source.id
  - code: source.code
  - name: source.name
  - is_active: TRUE
  - created_at: Time.now()
  - updated_at: Time.now()')
=> {"table"=>[{"name"=>"table_a"}],
 "select"=>
  [{"id"=>"source.id"},
   {"code"=>"source.code"},
   {"name"=>"source.name"},
   {"is_active"=>true},
   {"created_at"=>"Time.now()"},
   {"updated_at"=>"Time.now()"}]}

Your YAML isn't creating an easily parsed data structure, which is making you jump through hoops to access elements:
asdf['table'][0]['name']
=> "table_a"

asdf['select'][4]['created_at']
=> "Time.now()"

Instead, it should look like:
table:
  name: table_a
select:
  id: source.id
  code: source.code
  name: source.name
  is_active: TRUE
  created_at: Time.now()
  updated_at: Time.now()

Which, after parsing, will create a hash of hashes looking like:
{
  "table"=>{
    "name" => "table_a"
  },
  "select" =>
  {
    "id"         => "source.id",
    "code"       => "source.code",
    "name"       => "source.name",
    "is_active"  => true,
    "created_at" => "Time.now()",
    "updated_at" => "Time.now()"
  }
}

That allows you to easily, and very intuitively, access elements:
asdf['table']
=> {"name"=>"table_a"}
asdf['select']['created_at']
=> "Time.now()"

YAML won't turn the string "Time.now()" into a Ruby Time.now method call, so encoding that string into the YAML data won't help.
Instead, after parsing it, use:
time_now = Time.now
select = asdf['select']
select['created_at'] = time_now
select['updated_at'] = time_now

You can update your "Time.now()" strings by pre-manipulating your incoming YAML, then parsing it:
yaml_string = '
table:
  name: table_a
select:
  id: source.id
  code: source.code
  name: source.name
  is_active: TRUE
  created_at: Time.now()
  updated_at: Time.now()
'
yaml_string.gsub!('Time.now()', Time.now.to_s)

Which results in:
table:
  name: table_a
select:
  id: source.id
  code: source.code
  name: source.name
  is_active: TRUE
  created_at: 2012-12-28 10:09:21 -0700
  updated_at: 2012-12-28 10:09:21 -0700

Parsing it now returns:
=> {"table"=>{"name"=>"table_a"},
 "select"=>
  {"id"=>"source.id",
   "code"=>"source.code",
   "name"=>"source.name",
   "is_active"=>true,
   "created_at"=>2012-12-28 10:09:21 -0700,
   "updated_at"=>2012-12-28 10:09:21 -0700}}

And YAML can do something with that time value, because it recognizes it:
[14] pry(main)> asdf['select']['created_at']
=> 2012-12-28 10:09:21 -0700
[15] pry(main)> asdf['select']['created_at'].class
=> Time

In addition, rather than write your own SQL, I strongly recommend using an ORM, like Sequel or DataMapper. I favor Sequel, but, in either case, the advantage is you don't have to write the queries, the ORM does. You tell it what database and tables to access and it figures out the schema and relationships. If you're using Rails, ActiveRecord is a good ORM, which is coupled with Rails. It can be used separately, but I'd recommend the other two first if you are not using Rails.


Q:

adding a node in Multi Level Doubly link list in c

I am creating a multilevel doubly link list, I am performing the adding nodes operation in it.  I'm confused because according to my logic code mentioned below it should print the value, but it is not printing.  The output is not wrong but maybe I'm doing something wrong which could affect while flatten that list.
I have 3 levels of this list. addNode function will add at the very first level, where as addChild function will add a node anywhere in 2nd or 3rd level.
code is:
Student* StudentList::addNode(int num)
{
    Student* node = new Student(num);
    if(head == 0) {
       head = node;
       tail = node;
    } else {
       node->prev = tail;
       tail->next = node;
       tail = tail->next;
    }

    return node;
}

add child:
Student* StudentList::addChild(Student* node1, int num)
{
    Student* node = head;
    Student* temp;
    Student* temp1;

    // traversing the list to find exact location
    while(node != 0)
    {
        if(node->num == node1->num) {
            break;
        } else {
            temp = node->child;
            while(temp)
            {
                if(temp->num == node1->num) {
                    node = temp;
                    break;
                } else {
                    temp1 = temp->child;
                    while(temp1)
                    {
                        if(temp1->num == node1->num) {
                            node = temp1;
                            break;
                        } else {
                            temp1 = temp1->next;
                        }
                    }
                    temp = temp->next;
                }
            }
            node = node->next;
        }
    }

    Student* newChild = new Student(num);
    Student* curr = node->child;
    if(curr == 0)
    {
        node->child = newChild;
    } else {
        while(curr->next)
        {
            curr = curr->next;
        }
        newChild->prev = curr;
        curr->next = newChild;
    }
    return node1;
}

Main Method code is:
StudentList* sl = new StudentList();
Student* newNode;
Student* newNode1;

newNode = sl->addNode(1);
    newNode1 = sl->addChild(newNode,11);
        sl->addChild(newNode1, 111);
        sl->addChild(newNode1, 112);
    newNode1 = sl->addChild(newNode,12);
newNode = sl->addNode(2);
    newNode1 = sl->addChild(newNode,21);
    newNode1 = sl->addChild(newNode,22);
        sl->addChild(newNode1, 221);
        sl->addChild(newNode1, 222);
        sl->addChild(newNode1, 223);
newNode = sl->addNode(3);
newNode = sl->addNode(4);
    newNode1 = sl->addChild(newNode,41);
        sl->addChild(newNode1, 411);

sl->printList();

and my print list code is:
void StudentList::printList(){
Student* curr = head;
while(curr){
    cout<< *curr <<endl;
    if(curr->child){
        Student* newCurr = curr->child;
        while(newCurr){
            cout<< "*{"<<newCurr->num <<"}"<<endl;
            if(newCurr->child){
                Student* newCurr2 = newCurr->child;
                while(newCurr2){
                        //according to my login this 3rd level childs num(id) value
                        //should be printed used only for 2nd level according to my
                        //logic.. where is the problem am i doing wrong any thing?
                        cout<< "**{"<<newCurr2->num <<"}"<<endl;
                        newCurr2 = newCurr2->next;
                }
            }
            newCurr = newCurr->next;
        }
    }
    curr = curr->next;
}

}
Kindly help me in this, thanks in advance for everyone.

A:

From the output you've put in your comment it looks like nothing is being added at the second level. Where you're expecting nodes to be added at the second level, they are being added to the first.
I think the problem is at the bottom of the add child function:
Student* StudentList::addChild(Student* node1, int num)
{
    // rest of function. node1 is never modified
    return node1;
}

You are always returning the node input to that function. I think in your following code
newNode = sl->addNode(1);
    newNode1 = sl->addChild(newNode,11);
        sl->addChild(newNode1, 111);
        sl->addChild(newNode1, 112);

That you will find that newNode1 == nodeNode and not the child node as I think you are expecting. Probably the add child function should be returning newChild


Q:

Consolidate two Excel Workbooks based on multiple criteria

I want to consolidate two excel files, both with a different layout. The only common columns between the two files are "name" and "postal code".
File 1 is the "basefile", file 2 contains the additional information I want to integrate into file 1.
The additional information (address, country, field7 and field8) should only be copied into the basefile when both name and postal code of the corresponding rows are the same. The basefile has multiple worksheets, the corresponding row could be in any of the sheets.
Both excel files are quite large (>60000 rows, 5 columns). The code is supposed to take the first entry from file 2 and search for the corresponding entry in file 1. If found, the additional information will be copied into file 1. Then (or if no corresponding entry found) the procedure is rerun, this time with the second entry from file 2 - as long as all entry from file 2 have been consolidated into file 1.
The below code works, but is way too slow. It took about two minutes to consolidate one single row.
Do you have any suggestions on how to improve the performance?
Sub merging_two_excel_files()
'

Dim data_path As String
Dim filename_base As String
Dim filename_addon As String

Dim xlApp As Excel.Application
Dim xlBook_base As Workbook
Dim xlBook_addon As Workbook

data_path = "..."
filename_base = "file1"
filename_addon = "file2"
Set xlApp = CreateObject("Excel.Application")
Set xlBook_base = xlApp.Workbooks.Open(data_path & filename_base)
Set xlBook_addon = xlApp.Workbooks.Open(data_path & filename_addon)

screenUpdateState = xlApp.ScreenUpdating
statusBarState = xlApp.DisplayStatusBar
calcState = xlApp.Calculation
eventsState = xlApp.EnableEvents
xlApp.ScreenUpdating = False
xlApp.DisplayStatusBar = False
xlApp.Calculation = xlCalculationManual
xlApp.EnableEvents = False

With xlBook_addon.Worksheets(1)
Dim number_of_rows_addon As Long
number_of_rows_addon = .Range("B1", .Range("B" & .Rows.Count).End(xlUp)).Rows.Count
End With

For k = 2 To number_of_rows_addon Step 1
Dim name_addon As String
Dim postalcode_addon As String
Dim address_addon As String
Dim country_addon As String
Dim field7_addon As String
Dim field8_addon As String

name_addon = xlBook_addon.Worksheets(1).Cells(k, 2).Value
postalcode_addon = xlBook_addon.Worksheets(1).Cells(k, 4).Value
address_addon = xlBook_addon.Worksheets(1).Cells(k, 3).Value
country_addon = xlBook_addon.Worksheets(1).Cells(k, 6).Value
field7_addon = xlBook_addon.Worksheets(1).Cells(k, 7).Value
field8_addon = xlBook_addon.Worksheets(1).Cells(k, 8).Value

Dim number_of_worksheets_base As Long
number_of_worksheets_base = xlBook_base.Worksheets.Count
For d = 1 To number_of_worksheets_base Step 1

With xlBook_base.Worksheets(d)
Dim number_of_rows_base As Long
number_of_rows_base = .Range("B1", .Range("B" & .Rows.Count).End(xlUp)).Rows.Count

For c = 2 To number_of_rows_base Step 1
If name_addon = .Cells(c, 6).Value And postalcode_addon = .Cells(c, 1).Value Then
.Cells(c, 7).Value = address_addon
.Cells(c, 8).Value = country_addon
.Cells(c, 9).Value = field7_addon
.Cells(c, 10).Value = field8_addon
Else
End If

Next c
End With

Next d

Next k

xlApp.ScreenUpdating = screenUpdateState
xlApp.DisplayStatusBar = statusBarState
xlApp.Calculation = calcState
xlApp.EnableEvents = eventsState

Application.DisplayAlerts = False
xlBook_base.Close SaveChanges:=True
Application.DisplayAlerts = True
xlBook_addon.Close SaveChanges:=False

xlApp.Application.Quit
Set xlApp = Nothing

MsgBox "Done!"

End Sub

A:

The fact you're creating a whole new instance of Excel to do this in is going to slow you down a lot - every one of those calls to the second instance has to be passed between the two processes (the new instance and the one where your code is running) - that takes a lot of overhead as the test method below shows:
Sub TEST()

    Dim xlapp As Excel.Application, wb As Excel.Workbook
    Dim c As Range, v, r As Long, t

    Set xlapp = CreateObject("excel.application")
    xlapp.Visible = True

    'using another Excel instance
    t = Timer
    Set wb = xlapp.Workbooks.Add()
    For r = 1 To 10000
        v = wb.Sheets(1).Cells(r, 1).Value
    Next r
    Debug.Print Timer - t '~ 20secs <<<<<<<<<

    xlapp.Quit

    'using the current instance
    t = Timer
    Set wb = ThisWorkbook
    For r = 1 To 10000
        v = wb.Sheets(1).Cells(r, 1).Value
    Next r
    Debug.Print Timer - t '~0.08 secs <<<<<<<<

End Sub

Using a second instance is much slower.
Without the second Excel instance, and exiting the loop as soon as a match is found:
Sub merging_two_excel_files()

    Const data_path As String = "..."
    Const filename_base As String = "file1"
    Const filename_addon As String = "file2"

    Dim xlBook_base As Workbook
    Dim xlBook_addon As Workbook, shtAddon As Worksheet
    Dim last_row_addon As Long, name_addon As String
    Dim postalcode_addon As String, shtBase As Worksheet
    Dim last_row_base As Long, k As Long, c As Long, rw As Range

    Set xlBook_base = Workbooks.Open(data_path & filename_base)
    Set xlBook_addon = Workbooks.Open(data_path & filename_addon)
    Set shtAddon = xlBook_addon.Worksheets(1)

    last_row_addon = shtAddon.Cells(shtAddon.Rows.Count, 2).End(xlUp).Row

    For k = 2 To last_row_addon

        Set rw = shtAddon.Rows(k)

        name_addon = rw.Cells(2).Value
        postalcode_addon = rw.Cells(4).Value

        For Each shtBase In xlBook_base.Worksheets

            With shtBase

                last_row_base = .Cells(.Rows.Count, 2).End(xlUp).Row

                For c = 2 To last_row_base
                    If name_addon = .Cells(c, 6).Value And _
                       postalcode_addon = .Cells(c, 1).Value Then

                        .Cells(c, 7).Value = rw.Cells(3).Value
                        .Cells(c, 8).Value = rw.Cells(6).Value
                        .Cells(c, 9).Value = rw.Cells(7).Value
                        .Cells(c, 10).Value = rw.Cells(8).Value
                        GoTo found '### exit loop after finding the matching row....
                    End If
                Next c

            End With

        Next shtBase
found:

    Next k

    Application.DisplayAlerts = False
    xlBook_base.Close SaveChanges:=True
    Application.DisplayAlerts = True
    xlBook_addon.Close SaveChanges:=False

    MsgBox "Done!"

End Sub

Compiles but untested.


Q:

How to combine common dates into 1 row in Oracle SQL

My query is:
SELECT EXTRACT(DAY FROM CO.ORDER_DATE) "DATE",
       TO_CHAR(CO.ORDER_DATE, 'DY') "BUSIEST DAY",
       SUM(OLI.QUANTITY) "NO. OF DISHES"
FROM CUSTOMER_ORDER CO INNER JOIN ORDER_LINE_ITEM OLI
ON CO.ORDER_ID = OLI.ORDER_ID
WHERE CO.ORDER_DATE >= TO_DATE('01 SEPTEMBER 2019', 'DD MONTH YYYY')
AND CO.ORDER_DATE <= TO_DATE('30 SEPTEMBER 2019', 'DD MONTH YYYY')
GROUP BY CO.ORDER_DATE
ORDER BY CO.ORDER_DATE

My current output is:
DATE   BUSIEST DAY    NO. OF DISHES
-----------------------------------
1      SUN            27
1      SUN            10
14     SAT            10

The output I want is:
DATE   BUSIEST DAY    NO. OF DISHES
-----------------------------------
1      SUN            37
14     SAT            10

What changes do I need to make in my Oracle SQL query?

A:

The problem here is that while you are selecting the day of the month, you are actually aggregating by the date.  This means that two different dates on the first of the month would end up appearing as two separate records.  You should instead aggregate by the actual day value and busiest day values:
SELECT
    EXTRACT(DAY FROM CO.ORDER_DATE) "DATE",
    TO_CHAR(CO.ORDER_DATE, 'DY') "BUSIEST DAY",
    SUM(OLI.QUANTITY) "NO. OF DISHES"
FROM CUSTOMER_ORDER CO
INNER JOIN ORDER_LINE_ITEM OLI
    ON CO.ORDER_ID = OLI.ORDER_ID
WHERE
    CO.ORDER_DATE >= TO_DATE('01 SEPTEMBER 2019', 'DD MONTH YYYY') AND
    CO.ORDER_DATE <= TO_DATE('30 SEPTEMBER 2019', 'DD MONTH YYYY')
GROUP BY
    EXTRACT(DAY FROM CO.ORDER_DATE),
    TO_CHAR(CO.ORDER_DATE, 'DY')
ORDER BY
    "DATE";