Q:

gettext compile fails in crosstool-ng build on cygwin

I am new to crosscompiling and I followed the steps from using-crosstool-ng-and-cygwin by MAKSYM SHYTE
The crosstool fails to build gettext when generating crosscompiler for i686-nptl-linux-gnu target
build  = x86_64-unknown-cygwin
host   = x86_64-unknown-cygwin
target = i686-nptl-linux-gnu or x86_64-unknown-linux-gnu

NOTE: This gnulib patch from Ken Brown is needed to get gettext module compile. Alternatively, it also compiles if we just comment out  #include  in /usr/include/sys/types.h as per thorrr from bountysource
[UPDATE1] building gettext module for host gives the exact same errors for the x86_64-unknown-linux-gnu target also.
The ct-ng build fails in the linking phase while building gettext module for host.
[ALL  ]    libtool: link: x86_64-build_unknown-cygwin-g++ -shared -nostdlib
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/crtbeginS.o
.libs/libgettextsrc_la-message.o .libs/libgettextsrc_la-po-error.o
.libs/libgettextsrc_la-po-xerror.o .libs/libgettextsrc_la-read-catalog-abstract.o
.libs/libgettextsrc_la-po-lex.o .libs/libgettextsrc_la-po-gram-gen.o
.libs/libgettextsrc_la-po-charset.o .libs/libgettextsrc_la-read-po.o
.libs/libgettextsrc_la-read-properties.o .libs/libgettextsrc_la-read-stringtable.o
.libs/libgettextsrc_la-open-catalog.o .libs/libgettextsrc_la-dir-list.o
.libs/libgettextsrc_la-str-list.o .libs/libgettextsrc_la-read-catalog.o
../woe32dll/.libs/libgettextsrc_la-c++color.o ../woe32dll/.libs/libgettextsrc_la-c++write-catalog.o
../woe32dll/.libs/libgettextsrc_la-c++write-properties.o
../woe32dll/.libs/libgettextsrc_la-c++write-stringtable.o
../woe32dll/.libs/libgettextsrc_la-c++write-po.o
.libs/libgettextsrc_la-msgl-ascii.o .libs/libgettextsrc_la-msgl-iconv.o
.libs/libgettextsrc_la-msgl-equal.o .libs/libgettextsrc_la-msgl-cat.o
.libs/libgettextsrc_la-msgl-header.o .libs/libgettextsrc_la-msgl-english.o
.libs/libgettextsrc_la-msgl-check.o .libs/libgettextsrc_la-file-list.o
.libs/libgettextsrc_la-msgl-charset.o .libs/libgettextsrc_la-po-time.o
.libs/libgettextsrc_la-plural-exp.o .libs/libgettextsrc_la-plural-eval.o
.libs/libgettextsrc_la-plural-table.o .libs/libgettextsrc_la-sentence.o
.libs/libgettextsrc_la-libexpat-compat.o ../woe32dll/.libs/libgettextsrc_la-c++format.o
.libs/libgettextsrc_la-format-c.o .libs/libgettextsrc_la-format-sh.o
.libs/libgettextsrc_la-format-python.o .libs/libgettextsrc_la-format-python-brace.o
.libs/libgettextsrc_la-format-lisp.o .libs/libgettextsrc_la-format-elisp.o
.libs/libgettextsrc_la-format-librep.o .libs/libgettextsrc_la-format-scheme.o
.libs/libgettextsrc_la-format-java.o .libs/libgettextsrc_la-format-csharp.o
.libs/libgettextsrc_la-format-awk.o .libs/libgettextsrc_la-format-pascal.o
.libs/libgettextsrc_la-format-ycp.o .libs/libgettextsrc_la-format-tcl.o
.libs/libgettextsrc_la-format-perl.o .libs/libgettextsrc_la-format-perl-brace.o
.libs/libgettextsrc_la-format-php.o .libs/libgettextsrc_la-format-gcc-internal.o
.libs/libgettextsrc_la-format-gfc-internal.o .libs/libgettextsrc_la-format-qt.o
.libs/libgettextsrc_la-format-qt-plural.o .libs/libgettextsrc_la-format-kde.o
.libs/libgettextsrc_la-format-kde-kuit.o .libs/libgettextsrc_la-format-boost.o
.libs/libgettextsrc_la-format-lua.o .libs/libgettextsrc_la-format-javascript.o
.libs/libgettextsrc_la-read-desktop.o ../woe32dll/.libs/libgettextsrc_la-gettextsrc-exports.o
 -L/home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/intl/.libs
../gnulib-lib/.libs/libgettextlib.dll.a
-L/home/admin/l64/.build/i686-nptl-linux-gnu/buildtools/lib /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/intl/.libs/libintl.dll.a
-lncurses ../intl/.libs/libintl.dll.a /home/admin/l64/.build/i686-nptl-linux-gnu/buildtools/lib/libiconv.dll.a
-L/usr/lib/gcc/x86_64-pc-cygwin/5.4.0
-L/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/lib/../lib
-L/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../lib -L/lib/../lib
-L/usr/lib/../lib -L/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/lib
-L/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../.. -lstdc++ -lgcc_s -lgcc
-lcygwin -ladvapi32 -lshell32 -luser32 -lkernel32 -lgcc_s -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/crtend.o  -g -O2
-Wl,--export-all-symbols -Wl,--disable-auto-import   -o .libs/cyggettextsrc-0-19-6.dll
-Wl,--enable-auto-image-base -Xlinker --out-implib -Xlinker .libs/libgettextsrc.dll.a

[ALL  ]    .libs/libgettextsrc_la-libexpat-compat.o: In function `is_XML_LARGE_SIZE_ABI':
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/libexpat-compat.c:74: undefined reference to `XML_GetFeatureList'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/libexpat-compat.c:74:(.text+0x28): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `XML_GetFeatureList'
[ALL  ]    .libs/libgettextsrc_la-libexpat-compat.o: In function `rpl_XML_GetCurrentLineNumber':
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/libexpat-compat.c:90: undefined reference to `XML_GetCurrentLineNumber'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/libexpat-compat.c:90:(.text+0x96): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `XML_GetCurrentLineNumber'
[ALL  ]    .libs/libgettextsrc_la-libexpat-compat.o: In function `rpl_XML_GetCurrentColumnNumber':
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/libexpat-compat.c:99: undefined reference to `XML_GetCurrentColumnNumber'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/libexpat-compat.c:99:(.text+0xb6): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `XML_GetCurrentColumnNumber'
[ALL  ]    .libs/libgettextsrc_la-format-kde-kuit.o: In function `format_parse':
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:236: undefined reference to `XML_ParserCreate'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:236:(.text+0x27d): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `XML_ParserCreate'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:244: undefined reference to `XML_SetElementHandler'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:244:(.text+0x29f): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `XML_SetElementHandler'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:248: undefined reference to `XML_Parse'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:248:(.text+0x2b8): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `XML_Parse'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:258: undefined reference to `XML_Parse'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:258:(.text+0x2d3): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `XML_Parse'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:269: undefined reference to `XML_ParserFree'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:269:(.text+0x2eb): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `XML_ParserFree'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:261: undefined reference to `XML_GetErrorCode'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:261:(.text+0x4ec): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `XML_GetErrorCode'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:261: undefined reference to `XML_ErrorString'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:261:(.text+0x4f3): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `XML_ErrorString'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:264: undefined reference to `XML_ParserFree'
[ALL  ]    /home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src/format-kde-kuit.c:264:(.text+0x52a): additional relocation overflows omitted from the output

[ERROR]    collect2: error: ld returned 1 exit status
[ERROR]    make[6]: *** [Makefile:2388: libgettextsrc.la] Error 1
[ALL  ]    make[6]: Leaving directory '/home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src'
[ERROR]    make[5]: *** [Makefile:2300: all] Error 2
[ALL  ]    make[5]: Leaving directory '/home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools/src'
[ERROR]    make[4]: *** [Makefile:1742: all-recursive] Error 1
[ALL  ]    make[4]: Leaving directory '/home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools'
[ERROR]    make[3]: *** [Makefile:1608: all] Error 2
[ALL  ]    make[3]: Leaving directory '/home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin/gettext-tools'
[ERROR]    make[2]: *** [Makefile:380: all-recursive] Error 1
[ALL  ]    make[2]: Leaving directory '/home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin'
[ERROR]    make[1]: *** [Makefile:336: all] Error 2
[ALL  ]    make[1]: Leaving directory '/home/admin/l64/.build/i686-nptl-linux-gnu/build/build-gettext-host-x86_64-build_unknown-cygwin'
[ERROR]
[ERROR]  >>

[ERROR]  >>  Build failed in step 'Installing gettext for host'
[ERROR]  >>        called in step '(top-level)'
[ERROR]  >>
[ERROR]  >>  Error happened in: CT_DoExecLog[scripts/functions@257]
[ERROR]  >>        called from: do_gettext_backend[scripts/build/companion_libs/330-gettext.sh@131]
[ERROR]  >>        called from: do_gettext_for_host[scripts/build/companion_libs/330-gettext.sh@63]
[ERROR]  >>        called from: do_companion_libs_for_host[scripts/build/companion_libs.sh@36]
[ERROR]  >>        called from: main[scripts/crosstool-NG.sh@646]
[ERROR]  >>
[ERROR]  >>  For more info on this error, look at the file: 'build.log'

[UPDATE2] filled in all the logs before "collect2: error: ld returned 1 exit status"
1) The build logs show that the "building and installing gettext module for build" succeeding but it failing when "building and installing gettext module for host" - What could be the difference since build and host architecture is the same - x86/cygwin ?? Am I missing any configuration settings?
2) If anyone got the crosstool-ng working on recent cygwin releases for a linux 64/32bit targets, please share detailed steps or links.
[UPDATE3]
As I was going no where trying to crosscompile for linux(ubuntu) I tried arm-unknown-linux-gnueabi and armv7-rpi2-linux-gnueabihf targets, cygwin can generate the cross-compoilers just fine for both targets. Its strange that crosscompiler generation for 32 and 64 bit plain linux target fails in Cygwin. I am probably missing something trivial.
[/UPDATE3]
Anyone with recent success on (x86/i686)_linux target please share your steps or links.

A:

The undefined symbols (XML_GetFeatureList XML_GetCurrentLineNumber XML_GetCurrentColumnNumber XML_ParserCreate XML_SetElementHandler XML_Parse XML_ParserFree XML_GetErrorCode XML_ErrorString) were defined in expat-2.1.0.tar - a separate package. I could not get that to link into the crosstool builds but I got past the gettext linker error by removing the following from the .config file
CT_EXPAT=y
CT_EXPAT_NEEDED=y
CT_EXPAT_VERSION="2.1.0"
CT_EXPAT_V_2_1_0=y


Q:

What kind of hash function can give me a 32 bit value from a string?

I'm using the QT framework so if there is something like this implemented in that, I would use it, but I couldn't find it.
I would like to get random color values for variable length strings.

A:

If you include <QHash>, then you get overloads of the function qHash(), one of which is:
uint qHash(const QString & key)


Q:

Prevent Listbox Duplicates

Okay, newbie question here. I'm creating a random key generator which will generate keys from a string, and add each key combination to a Listbox. My question is how would I be able to prevent duplicates from appearing/being added to the listbox thus preventing duplicate keys. Currently the key is generated into 5 separate sections and is then (crudely) brought together into an invisible textbox for temp storage before it's added into the listbox1.
  generatetextonlycode = strName

    TextBox1.Text = Key1.Text & "-" & Key2.Text & "-" & Key3.Text & "-" & Key4.Text & "-" & Key5.Text`

