text:
Q: Python - passing a function (from scratch!) to another function? Is it possible to pass a function written from scratch to another function or class instantiation?
This is what I have right now:
class Foo(Object):
    def __init__(self, name, somefunction):
        self.name = name
        self.somefunction = somefunction

def afunction(param1, param2):
    return param1 + param2

Bar = Foo("Something", afunction)

Bar.somefunction(2, 3)
#returns 5

I'm wondering whether it's possible to not have to declare afunction beforehand, but just write the code directly as a parameter to somefunction during instantiation. Something like this?
class Foo(Object):
    def __init__(self, name, somefunction):
        self.name = name
        self.somefunction = somefunction

Bar = Foo("Something", def afunction(param1, param2): return param1 + param2)

#OR

Bar = Foo("Something", Anonymousfunctiontechnique: return param1 + param2)

Bar.somefunction(2, 3)
#returns 5

And also, this is not a job for lambda! The functions may be pretty complex, which function calls inside of them and with multiple parameters. Also, I shouldn't be able to access it anywhere else (so a declaration outside won't work it seems).
Is something like this possible? If so, how? And if not, what would be the best way to do what I'm trying to do?
Thanks!!!

A: You cannot do this in Python beyond the limitations of lambda.
But you can define the function right above the call and pass it in, even if you are in another scope, making its name a temporary variable that does not pollute your address space.
The logical difference between
Bar = Foo("Something", def afunction(param1, param2): return param1 + param2)

and
def _foo(param1, param2): return param1 + param2
Bar = Foo("Something", _foo)

Is the same difference as between
Bar = foo(param1 + param2)

and
_good_name = param1 + param2
Bar = foo(_good_name)

Having names for any compound computation is a good idea for documentation purposes.  It also helps people use any good debugger. And it keeps formatting considerations to a minimum.  All told -- just name things.
The reason this is "left out" of Python comes down to:

*

*How many people would not assign an inline computation over three lines long to a local variable?

*How many of these functions are less than three lines long?

*So why bother?

(I always use an underscore doing this.  The underscores mark these 'private', but they are not members, generally, so it just emphasizes that they are ephemeral.  If the scoping forces them to be members, it clues people that they are internal and not for wider consumption.  If you are totally paranoid about class clutter, use the same ones over and over and del them at the end of the class definition.).

A: What you're asking is really about a way to define functions inline.
Unfortunately, python does not support this. People have asked about this before.
In this PEP:

lambda will not be renamed.

At one point lambda was slated for removal in Python 3000. Unfortunately no one was able to come up with a better way of providing anonymous functions. And so lambda is here to stay.
But it is here to stay as-is. Adding support for statements is a non-starter. It would require allowing multi-line lambda expressions which would mean a multi-line expression could suddenly exist. That would allow for multi-line arguments to function calls, for instance. That is just plain ugly.
Thread: "genexp syntax / lambda", http://mail.python.org/pipermail/python-3000/2006-April/001042.html


text:
Q: Retrieve from a map by comparing the key to a string array I have some Go code that is returning a map of values but I only need some of the results.  Is there a way I can test/filter the key of the map against a string array (or something similar) to give a simplified result rather than a bunch of if statements?  All the samples I have looked up had fixed values to filter against.
A simple example is below, but rather than supplying the string I want to have a list of possible values so I can get a reduced list.
package main

import "fmt"

type colors struct {
    animal  string
    COLOR   []string
}

func main() {
    // Map animal names to color strings.
    colors := map[string]string{
        "bird":  "blue",
        "snake": "green",
        "cat":   "black",
    }

    // Display string.
    fmt.Println(colors)
}

A: Yes, you can test/filter a map using range. If you have all the possible values, you can simply compare them to the map using a key/value lookup and make the structs based off of that.
package main

import (
    "fmt"
)

type colors struct {
animal  string
COLOR   []string
}

func main() {
    //the list of values
    possibleValues := []string{"bird","dog", "cat"}
    // Map animal names to color strings.

    foo := map[string]string{
        "bird":  "blue",
            "snake": "green",
            "cat":   "black",
        }

    //slice of objects of your struct
    objects := []colors{}
    //for every value in the possible values
    for _, v := range possibleValues {
        //if it's in the map, make a new struct and append it to the slice of objects
        if val,ok := foo[v]; ok {
            objects = append(objects, colors{animal:v,COLOR:[]string{val}})
        }
    }
    // Display string.
    fmt.Println(objects)

}

https://play.golang.org/p/njD6E_WssHT

redpajama_set_name: RedPajamaStackExchange


text:
Q: what does =! means in javascript I came across this line while reading source code of an application.
$scope.editMode = ! $scope.editMode;

I wonder what does this is not the not the not equal to operator. I tried it in this jsfiddle the answer is correct but I still do not understand the logic is this somehow an equal to operator?
jsfiddlecode
  $scope.name = 'Superhero';
        $scope.hero = '123'
        $scope.name = ! $scope.hero

A: ! is used to reverse boolean value.
For example:
!(true) = false and
!(false) = true

In your example
, reversion of $scope.editMode value has been assigned to itself.


text:
Q: Custom separator in tableView I have my own separator in .jpg and would like to use it instead of default one in TableView, but the only thing I get is that it disappears.
Swift 3.0:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "musicCell", for: indexPath) as! SongTableViewCell

    let color = UIColor(patternImage: UIImage(named:"Separator.jpg")!)
    let separator = tableView.separatorColor(color)

    tableView.tableFooterView = UIView(frame: .zero)
    tableView.backgroundView = UIImageView(image: UIImage(named: "bckgrd.jpg"))
    cell.backgroundColor = UIColor.clear

    //tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
    //tableView.separatorColor = UIColor(patternImage: UIImage(named: "Separator.jpg"))

This is one of the ways I've tried to implement. Is there other way to do that?

A: You need to set separator style also not color only. Set separator style to single line and make sure that your Separator.jpg image looks like single line and you are getting color by let color = UIColor(patternImage: UIImage(named:"Separator.jpg")!) this statement!
you can set seperator style something like,
 tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine

P.S : If you are checking this on simulator then check it in full resolution (i.e. cmd + 1 or in simulator window - > scale - > 100%), becasue sometime actually there is no problem but because of smaller scale you can't see it
Update :
Another way : Set SeparatorStyle to None from interface builder or by code like,
   tableView.separatorStyle = UITableViewCellSeparatorStyle.None

then you can add seperator image(imageview of height 1 pixel or 2 pixel) to cell at bottom in content view of cell by code or interface builder like,
   let seperatorImageView = UIImageView.init(image: UIImage.init(named: "yourseperatorimg.jpg"))
    seperatorImageView.frame = CGRectMake(0, cell.contentView.frame.size.height - 1.0,  cell.contentView.frame.size.width, 1)
    cell.contentView.addSubview(seperatorImageView)

A: Set separator color on viewDidLoad method...
override func viewDidLoad() {

    super.viewDidLoad()
    let color = UIColor(patternImage: UIImage(named:"Separator.jpg")!)
    tableView.separatorColor = color
}

A: override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    let color = UIColor(patternImage: UIImage(named:"Separator.jpg")!)
    tblView.separatorColor = color
}


text:
Q: Excel VBA - How to Redim a 2D array? In Excel via Visual Basic, I am iterating through a CSV file of invoices that is loaded into Excel. The invoices are in a determinable pattern by client.
I am reading them into a dynamic 2D array, then writing them to another worksheet with older invoices. I understand that I have to reverse rows and columns since only the last dimension of an array may be Redimmed, then transpose when I write it to the master worksheet.
Somewhere, I have the syntax wrong. It keeps telling me that I have already Dimensionalized the array. Somehow did I create it as a static array? What do I need to fix in order to let it operate dynamically?
WORKING CODE PER ANSWER GIVEN
Sub InvoicesUpdate()
'
'Application Settings
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual

'Instantiate control variables
Dim allRows As Long, currentOffset As Long, invoiceActive As Boolean, mAllRows As Long
Dim iAllRows As Long, unusedRow As Long, row As Long, mWSExists As Boolean, newmAllRows As Long

'Instantiate invoice variables
Dim accountNum As String, custName As String, vinNum As String, caseNum As String, statusField As String
Dim invDate As String, makeField As String, feeDesc As String, amountField As String, invNum As String

'Instantiate Workbook variables
Dim mWB As Workbook 'master
Dim iWB As Workbook 'import

'Instantiate Worksheet variables
Dim mWS As Worksheet
Dim iWS As Worksheet

'Instantiate Range variables
Dim iData As Range

'Initialize variables
invoiceActive = False
row = 0

'Open import workbook
Workbooks.Open ("path:excel_invoices.csv")
Set iWB = ActiveWorkbook
Set iWS = iWB.Sheets("excel_invoices.csv")
iWS.Activate
Range("A1").Select
iAllRows = iWS.UsedRange.Rows.Count 'Count rows of import data

'Instantiate array, include extra column for client name
Dim invoices()
ReDim invoices(10, 0)

'Loop through rows.
Do

    'Check for the start of a client and store client name
    If ActiveCell.Value = "Account Number" Then

        clientName = ActiveCell.Offset(-1, 6).Value

    End If

    If ActiveCell.Offset(0, 3).Value <> Empty And ActiveCell.Value <> "Account Number" And ActiveCell.Offset(2, 0) = Empty Then

        invoiceActive = True

        'Populate account information.
        accountNum = ActiveCell.Offset(0, 0).Value
        vinNum = ActiveCell.Offset(0, 1).Value
        'leave out customer name for FDCPA reasons
        caseNum = ActiveCell.Offset(0, 3).Value
        statusField = ActiveCell.Offset(0, 4).Value
        invDate = ActiveCell.Offset(0, 5).Value
        makeField = ActiveCell.Offset(0, 6).Value

    End If

    If invoiceActive = True And ActiveCell.Value = Empty And ActiveCell.Offset(0, 6).Value = Empty And ActiveCell.Offset(0, 9).Value = Empty Then

        'Make sure something other than $0 was invoiced
        If ActiveCell.Offset(0, 8).Value <> 0 Then

            'Populate individual item values.
            feeDesc = ActiveCell.Offset(0, 7).Value
            amountField = ActiveCell.Offset(0, 8).Value
            invNum = ActiveCell.Offset(0, 10).Value

            'Transfer data to array
            invoices(0, row) = "=TODAY()"
            invoices(1, row) = accountNum
            invoices(2, row) = clientName
            invoices(3, row) = vinNum
            invoices(4, row) = caseNum
            invoices(5, row) = statusField
            invoices(6, row) = invDate
            invoices(7, row) = makeField
            invoices(8, row) = feeDesc
            invoices(9, row) = amountField
            invoices(10, row) = invNum

            'Increment row counter for array
            row = row + 1

            'Resize array for next entry
            ReDim Preserve invoices(10,row)

         End If

    End If

    'Find the end of an invoice
    If invoiceActive = True And ActiveCell.Offset(0, 9) <> Empty Then

        'Set the flag to outside of an invoice
        invoiceActive = False

    End If

    'Increment active cell to next cell down
    ActiveCell.Offset(1, 0).Activate

'Define end of the loop at the last used row
Loop Until ActiveCell.row = iAllRows

'Close import data file
iWB.Close

A: here is updated code of the redim preseve method with variabel declaration, hope @Control Freak is fine with it:)
Option explicit
'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve As Variant, nNewFirstUBound As Variant, nNewLastUBound As Variant) As Variant
    Dim nFirst As Long
    Dim nLast As Long
    Dim nOldFirstUBound As Long
    Dim nOldLastUBound As Long

    ReDimPreserve = False
    'check if its in array first
    If IsArray(aArrayToPreserve) Then
        'create new array
        ReDim aPreservedArray(nNewFirstUBound, nNewLastUBound)
        'get old lBound/uBound
        nOldFirstUBound = UBound(aArrayToPreserve, 1)
        nOldLastUBound = UBound(aArrayToPreserve, 2)
        'loop through first
        For nFirst = LBound(aArrayToPreserve, 1) To nNewFirstUBound
            For nLast = LBound(aArrayToPreserve, 2) To nNewLastUBound
                'if its in range, then append to new array the same way
                If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
                    aPreservedArray(nFirst, nLast) = aArrayToPreserve(nFirst, nLast)
                End If
            Next
        Next
        'return the array redimmed
        If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
    End If
End Function

A: I know this is a bit old but I think there might be a much simpler solution that requires no additional coding:
Instead of transposing, redimming and transposing again, and if we talk about a two dimensional array, why not just store the values transposed to begin with. In that case redim preserve actually increases the right (second) dimension from the start. Or in other words, to visualise it, why not store in two rows instead of two columns if only the nr of columns can be increased with redim preserve.
the indexes would than be 00-01, 01-11, 02-12, 03-13, 04-14, 05-15 ... 0 25-1 25 etcetera instead of 00-01, 10-11, 20-21, 30-31, 40-41 etcetera.
As only the second (or last) dimension can be preserved while redimming, one could maybe argue that this is how arrays are supposed to be used to begin with.
I have not seen this solution anywhere so maybe I'm overlooking something?

A: This isn't exactly intuitive, but you cannot Redim(VB6 Ref) an array if you dimmed it with dimensions. Exact quote from linked page is:

The ReDim statement is used to size or resize a dynamic array that has
  already been formally declared using a Private, Public, or Dim
  statement with empty parentheses (without dimension subscripts).

In other words, instead of dim invoices(10,0)
You should use
Dim invoices()
Redim invoices(10,0)

Then when you ReDim, you'll need to use Redim Preserve (10,row)
Warning: When Redimensioning multi-dimensional arrays, if you want to preserve your values, you can only increase the last dimension. I.E. Redim Preserve (11,row) or even (11,0) would fail.

A: Here ya go.
Public Function ReDimPreserve(ByRef Arr, ByVal idx1 As Integer, ByVal idx2 As Integer)

    Dim newArr()
    Dim x As Integer
    Dim y As Integer

    ReDim newArr(idx1, idx2)

    For x = 0 To UBound(Arr, 1)
        For y = 0 To UBound(Arr, 2)
            newArr(x, y) = Arr(x, y)
        Next
    Next

    Arr = newArr

End Function

A: Here is how I do this.
Dim TAV() As Variant
Dim ArrayToPreserve() as Variant

TAV = ArrayToPreserve
ReDim ArrayToPreserve(nDim1, nDim2)
For i = 0 To UBound(TAV, 1)
    For j = 0 To UBound(TAV, 2)
        ArrayToPreserve(i, j) = TAV(i, j)
    Next j
Next i

A: I stumbled across this question while hitting this road block myself. I ended up writing a piece of code real quick to handle this ReDim Preserve on a new sized array (first or last dimension). Maybe it will help others who face the same issue.
So for the usage, lets say you have your array originally set as  MyArray(3,5), and you want to make the dimensions (first too!) larger, lets just say to MyArray(10,20). You would be used to doing something like this right?
 ReDim Preserve MyArray(10,20) '<-- Returns Error

But unfortunately that returns an error because you tried to change the size of the first dimension.  So with my function, you would just do something like this instead:
 MyArray = ReDimPreserve(MyArray,10,20)

Now the array is larger, and the data is preserved. Your ReDim Preserve for a Multi-Dimension array is complete. :)
And last but not least, the miraculous function: ReDimPreserve()
'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve,nNewFirstUBound,nNewLastUBound)
    ReDimPreserve = False
    'check if its in array first
    If IsArray(aArrayToPreserve) Then
        'create new array
        ReDim aPreservedArray(nNewFirstUBound,nNewLastUBound)
        'get old lBound/uBound
        nOldFirstUBound = uBound(aArrayToPreserve,1)
        nOldLastUBound = uBound(aArrayToPreserve,2)
        'loop through first
        For nFirst = lBound(aArrayToPreserve,1) to nNewFirstUBound
            For nLast = lBound(aArrayToPreserve,2) to nNewLastUBound
                'if its in range, then append to new array the same way
                If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
                    aPreservedArray(nFirst,nLast) = aArrayToPreserve(nFirst,nLast)
                End If
            Next
        Next
        'return the array redimmed
        If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
    End If
End Function

I wrote this in like 20 minutes, so there's no guarantees. But if you would like to use or extend it, feel free.  I would've thought that someone would've had some code like this up here already, well apparently not. So here ya go fellow gearheads.