I know this is a really bad way to go about it, but it's easy and works -- Only it is prone to duplicates ;( This code obviously will go into a Loop statement once it works. Here's the full thing:
Private Sub Generatebtn_Click(sender As Object, e As EventArgs) Handles Generatebtn.Click
    Key2.Text = generatetextonlycode()
    Key3.Text = generatetextonlycode()
    Key4.Text = generatetextonlycode()
    Key5.Text = generatetextonlycode()
End Sub

Public Function generatetextonlycode() As Object
    Dim intRnd As Object
    Dim strName As Object
    Dim intNameLength As Object
    Dim intLenght As Object
    Dim strInputString As Object
    Dim inStep As Object

    strInputString = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    intLenght = Len(strInputString)

    intNameLength = 5

    Randomize()

    strName = ""

    For inStep = 1 To intNameLength

        intRnd = Int((intLenght * Rnd()) + 1)

        strName = strName & Mid(strInputString, intRnd, 1)

    Next

    generatetextonlycode = strName

    TextBox1.Text = Key1.Text & "-" & Key2.Text & "-" & Key3.Text & "-" & Key4.Text & "-" & Key5.Text

    '
    '
    'THIS IS WHERE I'D LIKE TO ADD THE CONTENTS OF Textbox1 INTO Listbox1 IF THE LISTBOX DOESNT ALREADY CONTAIN THE KEY!
    '
    '

End Function

(Note that Key1.text contains a static value so that all keys start of the same. I'm using visual basic with .net 4.5)

A:

Use the list box's Contains() method to test if the value is already in the list box or not, like this:
If Not listBox1.Items.Contains(TextBox1.Text) Then
    ' It is not already in the list box so add it
    ListBox1.Items.Add(TextBox1.Text)
End If

A more efficient approach is to use a .NET collection that does not allow duplicates (i.e. HashSet<T>).
Per MSDN:

The HashSet class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

Note: HashSet<T>.Add() method returns a Boolean (True if the item was added to the collection and False if the item is already present).
So your code could be this:
Dim theValues As New HashSet(Of String)
Dim success As Boolean = theValues.Add(TextBox1.Text)

' Was the addition of the string successful or not?
If success Then
    ' Yes, so re-bind the list box
End If


Q:

Where is Empty Code First Model in Entity Data Model Wizard?

I am using Visual Studio 2010 and want to use EF Code First as ORM. I cant find that template in Entity Data Model Wizard as it is in this thread. Yes, I installed Nuget Package Manager and Entity Framework 6.2 for my project. Can't I use code first approach in my project? what is there to be additionally installed?

A:

The Entity Data Model Wizard refers to model first, if you want to use code first, then you will design your POCO classes firstly, and use your classes to generate database for you. HTH.


Q:

Photo Upload in ASP.NET

I have an image box and a Photo Upload control with a Save button. I need to upload an image into the Image Box.
When I click the Upload button, it should show the Image in the Image Box.
When I click the Save button, the path of the uploaded image should be saved in the database.
My issue is the photo gets uploaded, but only after I click the Upload button for the second time.
P.S. I use a Client side function for uploading the photo.
Following are my codes.
CLIENT SIDE FUNCTION FOR UPLOADING THE PHOTO
function ajaxPhotoUpload() {

        var FileFolder = $('#hdnPhotoFolder').val();
        var fileToUpload = getNameFromPath($('#uplPhoto').val());

        var filename = fileToUpload.substr(0, (fileToUpload.lastIndexOf('.')));
        alert(filename);
        if (checkFileExtension(fileToUpload)) {

            var flag = true;
            var counter = $('#hdnCountPhotos').val();

            if (filename != "" && filename != null && FileFolder != "0") {
                //Check duplicate file entry
                for (var i = 1; i <= counter; i++) {
                    var hdnPhotoId = "#hdnPhotoId_" + i;

                    if ($(hdnPhotoId).length > 0) {
                        var mFileName = "#Image1_" + i;

                        if ($(mFileName).html() == filename) {
                            flag = false;
                            break;
                        }

                    }
                }
                if (flag == true) {
                    $("#loading").ajaxStart(function () {
                        $(this).show();
                    }).ajaxComplete(function () {
                        $(this).hide();
                        return false;
                    });

                    $.ajaxFileUpload({
                        url: 'FileUpload.ashx?id=' + FileFolder + '&Mainfolder=Photos' + '&parentfolder=Student',
                        secureuri: false,
                        fileElementId: 'uplPhoto',
                        dataType: 'json',
                        success: function (data, status) {

                            if (typeof (data.error) != 'undefined') {
                                if (data.error != '') {
                                    alert(data.error);
                                } else {

                                    $('#hdnFullPhotoPath').val(data.upfile);
                                    $('#uplPhoto').val("");
                                    $('#<%= lblPhotoName.ClientID%>').text('Photo uploaded successfully')
                                }
                            }

                        },
                        error: function (data, status, e) {
                            alert(e);
                        }
                    });
                }

                else {
                    alert('The photo ' + filename + ' already exists');
                    return false;
                }
            }
        }
        else {
            alert('You can upload only jpg,jpeg,pdf,doc,docx,txt,zip,rar extensions files.');
        }
        return false;

    }

PHOTO UPLOAD CONTROL WITH SAVE BUTTON AND IMAGE BOX

    <asp:Image ID="Image1" runat="server" Height="100px" Width="100px" ClientIDMode="Static" />
                <asp:FileUpload ID="uplPhoto" runat="server" ClientIDMode="Static"/>
                <asp:Label ID="lblPhotoName" runat="server" Text="" ForeColor ="Green" ClientIDMode="Static"></asp:Label>
<asp:Button id="btnSave" runat="server" Text="Upload Photograph" onClick="btnSave_Click"  OnClientClick="return ajaxPhotoUpload();"/>

SAVE BUTTON CLICK EVENT IN SERVER SIDE (to show the uploaded image in the image box)
Protected Sub btnSave_Click(sender As Object, e As EventArgs)
    Image1.ImageUrl = hdnFullPhotoPath.Value

End Sub

A:

All, thanks for your time and help.! The tilde(~) symbol was the issue - the file's path wasn't recognized. So I modified my code to replace it with empty space.
var orgpath = data.upfile;
var photopath = orgpath.replace('~/', '');
$('#<%= ImgFacultyPhoto.ClientID%>').attr('src', photopath);


Q:

Read records dbf foxpro 2.6 have been deleted on excel

How to read records that have been deleted. Can the record be read on excel or another software? If so, how?

A:

If they have been deleted but the table has not been PACKed, then issuing the RECALL ALL command will undelete them.
You can also issue SET DELETED OFF to make records marked for deletion available to SELECT-SQL commands and so forth.
If you're connecting to the data with the OLEDB driver, include 'DELETED=FALSE' in the connection string.
If the table has been PACKed then they are gone, restore a backup.


Q:

How can I parse a Date from a string and keep it in its format?

I have this code to convert a string to a date. but the resulting date is always in another format.
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        try {
            String dateString  = "18/01/2013 11:59";
            dateTest = format.parse(dateString);
            System.out.println(dateTest); //output: Tue Jan 18 11:59:00 GMT 2013
           }

How can I make it so that dateTest is in the same format as the original?

A:

Format the date using the same SimpleDateFormat you used to parse it.

A:

This
System.out.println(format.format(dateTest));

will do the job. You can use the format() method of your SimpleDateFormat to format the output the same way your input should be.


Q:

UITextField clearButtonMode and UIPicker

I have an extended UITextField (added a NSString property, inputType to it) to take in user input. when the user tap's the text field, i use a picker for the user to select the input. i also need to allow the user to clear the text box so i thought i could use
tillageTextField.clearButtonMode = UITextFieldViewModeAlways;

to clear the text field.
the issue is when you tap the X to clear the text box, it also fires my picker. i use:
-(BOOL) textFieldShouldBeginEditing:(MyTextField *) textField
{
    //other code
    else if ([textField.inputType isEqualToString:@"tillageMethod"])
    {
        self.customArray = [NSArray arrayWithObjects:@"No Till", @"Strip Till", @"Full Till", nil];
        self.tempTextField = textField;
        [self showPicker];

        return  NO;
    }
    //other code
}

to show the picker.
is there a way for me to tell if the user tapped the clear button and not show the picker?

A:

You could also implement textFieldShouldClear: and set a flag on your class (e.g. doNotShowPickerOnNextCallback)
- (BOOL)textFieldShouldClear:(UITextField *)textField {

    if ([textField.inputType isEqualToString:@"tillageMethod"]) {

        if (![self pickerIsShowing]) {
            self.doNotShowPickerOnNextCallback = YES;
        }
    }

    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    //other code
    else if ([textField.inputType isEqualToString:@"tillageMethod"]) {

        if (self.doNotShowPickerOnNextCallback) {

            self.doNotShowPickerOnNextCallback = NO;
            return NO;
        }

        self.customArray = [NSArray arrayWithObjects:@"No Till", @"Strip Till", @"Full Till", nil];
        self.tempTextField = textField;
        [self showPicker];

        return  NO;
    }
}


Q:

How can I marshal a Delphi short string using p/invoke?

I have a problem with a variable type from a dll which i am importing in C#. It is written in object oriented pascal and it says it is developed with the Delphi Development Tool.
On the manual of the library it says that shortstring is a packed array of bytes. The first byte is the length and the following are exaclty 255 bytes with the string data that i need.
So after importing the dll in C# i wrote:
[return: MarshalAs(UnmanagedType.LPArray)]

Then called the function from the dll:
public static extern byte[] xxxx();

But i am getting the following error:

Cannot marshal 'return value': invalid managed/unmanaged type combination

On the other hand i tried the following:
[return: MarshalAs(UnmanagedType.SafeArray)]

This time i get the error:

SafeArray of rank 18727 has been passed to a method expecting an array of rank 1

Can you please tell me what i am doing wrong, and firstly is correct like this to get a shortstring from a compiled library?
Regards

A:

I think the cleanest way to marshal a Delphi short string is to wrap it in a struct.
[StructLayout(LayoutKind.Sequential)]
public struct DelphiShortString
{
    private byte length;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst=255)]
    private byte[] payload;

    public string Value
    {
        get
        {
            return Encoding.Default.GetString(payload, 0, length);
        }
        set
        {
            length = (byte)Math.Min(value.Length, 255);
            payload = Encoding.Default.GetBytes(value.Substring(0, length));
        }
    }
}