A: A small update to what @control freak and @skatun wrote previously (sorry I don't have enough reputation to just make a comment). I used skatun's code and it worked well for me except that it was creating a larger array than what I needed. Therefore, I changed:
ReDim aPreservedArray(nNewFirstUBound, nNewLastUBound)

to:
ReDim aPreservedArray(LBound(aArrayToPreserve, 1) To nNewFirstUBound, LBound(aArrayToPreserve, 2) To nNewLastUBound)

This will maintain whatever the original array's lower bounds were (either 0, 1, or whatever; the original code assumes 0) for both dimensions.

A: i solved this in a shorter fashion.
Dim marray() as variant, array2() as variant, YY ,ZZ as integer
YY=1
ZZ=1

Redim marray(1 to 1000, 1 to 10)
Do while ZZ<100 ' this is populating the first array
marray(ZZ,YY)= "something"
ZZ=ZZ+1
YY=YY+1
Loop
'this part is where you store your array in another then resize and restore to original
array2= marray
Redim marray(1 to ZZ-1, 1 to YY)
marray = array2

A: You could do this array(0)= array(0,1,2,3).
Sub add_new(data_array() As Variant, new_data() As Variant)
    Dim ar2() As Variant, fl As Integer
    If Not (isEmpty(data_array)) = True Then
        fl = 0
    Else
        fl = UBound(data_array) + 1
    End If
    ReDim Preserve data_array(fl)
    data_array(fl) = new_data
End Sub

Sub demo()
    Dim dt() As Variant, nw(0, 1) As Variant
    nw(0, 0) = "Hi"
    nw(0, 1) = "Bye"
    Call add_new(dt, nw)
    nw(0, 0) = "Good"
    nw(0, 1) = "Bad"
    Call add_new(dt, nw)
End Sub


text:
Q: How to tell when code is running in console and Source This isn't a question about code-my apologies, I'm just not sure where to ask it...
When I run code that takes time in markdown, the console section has a STOP button which I use to tell me if my code is still running (if the stop button is visible-it is still running).
The folder list where I keep my script is very long, so I keep having to drag over the Console button to make it bigger so that I can see if the code is still running. I have two questions:

*

*Is there a better way of seeing if my code is still running rather than looking to see if the stop button is visible?

*Is there a way of hiding the various folders that my document is in so that I can easily see the stop button without having to make that Console section bigger?

There used to be a red bar in the source pane that progressed vertically down the chunk I was running, but it is gone!


text:
Q: How to reset Keytab for FreeIPA Server and Client I followed the standard documentation to install FreeIPA server and client on hosts 'SRV' and 'CLT' respectively.
I then added a user 'X' to FreeIPA using Web UI.
Now when i try to SSH as X to CLT, i get a 'Permission denied, please try again.' error.
I check '/var/log/messages' on the client, and saw this - '[sssd[krb5_child[3277]]]: Decrypt integrity check failed'.
I reset the password multiple times, but that didn't solve the problem.
Then I came across these -

*

*http://www.cmf.nrl.navy.mil/krb/kerberos-faq.html#badpass

*https://groups.google.com/forum/#!topic/comp.protocols.kerberos/g-s76WeWyUU
Sounds like removing the '/etc/krb5.keytab' file from SRV and CLT and then recreating them will solve the problem.

*

*How should I go about doing this keytab reset?

*Should I first un-provision/remove CLT from FreeIPA inventory?

A: Which SSH authentication method are you using? Are you typing in your password, or trying to use Kerberos ticket-based authentication (gssapi-with-mic or gssapi-keyex)?
The "decrypt integrity check failed" message could come from two sources. If you give it the wrong password (your password doesn't match the keys for your principal in the KDC), you'd get that. You'd also get it if your password is fine, but the keytab on the server is out of date; this would happen with both ticket and password authentication (because with a password, the server obtains a ticket for its own host principal after doing kinit, to authenticate the KDC).

Sounds like removing the '/etc/krb5.keytab' file from SRV and CLT and
  then recreating them will solve the problem.

The keytab on the client is irrelevant; it's not part of this scenario. The likely problem here is that the keytab on the server is out of sync with the KDC (the Kerberos authentication server, or "Key Distribution Center," which is part of FreeIPA). With Kerberos, all identities (or "principals") in the system have keys they share with the KDC. A user's keys are generated from his password. The keys for a software service like sshd are randomly generated, and stored in a file called a keytab (for "key table") so the service can access them. This sounds like the keys for the SSH principal have been changed in the KDC, but the keytab hasn't been updated to match. Your principal name is of the form user@REALM. The principal name for the SSH service is of the form host/hostname@REALM. Try:
$ ipa-getkeytab -s <FreeIPA server> -p host/<hostname>@REALM -k <keytab file>.

... to extract the current keys for the SSH service principal into a new keytab. You can use klist -ek <keytab> to view the contents of the old and new keytabs. If you have a key mismatch, it should show up as the keys for the same principal having different key version numbers (or "kvno"). You might see something like:
# look at the system keytab
$ sudo klist -ek
KVNO Principal
---- --------------------------------------------------------------------------
   1 host/foo.example.com@EXAMPLE.COM (AES-256 CTS mode with 96-bit SHA-1 HMAC)

# look at the new keytab
$ klist -ek <new keytab>
KVNO Principal
---- --------------------------------------------------------------------------
   2 host/foo.example.com@EXAMPLE.COM (AES-256 CTS mode with 96-bit SHA-1 HMAC)

A: I also resolved this problem.
because  ccache contained a old key for the IPA server from the previous installation
just need delete /var/lib/sss/db/ccache_* file
more detail in ticket:
https://fedorahosted.org/sssd/ticket/2781

A: Occasionally IPA clients arent able to retrieve update host keytabs before expiry for reasons such as DNS or network connectivity. Because of this a manual update of the keytab may be necessary to get the server back into sync with IPA.
On the client, login with kinit to get a kerberos ticket-granting-ticket for a user on the KDC with privileged access to get a new host keytab (admin will work)
kinit admin

Update the keytab for the host from the KDC where

*

*ipahostname.mydomain.com is the fully qualified domain name of the IPA server

*host/ipahostname.mydomain.com@mydomain.com is the service principal for the host ipahostname.mydomain.com in the mydomain.com realm

*/etc/krb5.keytab is the location of the system keytab being used. This path is the default for many installations.

ipa-getkeytab -s ipahostname.mydomain.com -p host/ipahostname.mydomain.com@mydomain.com -k /etc/krb5.keytab

Once completed successfully - restart SSSd for it to start using the new keytab
systemctl restart sssd

A: On client I deleted /etc/krb5.keytab
On server I deleted host ipa host-del host.example.com
I uninstall ipa client software.
I reinstall ipa client
BUT, the client doesnt work.
At Last, I had to restart ipa-server ipactl restart and ...
The client work fine. I suppose that the kdc server o similar had something in cache about client keys.
Regards.


text:
Q: Django admin: Get logged In users id in django I am new to django and learnign it. I am using django's Auth and i need to get the id of the logged in user at some place. I have tried :
HttpRequest.user.id referring to the Django docs but this throws exception :
Exception Type: AttributeError
Exception Value: type object 'HttpRequest' has no attribute 'user'

My code :
from django.http import HttpRequest
#...some other code here..#

class Post(models.Model):
     title = models.CharField(max_length=200)
     body = models.TextField('post body')
     author = models.ForeignKey(User)

     def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
          self.author = HttpRequest.user.id
          super(Post, self).save(force_insert, force_update, using, update_fields)

--UPDATE ---
I have also tried :
from django.http import request

and then in save method :
self.author = request.user.id

but it gives me exception -
Exception Type: AttributeError
Exception Value: 'module' object has no attribute 'user'

A: You shouldn't override the model's save() method, but override the admin save_model() method instead:
class Post(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.user = request.user
        super(Post, self).save_model(request, obj, form, change)

A: HttpRequest is a class, which doesn't have an user attribute. You need to obtain the request object, most likely from a view function. Then you can pass the user object, or its id to your model save() method:
def view_function(request):
     user = request.user
     # Get the object you want to save the user field to
     post = Post.objects.get(...)
     post.user = user
     # Or post.user_id = user.id
     post.save()
     ... ...


text:
Q: How to test composite Rails model scopes? Consider the following model:
class Model < ActiveRecord::Base
  scope :a,       -> () { where(a: 1) }
  scope :b,       -> () { where(b: 1) }
  scope :a_or_b,  -> () { a.or(b) }
end

now to properly test each scope, I would at least provide an exaple that
matches and one that doesn''t for each possible variable. Something like this:
RSpec.describe Model do
  describe "scopes" do
    describe ".a" do
      subject { Model.a }
      let!(:with_a_0) { create(:model, a: 0) }
      let!(:with_a_1) { create(:model, a: 1) }

      it { should_not include(with_a_0) }
      it { should     include(with_a_1) }
    end

    describe ".b" do
      subject { Model.b }
      let!(:with_b_0) { create(:model, b: 0) }
      let!(:with_b_1) { create(:model, b: 1) }

      it { should_not include(with_b_0) }
      it { should     include(with_b_1) }
    end

    describe ".a_or_b" do
      subject { Model.a_or_b }
      let!(:with_a_0_and_b_0) { create(:model, a: 0, b: 0) }
      let!(:with_a_0_and_b_1) { create(:model, a: 0, b: 1) }
      let!(:with_a_1_and_b_0) { create(:model, a: 1, b: 0) }
      let!(:with_a_1_and_b_1) { create(:model, a: 1, b: 1) }

      it { should_not include(with_a_0_and_b_0) }
      it { should     include(with_a_0_and_b_1) }
      it { should     include(with_a_1_and_b_0) }
      it { should     include(with_a_1_and_b_1) }
    end
  end
end

But then it feels like I'm retesting .a and .b on the .a_or_b test, and
if I compose it again, with yet another scope, it'll get bigger and bigger.
What is the sane way of dealing with this?
Also: is this a unit or integration test?

A: That's a tough one. I'd say you have to find an Aristotelian mean between full coverage, and your specs readability. It's probably not reasonable to test every combination of possible states that influence how your scopes are behaving.
Also it's not really a unit test, because it's coupled with the DB layer.
My approach is this:
Don't test simple scopes (like a and b in your example), trust that AR is well tested, make yous scope names clear and leave it.
In more complex scopes, you can invert the way you compose tests:
Create specimens once, then define expectations for different scopes (and make the specimens names very clear, like you're doing already).
This will reduce the size of the spec a bit, and it's easier to read such specs. But it still will grow the spec size if you want to have full coverage for every scope.
RSpec.describe Model do
  describe "scopes" do
    let!(:with_a_0_and_b_0) { create(:model, a: 0, b: 0) }
    let!(:with_a_0_and_b_1) { create(:model, a: 0, b: 1) }
    let!(:with_a_1_and_b_0) { create(:model, a: 1, b: 0) }
    let!(:with_a_1_and_b_1) { create(:model, a: 1, b: 1) }

    it { expect(described_class.a).to include(with_a_1_and_b_1).and include(with_a_1_and_b_1) }
    it { expect(described_class.a).not_to include(with_a_0_and_b_0) }

    # you get the idea

To make this^ even more readable, I'd suggest creating a custom matcher, you could use like this:
  it do
    expect(described_class.a)
      .to retrieve(with_a_1_and_b_0, with_a_1_and_b_1)
      .and not_retrieve(with_a_0_and_b_0, with_a_0_and_b_1)
  end


text:
Q: Перебрать массив QJsonArray Никак не могу понять, каким образом можно вытащить значения из этого  массива? Пробовал по разному, ничего не выходит.
Массив вида [11111111111111,22222222222222,33333333333333]
QJsonArray data = jb.value("test").toArray();

qDebug() << data; // в массиве 3 элемента
//вывод: QJsonValue(array, QJsonArray([11111111111111,22222222222222,33333333333333]))

//пробую так, вывод пустой.
for(const QJsonValue& v: data)
{
    qDebug() << v.toString();
}

//""
//""
//""

A: QString jsonRaw = "[1111, 2222, 3333]";

QVariantList jsonList = QJsonDocument::fromJson(jsonRaw.toUtf8()).toVariant().toList();

for(auto &it : jsonList)
{
    qDebug() << it;
}

Вывод:
QVariant(double, 1111)
QVariant(double, 2222)
QVariant(double, 3333)

A: Полностью "до кучи" перебор элементов и подэлементов. Надеюсь доступно.
json
[
 {"Id": 0,
  "Text": "element1",
  "SubItems": ["subelement1.1","subelement1.2"]
 },
 {"Id": 1,
  "Text": "element2",
  "SubItems": ["subelement2.1","subelement2.2"]
 }
]

код:
QByteArray myjson="[{\"Id\": 0, \"Text\": \"element1\", \"SubItems\": [\"subelement1.1\",\"subelement1.2\"] },    {\"Id\": 1,     \"Text\": \"element2\",     \"SubItems\": [\"subelement2.1\",\"subelement2.2\"] }   ]";
QJsonParseError err;
QJsonDocument document = QJsonDocument::fromJson(myjson,&err);
if(err.error!=QJsonParseError::NoError){
    qDebug()<<"error: "<<err.errorString();
    return 0;
}
QJsonArray array = document.array();
foreach(QJsonValue val,array){
    QJsonObject obj = val.toObject();
    qDebug()<< obj.value("Id").toInt()<<": "<<obj.value("Text").toString();
    QJsonArray array = obj.value("SubItems").toArray();
    foreach(QJsonValue arrval,array){
        qDebug()<<"   "<<arrval.toString();
    }
}


text:
Q: CLLocationManager time format? I have an app that saves a user's location to a backend database, and then later reads these in for use elsewhere.
I am getting and saving the location timestamp to my server using the following code:
CLLocation *currentLocation = [locations lastObject];
currentLocation.timestamp // this is the timestamp I save to the database.

Later on, I read this back in, but I am having trouble formatting this back to a useable date object.
My code is:
    NSLog(@"time from server = %@", item.timestamp);
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *savedTime = [[NSDate alloc] init];
    savedTime = [dateFormatter dateFromString:item.timestamp];
    NSLog(@"time formatted = %@", savedTime);

When I run this, I get the following output:
time from server = 2015-07-05 13:32:36  0000
time formatted = (null)

Can anyone help get this "time formatted" output working?
Is it because the setDateFormat is not correct? I am not sure what the '0000' at the end of the 'time from server' is?

A: Try using this as your format:
@"yyyy-MM-dd HH:mm:ss zzz"

This now works fine for me:

This is swift in the picture, but the important part is the date format string.  That is language independent and I just wanted to show you that it was working.  Replacing the format string in ObjC will work just fine.


text:
Q: retina image on a 3gs or 3g phone I have a kind of problem where there are two set of photos in my photo viewer. One is a retina image and another is a image with less resolution. the size of the placeholder is around 300X200. The no retina based image is exactly the same size 300X200 and retina images is almost double the size. My question is what problem will we face when a high resolution image is placed in a non retina image, i know the image will get displayed for sure, but i want to know what could be other hidden issues.
can someone surely say that a high resolution image in the placeholder is not going to create any image that will be fine. i know my question looks real silly, but want to clear that up.

A: Well there is only one problem, memory.
Since the 3G and 3GS have less ram then 4/4S you will run out of memory faster.

A: One more problem may arise,
It is the frame size of your UIImageView. If you are creating the frame dynamically (based on image size), it will create bigger frame (which is not accepted). However if you are creating the frame with hard code values, its fine.


text:
Q: Ebean @Transactional annotation not working on Heroku I have a Play Framework 2.1.1 app running on Heroku.
I've written a bunch of new code in my local dev environment, and it works fine, but when I deploy it to Heroku the app crashes and I get this in the logs:
Configuration error: Configuration error[Cannot register class [models.Article] in Ebean server]
Oops, cannot start the server.
...
Caused by: java.lang.NoClassDefFoundError: com/avaje/ebean/bean/EnhancedTransactional
...
Caused by: java.lang.ClassNotFoundException: com.avaje.ebean.bean.EnhancedTransactional
...
Process exited with status 255
State changed from starting to crashed

When I remove the @Transactional annotations from my models, I no longer get the errors.
Here is an example of how I'm using @Transactional in one of my models:

    @Transactional
    public static Product find(Long id) {
        return find.byId(String.valueOf(id));
    }

Has anyone experienced this or have any idea why it works fine locally, but not in Heroku?
Per request, here is my build.scala
import sbt._
import Keys._
import play.Project._

object ApplicationBuild extends Build {

  val appName         = "myapp"
  val appVersion      = "1.0-SNAPSHOT"

  val appDependencies = Seq(
    // Add your project dependencies here,
    "postgresql" % "postgresql" % "8.4-702.jdbc4",
    "com.typesafe" %% "play-plugins-mailer" % "2.1.0",
    "com.stripe" % "stripe-java" % "1.15.1",
    "com.amazonaws" % "aws-java-sdk" % "1.3.11",
    javaCore,
    javaJdbc,
    javaEbean
  )

  val main = play.Project(appName, appVersion, appDependencies).settings(
    // Add your own project settings here
  )

}


text:
Q: Why is image rotated in SVG? I have this SVG output:
http://www.angliru.nl/kaftschoon/143/
The original photo is: http://www.angliru.nl/upload/IMG_IX3346.JPG
The original photo is standing. The photo is still standing after uploading. But when placed in a SVG the photo is rotated sideways.
Why? And how to prevent it? I'm scratching my head on that one.
   <svg version="1.1" id="Laag_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    width="447" height="833"
viewBox="265 90 311.9 495.3" enable-background="new 0 0 841.9 595.3" xml:space="preserve">
<g>
    <defs>
        <pattern id="img1" patternUnits="userSpaceOnUse" width="842" height="595">
            <image xlink:href="http://www.angliru.nl/upload/IMG_IX3346.JPG" x="0" y="0"
                width="842" height="595" style="max-width:842px; max-height: 595px; min-width: 842px; min-height: 595px;" />
        </pattern>
    </defs>
    <path d="M549.9,476.2c-3.3,0-6.1,0-8.9,0c-15.2,0-30.3-0.1-45.5,0.1c-2.3,0-5,1.3-6.8,2.9c-3.6,3-6.7,6.5-10,9.8
        c-3.2,3.1-6.4,3.3-9.5,0c-0.1-0.1-0.3-0.2-0.3-0.4c-7.5-11.2-18.1-13.6-31-12.6c-13.6,1-27.3,0.1-41,0.3c-2,0-4.4,1.1-6,2.5
        c-3.5,3-6.6,6.6-10,9.8c-3.9,3.7-7.1,4.1-10.1-0.1c-7.9-10.9-18.3-13.5-31.1-12.5c-12.8,1-25.6,0.2-38.5,0.1
        c-0.3,0-0.6-0.2-1.5-0.6c0-11.7,0-23.6,0-35.6c0-7.7,0.3-15.3-0.1-23c-0.1-2.3-1.4-5-3-6.8c-3.7-4.3-8-8-11.9-12.1
        c-3.7-3.9-3.6-6.3,0.1-10.2c0.2-0.2,0.4-0.5,0.7-0.7c12.3-8.5,16.2-20,14.5-34.8c-1.3-11,0-22.3-0.3-33.4c-0.1-2.4-1.3-5.1-2.9-7
        c-3.9-4.9-8.4-9.4-12.6-14.2c-2.5-2.9-2.3-5.6,0.5-8.3c4.1-3.9,8.3-7.7,12-12c1.6-1.8,2.8-4.6,2.8-7c0.2-16.7,0.2-33.3,0-50
        c0-2.2-1.2-4.8-2.6-6.5c-3.7-4.5-7.9-8.6-11.9-12.8c-3.5-3.8-3.4-6,0.2-9.8c2.4-2.5,4.5-5.5,7.2-7.6c6.8-4.9,7.6-11.5,7.4-19.3
        c-0.4-15.8-0.1-31.6-0.1-47.7c7.3,0,14.4,0,21.5,0c10.8,0,21.6,0.2,32.5,0.1c1.1,0,2.5-0.7,3.3-1.6c4.4-4.5,8.6-9.3,13-13.8
        c4.2-4.3,6.9-4.2,11-0.1c5.1,4.9,9.5,11.8,15.7,14.3c6.2,2.5,14.1,0.6,21.3,0.7c10.5,0,21,0.3,31.5,0c2.5-0.1,5.4-1.4,7.3-3
        c4-3.5,7.5-7.6,11.2-11.4c4.6-4.6,7.2-4.7,11.8-0.2c2.3,2.2,4.9,4.2,6.7,6.7c5,7.1,11.9,8.4,19.9,8.3c12.7-0.3,25.3,0,38,0
        c1.5,0,2.9,0,5.2,0c0,10.7,0,21,0,31.3c0,8.7-0.3,17.3-0.1,26c0,1.8,1.2,3.9,2.5,5.3c4,4.2,8.3,8.1,12.5,12.3c3.2,3.2,3,6.4,0,9.7
        c-1.5,1.6-2.8,3.3-4.6,4.6c-8.7,6.2-11.1,14.5-10.5,25c0.8,13.5,0.2,27,0.5,40.5c0,1.9,1,4.2,2.3,5.6c3.8,4.2,7.9,8.1,11.9,12.1
        c4,4,3.9,7,0,11.1c-2,2-3.7,4.4-6,6c-7.4,5.1-8.8,12.2-8.5,20.7c0.6,14.3-0.1,28.7,0.1,43c0,2.2,1.3,4.7,2.8,6.4
        c3.8,4.4,8.1,8.3,12.1,12.6c2.7,2.9,2.6,6-0.2,8.9c-3.7,3.8-7.4,7.6-11.3,11.3c-2.5,2.3-3.4,4.9-3.3,8.3
        C550,436.7,549.9,456.1,549.9,476.2z"
        fill="url(#img1)" />
</g>
</svg>

A: Your issue comes down to the EXIF data stored against the original image.
EXIF - Exchangable image file format - is a set of metadata relating to the image itself, stored alongside it in the same file. The data can be quite comprehensive, covering for example:

*

*GPS coordinates of the location

*Camera hardware

*Camera settings (ISO, etc)

*Orientation

It's this last one that you're tripping over, and it's quite likely in this case that the phone was being held sideways when this photograph was taken. Your web browser is respecting the Orientation setting, and is rotating it accordingly; the SVG processor on the other hand is ignoring it.
That's the "why" part handled.
The "how to prevent" is more complicated, and without knowing more about how the image ended up in your system it's impossible to answer precisely.
Obviously you've discovered that loading it into Photoshop and re-saving has fixed the issue (Photoshop has stripped out the orientation tag), but for a longer-term solution you will need to process your uploaded images; a tool such as Exiftool should suffice for this.


text:
Q: Contents from all tabs is initially displayed I have the below code to display tabs. The tabs work when I click on them but not on page load (it shows the content of all tabs). I also need to be able to open all 1st/2nd or 3rd tabs on the page with a click of a button (multiple tab groups on the page)
$("ul.tabs").each(function() {
    $(this).find('li:first').addClass("active");
    $(this).next('.tab_container').find('.tab_content:first').show();
});

$("ul.tabs li a").click(function() {
    $(".tab_content").hide();
    var cTab = $(this).closest('li');
    cTab.siblings('li').removeClass("active");
    cTab.addClass("active");
    cTab.closest('ul.tabs').nextAll('.tab_container:first').find('.tab_content').hide();

    var activeTab = $(this).attr("href"); //Find the href attribute value to identify the active tab + content
    $(activeTab).fadeIn(); //Fade in the active ID content
    return false;
});

jsfiddle.
I'm also open to other tab solutions.

A: http://jsfiddle.net/agBgL/1/
You just need to hide tab content initially.

A: removing:
.ui-tabs .ui-tabs-panel { display: block; }

Reference


text:
Q: How do I put a variable in an src attribute? Ok so I have this problem .  I want to put the myPath variable into my src attribute of my image.
var myPath = img/image.png;
//it's actually set by another function

document.getElementById("myDiv").innerHTML = "";

But it doesn't seem to work. How do I do it ?
(I'm really new with js)

A: With javascript:

*

*you can add and remove elements to and from documents; and

*you can add and remove attributes to and from elements
So if in your markup you have something like:

You can add an img element as a child of the div element, like so:
var myDiv = document.getElementById('my-div'); // grabs #my-div
var myPath = 'img/image.png'; // initialises string variable myPath
var myImg = document.createElement('img'); // creates a new img element

myImg.setAttribute('src', myPath); // adds a src attribute (with the value myPath) to myImg
myDiv.appendChild(myImg); // adds a child element (myImg) to myDiv

A: myPath already contains a string, in your code you are not using the variable myPath rather myPath is just a part of string literal, you need to use string concatenation, you can do something like this:
var myPath = "img/image.png";
//it's actually set by another function

document.getElementById("myDiv").innerHTML = "";

A: Just concat it as an string
var myPath = "img/image.png";
//it's actually set by another function

document.getElementById("myDiv").innerHTML = "";


text:
Q: Wordpress "HTML editor" which doesn't trash hand-coded HTML? I've been putting up with this for years, but it's just getting to be too much trouble. I'm on 6.0.1. If I select a page, and select the Code Editor, and make a trivial change, it can  modify the HTML, and make the page useless. And it's not recoverable unless you can remember exactly what you wrote before, or you go back to a backup database.
On the current page I'm editing, a trivial text change deletes all the hand-coded span tags on the page, and changes all occurences of
text
 to
text
; this has lost all the links and changed the colours.
I'm on Gutenberg at the moment. I've tried to fix this historically (pre-WP6) by installing the Classic editor, but it made no difference.
Any ideas? Thanks.


text:
Q: Dynamic Tab names in Tabholder in Django-crispy-forms I wondering is there any chance to use "dynamic" names for Tabs.
Like in next example Tab names are hardcoded 'First Tab' and 'Second Tab' in ModelForm. I have dynamic titles (head1, 2 etc.) for every tabs and I am using values from database for titles. I like to use same text dynamically in tab names.
    Tab('First Tab',
        HTML("""
{{ head1.0 }}
"""),
        'field_name_1',
        Div('field_name_2')
    ),
    Tab('Second Tab',
        HTML("""
{{ head2.0 }}
"""),
        Field('field_name_3', css_class="extra")
    )

I would like to add same dynamic title texts to tab names also like in next example, but I have not found solutions.
    Tab({{ head1.0 }},
        HTML("""
{{ head1.0 }}
"""),
        'field_name_1',
        Div('field_name_2')
    ),
    Tab({{ head2.0 }},
        HTML("""
{{ head2.0 }}
"""),
        Field('field_name_3', css_class="extra")
    )

A: Can you assign the value from the database to a variable and pass it in to the form?
title = value_from_database
    Tab(title,
        HTML("""
{{ head1.0 }}
"""),
        'field_name_1',
        Div('field_name_2')
    ),


text:
Q: Dartium in Ubuntu I'm working on a Dart/Polymer app using Chrome Dev Editor on Ubuntu 14.04.
I'd like to run in Dart (not JavaScript and dart.js) using Dartium, but I'm not sure how to actually open and use Dartium. I downloaded the zip from dartlang.org. I just need to open the browser...
Is this something I can do without having to download the Dart Editor package and run Dartium from within that?

A: If you have problems running Dartium, I found an answer here that helped me with this - just make sure that that the file locations are correct on your system.
The answer was to link the missing file together with an existing file:
sudo ln -s /lib/x86_64-linux-gnu/libudev.so.1 /lib/x86_64-linux-gnu/libudev.so.0
Make sure you take a look at the original post, but this solved it for me.
After this I ran Dartium with ./chrome on ubuntu 14.04

A: You can start it from the command line.
Unzip the package.
cd chromium
./chrome


text:
Q: SQL Statement is too complex for Microsoft Access, after I changed the Source to a DB I wrote an sql query with a subselect in Microsoft Access and tried it with local tables and it worked perfectly. But then i changed the source to a table that is linked to an SQL Server DB and all of a sudden it tells me that the statement is too complex. It only has a group by, subselect and SUM. I dont understand why the source of the table makes a difference in the complexity. I dont know what to do.
PARAMETERS [von Datum] DateTime, [bis Datum] DateTime;

SELECT Sum(auftraege.Netto) AS NettoAuftraege, (SELECT Sum(angebote.Netto)
                                                FROM angebote
                                                WHERE angebote.Verkaeufer IS NOT NULL and
                                                ((angebote.Date) Between [von Datum] And [bis Datum])) AS NettoAngebote,
                                                round((NettoAuftraege/NettoAngebote),2) AS Prozent
FROM auftraege
WHERE ((auftraege.Date) Between [von Datum] And [bis Datum]) and auftraege.Verkaeufer IS NOT NULL;

A: (would be a mess as a comment. Disclaimer: I am not a fan of access, syntax might be wrong for access, like missing parentheses)
PARAMETERS [von Datum] DateTime, [bis Datum] DateTime;

select NZ(x.seller, y.seller) as seller,
   x.NettoAufTrage, y.NettoAngebote, round((x.NettoAuftraege/y.NettoAngebote),2) AS Prozent
from
(
SELECT seller, Sum(Netto) AS NettoAuftraege
FROM auftraege
WHERE ((auftraege.Date) Between [von Datum] And [bis Datum]) and auftraege.Verkaeufer IS NOT NULL
group by seller
) x
full join
(
   SELECT seller, Sum(angebote.Netto) as NettoAngebote
   FROM angebote
   WHERE angebote.Verkaeufer IS NOT NULL and
   ((angebote.Date) Between [von Datum] And [bis Datum]))
   group by seller
) x on x.Seller = y.Seller;


text:
Q: how to request and post an object to a foreignkey field When I do this exactly as provided below, a shipping address object is created without the customer assigned in the shipping address foreignkey field, I can add it from the admin panel manually but I'm not able to make it work through code, idk what I'm doing wrong, please help!
**models.py**

class Customer(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField(max_length=150)

class ShippingAddress(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
    address_one = models.CharField(max_length=200)
    address_two = models.CharField(max_length=200)
    ...

**views.py**

def checkout(request):

    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderitem_set.all()
    else:
        items = []
        order = {'get_cart_total': 0, 'get_cart_items': 0}

    if request.method == 'POST':
        form = ShippingForm(request.POST)

        if form.is_valid():

            #how do I get the customer to get added in the foreignkey field for the shipping address model

            form.save()
            return redirect('store:checkout_shipping')
        else:
            form = ShippingForm()

    else:
        form = ShippingForm()

    context = {"items": items, "order": order, "form": form}
    return render(request, 'store/checkout.html', context)

A: In response to your comment #how do I get the customer to get added... etc, in the case that your ShippingForm() points to your ShippingAddress model, or at least something with a customer foreign key field, you may need to do something like this:
def checkout(request):

    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderitem_set.all()
    else:
        items = []
        order = {'get_cart_total': 0, 'get_cart_items': 0}

    if request.method == 'POST':
        form = ShippingForm(request.POST)

        if form.is_valid():
            new_shipment = form.save(commit=False)
            new_shipment.customer = customer
            new_shipment.save()
            return redirect('store:checkout_shipping')
        else:
            form = ShippingForm()

    else:
        form = ShippingForm()

    context = {"items": items, "order": order, "form": form}
    return render(request, 'store/checkout.html', context)

Using commit=False on the form.save() will allow you to subsequently modify other fields, in this case, by adding the customer relation, then saving it.  More information here in the Django documentation.  Salient quote:

This save() method accepts an optional commit keyword argument, which
accepts either True or False. If you call save() with commit=False,
then it will return an object that hasn't yet been saved to the
database. In this case, it's up to you to call save() on the resulting
model instance. This is useful if you want to do custom processing on
the object before saving it, or if you want to use one of the
specialized model saving options. commit is True by default.

"Custom processing" in this case is the creation of the foreign key relationship to the model instance (customer).


text:
Q: Inner Join On Keys Listed In a List in JSON I have a json like:
{"key": [1,2], "group": 1}
{"key": [1,3], "group": 2}

I'm loading my json into hive and I want to do an inner join with these keys on another table in the DB.
The results should be something like
Group  Value
  1    "this is some value corresponding to 1 in another table"
  1    "this is some value corresponding to 2"
  2    "this is some value corresponding to 1"
  2    "this is some value corresponding to 3"

Is this a basic built in functionality, or do I need to be creative?

A: select      kg.group,k.value
from                      my_json_table                                               jt
            lateral view  json_tuple(jt.my_json_column,'key','group')                 kg as key,group
            lateral view  explode (split(regexp_extract(kg.key,'\\[(.*)\\]',1),','))  k  as value
;

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF


text:
Q: chrome extension get cookies doesnt return all cookies I am creating an extension which gets cookie from my domain and process it. But the problem here is that chrome.cookies.getAll(domain:"mydomain") doesnt return the all the cookies. for example i am getting cookies of firebase.google.com but its retuning only one cookie but when i go to firebase.google.com i could many cookie items
Manifest permission i used
"permissions": [
        "tabs",
        "activeTab",
        "cookies",
        "https://*/*",
        "contextMenus",
        "storage",
        "webNavigation"
    ],

backgroundjs:
chrome.cookies.getAll({domain:""firebase.google.com"},function(cookie){
        console.log(cookie);
});

What i could see in console contains only one cookie value. But when i go to url firebase.google.com i could see more number of cookies in developer tools.

How could i get all the cookie values in getAll function?


text:
Q: How to configure and control mangling of module names in webpack Background:
A is an Angular shell with top and left nav. We have multiple apps B, C, D, etc built with different technologies which we want to load into the shell.
For example, B is Angular app whose feature modules will be lazy loaded into the shell, C is an old Dojo app whose features will be loaded into an iframe in the shell and D is a react app whose feature modules will be wrapped in an Angular component and loaded into the shell.
These apps are developed by different teams, hosted at different domains and they have their own release cycles. The shell A is being built in such a way that when an app wants to release an update, the shell doesn't have to be deployed again.
Lazy Load Workflow:
I am trying to lazy load a feature module built by Angular app B and hosted at a remote URL into the Angular shell A. Below is the workflow I am trying to achieve:

*

*User clicks on link B in the shell.

*An API call is made to get the list of features under B (B1, B2, B3, etc) and routes are pushed dynamically to the angular router for each feature.

*User navigates to the feature B1 route in the shell.

*The dependencies of B1 and B1's chunk file are fetched from a remote location and lazy loaded into the shell.

Problem:
Both shell A and app B have identical webpack configurations.
Shell A has unmangled module names as seen in image below.

Whereas app B has mangled module names as seen below with some modules removed by tree shaking I guess.

I will be able to lazy load feature module from app B into shell A if I can generate unmangled output in both projects, which is more reliable. Is there option in webpack that I can set to achieve this? If not, which part of webpack code is responsible for this, so that I can take a look and create a feature request maybe?
I use Webpack version 2.4.1, Angular CLI 1.1.1 and Angular 4.2.6.


text:
Q: Security Без Spring'a в REST Api В проекте был написан фильтр авторизации через токены, но без использования spring-security.
Это обычный класс RestAuthenticationFilter, который наследуется от Filter и записывается в проперти web.xml.
Теперь нужно доделать секюрити, написать какой-то конфиг файл, который работал бы как spring-context.xml. Проверял юзера до права доступа к тому или иному url.
Кроме этого в spring-security, можно проверить, какой пользователь сейчас вошел с помощью Principal, но в этом случае этот вариант не пройдет.
Вопросы:

*

*Как в таком RESTful Api с кастомным секюрити, дописать свой конфиг файл, который будет задавать доступ юзеров к материалам?

*Как можно проверять  такой системе, вошедшего пользователя и выдавать о нем всю информацию(username, password, email .... )?
Update
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain filter) throws IOException, ServletException {
    final HttpServletRequest httprequest = (HttpServletRequest) request;
    final HttpServletResponse httpresponse = (HttpServletResponse) response;
    final HttpSession session = httprequest.getSession();
    boolean isNewSession = session.isNew();
    AccountInfo accountInfo = null;
    if (isNewSession) {
        log.debug("New Session get user Info");
        try {

            accountInfo = this.isAuthenticated(httprequest, httpresponse);
            if (accountInfo != null) {

                session.setAttribute("accountInfo", accountInfo);
                request.setAttribute("accountInfo", accountInfo);
                request.setAttribute(SM_USER, accountInfo.getUserName());
                System.out.println("AND WHERE IS THIS FUCKIN USER?!!!!");
            } else {
                httpresponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            }

        } catch (Exception e) {
            httprequest.setAttribute("message",
                    "Please contact your administrator to get an access to this application "
                            + e.getMessage());
            return;
        }
    } else {
        accountInfo = (AccountInfo) session.getAttribute("accountInfo");
        if (accountInfo == null || accountInfo.getAccountId() == null
                || accountInfo.getAccountId() <= 0) {
            // ReValidate
            try {
                accountInfo = this.isAuthenticated(httprequest,
                        httpresponse);
                if (accountInfo != null) {

                    session.setAttribute("accountInfo", accountInfo);
                    request.setAttribute("accountInfo", accountInfo);
                    request.setAttribute(SM_USER, accountInfo.getUserName());
                } else {
                    httpresponse
                            .setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    httprequest.setAttribute("message",
                            "Please contact your administrator to get an access to this application "
                                    + "Invalid User Info");
                }
            } catch (Exception e) {
                httprequest.setAttribute("message",
                        "Please contact your administrator to get an access to this application "
                                + e.getMessage());
                return;
            }

        } else {
            request.setAttribute(SM_USER, accountInfo.getUserName());
            request.setAttribute("accountInfo",
                    session.getAttribute("accountInfo"));
            accountInfo = (AccountInfo) session.getAttribute("accountInfo");
            log.debug("user in old Session");

        }
    }

    // Get user from session
    // Set User Context info
    try {
        if (session.getAttribute("accountInfo") != null) {
            AccountService acctService = springContext
                    .getBean(AccountService.class);
            AccountInfo info = (AccountInfo) session
                    .getAttribute("accountInfo");
            if (info.getAccountId() != null) {
                Account val = acctService.get(accountInfo.getAccountId());
                ProfileContext.setAccountContext(val);
            }
            // Set this user Name to log4j MDC
            MDC.put("userName", AbstractServiceModel
                    .formatUserDetails(ProfileContext.getProfileContext()));
        }
    } catch (Exception e) {
        log.debug("Invalid user information" + e);
        return;
    }

    if (httprequest.getRequestURI() != null
            && httprequest.getRequestURI().contains("logoutApp")) {
        session.invalidate();
    }

    filter.doFilter(request, response);

    // End setting
    // remove context
    this.destroy();

}

A: *

*Просто придумываете свой формат конфигурации: xml, json, properties - все, что хотите. Конфиг может соотносить, например, роли пользователей и разрешенные им URL-ы. При старте приложения грузите его в память. Фильтр проверяет каждый запрос на соответствие роли текущего пользователя URL-у.

*Сделайте так же, как это реализовано в Spring Security. У них есть класс SecurityContextHolder со статическим thread-local полем, в котором хранится информация о пользователе. Это поле заполняется как раз в фильтре после прохождения аутентификации и доступно в текущем потоке из любого класса. Если упрощенно:
public class SecurityContextHolder {
    private static final ThreadLocal<UserInfo> userInfoHolder = new ThreadLocal<>();

    public static UserInfo getUserInfo() {
        return (UserInfo)userInfoHolder.get();
    }

    public static void setUserInfo(UserInfo userInfo) {
        userInfoHolder.set(userInfo);
    }
}


text:
Q: How can I set my own custom keys and values from JSON deserialized output? How do I copy JSON deserialized output into the keys AND values positions in a Map variable? I see plenty of examples discuss setting values but NOT the keys themselves. Would it be something like the following if my JSON output was the below?
Map<String, Object> json_output = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    List<Object> parsed_json = (List<Object>)json_output.get('value');
    Map<String, Object> return_atts = new Map<String, Object>();
    for (Object LvL1attributes : parsed_json){
        return_atts.put(((Map<String, Object>)l1atts).get('displayName'), ((Map<String, Object>)l1atts).get('id'))
    }

JSON output:
{
    "value": [
        {
            "name": "Air Folder",
            "webUrl": "https://example.com/xxxxx/",
            "createdBy": {
                "user": {
                    "email": "Mark@example.com",
                    "id": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
                    "displayName": "Mark"
                }
            },
            "lastModifiedBy": {
                "user": {
                    "email": "Mark@example.com",
                    "id": "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
                    "displayName": "Mark"
                }
            },
....}]
}

Thanks!

A: I think the only issue I see in your code is that I don't see "displayName" as a value in your JSON so you may get a "null" as your key which would not be good. I think you meant to do something more like this:
for (Object LvL1attributes : parsed_json){
    Map<String, Object> obj = (Map<String, Object>) LvL1attributes;
    return_atts.put('displayName', obj.get('id'));
}

But than again I also don't see Id as an attribute of JSON so it could just be left out. If you really do have an attribute called "displayName" and an attribute called "Id" then your code is probably fine. Maybe consider adding in a null check on the attributes before attempting to use them:
Map<String, String> return_atts = new Map<String, String>();

for (Object LvL1attributes : parsed_json) {
    Map<String, Object> obj = (Map<String, Object>) LvL1attributes;
    String displayName = (String) obj.get('displayName');
    String Id = (String) obj.get(Id);

    if (displayName != null && Id != null) {
        return_atts.put(displayName, Id);
    }
}


text:
Q: integral of sum of function involving legendre polynomials Consider the integral $$\int_{-1}^1\left(\sum_{j=1}^n\sqrt{j(2j+1)}P_j(x)\right)^2dx$$
How to evaluate the integral? Specifically, say, if $n=5$, then what would be the value? Which property of Legendre polynomials should I use here? Should I use completeness of Legendre polynomials here?

A: As pointed out in the comments by @Christoph, the answer is simple owing to the orthogonality of Legendre polynomials. We have:
$$\left(\sum_{j=1}^n\sqrt{j(2j+1)}P_j(x)\right)^2=\sum_{j,k=1}^n\sqrt{j(2j+1)}P_j(x)\sum_{k=1}^n\sqrt{k(2k+1)}P_k(x)$$
Now, On integration, owing to orthogonality and the result $\int_{-1}^1P_n^2dx=\frac{2}{2n+1}$, we obtain,
the required integral equal to $$2\sum_{j=1}^nj=n(n+1)$$


text:
Q: Pass Angular component selector having svg file as templateUrl dynamically into other shared Angular component from main route component without *ngIf Conditionally I've to modify the SVG element so I've created multiple components having SVG files as templateUrl and performing attribute binding [attr.fill].
Also I need to perform zoom and pan operations on SVG files. So I created one shared component in which I'll be having mouse events.
Now I need to pass SVG component dynamically to other component from parent route component where I'll be doing mouse events on SVG.
I'm able to do all the operations if just passing img src using @input decorator to shared component
@Component({
  selector: 'abc-svg',
  templateUrl: './abc-svg.svg',
  styleUrls: ['./abc-svg.component.css']
})

In the above way multiple svg components will be created.
The following is shared component having all the mouse events
@Component({
      selector: 'shared-component',
      templateUrl: './shared-component.html',
      styleUrls: ['./shared-component.css']
    })

Now I need to pass abc-svg selector and other svg selectors to shared-component.
It can be done using *ngIf, along passing svg name using @Input decorator in shared component
<!-- shared-component.component.ts -->
@Input() requiredSvg:string;

<!-- shared-component.component.html -->
<abc-svg *ngIf="requiredSvg === 'abc'"></abc-svg>
<def-svg *ngIf="requiredSvg === 'def'"></def-svg>

<!-- parent.component.html -->
<shared-component requiredSvg="abc">

I need the way without using *ngIf structural directive.

A: Declare your SvgComponent in the same module in which you have declared the SharedComponent. Then you can use the <abc-svg></abc-svg> tag inside your shared.component.html template file.
EDIT:
You can use Angular's dynamic component loader to create components programmatically. You can find a very good tutorial here. There is stated:

Component templates are not always fixed. An application may need to load new components at runtime.

It is not easy to implement but here you go
export class ContainerComponent implements OnInit {

  constructor(private componentFactoryResolver: ComponentFactoryResolver, private elementRef: ElementRef) { }

  ngOnInit() {
    const svgComponentFactory = this.componentFactoryResolver.resolveComponentFactory(SvgComponent);
    const componentRef = this.elementRef.createComponent(svgComponentFactory);
  }
}


text:
Q: Is the leftmost bit of the mantissa always 1? I am reading the book "the secret life of programs". In the first chapter there is an explanation of a trick invented by Digital Equipment Corporation (DEC) that allows to double accuracy: "throwing away the leftmost bit of the mantissa doubles the accuracy, since we know that it will always be 1, which makes room for one more bit."
I cannot understand. As an example: Let's consider a 4-bit floating-point representation with 2 bits of mantissa and 2 bits of exponent. The binary number 01.11 then represents 4.0. The leftmost bit is 0 and not 1.
Can anyone explain to me, what is meant by "throwing away the leftmost bit" and " doubling accuracy" with a simple example?

A: Floating-point formats differ, but, for the most part, a floating-point representation is s•be•f, where s is +1 or −1 to represent a sign, b is a base (usually 2 or 10), e is an exponent, and f is a p-digit numeral in base b. b and p are fixed numbers determined by the format. s, e, and f vary according to the number represented. f is called the significand. (This is the preferred term for the fraction portion of a floating-point number. "Mantissa" is a historic term for the fraction portion of a logarithm.)
Bounds on e and how f is scaled are determined by the format. Sometimes f is specified to have a radix point (the general form of a decimal point) after its first digit, so its form is d0.d−1d−2…d1−p, where each di is a base-b digit (an integer from 0 to b−1, inclusive). In this form, 0 ≤ f < b. (We do not need to be concerned with other forms in this answer.)
For the most part, there is no need for the first digit of f to be zero. If it were zero, we could remove it and shift the other digits left one position. This multiplies f by b, but we can compensate by decreasing the exponent e by one. For example, if the floating-point number were 0.1112•27, we could instead represent it as 1.1102•26. This opens up room for a new digit at the end of f, which gives us better precision than if the first digit is zero.
Thus, we prefer to have the first digit be non-zero. This is called normal form. A number with a zero first digit is denormalized. At the very "bottom" end of the representable numbers, e reaches its bound, and we cannot decrease it further, so we cannot shift the digits of f left, and we have to leave a zero in the first position. These numbers, which are necessarily denormalized, are subnormal numbers. Some floating-point formats support them. Some do not.
When the base is two, there are only two possible digit values (0 and 1), so, if the first digit is not zero, it must be one. Therefore, when we are using base two and a number is normal form, we know its first digit is one. Therefore, there is no need to record this digit along with the others if we know the number is normal.
In IEEE-754 formats, the bits used to record the exponent also record whether the number is normal or not. The numbers s, e, and f above are stored in fields of bits we might call S, E, and F. However, they are not directly stored as binary integers in these bits. In an exponent field E, if the bits are all zeros, that indicates a subnormal number. This tells us both that the exponent e is at its lowest value and that the first digit of the significand is zero. If bits are all ones, that indicates the item is an infinity or a NaN. All values of e between all zeros and all ones indicate values of e and also that the first digit of the significand is one. (The values of E are not directly the values of e; there is a bias used to adjust, so that e = E − bias. For example, IEEE-754 binary32 has a bias of 127, so an E of 00000001 represents e = 1 − 127 = −126.)
Thus, it is incorrect to say we "throw away" the leftmost bit of the significand. What actually happens is that the leftmost bit is encoded in the exponent field, and the rightmost bits are stored in the significand field.
It is also sloppy to say that handling the leftmost bit this way "doubles the accuracy." It is true that a significand with p bits instead of p−1 bits has twice as many possible values, because each bit doubles the number of values representable. So encoding one bit via the exponent field gives us twice as many possible values than if we had to use only the field F for the significand. But it is clearer to describe that as one more bit of accuracy rather than a doubling of accuracy.


text:
Q: Visual Studio 2010 - Post-build event - cd "$(ProjectDir)" exits with code 1 when project is loaded from a network drive I have a solution running in Visual Studio 2010 SP1.
As part of the solution I have a post-build event where the first line is:
   cd "$(ProjectDir)"
   ...
The post build event works fine when the project is loaded locally.
I have setup my laptop with the TFS workspace mapped to a network drive.  The solution builds and the website runs just fine - except for the features relying on the post-build event.  I have removed all of the Post-build event except the change directory line.
This is the error I get when I build:   The command "cd "\\[ComputerName]\b$[ProjectPath]\"" exited with code 1.
The solution is residing solely on the network drive, and it build and runs.  I can navigate to the directory in an explorer window without any problems (I saved the network credentials).
The only thing I can find through searching is that exit code 1 means that the path is incorrect, but I can copy and paste the path from the error into an explorer window and browse the directory on the network drive.
Any ideas why the change directory command wont work?

A: CD is a command used by your shell command interpreter (CMD.EXE).
You cannot pass a CD \\server\share command to CMD.EXE.
Instead I suggest to map your share name to a drive letter like (from the command prompt)
NET USE Z: \\server\share /PERSISTENT:YES

Now you could write a batch file that uses your Z: drive and executes the commands required
For example
CD Z:\projectfolder\bin\release
copy *.exe z:\projectfolder\distribution /Y

You could also pass the predefined macros to this batch file as arguments and use them inside the batch file.


text:
Q: Application.properties in parent and child projects I'm trying to load child project's properties in parent project.

*

*parent
--------/application.properties

*child
--------/application.properties

Is it possible to add child's properties as property source in parent project?
More important question, it this property file from child project visible in parent project?

A: You should add a resources/META-INF folder to your child project and add files  additional-spring-configuration-metadata.json and spring.factories to prime the auto configuration pump for parent projects.  See Spring Boot docs.
I think the two should be orthogonal.  Repetition is always a bad idea.


text:
Q: MongoDB/RethinkDB Use ODM or not? I am building a boilerplate app in koajs for later use. I cannot decide if I should use an ODM or not. I can define my schemas using ES6 classes and even if I use something like mongoose I will probably end up writing a lot of custom validators so these are not really deciding factors. Odm engines contain a lot of functionality that I will hardly ever use.

*

*Are there any other advantages of using odm over writing custom methods?

*How much is the overhead caused by the odm engine, is it worth to not use it?

*How would you compare the two options in terms of performance, would you say badly optimized queries will perform worse?

A: The questions you're asking require a lot more background into your environment, stack, and application functionality. Whenever you're parsing the results and generating convenient objects out of them, you're spending CPU time doing that, plus you'll be incurring additional memory overhead generating objects versus just dealing with the raw query results.
Based on my understanding on ODMs, the advantage of using one is the convenience when writing app logic as well as easy code readability. This factor should not be taken lightly for larger projects and can help you organize and implement new features more quickly than without it.
If you're worried about performance, you can always test? But I don't think an ODM is going to make or break your system if you use one.


text:
Q: Having problems using a Switch statement in Java I'm making a Character Creator for fun and I seem have run into yet another java problem! I tried googling around for a bit but I didn't seem to find a working solution... I'm trying to use a switch statement for the compiler to output certain information depending on what class (Knight, Archer, Mage) the user chose, but when inputting my code I get error messages
My code so far (cleaned up a bit) is :
    String name;
    String className;
    int attPoints;

    System.out.println("Welcome to 'GameName's' Character Creator 2.0!\n");
    Thread.sleep(500);
    System.out.print("First off, what do you want your characters name to be? \n\nName : ");
    name = Scan.nextLine();
    Thread.sleep(500);
    System.out.print("\nYou are now to be known as "+ name + "!");

    System.out.print("\n\n" + name + ", what class do you want to be? ");
    System.out.print("\n\nClasses available :\nKnight");
    Thread.sleep(1500);
    System.out.print("\nMage");
    Thread.sleep(300);
    System.out.print("\nDruid");
    Thread.sleep(300);
    System.out.print("\nNinja");
    Thread.sleep(300);
    System.out.print("\nArcher");
    Thread.sleep(300);
    System.out.print("\nAdventurer");
    Thread.sleep(300);
    System.out.print("\nBerserker");
    Thread.sleep(300);

    System.out.print("\n\nClass : ");
    className = Scan.next();

    Class userClass = Class.valueOf(className);
    Thread.sleep(500);
    System.out.println("\nCongratulations! Your class is now : "+ className + "!");
    Thread.sleep(500);

      // This is where I get an error.
      // - Syntax error, insert "enum Identifier" to complete EnumHeaderName
      // - Syntax error, insert "EnumBody" to complete BlockStatement
  // - Syntax error on token "void", @ expected

    public void setClass()
        switch (Class) {

        case Knight:
            System.out.println(" Various lore about knights ");

            break;

    }
}

I THINK I may be trying to create a class inside another class - but when I tried putting it outside it got another error...
Also, I have an int called attPoints, and after I choose a class I want to add 10 to it, but unsure how.

A: You're switching on Class which is a Java type. Take a look at this tutorial: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
You probably want to do something like:
switch (userClass) {
    case Class.KNIGHT:
        System.out.println(" Various lore about knights ");
        break;
}


text:
Q: MVC3 TextBoxFor vs. EditorFor - issues with each I've looked around the web for a while, but can't find a good solution to my specific issue.  I'm working on a MVC3 Razor app.  I'm doing a bunch of stuff on the client side with jQuery as well so in this case I need my input fields to have html Id attributes.
In this specific issue when I use a TextBoxFor to display a currency (type is decimal), the value renders with 4 decimal places (I only want 2).  I put in the model attribute
[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
When it renders it seems to ignore this "displayFormat".  I've seen other posts online confirming that this problem exists with the TextBoxFor html helper.
On the other hand, I can change to use an EditorFor html helper and the DisplayFormat model attribute works for formats my textbox value to 2 decimal places. The down-side is I loose the ability to apply html attributes to my html helper which I need for jQuery.  What is the best way to get the best of both worlds?  I've seen a bunch of workarounds, but it seems like there must be an easier way to do this.
As a side note, my specific project requires most of my fields to have html Id attributes and sometimes classes so I can perform client side jQuery operations.  Not sure if this means I should focus on extending the EditorFor html helper to also accept html attributes or not.

A: DisplayFormat is only used by MVC in any of the Display extension methods for razor. (such as DisplayFor) Unfortunately to do what you want you would have to write some "by hand" code...here's an example to get you going. It basically reproduces the TextBoxFor code but makes some assumptions that are most likely bad for production. Note the assignment of displayText below, that's where we actually care about the DisplayFormatString you set in your DisplayFormat.
To call it in your view @Html.TextEditorFor(m => m.Value)
public static class CustomEditorFor
{
    public static IHtmlString TextEditorFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        return TextEditorFor(helper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    public static IHtmlString TextEditorFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        object value = metadata.Model;
        string displayText = string.Format(metadata.DisplayFormatString, value);

        string fullName = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));

        TagBuilder tagBuilder = new TagBuilder("input");
        tagBuilder.MergeAttributes(htmlAttributes);
        tagBuilder.MergeAttribute("type", "text");
        tagBuilder.MergeAttribute("name", fullName, true);

        tagBuilder.MergeAttribute("value", displayText);
        tagBuilder.GenerateId(fullName);
        ModelState modelState;
        if (helper.ViewData.ModelState.TryGetValue(fullName, out modelState))
        {
            if (modelState.Errors.Count > 0)
            {
                tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
            }
        }

        tagBuilder.MergeAttributes(helper.GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata));

        return new HtmlString(tagBuilder.ToString(TagRenderMode.SelfClosing));

    }
}

A: The simple solution here is to create a custom display and editor template for your custom currency type.  Do this.
public class MyModel {
    [DataType(DataType.Currency)]
    public decimal mycurrency {get;set;}
}

Then in ~/Views/Shared/EditorTemplates/Currency.cshtml (or DisplayTemplates)
@model decimal?

@Html.TextBox("", string.Format("{0:0.00}", Model), new { whateveryourattributes="attributevalues"})

Then you can just use DisplayFor or EditorFor or whatever.

A: I ended up using Telerik's Numeric Textbox control.  I'm sure both of the above answers would fix the decimal formatting.
I'm still need to circle back on the model validation.  I was having problems with the EditorFor html helper pulling validation the data annotations on the model for validation while doing the same with a TextBoxFor was not.  But at the same time the downside to the EditorFor helper didn't accept HtmlAttributes which I needed for jQuery.
I've started to use the MVC4 RC so I'm hoping many of these things are fixed in version 4.


text:
Q: viewWillAppear is not executing I have a tableview loaded withe records, see the code below:
- (void)viewDidLoad
{
    self.navigationItem.title=@"Accounts";
//    NSString *accountFile = [[NSBundle mainBundle] pathForResource:@"Accounts2" ofType:@"plist"];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [paths objectAtIndex:0];
    NSString *plistPath = [documentPath stringByAppendingPathComponent:@"Accounts2.plist"];
    accounts = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    NSLog(@"Accounts contains : %@", accounts);
    account = [accounts objectForKey:@"Account"];
    NSLog(@"account %@", account);
    number = [accounts objectForKey:@"Number"];
    dueDay = [accounts objectForKey:@"DayDue"];
    minAmount = [accounts objectForKey:@"MinAmount"];
    balance = [accounts objectForKey:@"Balance"];

    NSLog(@"data loaded");

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.navigationItem.leftBarButtonItem = self.editButtonItem;

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)];
    self.navigationItem.rightBarButtonItem = addButton;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)insertNewObject:(id)sender
{
//    if (!_objects) {
//        _objects = [[NSMutableArray alloc] init];
 //   }
 //   [_objects insertObject:[NSDate date] atIndex:0];
 //   NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
 //   [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    if (!self.addView) {
        self.addView = [[AddView alloc] initWithNibName:@"AddView" bundle:nil];
    }
          [self.navigationController pushViewController:self.addView animated:YES];
    NSLog(@"I am done, now what");
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"Number of records is %d", [account count]);
    return [account count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

     NSDate *object = _objects[indexPath.row];
     cell.textLabel.text = [object description];

    NSString *nameOfAccount = [account objectAtIndex:indexPath.row];
    cell.textLabel.text = nameOfAccount;
    NSString *accountNumber = [number objectAtIndex:indexPath.row];
    cell.detailTextLabel.text = accountNumber;
    NSLog(@"Index %d", indexPath.row);
    return cell;
}

I want to add a record to table, so I use the "InsertNewObject" method ... new screen appears, I am able to add the record to my plist, and then I execute the following line in the DetailView to return:
[self.navigationController popToRootViewControllerAnimated:NO];

Now, I want to reload my TableView with my new record:
I thought I just had to have the following viewWillAppear method like below:
- (void) viewWillAppear {
    NSLog(@"View will appear");
    [super viewWillAppear:YES];
    [self.tableView reloadData];

}

but, my NSLog is never executed, therefore my program is never getting here... am I doing something incorrectly, thank you for any response
I have added the following two methods:
- (void) navigationController:(UINavigationController *) navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{

    [self.tableView reloadData];

}

-(void) navigationController:(UINavigationController *) navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    [self.tableView reloadData];
}

and changed the line
[self.navigationController popToRootViewControllerAnimated:YES];

still not working, is something still wrong.

A: You are not using the correct method. You are leaving out the animated argument, try using -(void)viewWillAppear:(BOOL)animated:
See UIViewController - viewWillAppear:
- (void)viewWillAppear:(BOOL)animated {
    NSLog(@"View will appear");
    [self.tableView reloadData];
    [super viewWillAppear:animated];
}

A: if you are using a nav controller I belive the correct way to reload a view would be to call  somethihng like this
  -(void) viewWillAppear: (BOOL) animated
 {
   [self.tableView reloadData];
 }