This type is not blittable and so cannot be used as a function return value. If you have control of the Delphi code, then you can ensure that you don't use short strings as function return types. However, I suspect that you don't have control of it. In which case you'd need a blittable version of the struct. Which would look like this:
[StructLayout(LayoutKind.Sequential)]
public unsafe struct DelphiShortString
{
    private byte length;

    private fixed byte payload[255];

    public string Value
    {
        get
        {
            {
                byte[] bytes = new byte[length];
                fixed (byte* ptr = payload)
                {
                    Marshal.Copy((IntPtr)ptr, bytes, 0, length);
                }
                return Encoding.Default.GetString(bytes, 0, length);
            }
        }
        set
        {
            byte[] bytes = Encoding.Default.GetBytes(value);
            length = (byte)Math.Min(bytes.Length, 255);
            fixed (byte* ptr = payload)
            {
                Marshal.Copy(bytes, 0, (IntPtr)ptr, length);
            }
        }
    }
}

It is indicative of poor design for a DLL to export a Delphi short string. That suggests that the author of the library has not designed it to be compatible with other compilers. Which in turn suggests that the functions may well use the default Delphi calling convention. Which is register and is not supported by Microsoft tools. If my hunch is right, then this DLL cannot be consumed directly. You would need to write an adapter DLL that exposed a more interop friendly interface.


Q:

Better description of "Tenacious Badge"

I just got the Tenacious Badge, and I clicked my way to find out what it was for.
I have read it ten times, and I still don't fully understand what I got it for. Maybe it's just because I'm Norwegian, but still, please, write a better description!
2 years later the description is still confusing:

Zero score accepted answers: more than 5 and 20% of total.

Jeff wrote in a blog comment that it meant:

You have more than 5 zero score accepted answers, and zero score
  accepted answers make up 20% of your total accepted answers.
You can see why we didn’t include the full text here, I hope.. :)

However the description remains unchanged and is not in any way comprehensible even to native English speakers. Jeff's comment can be rewritten to make it absolutely crystal clear:

You have more than 5 accepted answers with a score of zero, and these
  answers make up 20% of your total accepted answers.

This is a feature-request.

A:

It's not just because you are Norwegian. I read it several times and had to search meta before I understood it.
The Tenacious badge is awarded to someone who has answered other people's questions, where at least five of his answers have received no votes and are the accepted answer to the question.

A:

I think the most unclear thing is what the 20% is of. As user unknown already posted, you can reasonably read that as a percentage of either all your answers, or just your accepted answers.
If the devs want to keep the description a little more succinct (you've proposed easily the longest badge description on the site) while gaining some of the added clarity and explictness of your proposed wording, they could go for this wording:

More than 5 zero-score accepted answers, making up more than 20% of your accepted answers.

There are already a couple of badge descriptions that are of greater length, like the ones for populist and the tag badges, so I can't see any reason not to swap the wording to something like this.

A:

How about:

At least 20% of accepted answers have no votes (minimum of 5 no-vote accepted answers)


Q:

Mixing time for a random walk on an interval

I take a random walk on a bounded one-dimensional interval of length $N$, with possible walker positions $1$ through $N$.  If I start at position $1$, how many steps should it take before my walker is approximately uniformly distributed on the interval?  Perhaps we could call this a "mixing" time?  Does it require $\Theta(N^2)$ steps, similar to the cover time?

A:

Let $t_{ij}$ be the probability of going from position $j$ to position $i$ in one step.  Then the distribution of the walker will converge over time to an eigenvector of $T=[t_{ij}]$ with eigenvalue $\lambda_1=1$.  The rate at which this happens is governed by $\lambda_2$, the second largest (in absolute value) eigenvalue of $T$: non-uniformity in the initial distribution will decay as $\exp(-(1-\lambda_2)n)$ after $n$ steps.
The bounded walk you describe has $t_{2,1}=1$, $t_{N-1,N}=1$, and $t_{ij}=\frac{1}{2}\delta_{i,j+1}+\frac{1}{2}\delta_{i,j-1}$ for $i\neq 1,N$.  As you might expect (since it's translation-independent except at the boundaries), the eigenvectors of this matrix are standing waves with wavelengths compatible with the box: $$u_{k}(x)=\cos\left(\pi k \frac{x-1}{N-1}\right),$$
where $k=0,1,2,...,N-1$, with corresponding eigenvalues $\lambda_{k}=\cos(\pi k/(N-1))$.  The second-largest absolute value is $\cos(\pi/(N-1))$, which is approximately $\frac{1}{2}\pi^2/(N-1)^2$ away from $1$, giving a decay time that is in fact $\Theta(N^2)$.
You should note, however, that there are two eigenvalues of magnitude $1$ for this random walk: one ($+1$) corresponds to uniform distribution, while the other ($-1$) corresponds to an alternating even-odd distribution.  Since the walker can never return to its initial position after an odd number of steps, you never achieve true "mixing" with this random walk.


Q:

How do I get the current step in jQuery steps wizard?

I'm looking for a way to get the current step in my jQuery Steps wizard. I would like to perform an action if the current step is step 1.

A:

This will return the current step index as an integer.
$("#wizard").steps("getCurrentIndex");

This step index is zero-based.
So, to perform an action on the first step (what I assume you mean by "step 1"), you would do:
if ( $("#wizard").steps("getCurrentIndex") == 0 ) {
    perform_action();
}

Ref: https://github.com/rstaib/jquery-steps/wiki/Methods


Q:

Delete laravel's controller, blades, etc. after installation

i just made another Laravel project, but it is a little bit boring, to delete all the Laravel's files like app.blade, login.blade, contollers etc.
So i am asking, is there any option to delete them all or make Laravel project without it?
Thanks for help.

A:

Im not following you. Laravel is all about jump starting the project. That's why all those controllers and views are already there. If you don't like the default Laravel file structure you may make your own as a git repo and use that to create new projects. There's nothing wrong with doing that. Except if there's a major update in the structure of the bootstrap file or the kernel.. etc. you will need to manually update them. Which is same for the official Laravel as well. Major updated come once a year (usually)


Q:

lambda fct returning reference

I have tried hard to make a lambda function return a value by reference without making a copy of the referenced value.
My code example below illustrates the problem. It compiles and runs ok, but with the "//" commented line instead of the line above, it doesn't.
I have found two workarounds (both illustrated in my example):

wrap the result with std::ref()
return a pointer instead of a reference

But both workarounds are not what I really want, and I do not understand why they are necessary: The expression "makeRefA()" has already the type the lambda function returns (const A&) and thus must neither be copied nor converted. By the way: The copy constructor is really called when I do not explicitly delete it (which in my "real" code is a performance problem).
To me it looks like a compiler bug, but I have tried with several C++11-compilers which all show up the same error. So is there something special concerning the "return" statement in a lambda function?
#include <functional>
#include <iostream>

struct A {
  A(int i) : m(i) { }
  A(const A&) = delete;
  int m;
};

void foo(const A & a) {
  std::cout << a.m <<'\n';
}

const A & makeRefA() {
  static A a(3);
  return a;
}

int main() {
  std::function<const A&()> fctRef = [&]
    { return std::ref(makeRefA()); }; //compiles ok
    //{ return makeRefA(); }; //error: use of deleted function 'A::A(const A&)'
  foo(fctRef());

  std::function<const A*()> fctPtr =
    [&] { return &makeRefA(); };
  foo(*fctPtr());

  return 0;
}

output:
3
3

A:

You can specify the return type
#include <functional>
#include <iostream>

struct A {
    A(int i) : m(i) { }
    A(const A&) = delete;
    int m;
};

void foo(const A & a) {
    std::cout << a.m <<'\n';
}

const A & makeRefA() {
    static A a(3);
    return a;
}

int main() {
    std::function<const A&()> fctRef = [&]()->const A&
//    { return std::ref(makeRefA()); }; //compiles ok
    { return makeRefA(); }; // works
    foo(fctRef());

    std::function<const A*()> fctPtr =
    [&] { return &makeRefA(); };
    foo(*fctPtr());

    return 0;
}

A:

By default, the automatically-deduced type of a lambda is the non-reference version of a type

... the return type is the type of the returned expression (after lvalue-to-rvalue, array-to-pointer, or function-to-pointer implicit conversion);  (source)

If you want a return type with a reference, you will have to specify it more explictly. Here are some options:
[&]()
-> decltype( makeRefA() )
{ return makeRefA()); };

or simply be fully explicit about the return type with ->
[&]()
-> const A&
{ return makeRefA(); }

If using C++14, then simply use decltype(auto),
[&]()
-> decltype(auto)
{ return makeRefA(); }

The rules for decltype can be complicated at times. But the fact that makeRefA() is an expression (as opposed to simply naming a variable) means that the type of the expression (const A&) is faithfully returned by decltype( makeRefA() ).


Q:

Does stuff strapped to the outside of a Backpack count toward the total weight a backpack can carry?

I'm going for a more gritty/realistic game, and so I'm having my players be careful about their carrying capacities and weight. While helping a new player build a character, I noticed that the explorer's pack they received is overweight if the waterskin is considered to be full and the rope isn't counted. It notes that backpacks can have things strapped to the outside, but does this weight count toward the total weight a backpack can carry? If stuff strapped to the outside doesn't count toward capacity, is there any limitation besides imagination to just how much could be strapped to the outside of the bag?

A:

The weight limit for packs/bags/etc is for the contents of the pack/bag/etc.  A container can only hold this much.  There is no explicit limit to how much can be tied to the outside of a pack, besides a character's total Carrying Capacity, and objects attached to the outside do not count against the weight limit for objects placed inside.

A:

Beyond the fact that you are asking about a level of granular detail that the rules to not cover, I suggest that you do some research into what a loadmaster has to do for a truck or an aircraft. There are three primary challenges to address:

Maximum weight
Maximum cube
Order of loading.

I had to address the cube problem a lot when I worked during the summers for a moving company.  It all had to fit, and the truck could carry more if it were just the weight being carried.
Each of these constraints can be applied in a micro sense to the pack that an adventurer carries, though "what has to come out first" is the most easily planned for.

Some things aren't that heavy, but are a bit awkward to carry.  The front door of your house/apartment is an example.
Some things fit into a small space but are very heavy: a cubic foot of lead being one example.
Some things you carry and need to get to "in a hurry" and other things you carry and can get to at your leisure.

As an illustration, look at the seventh edition of the Boy Scout Handbook, pages 250-251, on a properly packed Yucca pack.  (If the link doesn't take you to that page, flip to those pages).  That demonstrates a model of "how much stuff fits into a certain sized pack" without too much complexity.
To scale this up a bit, a US Army Infantryman carries about three times that much in his pack: partly due to the density of the contents (ammo is dense and heavy) and partly due to the size of the pack.  The cube is a bit more than twice that of the Yucca pack, but when all of the items are added up, the density increase is non trivial. The soldier's pack will typically top out at 80 pounds, sometimes a bit more.  That doesn't include the weapon carried.
With these practical points provided, you may be able to better visualize the limitations of a back pack full of gear.  If nothing else, once beyond the weight limit of the pack, now and again roll a saving throw versus straps breaking.  Pick a DC: I've had straps on a pack break.  Not a good thing.


Q:

How to change font size in message box in eclipse RCP?

I want to display the message with larger font than the usual size in the message box. I don't know how to do this task. I also searched trying google but couldn't find a solution. Is there any way in eclipse rcp to accomplish this task ?

A:

Depends on what kind of "message box" do you open. Generally there is:

SWT message box API (org.eclipse.swt.widgets.MessageBox) - this uses the OS system message box and can be customized only with title, text and icon type (error, info, question,...).
JFace message dialog API (org.eclipse.jface.dialogs.MessageDialog) - this uses "Basic->Dialog" font defined in "Colors and Fonts" preference page. See the code in org.eclipse.jface.preference.PreferenceDialog#createTitleArea method which attaches a listener to the JFaceResources.getFontRegistry()


Q:

Expand width to take remaining width of parent div

An example of my code can be found on JSFiddle http://jsfiddle.net/WdZgV/
CSS

HTML

What i want is that when you resize the window width to less than 1000px the .menu div resize to the size of the parent div.
So as an example:
If you have your window width as 900px, the .logo div has 200px and the .menu div has 700px.
Is there anyway i can do this with CSS, or i need to use Javascript?

A:

Yes — remove the float, don't specify width, and set overflow to hidden. Example here; .menu becomes:
.menu {
    height: 100px;
    background: #999;
    overflow: hidden;
}


Q:

Xcode Designer: How Do I Create 2 Sliding Selector Controls?

Hi,I want to list for ex. speechers in an organization. Let's say a schedule. I've seen a couple apps in AppStore and liked this most. How do we create such controls? Like select the date then the place of speech. Those two don't have to be dependent.I couldn't see a control like this in Xcode designer.Thanks in advance.

A:

You would have to write your own control. Something like that could be a UIScrollView set to paging mode that gets its 3D effect from some neatly positioned gradients. Interface Builder won't help you much (if at all) with this task.


Q:

operate on row-compressed format from igraph_sparsemat_t

Is it possible to build an igraph_sparsemat_t from an already available matrix stored in row-compressed (CSR) format and not set every value with igraph_sparsemat_entry()?
Also can I extract the CSR structure from an igraph_sparsemat_t so that I can use the CSR-matrix with other libraries?
I know that conversion from igraph_sparsemat_t to igraph is possible, but I don't know what I could do from there on.

A:

The igraph documentation mentions that igraph_sparsemat_t is a thin wrapper for the CXSparse library's datatype. The documentation for that library is essentially this book:

Timothy A. Davis: Direct Methods for Sparse Linear Systems

But you don't really need the book to solve this. You can dig a bit in the source and find igraph_sparsemat_t just contains a cs_di_sparse, which is
typedef struct cs_di_sparse  /* matrix in compressed-column or triplet form */
{
    int nzmax ;     /* maximum number of entries */
    int m ;         /* number of rows */
    int n ;         /* number of columns */
    int *p ;        /* column pointers (size n+1) or col indices (size nzmax) */
    int *i ;        /* row indices, size nzmax */
    double *x ;     /* numerical values, size nzmax */
    int nz ;        /* # of entries in triplet matrix, -1 for compressed-col */
} cs_di ;

You can build or read this directly.
The igraph documentation mentions that this may contain either a CSC representation of a triplet matrix. Pay attention to this (see comment on the last entry).
Do look at the memory allocation/deallocation functions in cs.h (cs_di_malloc/cs_di_free/etc.) and use them instead of you standard malloc/free, to ensure that a compatible free is used on memory allocated with a certain malloc.
Note that the MATLAB interface of CSparse (take a look at the sources I linked above) also uses this approach: it manipulates the struct directly.
Finally, do pay attention that igraph interprets this matrix as CSC, not CSR. If you convert to another library's data structure, you might need to transpose. If you do that, you would need to convert to (index, value) pairs anyway.


Q:

What kind of user info is ok to be stored as plain text in SQL Database?

I'm practicing around building e-commerce asp.net applications that allows for users to register to the site and their user credentials are stored in a MySQL database. In my sample project the registration asks for the users username, password, full name, phone #, email, home address (for shipping of products purposes).
I know its good practice to store the user's password as a salted hash.  But is there any other info that should be stored the same way or not?  For example should the username also be stored as a salted hash or even encrypted?
I guess I'm just wondering what kinds of information is it ok to be stored in plain text in MySQL database for an asp.net web app? And which items are recommended to be stored in a salted hash? And which items should be stored using encryption?

A:

Passwords must be stored hashed always, and make sure they are never logged, for example by query loggers. Hashing is important as opposed to encryption, because it should be a one-way, nonreversible process.
Secret questions to help recover passwords are good to encrypt. As these are secret, and they themselves can reveal something about the user, it wouldn't be good if they got leaked. In addition to revealing something personal about the user, they could also help attackers to make better guesses.
Answers to secret questions should be hashed, as these could be intimate secrets. It can be a good idea to hash a sanitized form, such as lowercased and trimmed, to make it easier for users to reenter correctly.
As for other fields, it's case by case, and depends on many factors. You really need to think through each and every one of them, and evaluate in terms of sensitivity, and decide which method is prudent, or overengineering, or paranoia.
Don't forget to secure the communication channel too. For example if the system is accessible via web, make sure it's https, otherwise your hashing and encrypting makes little difference to your overall security, as everything can be eavesdropped en route between your users and your website.
UPDATE
As @MichaelT pointed out in a comment,
the Payment Card Industry Data Security Standard (PCI DSS) document seems to be a comprehensive document, and well worth reading if you're serious about securing your customer data.
The documents library of PCI may have other interesting items too.


Q:

iPhone UIScroll Fixed Background Not Working

I have an iPhone app where I have a view and following hierarchy.
View
   ImageView
   ScrollView
      OtherItems

I have ImageView background set to an image and ScrollView color to clearColor but still the background is white in simulator and iphone both. Why is that so? Although I can see the background in the IB.

A:

I restarted XCode and it worked!


Q:

Merge multiple m4a files

Is there an easy way to do this?
I have several folders with music files that I want to join. So it would be good if there is a batch solution to this problem.

A:

brew install ffmpeg sox
#!/bin/bash

for f in *.m4a; do ffmpeg -i "$f" "${f%m4a}wav"; done
sox *.wav combined.wav
ffmpeg -i combined.wav -acodec libfaac -ac 2 -ab 192k combined.m4a
rm *.wav

A:

I use Rogue Ameoba's excellent Fission to do this.

Join Files. Drag and drop one file into another to instantly join them
  together.

Not quite a batch process if you've got lots of files to join, but dragging and dropping audio files to concatenate into its window is straightforward. Fission does have a free trial but won't allow you to save anything without degrading the audio.

Are these files you want to join part of the same audio stream that have been split up? Be aware that if you're joining compressed audio, the transitions between one track and another at the point of the join may not be seamless, as the compression process removes part of the audio which may be audible when joined back together (if they're lossless, then there should be no problem).
Alternatively, if you want something free, I beleive Audacity will also do this for you.


Q:

MSTest - How do I initialize log4net for a UnitTest project?

I have a Visual Studio unit test project for testing an ASP.NET MVC project.
Adding the assembly-level log4net.Config.XmlConfigurator attribute to AssemblyInfo.cs doesn't work and other people on SO have found they have to use a direct call to log4net.Config.XmlConfigurator.Configure();
The question is, how can this be done for a unit test? The answer to use Microsoft.VisualStudio.TestTools.UnitTesting.AssemblyInitialize attribute on a class method doesn't work.
For me, this code results in an InvalidOperationException logged in the output window and the test session bombs early.
[TestClass]
public sealed class Startup
{
    [AssemblyInitialize]
    public void Configure()
    {
        System.Diagnostics.Debug.Write("Microsoft.VisualStudio.TestTools.UnitTesting.AssemblyInitialize");
    }
}

Reading the documentation, MSDN says not to use AssemblyInitialize on test projects for ASP.NET since they may be called more than once.
So how can this be done so that log4net is configured before any tests are run?

A:

The answer was that I was mis-using AssemblyInitialize.
Once I'd set the debugger to halt on first chance exceptions I was able to read that my method was not static and I'd not added a parameter accepting a TestContext to it.
A pretty crappy use of an attribute if the method has to be a certain way, if you ask me. Not very discoverable.
Anyway, this works:
[TestClass]
public static class Startup
{
    [AssemblyInitialize]
    public static void Configure(TestContext tc)
    {
        log4net.Config.XmlConfigurator.Configure();
    }
}

Regarding the advice not to use this for ASP.NET test, sod it. It might get run more than once but that doesn't matter.


Q:

mobiscroll date control startYear is not getting set

I have pretty straight forward MobiScroll date component initialization code as follows.
function attachMobiDate(id) {
        var now = new Date();
        $('#'+id).mobiscroll().date({
            minDate: new Date(now.getFullYear(), now.getMonth(), now.getDate()),
            dateFormat: 'dd, M yyyy',
            theme: 'android',
            display: 'modal',
            mode: 'scroller',
            startYear: 2000
        });
    }

Everything is working perfectly. The start year is not getting set. The UI only showing me 2013 and 2014. However, if I set 'endYear' to 2020 its working fine.
May I now whats going wrong here?

A:

OKay, Found my mistake! :)
minDate: new Date(*now.getFullYear()*, now.getMonth(), now.getDate()),

in the initialization part and again trying to set through 'startYear'.
When I modified minDate as below and removed 'startYear', it worked fine!
minDate: new Date(*now.getFullYear()-10*, now.getMonth(), now.getDate()),


Q:

Getting the value from a Select tag (Grails)

I'm having a problem getting the select tag to work for me in Grails. Basically, I am trying to get a value from the select field and use it to sort a list being displayed on the gsp. The select tag looks like this:
<g:select from="['Ascending','Descending']" name="selectTest" id="selectTest" />

I am trying to use g:links to pass the information on. I was hoping I could do something similar to
<g:link action="sort" id="pid" params="[direction:${selectTest.value}]">Sort</g:link>