You could also create your own custom reloadData method that sets what you want changed and then call that method.

A: As pointed out, viewWillAppear takes an animated argument. However, even when you add that, popping a view controller off the navigation stack does not trigger a call to viewWillAppear:. You need to use UINavigationControllerDelegate's navigationController:willShowViewController:animated: and navigationController:didShowViewController:animated: methods to reload your table view.


text:
Q: How to log events from a background thread when my app is closed? In my app I am doing certain tasks in a background thread(ExecutorService to be precise). This is working fine. However, I want to make sure that when the user closes the app, the task continues to run and finishes its job. In order to know this, I need some way to know whether the task finished after closing the app or not?
I tried using android.util.Log class to log certain events on app close, but I don't see the events logging. I also tried using Toast message but that doesn't work too. I was expecting to get a Can't create handler inside thread that has not called Looper.prepare() exception since I called the Toast message from the background thread but that didn't happen either, nothing happened.
I am not able to know for sure, if my task ends, which it shouldn't since it runs on a background ExecutorService or if these methods won't work when the app is closed? What should I do to log certain events to debug my app when it is closed and events are running in a background thread? Thanks!!


text:
Q: g++ : array bound is not an integer constant before ']' token I'm having trouble with g++ producing this error code when I try to compile my code:
maze.h:16:29: error: array bound is not an integer constant before ']' token
 bool canMove(int m[mazeSize][mazeSize], int r, int c);