However, this does not work as the value is always passed as null. I can pass the data I want using a form and an actionSubmit, but I have 3 different tables columns that I need to be able to sort, so determining the desired column would be a pain. Also, there is no domain object being used, so using g:sortableColumn tags doesn't work either.
Is there a way to do this without having to use javascript and hiddenFields? Any advice is greatly appreciated.

A:

The problem was caused by me forgetting to wrap the select tags in a form tag. I wrapped them in a form submit tag and I can now access the information by using the select tags id and clicking on an actionSubmit button.


Q:

MySQL Query for finding distinct values in columns and getting the sum

I am having few Movie DVDs and want to create a simple database in MySQL. PF the DB structure. Am having a MySQL query which actually doesn't list out the exact no. of movies I am having. The query below is -
SELECT SUM(Total) as total
FROM (
SELECT COUNT(DISTINCT(Movie1)) AS Total FROM tbl_movie
      WHERE Movie1 !='' AND Movie1 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie2)) FROM tbl_movie
       WHERE Movie2 !='' AND Movie2 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie3)) FROM tbl_movie
       WHERE Movie3 !='' AND Movie3 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie4)) FROM tbl_movie
       WHERE Movie4 !='' AND Movie4 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie5)) FROM tbl_movie
       WHERE Movie5 !='' AND Movie5 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie6)) FROM tbl_movie
       WHERE Movie6 !='' AND Movie6 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie7)) FROM tbl_movie
       WHERE Movie7 !='' AND Movie7 IS NOT NULL AND DVDCategory='Movie'
) AS Total;

DB Structure -
ID DVD Movie1   Movie2   Movie3      Movie4          Movie5   Movie6   Movie7
__________________________________________________________________
1  1  IronMan  Movie11   MindHunters  300            Jumper   7
2  2  IronMan2 Movie22   Grey         Blood Diamond
3  3  Movie33  Red Eye   Departed     300
4  4  Movie44  Gladiator King Kong
5  5  Movie55  Hitman

It shows 13 results instead of 18 movies in DB. I searched your list of questions, but didn't find any suitable answer. Could you convey where am I going wrong or is there any better way I can arrange this query?

A:

Update -
You are going wrong with the UNION. It removes duplicates. Your inner queries are returning (5,5,4,2,1,1,0) but the union turns them into (5,4,2,1,0) after removing duplicates.
You need to use UNION ALL to count everything. Just replace all UNIONs with UNION ALL
When you do, you will notice that if there are movies across columns i.e. if movie 300 was in column Movie4 and Movie5 for different users, it will count twice.
If you need to just get the distinct movies across all columns, get distinct movies from individual columns first, UNION them to remove duplicates and then count movies.
SELECT COUNT(movie) as total
FROM (
SELECT DISTINCT Movie1 AS movie FROM tbl_movie
    WHERE Movie1 !='' AND Movie1 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie2 FROM tbl_movie
    WHERE Movie2 !='' AND Movie2 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie3 FROM tbl_movie
     WHERE Movie3 !='' AND Movie3 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie4 FROM tbl_movie
     WHERE Movie4 !='' AND Movie4 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie5 FROM tbl_movie
     WHERE Movie5 !='' AND Movie5 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie6 FROM tbl_movie
     WHERE Movie6 !='' AND Movie6 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie7 FROM tbl_movie
     WHERE Movie7 !='' AND Movie7 IS NOT NULL AND DVDCategory='Movie'
) AS AllDistinctMovies;


Q:

using a single variable to index into nested dictionaries

Imagine you have a dictionary in python: myDic = {'a':1, 'b':{'c':2, 'd':3}}.  You can certainly set a variable to a key value and use it later, such as:
myKey = 'b'
myDic[myKey]
>>> {'c':2, 'd':3}

However, is there a way to somehow set a variable to a value that, when used as a key, will dig into sub dictionaries as well?  Is there a way to accomplish the following pseudo-code in python?
myKey = "['b']['c']"
myDic[myKey]
>>> 2

So first it uses 'b' as a key, and whatever is reurned it then uses 'c' as a key on that.  Obviously, it would return an error if the value returned from the first lookup is not a dictionary.

A:

No, there is nothing you can put into a variable so that myDict[myKey] will dig into the nested dictionaries.
Here is a function that may work for you as an alternative:
def recursive_get(d, keys):
    if len(keys) == 1:
        return d[keys[0]]
    return recursive_get(d[keys[0]], keys[1:])

Example:
>>> myDic = {'a':1, 'b':{'c':2, 'd':3}}
>>> recursive_get(myDic, ['b', 'c'])
2

A:

No, not with a regular dict.  With myDict[key] you can only access values that are actually values of myDict.  But if myDict contains other dicts, the values of those nested dicts are not values of myDict.
Depending on what you're doing with the data structure, it may be possible to get what you want by using tuple keys instead of nested dicts.  Instead of having myDic = {'b':{'c':2, 'd':3}}, you could have myDic = {('b', 'c'):2, ('b', 'd'): 3}.  Then you can access the values with something like myDic['b', 'c'].  And you can indeed do:
val = 'b', 'c'
myDic[val]


Q:

Strange text in Ag-grid pagination

I can't post the entire code, but this is the salient part.
$scope.previousCandidatesGrid =
    {
        columnDefs: [ {headerName: "Candidate", field: "candidate_name"},
                      {headerName: "Skills", field: "skills"},
                      {headerName: "Start date", field: "start_date"},
                      {headerName: "End date", field: "end_date"}
                    ],
        rowData: [],  // will be added in $scope.MarkerClicked()
        pagination: true,
        paginationAutoPageSize: true,
    };

only the last two lines are necessary to add automating pagination according to the documentation.
The grid continues to display correctly - at least, its contents do. However, the pagination text looks which AG-grid generateslike this (sorry, I can't select it and copy/paste here):

clicking the "strange text" allows me to page to start/end and back forward by a page.
It's probably just a character set thing, but I don't know how to fix it. Any ideas?

[Update] as per @georgeawg's comment, I inspected those elements and got this (apologies that it is an image, I can't figure how to copy/paste it as text):

[Update 2] I had think that this might be either a charset problem, or CSS. I have added both ag-grid.min.csss and ag-theme-balham.min.css (because I declared the grid in HTML as

), but that did not help.

A:

Just in case someone else has the same problem in future - it was the character set.
I changed

to

        <meta charset="utf-8"/>

i.e I added the language and charset info, now I see


Q:

Обязательное поле для заполнения (TextView)

Как сделать текстовое поле EditText обязательным для заполнения?
Что бы при нажатии на кнопку отправки сообщения, приложение не отправляло пустое сообщение, а проверяла на наличие информации в текстовых полях и при пустом поле кнопка игнорировала нажатие.

A:

Если в виджете нет текста (включая только пробелы) - заблокировать клик на виджете, если текст есть - разблокировать:
    textView.setClickable(!(textView.getText().toString().trim().equals("")));

или
    int l = textView.getText().toString().trim().length();
    textView.setClickable(l == 0 ? false: true);

Вызывать всякий раз когда необходимо проверить контент в виджите на предмет его наличия, либо отсутствия и соответственно позволить обработать клик на виджете или нет.
Подходит для любого виджета, который отрабатывает клики и может содержать текст. В данном случае на примере TextView


Q:

Can I use .delay() together with .animate() in jQuery?

I have this code, which slides open a basket preview on a website I am working on. It stays open if the user is hovered on it, but I want it to have a two second delay before the callback for my hover is triggered. This is just in case the user didn't want the mouse to leave the basket area.
Below is the code I am using to animate the basket:
$('.cart_button, .cart_module').hover(function(){
    $(".cart_module").stop().animate({top:'39px'},{duration:500});
}, function(){
    $('.cart_module').stop().animate({top: -cartHeight},{duration:500})
});

Here is the code I tried to use, but had no affect:
$('.cart_button, .cart_module').hover(function(){
    $(".cart_module").delay().animate({top:'39px'},{duration:500});
}, function(){
    $('.cart_module').delay().animate({top: -cartHeight},{duration:500})
});

A:

If you add the stop before the delay it works just fine:
$('.cart_button, .cart_module').hover(function() {
    $('.cart_module').stop(true, true).delay(100).animate({top:'39px'}, 400);
  },
  function() {
    $('.cart_module').stop(true, true).animate({top: -cartHeight}, 250);
});

A:

Looks like there may have been updates to jQuery in this vein since 2011. In Chrome I can use this sans timeout calls:
$('.thing').hover(function(){
    $(".thing").delay(2000).animate({top:'39px'},{duration:500});
}

A:

I've always managed this kind of things with the help of core setTimeout and clearTimeout js functions.
Here is an example on jsFiddle
Take a look at jquery.hoverIntent plugin too, it gives you a timeout on hover and out events


Q:

how to bind ArrayList to JList

i have a JList and an ArrayList.How to bind the datas in arraylist to the jlist.Are the any alternative methods?
    ArrayList arl = new ArrayList();
    arl.add("1asdsd");
    arl.add("2asdsd");
    arl.add("3asdsd");
    Object obj = arl.clone();
    JList list = new JList(obj);

how to bind the above code.Now the code give an error.

A:

You don't need to clone the ArrayList. Just call toArray()
JList list = new JList(arl.toArray());

A:

ArrayList<String> aList = new ArrayList<String>();
aList.add("blabla");
aList.add("blublu");
aList.add("blibli");
aList.add("bleble");
DefaultListModel<String> model = new DefaultListModel<String>();
for(String s:aList){
    model.addElement(s);
}
JList<String> contactList = new JList<String>(model);

Advantage of this is that you can later add/remove elements to already instantiated JList by adding elements to model using methods addElement(Obj o) and removeElement(Obj o).

A:

JList jList = new JList(arrayList.toArray());


Q:

Tracking how many cars are rented and available in a Class

I've been having some trouble with this code. This is an assignment for my java class.its past due but I'm going nuts just trying to figure out the problem.
Problem:
When I upload it to WileyPlus(automatic correcting server), it keeps saying that when 'int n = 14' it's expecting the result to be "24 , 15", but I get "23, 16". However, when I enter 12 I get what is expected, which is "7,5". I can't seem to find what's causing this.
With the code, it will make more sense.
public class RentalCar {
    private boolean rented;
    private static int availableCars = 0;
    private static int rentedCars = 0;

    public RentalCar() {
        availableCars++;
        rented = false;
    }

    public static int numAvailable() {
        return availableCars;
    }

    public static int numRented() {
        return rentedCars;
    }

    public boolean rentCar() {
        availableCars--;
        rentedCars++;
        rented = true;
        return rented;
    }

    public boolean returnCar() {
        if (rented) {
            availableCars++;
            rentedCars--;
            rented = false;
        }

        return false;
    }

    public static String check(int n) {
        RentalCar[] cars = new RentalCar[n];
        for (int i = 0; i < n; i++) {
            cars[i] = new RentalCar();
        }

        for (int i = 0; i < n; i = i + 2) {
            cars[i].rentCar();
        }

        for (int i = 0; i < n; i = i + 3) {
            cars[i].rentCar();
        }

        for (int i = 0; i < n; i = i + 4) {
            cars[i].returnCar();
        }

        return RentalCar.numRented() + " " + RentalCar.numAvailable();
    }
}

A:

In returnCar() you check, if the car you are trying to return is rented. In rentCar() you don't do that. It seems you can rent a car that's already rented. Try to prevent renting cars that are already rented.


Q:

Characterization of Frobenius complements

I have learned that Frobenius complements are characterized (among finite groups) by having a fixed point free complex representation.
That is, a finite group $G$ is a Frobenius complement if and only if there is a finite dimensional complex representation $\rho:G\to GL(V)$ so that the linear mapping $\rho(g)$ has no nonzero fixed points for any $g\in G\setminus\{1\}$.
Is there a citable reference for this fact?
I have found references that mention that this is well-known.
For example:

It is well-known that a finite group $H$ has the structure of a Frobenius complement if and only if it can act fixed-point-freely on some finite group $G$ (this means that non-trivial elements of $H$ fix only the identitty element of $G$).
  Equivalently, we may require that $H$ acts fixed-point-freely on some elementary abelian group $E$, or on a linear space $V$ over a field of characteristic zero.
  (Aner Shalev: A new characterization of frobenius complements)

I'm aware of Passman's book Permutation groups, but it does not state this characterization.
I would prefer a reference that states this characterization explicitly (and preferably includes a proof).
My intended audience does not have a strong background in representation theory, so references of a more implicit kind ("this can be inferred from various results in this book" or "it is folklore/well-known/true that…") would be inconvenient.

Edit:
The references and descriptions given in the comments and the answer are very useful but do not contain an explicit reference for the representation theoretical characterization of Frobenius complements I'm looking for.
The direction that Frobenius complements have fixed-point-free representations is given as Theorem 18.1v in Passman's book, but the other direction is still missing.

A:

Since you are asking for a justification of the characterization of Frobenius complements by a representation-theoretic property I am not sure that you can completely avoid representation theory altogether. Also this characterization of Frobenius complements is genuinely "folklore"-something which anyone who has worked seriously with Frobenius groups would be likely to know. I am not sure who first proved it-one place to look is work of H. Zassenhaus, who proved, for example, that ${\rm SL}(2,5)$ is the only perfect Frobenius complement.
Anyway, the proof of the direction " A Frobenius complement $H$ has an irreducible complex representation with each non-identity element acting without the eigenvalue 1" is as given in the comments of Derek Holt and myself- I know of no other way to do it, other than to show that $H$ has such an irreducible representation in characteristic $q \neq 0$ coprime to  $|H|$ in which each non-identity element has no non-trivial fixed-points. This may not be absolutely irreducible, but it is a sum of Galois conjugate absolutely irreducible representations, still over a finite field, and no non-identity element of $H$ has the eigenvalue $1$. The theory of Brauer characters shows that $H$ has a complex irreducible representation with the same property.
The opposite direction is similar. If $H$ has an irreducible complex representation in which no non-identity element has the eigenvalue $1$, we can reduce the representation (mod $q$) for any prime $q$ not dividing $|H|$, obtaining an absolutely irreducible representation over a finite field of characteristic $q$. Possibly increasing the dimension, we obtain an irreducible representation of $H$ over ${\rm GF}(q)$ such that each non-identity element of $H$ has no non-zero fixed point on the underlying module, say $V$. Then the semidirect product $HV$ is a Frobenius group with complement $H.$
If you want to get by without telling your readers all details, it would probably be reasonable to sketch the proof of the first direction (the necessary facts about coprime action can be found in many texts, eg Gorenstein's "Finite Groups"), and then to point out that the representation theory of $H$ in coprime characteristic is "essentially the same" as the complex representation theory, then to point out that the proof in the other direction follows for the same reason. The technicalities about fields of realizability, and worrying about realizability over the prime field, are probably best omitted in any case, at that level.
(By the way, $H$ acting in a Frobenius manner on a vector space is a much stronger requirement than $H$ acting fixed point freely. A Frobenius action of $H$ means that no non-identity element of $H$ has a non-zero fixed vector. To say "$H$ acts fixed-point freely" means (in common usage) that there is no non-zero vector fixed by all of $H$).

A:

I don't have enough reputation to comment, but if you're still looking for a reference, this is basically theorem 25.5 in Feit's Characters of Finite Groups.
Here is the exact statement of the theorem:

Let $C\neq\{1\}$ be a group. There exists a Frobenius group $G$ with kernel $K$ such that $G/K\cong C$ if and only if there exists an irreducible character $\chi$ of $C$ such that for every subgroup $1<H\le C$,
  $$ \langle \chi_H,1_H\rangle=0$$


Q:

UFT connection with Redshift

We are getting error while trying to connect UFT with Redshift:
Dim  dbConnection
Srvname = "Driver={Amazon Redshift (x64)};Server=serverName; Database=DBName; UID=****; PWD=****; Port=****;"
Set dbConnection = CreateObject("ADODB.Connection")
dbConnection.Open Srvname

Error coming as:
Datasource name not found and no default driver specified.

But with all same credential we can able to connect redshift with "SQL Workbench".

A:

SQL Workbench is using a different Connector (most probably JDBC or some other technology). The ADODB.Connection Object is trying uses the ODBC Drivers installed for the Operating System, so first things frist you need to install the ODBC Driver.
After this is don, depending on your credential management policy, you may need to simply use the proper Connection String or configure stuff in the ODBC wizard of Microsoft Windows.


Q:

Qt 5.9.0 to 5.9.4 work fine, but Qt 5.9.5 and 5.9.6 have issues

I'm playing around with this repo: https://github.com/qt-labs/qt3d-editor
My observation:

When using Qt 5.9.0, 5.9.1, 5.9.2, 5.9.3 and 5.9.4, the application can import files, like STL.
But with Qt 5.9.5 and 5.9.6 the application cannot import any file, it gets stuck in import process and never finishes importing. Also, the same issue happens when working with Qt 5.11.

I assume it might be related to Qt3D module. The 5.9.5 change log for Qt3D mentions that only minor code improvements are done. Can anybody give a hint why this is happening?

The screen shot of import button getting stuck is shown below:

A:

Tested with Qt 5.11.2 and it works fine. Take a look at this:
Importing objects in Qt3D doesn't work but there's not error message


Q:

How to release memory allocated in custom Constructor in SWIG?

I have a memory-management question in SWIG.
I have this object in C++ (TestStruct.h):
struct Buffer {
    uint8_t* data;
    int length;
}

I want to be able to initialize this object using a python list or string and destroy it from python without memory leak.
my swig file is:
%module test

%newobject Buffer;
%nodefaultctor Buffer;
%nodefaultdtor Buffer;

%{
    #include "TestStruct.h"
%}

%include "TestStruct.h"

%extend Buffer {
    Buffer(PyObject* inputList)
    {
        int leng = (int)PySequence_Length(inputList);
        uint8_t* temp = new uint8_t[leng];
        cout << "Buffer Constructor called: " << leng << "  " << (unsigned int)temp << endl;
        for(int i=0; i<leng; i++){
            PyObject *o = PySequence_GetItem(inputList,i);
            if (PyNumber_Check(o)) {
                temp[i] = (uint8_t) PyLong_AsLong(o);
                //cout << "uint8_t to C++: " << (int)temp[i] << endl;
            } else {
                PyErr_SetString(PyExc_ValueError,"Sequence elements must be integers");
                return NULL;
            }
        }
        Buffer* buff = new Buffer();
        buff->dataBuf = temp;
        buff->length = leng;
        return buff;
    }

    ~Buffer() {
        cout << "Buffer Destructor called: " << $self->length << "  " << (unsigned int)$self->dataBuf << endl;
        delete[] $self->dataBuf;
        delete $self;
    }
}

Running the simple test below sky-rockets the Python's memory usage to 30MB
import test
import sys
import time

times = 1000
printsteps = False
print("performing memory stress test")
for j in range(times):
    sizeBytes = 1024 * 1
    input_list = list(range(sizeBytes))
    buffer = test.Buffer(input_list)

    del buffer
    time.sleep(0.001)

each time the loop is run, both the constructor and destructor are called (I validate that with printouts), but it won't solve the memory allocation problem.
I need the Buffer to pass it as an argument to another SWIG-wrapped function and I want to be able to create the Buffer's data using a python list. I tried using typemaps (in and freearg) with more or less the same code, but it failed. So I figured out to use custom constructors and destructors, but it won't solve the problem with memory leak. Any input welcome

A:

Your usage of the Python C-API in converting the Python list to a C++ uint8_t[leng] is incorrect and causing the memory leak. The point is that the function PySequence_GetItem() returns a new reference to the sequence item. Because you fail to call Py_DECREF() on that item, Python will not release the memory for that item when the list itself gets deleted.
To fix, you simply need to add Py_DECREF(o); in the for loop.
By the way, the line del buffer in the Python loop is superfluous.


Q:

Один функция два элемента

$("#tel") || $("#code").keyup(function(){
    //code
});

Как сделать рабочим этот код?
Я хочу получить результат от обоих элементов!

A:

Передайте в функцию список селекторов/классов/id через запятую
$("#code, #tel").keyup(function(){
    //code
});


Q:

Connection refused while connecting from polybase to hadoop

While trying to create external table from sql server 2017 to Hadoop in Ubuntu 16.04 it throws the below error

Msg 105019, Level 16, State 1, Line 1
  EXTERNAL TABLE access failed due to internal error: 'Java exception raised on call to HdfsBridge_IsDirExist. Java exception message:
  Call From DESKTOP-VE8KNAG/xxx.xxx.x.xxx to xxx.xxx.x.x:54310 failed on connection exception: java.net.ConnectException: Connection refused: no further information; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused: Error [Call From DESKTOP-VE8KNAG/1xxx.xxx.x.xxx to xxx.xxx.x.x:54310 failed on connection exception: java.net.ConnectException: Connection refused: no further information; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused] occurred while accessing external file.'

External source location is fetched from core-site.xml
Tmp folder is created and added permission to the user and added it in core-site.xml
All nodes are running in Hadoop
 10625 DataNode
10869 SecondaryNameNode
17113 ResourceManager
17434 NodeManager
10490 NameNode
21566 Jps

sql query
create EXTERNAL DATA SOURCE [HDP2]
WITH (TYPE = HADOOP,
 LOCATION = N'hdfs://xxx.xxx.x.x:54310',
 CREDENTIAL = [HDPUser])
GO

create EXTERNAL TABLE [dbo].CLASS_DIM_EXP (
    [CLASS_ID] [varchar](8) NOT NULL,
    [CLASS_DESC] [varchar](100) NULL,
    [INSERT_DATE] [datetime2](7) NOT NULL,
    [LAST_UPDATE_DATETIME] [datetime2](7) NOT NULL)
WITH   (LOCATION='/user/pdw_user',
DATA_SOURCE = HDP2,
FILE_FORMAT = TSV,
REJECT_TYPE = VALUE,
REJECT_VALUE = 0);

Core-site.xml
<property>
  <name>hadoop.tmp.dir</name>
  <value>/app/hadoop/tmp</value>
  <description>A base for other temporary directories.</description>
</property>

<property>
  <name>fs.default.name</name>
  <value>hdfs://localhost:54310</value>
  <description>The name of the default file system.  A URI whose
  scheme and authority determine the FileSystem implementation.  The
  uri's scheme determines the config property (fs.SCHEME.impl) naming
  the FileSystem implementation class.  The uri's authority is used to
  determine the host, port, etc. for a filesystem.</description>
</property>

Is that something needed to be changed?

A:

The problem here is cores-site.xml file contains hdfs://localhost:54310 need to replace this with the corresponding IP address hdfs://xxx.xxx.x.x:54310.


Q:

file system vs url in php

I have built a little custom framework that is based on MVC architecture and I have both BASE_URL which would be something like 'http://example.com' and ROOT which would be something like '/Applications/XAMPP/htdocs/WEBSITENAME/'. I am trying to get a general consensus as to which is better to use when this would be deployed to a server. I do have ssh access to the server that it would be released on. I just honestly do not know which is preferred or why. I did a lot of googling and found conflicting arguments so I thought I would ask here since I trust this community. So Anyone have thoughts on which is better and why?
Oh, if it matters we are trying to use httpd-vhost.conf to create the web directories and no .htaccess files, and we are trying to remove all mod_rewrite. Not sure if that matters, but I thought I would give the info just in case.
Thank you all for your help in advance.
EDIT** I guess I should also mention that I do not mean when I am creating links, I mean for including css sheets, or js files, or including and requiring other php files, those types of actions.

A:

You have 2 cases:

for interacting with other files on the sever's side, while the php script is still executing - operations like including / requiring other php files, fopen-ing resources and so on you use paths relative to your ROOT.
for including CSS, javascript, images and so on - on client side - you're going to use the BASE_URL.

For example, in PHP:
require_once ROOT . DIRECTORY_SEPARATOR . 'my_configuration_file.php';

in the HTML:
<img src="<?=BASE_URL;?>/img/logo.png" alt="my company">

But consider using an existing PHP framework. It will make your life easier and let you focus on your product / site rather than maintaing it.


Q:

How much effort goes into designing and laying out a PC motherboard?

How much effort goes into designing and laying out a PC motherboard? By this, I do not include Intel's IP etc, but I do including having to read all the documentation concerning the chipsets. And getting it to work, if not 100% tested

A:

For a point of reference developing a reference design for a dual processor server type motherboard typically consumes the efforts of:

Three or four board design engineers who own the design and guide its way through development. Testing and verification of the electrical design is part of this work.
Four signal integrity engineers performing simulations on board stackup and waveform analysis for busses like DDR3, PCI3, USB, SATA, SMBUS, RMII, CHipSet Busses etc.
Two CAD engineers working board layout for a 8 or 10 layer board.
One or two mechanical engineers working on packaging, cabling and other mechanical details including board outline, mount holes and heatsinks.
One regulatory engineer who owns taking the board through emissions, immunity and safety testing.
One or two manufacturing and test engineers to review the design and assure that it meets the needs for high volume manufacturing.
One product development manager who owns the project schedule and manages the budget.
One or two BIOS engineers that support adapting a reference BIOS to the specific requirements of the board/system.

Expect the average design to require two re-spins. Through this process expect the board design engineers to be involved for 10 to 16 months. Other disciplines will be involved for lesser amounts of time.
This also assumes that the boards are built by a contract manufacturer that provides support to procure parts.
Not included here is the team of people that would be involved with validating the design from a performance and system functionality standpoint including the OS compatibility.

A:

I feel that I should mention standardized computer-on-modules (COMs), which take almost all of the headache out of designing your own motherboard (if that is your goal). These are basically nearly complete computers where you just need to design a carrier board to expose the functionality you're interested in.
As an example, I just designed a carrier for a COM Express mini module. My carrier exposes a single 1xPCIe, Gb ethernet, USB, I2C, SPI, GPIO, and HDMI (and power, of course). I was able to do all of this on a four-layer PCB, which ended up costing me $800 for 25 boards (which really isn't bad at all). I assembled everything myself (parts costing about ~$40 per board, plus $375 for the COM itself), but you can pay more to have the board house do that for you.
It took me about a week and a half to design my carrier board, and the great thing is there are several vendors selling the form factor I chose, so I can switch if needed.


Q:

Calculate margin based on elements and container size?

In my snippet below, I have three circles that act as a navigation, the circles are 15px by 15px, the container is a percent and can change at any time.
I am using margin-right as a percent, and just guessing the appropriate value. What I want to know, is there a formula to calculate the appropriate margin-right so that the circles are evenly spaced from end to end, dynamic so that I can add remove circles?
Is there a better solution, I tried flex-box but I could not get it to work.

ul {
  margin: 0;
  padding: 0
}
.guide-bar {
  position: relative;
}
.guide-bar:before {
  content: "";
  position: absolute;
  height: 1px;
  top: 7px;
  width: 100%;
  background-color: #303B44;
  color: #303B44;
  z-index: -1;
}
.guide-bar ul li {
  background-color: #fff;
  cursor: pointer;
  position: relative;
  list-style: none;
  display: inline-block;
  width: 15px;
  height: 15px;
  border: 2px solid;
  border-radius: 100em;
  margin-right: 39.56666%;
}
.guide-bar ul li:last-child {
  margin-right: 0;
}
.guide-bar ul li.active:before {
  content: "";
  position: absolute;
  height: 5px;
  width: 5px;
  background-color: #2AA1FA;
  border-radius: 100em;
  margin: auto;
  left: 0px;
  right: 0;
  top: 0;
  bottom: 0;
}
.guide-bar ul li.active:after {
  content: "";
  position: absolute;
  height: 25px;
  width: 25px;
  border: 1px solid #2AA1FA;
  border-radius: 100em;
  margin: auto;
  left: -7px;
  right: 0;
  top: 0;
  z-index: -1;
  bottom: 0;
}
.guide-bar ul li.watched {
  color: #4bd495;
  background: #4bd495;
}

A:

You can justify align inline-block elements with this technique: "text-align: justify;" inline-block elements properly?
Also, you can use percentage on the top and left and then use negative margin-top and margin-left on this rule .guide-bar ul li.active:after to make it align from center
Also, for drawing circle with border-radius, set it to 50%...
have a look here: http://jsfiddle.net/2vcuxt4k/2/

.guide-bar ul {
  text-align: justify;
}
.guide-bar ul:before {
  content: '';
  display: block;
  width: 100%;
}
.guide-bar ul:after {
  content: '';
  display: inline-block;
  width: 100%;
}
.guide-bar ul li.active:before {
  content: "";
  position: absolute;
  height: 5px;
  width: 5px;
  background-color: #2AA1FA;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  margin-top: -2.5px;
  /* half the size of the circle, including the border */
  margin-left: -2.5px;
}
.guide-bar ul li.active:after {
  content: "";
  position: absolute;
  height: 25px;
  width: 25px;
  border: 1px solid #2AA1FA;
  border-radius: 50%;
  z-index: -1;
  top: 50%;
  left: 50%;
  margin-top: -13.5px;
  /* half the size of the circle, including the border */
  margin-left: -13.5px;
}


Q:

Trying to Sort in Java 8 with Nulls in the Data

I am trying to sort a list that I get by the comparator given. I am passing the comparator through the NullsLast method to get a Null-Friendly version of my comparator like the JavaDoc states. However, when I run the code I am still getting a Null Pointer Exception when I pass a String comparator to the method.
private <T> void sortWithDirection(List<T> details, boolean isAscending, Comparator<T> comparator){

    if(isAscending){
        details.sort(Comparator.nullsLast(comparator));
    } else {
        details.sort(Comparator.nullsLast(comparator.reversed()));
    }
}

List<UserDTO> users = new ArrayList<>();
sortWithDirection(users, false, Comparator.comparing(UserDTO::getName));

Am I using this method wrong? Is there a different way that I can prevent NPEs without removing them from the result set?

A:

nullsLast will handle the case of UserDTO being null.  It will not save you from getName returning null.  To handle null names, you would need to apply nullsLast before comparing:
details.sort(comparing(
    UserDTO::getName,
    nullsLast(naturalOrder())
));

or, for reverse order:
details.sort(comparing(
    UserDTO::getName,
    nullsLast(reverseOrder())
));


Q:

Is it possible to use IMU of a phone in order to improve a user's walking path?

I have a service, from which I get the user's location on an interval of time (e.g. 7 seconds). The walking path is displayed on the map, but as you can see there're many invalid locations, since the GPS receiver is trying to obtain the exact current position.

The blue one is the displayed walking path and the black one is the actual walked. I was thinking of using the IMU as kind of a filter in order to check whether the retrieved location is on the path, or the location provider needs more time to update it.
Is it possible doing it in this way?

A:

Yes in theory its possible to improve the GPS position with an IMU, but it requires a Kalman-Filter, which is not trivial to set up correctly and get it working correctly on range of devices. There lots of resources on the internet explaining how a Kalman-Filter works and what it can be used for.
I also recommend reading this blog post: https://blog.maddevs.io/reduce-gps-data-error-on-android-with-kalman-filter-and-accelerometer-43594faed19c . The authors pretty much wanted to achieve the same thing as you by using a Kalman-Filter. They also published a library on github for a Kalman-based location estimation.


Q:

Mysql query variable inside function

<?php

function get_msg($c_id_fk) {

    $messages = $sql->query("SELECT * FROM conversation_reply WHERE c_id_fk = $c_id_fk");

    return $messages;

}

?>

How do I query a mysql database using a variable within a function. I'm using  $sql = new MySQLi($host, $username, $password, $database); to connect my database but and it is definitely connected because I can query it without using functions.
<?php $messages = get_msg(1);
                    foreach ( $messages as $message ) {
            ?>

            <div class="bubble <?php
                    if ( $message['user_id_fk'] == $uid ) {
                        echo "from-me";
                    }
                    else {
                        echo "from-them";
                    }?>">

                <?php echo $message['c_id_fk'];?><?php echo $message['user_id_fk'];?><?php echo $message['reply'];?>

            <?php } ?>

A:

$sql does not exist in the function's scope.  You need to pass $sql to the function, avoid using globals.  Read into variable scope.
function get_msg($sql, $c_id_fk) {

    // Protect against injections
    $c_id_fk = (int) $c_id_fk;

    $messages = $sql->query("SELECT * FROM conversation_reply WHERE c_id_fk = $c_id_fk");

    return $messages;

}

get_msg($sql, 1);


Q:

How to redirect python runtime errors?

I am writting a daemon server using python, sometimes there are python runtime errors, for example some variable type is not correct. That error will not cause the process to exit.
Is it possible for me to redirect such runtime error to a log file?

A:

It looks like you are asking two questions.
To prevent your process from exiting on errors, you need to catch all exceptions that are raised using try...except...finally.
You also wish to redirect all output to a log. Happily, Python provides a comprehensive logging module for your convenience.
An example, for your delight and delectation:
#!/usr/bin/env python

import logging
logging.basicConfig(filename='warning.log', level=logging.WARNING)

try:
    1/0
except ZeroDivisionError, e:
    logging.warning('The following error occurred, yet I shall carry on regardless: %s', e)

This graciously emits:
% cat warning.log
WARNING:root:The following error occurred, yet I shall carry on regardless: integer division or modulo by zero


Q:

drop down list combo box excel

I have a searchable combo box with suggestions to select from as I type letters in it (vba below). However i want to be able to click the arrow of the combo box (if i don't type anything else in it of course) and see the entire drop down list. For some reason the code below does not show me the entire list if I click the arrow.
Any suggestions much appreciated.
    Dim ws As Worksheet
    Dim x, dict
    Dim i As Long
    Dim str As String
    Set ws = Sheets("Lists")
    x = ws.Range("Listing").value
    Set dict = CreateObject("Scripting.Dictionary")
    str = Me.cbo1.value
    If str <> "" Then
     For i = 1 To UBound(x, 1)
    If InStr(LCase(x(i, 1)), LCase(str)) > 0 Then
        dict.Item(x(i, 1)) = ""
    End If
    Next i
     Me.cbo1.List = dict.keys
   Else
    Me.cbo1.List = x
   End If
   Me.cbo1.DropDown

A:

What you want is that if the arrow is clicked when nothing is yet selected or written in the combo by the user, to show all the items of the list, which you load from the named range "Listing" without any filtering.
To do so, add this event handler to your userform's code:
Private Sub Cbo1_DropButtonClick()
  'If Len(Trim(cbo1.text)) = 0 Then
  If Trim(cbo1.text) = "type here" Then
    cbo1.List = Sheets("Lists").Range("Listing").Value
    Exit Sub
  End If

  ' Your code to add only items that match the characters typed by the user
  ' ...
End Sub


Q:

Can anyone explain with multidimensional arrays in C#

I am new to this and am very confused. How do I set arr[55000][7], save the values in server (using ASP.NET with C#) and increase the array range whenever needed. I did not find a method to change two dimensional array size in C#.
In addition, my requirement is:
Variable Name      Values
Variable 1           =  ( 2, 4) , ( 5, 1)
Variable 2            =   ( 7, 4) , ( 1, 3)
Variable 3            =   ( 5, 7) , ( 5, 1)
Variable 4            =   ( 2, 4) , ( 2, 1)
Variable 5            =   ( 9, 8) , ( 2, 4)
Variable 6            =   ( 3, 4) , ( 5, 7)
Variable 7            =   ( 4, 7) , ( 4, 2)
Variable 8           =   ( 5, 4) , ( 5, 7)
Etc….
(This data will be stored on server.)

Now for example user give input variable 1, 4, 5, 7
The calculator will show result =( 2, 4).

I am getting to work on this but with no help. Can anyone guide me in this please

A:

This would be a simple implementation for a list of lists:
       List<List<int>> myList = new List<List<int>>();

       myList.Add(new List<int>());
       myList.Add(new List<int>());
       myList.Add(new List<int>());

       int list = 0;
       int element = 6;

       myList[0].Add(5);
       myList[list].Add(element);

If we inspect my list we have

You can then add or remove as you wish.
Edit
if you want to use a string name such as "Variable" 1 to get or set those values we need to change the structure a little.
First we declare a structure to hold the values in pair.
    class Valuegroup
    {
        public int FirsValue { get; set; }
        public int SecondValue { get; set; }
    }

Then what we need is collection key values pair, where the key must be unique. In .Net we can use Dictionary structure to achieve it.
We declare it as following:
        Dictionary<string, List<Valuegroup>> myList = new Dictionary<string, List<Valuegroup>>();

With the above declaration we will be able to use the key string Variable 1 , Variable 2 , Variable 3 ect as unique key. Then we can add our values as groups in the List<Valuegroup>. Each list element will represent a group of items such as (2, 4) , (5, 1) etc.
Putting it all together:
    class Valuegroup
    {
        public int FirsValue { get; set; }
        public int SecondValue { get; set; }
    }
    static void Main(string[] args)
    {
        //Variable 1 = (2, 4) , (5, 1)

        Valuegroup first = new Valuegroup
        {
            FirsValue = 2,
            SecondValue = 4
        };

        Valuegroup second = new Valuegroup
        {
            FirsValue = 5,
            SecondValue = 1
        };

        Dictionary<string, List<Valuegroup>> myList = new Dictionary<string, List<Valuegroup>>();
        myList.Add("Variable 1",new List<Valuegroup>{first,second});

        //retrive a value using a key name eg Variable 1
        List<Valuegroup> temp = new List<Valuegroup>();
        myList.TryGetValue("Variable 1", out temp);

        //do a search using Linq
        var t = myList.Where(x => x.Key == "Variable 2");
    }

This shows what myList contains

And here you can see that getting a value using key "Variable 1" return the correct result. Meanwhile doing a search for "Variable 2" held no results.


Q:

Replacing inner div content?

I'd like to replace the following inner div content:

$37

with this:
$37 $19

The $37 gets striked through and the new price is displayed next to it.  The above
 is generated dynamically.
I have tried the following but it isn't doing anything:
$( "div.price" ).replaceWith("$37 $19");

I'm trying this in jquery but is there a way to do it in angular?  I guess the issue with angular is that I can't add directives to the above code.

A:

run the code on document ready
// Code goes here
$(function(){
$( "div.price" ).html("$37 $19")
});


Q:

Optimize YUY2 to I420 conversion

I am writing a video conference application with x264 as encoder. I receive YUY2 raw frames from the webcam and then convert them into I420, as requested by x264. The problem is - I wrote conversion algoritm by myself and it is not so fast (up 20% of the whole CPU time, data provided by profiler). How can I make it faster? Here is my code:
int YUY2ToI420(BYTE *in, BYTE *out){

    long pixels = _width * _height;
    long macropixels = pixels / 2; // macropixel count
    // new size will be w * h * 3/2 -> 12 bits per pixel 4:2:0

    long mpx_per_row = info.biWidth / 2;

    // for each macropixel
    for (int i = 0, ci = 0; i < macropixels; i++){ // ci is chroma index
        // get macropixel address, order is Y0 U0 Y1 V0
        BYTE *mpAddress = in + i * 4;

        // copy luma data
        out[i * 2] = mpAddress[0];
        out[i * 2 + 1] = mpAddress[2];

        // copy chroma data - we skip odd rows because of 4:2:0 sampling
        long row_number = i / mpx_per_row;
        if (row_number % 2 == 0) {
            out[pixels + ci] = mpAddress[1]; // shift by Y vector
            out[pixels + pixels / 4 + ci] = mpAddress[3]; // shift by Y and U vector
            ci++;
        }
    }

    return pixels * 12 / 8; // I420
}

A:

I would highly recommend you use sws_scale from the ffmpeg project. It has optimized functions for most CPU and color formats. You could also use opencv I believe, but I have no first hand experience with it.


Q:

Javascript Value in Object returns Undefined

I'm doing an AJAX request with jQuery and trying to access the value in an object that is returned by the Post request , but when i try to use it like this result.VideoCode it shows undefined ( using console.log ) but when i do a console.log(result) it shows that there is an object and there is data in it
here is a screenshot

Any ideas tho why this is happening and how can i fix it ?
Update:// the server was returning an array of objects with a single object in it ... so that solved the mystery ... should have figured it out earlier

A:

Looking at the screenshot, result is an array containing one object.
You'd need to access it like:
result[0].VideoCode

which means: The first element of results, then from that object the VideoCode property.


Q:

Why is $\mathbb F_2 [X] / \langle X^2 + X + 1 \rangle \cong \mathbb F_4$?

What's the easiest way to see why $\mathbb F_2 [X] / \langle X^2 + X + 1 \rangle \cong \mathbb F_4$?
The polynomial is irreducible in $\mathbb F_2 [X]$, but that's about the only observation I've made...
Thanks

A:

Since the polynomial is irreducible, the quotient is a field. Since it has degree two, the dimension over $\mathbb F_2$ of the quotient is two.
Now, there is exactly one extension of $\mathbb F_2$ of dimension two over $\mathbb F_2$, namely $\mathbb F_4$, so the quotient has to be  $\mathbb F_4$ :)


Q:

Criar uma sessão no PHP

Estou tentando fazer com que o sistema de login do meu site crie uma sessão para o usuário logado, fazendo com que apareça seu nome na página seguinte que ele logar, mas não está aparecendo. Segue o código:
verificar_login.php
<?php
session_start();
$_SESSION['nome'] = $_POST['NOME'];
$_SESSION['senha'] = $_POST['SENHA'];

include 'bd.php';

if($_POST["NOME"] == "geral" && $_POST["SENHA"] == "geral"){
     echo
                "";
}

$link = mysqli_connect($servidor,$usuario,$senha,$banco);

if(isset($_POST["NOME"]) && isset($_POST["SENHA"]))
    {
        if(!empty($_POST["NOME"]) && !empty($_POST["SENHA"]))
        {
                $sql = "select * from empresa where  NOME =             '".$_POST['NOME']."' and SENHA = '".$_POST['SENHA']."';";

                $result = $link ->query($sql);

            if($result->num_rows > 0) {

            $_SESSION['nome'] = $nome;
            $_SESSION['senha'] = $senha;

            echo
                "";
            }

            else{
                unset ($_SESSION['nome']);
                unset ($_SESSION['senha']);
                echo
                "";

             }

index2.php
<?php
session_start();

if((!isset ($_SESSION['nome']) == true) and (!isset ($_SESSION['senha']) == true))
{
    unset($_SESSION['nome']);
    unset($_SESSION['senha']);
    header('location:index.php');
}
?>

<!DOCTYPE html>

<title>EVA system</title>
<meta charset="UTF-8">

Bem-Vindo, <?php echo $_SESSION['nome']; ?>

A:

As seguintes linhas estão estranhas ao meu ver:
 $_SESSION['nome'] = $nome;
 $_SESSION['senha'] = $senha;

As variáveis $nome e $senha não foram instanciadas, a session ficará sem dados nenhum nos respectivos campos. Você pode remover essas duas linhas, pois já está atribuindo os valores passados por POST antes:
$_SESSION['nome'] = $_POST['NOME'];
$_SESSION['senha'] = $_POST['SENHA'];