Now, I have already done some research into this error and it seems to be causes by the array size not being known at compile time. I have tried making the array constant, but that ends up causing more errors later on as the array is reassigned later on in the code and produces this error:
maze.cpp: In member function 'int Maze::startMazeGen()':
maze.cpp:185:15: error: assignment of read-only location 'maze[i][j]'
    maze[i][j] = 1;
               ^
I have also seen people mention that it would just be easier to work with vectors instead, but I'm also having issues with trying to repurpose the code to work with vectors instead of arrays.
Here's the rest of my code:
movement.h
#pragma once
#include <iostream>
#include <curses.h>
#ifndef MOVEMENT_H
#define MOVEMENT_H
class Movement
{
    public:
        static const int playerX = 2; // sets player starting position
        static const int playerY = 2;
};
#endif

movement.cpp
#include <iostream>
#include <curses.h>
#include <ctime>
#include "maze.h"
//#include "movement.h"

bool running = true;
int playerX = 2;
int playerY = 2;

//Maze::maze Maze::mazeGen;
//int Maze::mazeGen.Maze::maze::generateMaze::maze(int m[Maze::mazeSize]
[Maze::mazeSize], int r, int c);

// Detect Char input
// and move player in direction
void getUserInput()
{
    char userInput = getch();
    if (userInput == 'w') {
        int playerY2 = playerY - 1;
        if (Maze::maze[playerY2][playerX] == ' ') {
            Maze::maze[playerY][playerX] = ' ';
            playerY--;
            Maze::maze[playerY][playerX] = 'x';
    }
}
    if (userInput == 'a') {
        int playerX2 = playerX - 1;
        if (Maze::maze[playerY][playerX2] == ' ') {
            Maze::maze[playerY][playerX] = ' ';
            playerX--;
            Maze::maze[playerY][playerX] = 'x';
    }
}
    if (userInput == 's') {
        int playerY2 = playerY + 1;
        if (Maze::maze[playerY2][playerX] == ' ') {
            Maze::maze[playerY][playerX] = ' ';
            playerY++;
            Maze::maze[playerY][playerX] = 'x';
    }
}
    if (userInput == 'd') {
        int playerX2 = playerX + 1;
        if (Maze::maze[playerY][playerX2] == ' ') {
            Maze::maze[playerY][playerX] = ' ';
            playerX++;
            Maze::maze[playerY][playerX] = 'x';
        }
    }
}

// Main game update
// Runs through all functions required
void update()
{
    getUserInput();
    clear();
    Maze::generateMaze;
    refresh();
}

//
//
/*int main()
{
    // Initate nCurses display
    initscr();
    while (true) {
    update();
}
// End nCurses display
endwin();
return 0;
}*/

maze.h
#pragma once
// MAZE.h
#include <iostream>
#include <ctime>
#ifndef MAZE_H
#define MAZE_H
extern int r;
extern int c;
extern int mazeSize; //number can be changed to make some big sweaty mazes making it an even number makes it act a bit weird sometimes so its better to use an odd number
extern int maze[mazeSize][mazeSize];
class Maze
{
    public:
        int blockedSquare = 1;
        void move(int m[mazeSize][mazeSize], int &r, int &c);
        bool canMove(int m[mazeSize][mazeSize], int r, int c);
        void solve(int m[mazeSize][mazeSize], int &r, int &c);
        bool canSolve(int m[mazeSize][mazeSize], int r, int c);
        void generateMaze(int m[mazeSize][mazeSize], int r, int c);
        int findStart();
        void printMaze(int m[mazeSize][mazeSize]);
        int startMazeGen();
};
#endif

maze.cpp
#include <iostream>
#include <ctime>
#include <vector>
#include "maze.h"
bool foundExit = false;
int mazeSize = 31;
int maze[mazeSize][mazeSize] = { 0 };
void Maze::generateMaze(int const m[mazeSize][mazeSize], int r, int c)
{

    bool made = false;

    while (made == false)
    {
        if (c == mazeSize - 1)
            foundExit = true;

        if (canSolve(m, r, c))
        {
            solve(m, r, c);
        }
        else if (canMove(m, r, c))
        {
            m[r][c] = 2; //2 means you can't move from that square, setting any lower stops maze from being made
            move(m, r, c); //move to first open space that can be found
        }
        else
            made = true;

    }

}

void Maze::move(int m[mazeSize][mazeSize], int &r, int &c)
{
    if (m[r][c + 1] == 0)
        c++;
    else if (m[r + 1][c] == 0)
        r++;
    else if (m[r][c - 1] == 0)
        c--;
    else if (m[r - 1][c] == 0)
        r--;
    else
        generateMaze(maze, r, c); //if maze cant be solved it generates a new one so the player doesnt have something that is impossible to solve

}

bool Maze::canMove(int m[mazeSize][mazeSize], int r, int c) //if there is an adjacent zero space, return true
{
    if (m[r][c + 1] == 0)
        return true;
    else if (m[r + 1][c] == 0)
        return true;
    else if (m[r][c - 1] == 0)
        return true;
    else if (m[r - 1][c] == 0)
        return true;
    else
        return false;
}

void Maze::solve(int m[mazeSize][mazeSize], int &r, int &c) //solves maze through with dijkstras algorithmto ensure it can be solved
{
    bool foundSolution = false;

    while (foundSolution == false)
    {

        int direction = (1 + rand() % 4) * 3;

        switch (direction)
        {
        case 3:
            if (c + 1 <= mazeSize - 1 && m[r][c + 2] == blockedSquare && m[r - 1][c + 1] == blockedSquare && m[r + 1][c + 1] == blockedSquare && m[r][c + 1] == blockedSquare)
            {
                if (c == mazeSize - 2 && foundExit == true)
                    ; //do nothing
                else
                {
                    c++;
                    foundSolution = true;
                }
            }
            break;
        case 6:
            if (r + 1 <= mazeSize - 2 && m[r + 2][c] == blockedSquare && m[r + 1][c + 1] == blockedSquare && m[r + 1][c - 1] == blockedSquare && m[r + 1][c] == blockedSquare && c != 0 && c != mazeSize - 1)
            {
                r++;
                foundSolution = true;
            }
            break;
        case 9:
            if (c - 1 >= 0 && m[r][c - 2] == blockedSquare && m[r - 1][c - 1] == blockedSquare && m[r + 1][c - 1] == blockedSquare && m[r][c - 1] == blockedSquare && c - 1 != 0)
            {
                c--;
                foundSolution = true;
            }
            break;
        case 12:
            if (r - 1 >= 1 && m[r - 2][c] == blockedSquare && m[r - 1][c + 1] == blockedSquare && m[r - 1][c - 1] == blockedSquare && m[r - 1][c] == blockedSquare && c != 0 && c != mazeSize - 1)
            {
                r--;
                foundSolution = true;
            }
            break;
        }
    }

    m[r][c] = 0;
}

bool Maze::canSolve(int m[mazeSize][mazeSize], int r, int c) //if an adjacent square can be moved to, return true
{
    bool solvable = false;

    if (r <= mazeSize - 3 && m[r + 2][c] == blockedSquare && m[r + 1][c + 1] == blockedSquare && m[r + 1][c - 1] == blockedSquare && m[r + 1][c] == blockedSquare && c != 0 && c != mazeSize - 1) //if adjacent space can be moved to
    {
        solvable = true;
    }
    else if (c <= mazeSize - 2 && m[r][c + 2] == blockedSquare && m[r - 1][c + 1] == blockedSquare && m[r + 1][c + 1] == blockedSquare && m[r][c + 1] == blockedSquare)
    {
        if (c == mazeSize - 2 && foundExit == true)
            ; //do nothing
        else
        {
            solvable = true;
        }
    }
    else if (r >= 2 && m[r - 2][c] == blockedSquare && m[r - 1][c + 1] == blockedSquare && m[r - 1][c - 1] == blockedSquare && m[r - 1][c] == blockedSquare && c != 0 && c != mazeSize - 1) //if not on extreme left or right
    {
        solvable = true;
    }
    else if (c >= 1 && m[r][c - 2] == blockedSquare && m[r - 1][c - 1] == blockedSquare && m[r + 1][c - 1] == blockedSquare && m[r][c - 1] == blockedSquare && c - 1 != 0)
    {
        solvable = true;
    }

    return solvable;
}

int Maze::findStart()
{
    return 1 + rand() % (mazeSize - 2);
}

void Maze::printMaze(int m[mazeSize][mazeSize])
{

    std::cout << std::endl;

    for (int i = 0; i < mazeSize; ++i) {
        for (int j = 0; j < mazeSize; ++j)
        {
            switch (m[i][j])
            {
            case 0:
                std::cout << "  ";
                break;
            case 1:
                std::cout << "▓▓";
                break;
            case 2:
                std::cout << "  ";
                break;
            case 3:
                std::cout << "  ";
                break;
            }
        }
        std::cout << std::endl;
    }
}

int Maze::startMazeGen()
{
    srand(time(0));

    for (int i = 0; i < mazeSize; ++i)
        for (int j = 0; j < mazeSize; ++j)
            maze[i][j] = 1;

    int r = findStart();
    //int r = 0;
    int c = 0;

    maze[r][c] = 0;

    generateMaze(maze, r, c);
    maze[r][c] = 2;
    printMaze(maze);
    std::cout << "Press enter to continue ...";
    std::cin.get();
}

The purpose of this code is to randomly generate a maze, solve it, and then print it to the screen if it can be solved. If the maze can't be solved, it keeps generating a new one until it can be solved.I aim to make this work with the movement code so that the user can navigate the maze.
Any help is appreciated on this issue. Thank you!

A: "Now, I have already done some research into this error and it seems to be causes by the array size not being known at compile time. I have tried making the array constant, but that ends up causing more errors later on as the array is reassigned later on in the code"
You're conflating two things here, the array and the array size.
The array size should be a a compile-time constant. Since you're assigning to the array, the array elements shouldn't be const at all.
const int arrSize = 3;
int arr[arrSize][arrSize];