text:
Q: Get selected items from Listbox I am creating Windows Phone 8 app working with Nokia Mix Radio SDK. I have Listbox contains Genres. Each item (genre) in the ListBox has CheckBox, so that user can select only items he wants to listen to. How can I know what genres user selected?
Here is my XAML:
<phone:PhoneApplicationPage
x:Class="MusicApp.GenrePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel Grid.Row="0" Margin="12,17,0,28">
        <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <ListBox x:Name="GenresListBox" Grid.Row="0" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding Name}" HorizontalAlignment="Left" VerticalAlignment="Top"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Button Grid.Row="1" Content="Button" HorizontalAlignment="Left" Name="SelectButton" VerticalAlignment="Top" Click="SelectButton_Click"/>

    </Grid>

</Grid>

Here is my code:
   using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace MusicApp
{
    public partial class GenrePage : PhoneApplicationPage
    {
        public GenrePage()
        {
            InitializeComponent();

        }

        private async void GetGenres()
        {
            var genres = await App.GetClient().GetGenresAsync();

            GenresListBox.ItemsSource = genres;

            if (genres.Result == null || genres.Count == 0)
            {
                MessageBox.Show("No results available");
            }

        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            GetGenres();
        }

        private void SelectButton_Click(object sender, RoutedEventArgs e)
        {
            var selectedGenres = GenresListBox.SelectedItems;

        }
    }
}

A: I did  little change in your code. try this it help you
xaml
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
      <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
      </Grid.RowDefinitions>
  <ListBox x:Name="GenresListBox" Grid.Row="0" SelectionChanged ="GenresListBox_SelectionChanged">
      <ListBox.ItemTemplate>
         <DataTemplate>
          <CheckBox Content="{Binding Name}" HorizontalAlignment="Left" VerticalAlignment="Top"/>
          </DataTemplate>
      </ListBox.ItemTemplate>
 </ListBox>
<Button Grid.Row="1" Content="Button" HorizontalAlignment="Left" Name="SelectButton" VerticalAlignment="Top" Click="SelectButton_Click"/>
 </Grid>

IN Code Beind
private void GenresListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (GenresListBox.SelectedIndex == -1)
        return;
}

private void SelectButton_Click(object sender, RoutedEventArgs e)
        {
            var selectedGenres = GenresListBox.SelectedItem;
        }

A: I solved my problem using  Windows Phone Toolkit's LongListMultiSelector.
This is how it's going to look like:

Now my XAML is:
<phone:PhoneApplicationPage
x:Class="MusicApp.GenrePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel Grid.Row="0" Margin="12,17,0,28">
        <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <toolkit:LongListMultiSelector  x:Name="GenresListBox" Grid.Row="0" >
            <toolkit:LongListMultiSelector.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" />
                </DataTemplate>
            </toolkit:LongListMultiSelector.ItemTemplate>
        </toolkit:LongListMultiSelector>
        <Button Grid.Row="1" Content="Button" HorizontalAlignment="Left" Name="SelectButton" VerticalAlignment="Top" Click="SelectButton_Click"/>

    </Grid>

</Grid>

And code:
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Nokia.Music.Types;

namespace MusicApp
{
    public partial class GenrePage : PhoneApplicationPage
    {
        public GenrePage()
        {
            InitializeComponent();

        }

        private async void GetGenres()
        {
            var genres = await App.GetClient().GetGenresAsync();

            GenresListBox.ItemsSource = genres;

            if (genres.Result == null || genres.Count == 0)
            {
                MessageBox.Show("No results available");
            }

        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            GetGenres();
        }

        private void SelectButton_Click(object sender, RoutedEventArgs e)
        {
            var genres = GenresListBox.SelectedItems;

        }
    }
}


text:
Q: Angular 8 - CORS error using HTTP to download file from Firebase Storage I am trying to download the contents of a video file from Firebase Storage using Angular 8's HTTP Client.
Given the URL for the file in Firebase Storage, the following code is used to download its contents:
  public downloadVideo = (url: string): Observable<any> => {
    return this.http.get(url,
      {
        responseType: 'arraybuffer',
      }
    );
  };
}

The following error is received:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [url for resource] (Reason: CORS header 'Access-Control-Allow-Origin' missing). Status code: 200.
I tried the answer at Firebase Storage and Access-Control-Allow-Origin
But, it did not resolve the issue.
Any ideas?
Thanks in advance

redpajama_set_name: RedPajamaStackExchange


text:
Q: Initiating outlets when there is no xib file I have defined the RPM class which inherits from UIView
@interface RPM : UIView

this class doesnot have any xib file, but has two outlets defined in its header file:
@property (nonatomic,assign) IBOutlet Analog* outletOne;

@property (nonatomic,assign) IBOutlet Analog* outletTwo;

where Analog is a class inherited from UIView.
As I run the application, the two outlets are nil when I reach the awakeFromNib method. Because there is no xib file, I cannot use the method suggested here (i.e. dragging the outlet to the view):
 Why is my outlet nil?
How should I tell the class to initiate the outlets?

A: Initialize your properties in initWithFrame.
You can delete the IBOutlet keywords.


text:
Q: NHibernate - Session Singleton C# Trying to migrate NHibernate into an existing C# WinForms app and I am currently looking for the best way to manage sessions. I am only learning NHibernate so please excuse my lack of knowledge, can someone please provide me with any Session management code which we can use, most of the implementations that we have found are for web apps.
Any help is appreciated.

A: Assuming you're already comfortable with XML and the NHibernate configuration itself, there is one object that you need to make a singleton, that is, the ISessionFactory API. The reason why this should be made a singleton is that the full configuration in regards to your connection, plus all of the entity mappings are loaded in memory so that NHibernate know how and where to persist into the underlying datastore. Hence, the ISessionFactory API is very costly to instantiate.
As for the sessions, there are two aspects to consider, whether you want a stateless or a statefull session. This choice is yours entirely, but know the difference.
The ISession API keeps track of every single change on an attached entity. An attached entity is one that has either been loaded from the underlying datastore using one of the possible ways provided by NHibernate, or, on the other hand, an transient entity that has just been instantiated and that you have attached yourself to the session. Keeping such a statefull session alive for toolong may cause data loss as will come the time where this API leaks in memory. Once a leak occurs, the entire track of changes is trashed and the session can no longer be used. The ISession API shall always be used along with the ITransaction API. The ITransaction is likely the same as a Begin Transaction directly in SQL (TSQL, PL/SQL and others). Everytime you need to persist into the database, you should do so while using a transaction in order to prevent errors from voiding the changes or whatsoever. The ISession API should be instantiated in the beginning of a unit-of-work. One only  ISession API instance might be required to handle more than one form at a time. That said, making an ISession API instance a singleton is a really, really bad idea, for the memory management reason, for which the ISession keeps track of every changes occuring to an attached entity. Keeping the ISession API alive for too long will cause it to use more and more memory, which will result in memory leaks, and trash of the session.
The IStatelessSession API does what it says to be. Being stateless, it doesn't keep track of any changes made to an attached object. So you will have to manually know what is to be done as an action against the database for this entity you intend to persist, let's say. The IStatelessSession also uses the ITransaction API through which it can handle data integrity. These both should always be used along each other while connecting to the datastore. The IStatelessSession is often used under the create-when-needed basis, as it has no other use than to "talk" with the datastore. This API is mostly used, I believe, in Web application where stateless rules the most.
Once you have chosen what best meets your requirements between the ISession and the IStatelessSesion APIs, you're ready to go.


text:
Q: Prevent viewing webpage in Internet Explorer I recently created a web portal and it seems like internet explorer doesn't support all the new css properties in the page. The webpage looks good on the new edge, chrome and firefox. Is there any way that i can block the users from vewing my webpage in internet explorer by putting a message (just my concept)
"webpage not supported in internet explorer use chrome ,firefox or edge"
Thanks a lot for your time.

A: You can use the following Javascript validation. If Internet Explorer is detected a message will be shown to the user and it will then redirect to your custom error page. Modify the variable 'errURL' to reflect your custom error page URL.
var msg = "webpage not supported in internet explorer use chrome ,firefox or edge";
var errURL = "https://www.google.com";
var ua = window.navigator.userAgent;

if(ua.indexOf('Trident') > -1 || ua.indexOf('MSIE') > -1){
  alert(msg); document.location(errURL);
}

A: I suggest you refer to the example below may help you to display the message if the browser is Internet Explorer.
<!doctype html>

<title>
Test to detect IE browser
</title>

Test Page...

Output:


text:
Q: SQL table design for conversation message system In my web application backed by a MySQL database, I want to offer a messaging system where messages are grouped into conversations between multiple users, but I am stuck with designing a table structure that caters to some of my needs:

*

*Multiple users can participate in one conversation

*Users can join, read, leave and delete conversations

*An inbox view should generate as little queries as possible

Now, the first requirement for a many-to-many relation can be solved by using a junction table. But it has proven to generate quite a lot of problems when writing the select queries for the inbox view.
The second requirement also proved to be a challenge. If a user leaves a conversation, it should still be available for him to read through old messages. New messages between the remaining users in the conversation should not be shared with the user who left. I first thought about using a tree-like structure for conversations. Each time a user joins or leaves a conversation, a new conversation is created with a reference to the parent conversation and new relations with the remaining participants in the junction table are created.
The third requirement also seems not to be trivial. The inbox view should display a list of conversations with a specific user as participant. Also, additional information should be displayed for each conversation: The names of all current participants, the last reply to the conversation and that reply's author. Think of the inbox view as a list of messages with additional information about the conversation they belong to.
My current approach looks like this:
CREATE TABLE `conversation` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `parentId` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `parentId` (`parentId`),
  CONSTRAINT `conversation_ibfk_1` FOREIGN KEY (`parentId`) REFERENCES `conversation` (`id`)
);
CREATE TABLE `participant` (
  `userId` int(11) unsigned NOT NULL,
  `conversationId` int(11) unsigned NOT NULL,
  `readAt` datetime DEFAULT NULL,
  PRIMARY KEY (`userId`,`conversationId`),
  KEY `conversationId` (`conversationId`),
  CONSTRAINT `participant_ibfk_2` FOREIGN KEY (`conversationId`) REFERENCES `conversation` (`id`),
  CONSTRAINT `participant_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `user` (`id`)
);
CREATE TABLE `reply` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `conversationId` int(11) unsigned NOT NULL,
  `userId` int(11) unsigned NOT NULL,
  `text` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `conversationId` (`conversationId`),
  KEY `userId` (`userId`),
  CONSTRAINT `reply_ibfk_2` FOREIGN KEY (`userId`) REFERENCES `user` (`id`),
  CONSTRAINT `reply_ibfk_1` FOREIGN KEY (`conversationId`) REFERENCES `conversation` (`id`)
);
CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
);

I have hit a wall here and can't find a solution that caters to all my needs. Maybe someone here can give me some advice on how to approach this database design.

A: USERS ACTIVITY
I still would make a junction table, but with indices on tuples.
USER_CONV
---------------
id_user
id_conversation
active_flag
begin_flag              - flag indicating if id_first_reply == id_first_visible_reply
id_first_reply          - first reply in the conversation
id_first_visible_reply  - first visible for a given user
id_last_reply           - last visible for a given user, user if active_flag = false, otherwise NULL

index (id_user, id_conversation, active_flag)

USER_REPLY
---------------
id_user
id_conversaion
id_reply

index (id_user, id_conversation, id_reply)

The USER_CONV should make it less painless to create inbox. Still you will need to join it with USER_REPLY, and then with REPLY.
INBOX
If you want to make it fast, then create a kind of CACHED_INBOX, and a table with MOST_RECENT_USER_ACTIVITY. The CACHED_INBOX table will contain all the inbox data that you do not need to do any joins to fetch the relevant data, but you only have to do a UNION with the data from MOST_RECENT_USER_ACTIVITY. The MOST_RECENT_USER_ACTIVITY should be quite small (work fast), and CACHED_INBOX will be 'static'. Then once a day, or every several days at the time when the server is less likely to be used do a batch CACHED_INBOX update. It will work unless your users decide to stay in conversations forever.
OPTIMISATION
Of course you will need to use explain a bit, to see how the query optimizer uses indexing (if it uses it at all). Mybe you will need a table like ACTIVE_CONVERSATIONS, which will not have any indexing, that would hit performance a bit. But then you would do some batch updates to USER_CONV, which would have more extensive indexing. You have to try a bit, and see what do you expect from your users behaviour, that should be one of the architecture drivers.
NOTE: regarding indexes, there is a good website devoted to the topic of indexing use-the-index-luke.com


text:
Q: Magento2 - Attribute taking 0 as default value I have a strange issue and not sure what is wrong, I have identical attributes (see image below), but the strange part is when I keep Metal 02 Weight blank and save the product its taking 0 value automatically, while this is not happening with Metal 01 Weight, can anyone help me how to find out the reason.
I have cleared / flushed all caches, all indexes are reindexed, completely removed generated , static folders and recompiled everything, still no effect.


text:
Q: Regex Pattern for Textfield I am trying to write regex pattern for my textfield. I want it to accept letters, numbers as well as two special characters(underscore and hyphen). It can contain any number of words, and no other special characters are allowed except underscore and hyphen in between the words or starting/end of words. Space is also allowed between the words. But if a user will enter space/hyphen/underscore alone then it shouldn't accept.
i.e,
var a = "abc_def" //allowed
var b = "abc def" //allowed
var c = "abc-def" //allowed
var d = "abc*def" //not allowed, all other special characters are also not allowed
var e = " " // not allowed
var f = "_" // not allowed
var g = "-" // not allowed

I wrote below regex pattern
^(([A-Za-z0-9])+([\-|_])?)+$

but it's not accepting space if entered in between the words. It should accept as I wrote in above 7 scenarios. How can I rectify the issue?

A: Your current pattern is missing a space in the character class.
It will also match a trailing underscore or hyphen as the character class to match a char a-z or a digit followed by a special character is repeated as a whole using )+ at the end.
You could first match [A-Za-z0-9]+, use a character class [ _-] to match any of the 3 allowed characters and repeat the non capturing group (?: one or more times.
^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)+$

regex demo

A: Just add a space in your square brackets:
^(([A-Za-z0-9])+([\-|_ ])?)+$

Run the code below to test.

var a = "abc_def" //allowed
var b = "abc def" //allowed
var c = "abc-def" //allowed
var d = "abc*def" //not allowed, all other special characters are also not allowed
var e = " " // not allowed
var f = "_" // not allowed
var g = "-" // not allowed

var regex = /^(([A-Za-z0-9])+([\-|_ ])?)+$/;

console.log(regex.test(a));
console.log(regex.test(b));
console.log(regex.test(c));
console.log(regex.test(d));
console.log(regex.test(e));
console.log(regex.test(f));
console.log(regex.test(g));


text:
Q: javascript: I want radio button action change according to the loop that fetch from database My code is fetch data from database (suppose there are 4 records). Only first loop that effected when i changed radio button. Below is my code:
PHP CODE
while($row = mysql_fetch_array($sql)){
echo "
";

    echo "
<input type='checkbox' name='content_type' value='1' />
";
    echo "
<input type='checkbox' name='content_type' value='2' />
";
    echo "
<input type='checkbox' name='content_type' value='3' />
";

    //content_a
    echo "
";
        echo "<textarea name='text' id='textarea0'><textarea>";
    echo "
";

    //content_b
    echo "
";
        echo "<textarea name='text' id='textarea1'><textarea>";
    echo "
";

    //content_c
    echo "
";
       echo "<textarea name='text' id='textarea2'><textarea>";
    echo "
";

    //button
    echo "
";
        echo "Alert";
    echo "
";

echo "
";
}

Javascript
$('input[name=content_type]').bind('change', function(){
   var n = $(this).val();
   switch(n)
   {
    case '1':
            $(this).parents('.loop').find('#content_a').show(1000);
            $(this).parents('.loop').find('#content_b').hide(1000);
            $(this).parents('.loop').find('#content_c').hide(1000);
            break;
    case '2':
            $(this).parents('.loop').find('#content_b').show(1000);
            $(this).parents('.loop').find('#content_a').hide(1000);
            $(this).parents('.loop').find('#content_c').hide(1000);
            break;
    case '3':
            $(this).parents('.loop').find('#content_c').show(1000);
            $(this).parents('.loop').find('#content_a').hide(1000);
            $(this).parents('.loop').find('#content_b').hide(1000);
            break;
   }
});

I want radio button action change according to the loop that fetch from database. My code above, only first loop that effected. How to solve this problem?

A: that is beacuse id should always be unique...here (in your code ) you have multiple elements with same id id='content_a' (since it is inside a loop) . change this to class and use class selector
try this
html
  echo "
";
        //---^^^^^ here

jquery
  $(this).parents('.loop').find('.content_a').show(1000);\
                        //-------^-----here

change likewise to all other id selector
and while parents('.loop') works.. i recommend to use closest() for better performance
  $(this).closest('.loop').find('.content_a').show(1000);

and yes.. you can reduce your code to two lines if you chnage your html properly..
first change you content to match with the checkbox value..
echo "
";  //here class='content_' + value of checkbox
 .....
echo "
";
... //so on

try this
$('input[name=content_type]').bind('change', function(){
   var n = $(this).val();
   $('div[class^="content_"]').hide(); //hide all div
   $(this).closest('.loop').find('.content_' + n).show(1000); //so particular div
});


text:
Q: function pointer definition on ternary operator When I define a function pointer in C++ using the ternary operator I get the compiler error overloaded function with no contextual type information.
I'm confused. Could someone explain me the reason of this behavior?
#include <string>
#include <string.h>
#include <iostream>

const char *my_strstr1 (const char *__haystack, const char *__needle) {
    std::cout << "my_strstr" << std::endl;
    return strstr(__haystack, __needle);
}

const char *my_strstr2 (const char *__haystack, const char *__needle) {
    std::cout << "my_strstr2" << std::endl;
    return strstr(__haystack, __needle);
}

int main(int argc, char** argv) {
    std::cout << "argc:" << argc << std::endl;

    //ok
    // const char* (*StrStr)(const char*, const char*) = strstr;
    // const char* (*StrStr)(const char*, const char*) = (argc > 1) ? my_strstr2 : my_strstr1;

    // error: overloaded function with no contextual type information
    const char* (*StrStr)(const char*, const char*) = (argc > 1) ? my_strstr1 : strstr;

    StrStr("helloworld", "h");

    return 0;
}

A: The overload of strstr defined in string.h is:
char *strstr( const char* str, const char* substr );

And in <cstring> there are two strstrs:
const char* strstr( const char* str, const char* target );
      char* strstr(       char* str, const char* target );

Either way, that doesn't match your other function. The former has the wrong return type, and the latter has two overloads and you're using it in a context that doesn't allow for that.
The simplest approach is just to "fix" which strstr you want with a lambda and just use that:
using F = const char*(*)(const char*, const char*);
F std_version = [](const char* s, const char* t) -> const char* {
    return strstr(s, t);
};

F StrStr = (argc > 1) ? my_strstr1 : std_version ;

A: There are more than one version of strstr function. So compiler don't know which one should be used so you have to tell the compiler which one you want:
const char* (*StrStr)(const char*, const char*) = (argc > 1) ? my_strstr1 : (const char* (*)(const char*, const char*))strstr;

You can take a look to similar SO question: Return type of '?:' (ternary conditional operator).
And also section 5.16 in Working draft, Standard for Programming
Language C++


text:
Q: NodeJS Custom Module is Undefined So, I'm new to NodeJS (started learning it two weeks ago) and I decided to delve into the realm of creating my own modules. I looked up some articles and found the best way to create a module with a constructor was the following:
var Foo = function (params) {
    //Do constructor stuff
    this.params = params;
};

Foo.prototype.test = function () {
    console.log(this.params.Message);
};

module.exports = Foo;

Then I would be able do var myFoo = require("./utils/Foo.js")( { Message: "Some Message });
This runs the constructor. However, when I do myFoo.test() I get an error saying Cannot read property 'test' of undefined.
I don't understand why I'm getting the above error. When I add a console.log("Test") to the constructor, I see the log.
Any help would be appreciated.

A: Methods of the prototype require the use of the new keyword. However when you require it your not using the new keyword.
You have a couple of options. Either put the new keyword in when you require it. (Ive split the two apart by the way as im not entirely sure what will happen with the new keyword if it was new require('module')(). I think it would apply to the require call, not the function call after).
var fooModule = require('./foo.js'),
    myFoo = new fooModule('myMessage');

Or you could put that logic in your constructor so it will return a new version if the new keyword is omitted; Your require call would not change but your constructor could be something like:
var Foo = function (params) {
    if (!(this instanceof Foo)) {
        return new Foo(params);
    }
    //Do constructor stuff
    this.params = params;
};

See fiddle example: https://jsfiddle.net/84ssgare/1/
Generally i would avoid the use of new Keyword anyhow. Its trying to make JavaScript something its not. This article List some good examples of exactly how the new keyword works. It also makes the good point that its a tool and should be used when required, not because its familiar.

A: You need new to create the object from the constructor:
var foo=require("./utils/Foo.js");
var myFoo = new foo( { Message: "Some Message });

short version:
var myFoo = new require("./utils/Foo.js")( { Message: "Some Message });

In your actual code you are executing a foo function that reruns undefined. And then trying to access undefined as an object with a test property


text:
Q: Combine multiple Excel workbooks into individual Excel workbooks based on filenames - VBA I have multiple workbooks saved in C:\Temp.
They look like:

*

*AAAA_1.xlsx

*AAAA_2.xlsx

*AAAA_3.xlsx

*BBBB_1.xksx

*BBBB_2.xksx

*CCCC_1.xlsx

*CCCC_2.xlsx

*CCCC_3.xlsx

*CCCC_4.xlsx

*etc.

I want to combine these files into master workbooks, so in the above example, I would have master file AAAA with data from AAAA_1, AAAA_2 and AAAA_3, a master file BBBB with data from BBBB_1 and BBBB_2, etc.
Below is my current VBA.  I am able to search for prefix "AAAA" and that creates a new master file with all tabs from AAAA_1, AAAA_2 and AAAA_3, but then how to I start over (automatically) and create master files for all of the other prefixes that exist in C:\Temp?  Thanks from a VBA rookie!
Sub Merge()
Path = "C:\Temp\"
Filename = Dir(Path & "AAAA" & "*.xlsx")
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
 For Each Sheet In ActiveWorkbook.Sheets
   Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
 Application.DisplayAlerts = False
 Workbooks(Filename).Close
 Filename = Dir()
'Save workbook
Loop
 Application.DisplayAlerts = True

ActiveWorkbook.SaveAs Filename:="C:\Temp\File_" & Range("A1") & ".xlsx", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
End Sub

A: Using a dictionary and collections. Scans the directory to compile a list of master workbooks first and then uses the collections to open and copy the sheets.
Option Explicit

Sub consolidate()

    Const FOLDER = "C:\Temp\"

    Const SEP_COUNT = 0 'set to 0 to use fixed width
    Const SEP = "_"
    Const FIXED_WIDTH = 3 '

    Dim wb As Workbook, wbMaster As Workbook, ws As Worksheet
    Dim dict As Object, k, c As Collection, ar, f
    Dim m As Integer, n As Integer
    Dim sFile As String, s As String
    Set dict = CreateObject("Scripting.Dictionary")

    ' build collections
    sFile = Dir(FOLDER & "*.xlsx")
    Do While Len(sFile) > 0
        k = ""

        ' avoid masters
        If sFile Like "Master*" Then
            ' do nothing
        ElseIf SEP_COUNT > 0 Then
            If InStr(sFile, SEP) > 0 Then
                ' example INV_1104092_05_31_2021_000.xlsx
                ar = Split(sFile, SEP, SEP_COUNT + 1)
                If UBound(ar) >= SEP_COUNT Then
                     k = ar(0)
                     For n = 1 To SEP_COUNT - 1
                         k = k & "_" & ar(n)
                     Next
                End If
             End If
        ElseIf FIXED_WIDTH > 0 Then
            k = Left(sFile, FIXED_WIDTH)
        End If

        If Len(k) > 0 Then
            If Not dict.exists(k) Then
                dict.Add k, New Collection
            End If
            Set c = dict.Item(k)
            c.Add Trim(sFile), CStr(c.Count + 1)
        End If

        sFile = Dir
    Loop

    ' copy sheets
    Application.ScreenUpdating = False
    For Each k In dict
        ' create new master
        Set wbMaster = Workbooks.Add
        m = wbMaster.Sheets.Count
        n = m
        For Each f In dict(k) ' files in collection
            Set wb = Workbooks.Open(FOLDER & f, 1, 1)
            s = Replace(Mid(f, Len(k) + 1), ".xlsx", "")
            ' remove _ from front
            If SEP_COUNT > 0 And Left(s, 1) = "_" Then s = Mid(s, 2)
            For Each ws In wb.Sheets
                ws.Copy After:=wbMaster.Sheets(n)
                n = n + 1
                wbMaster.Sheets(n).Name = s & "_" & ws.Name
            Next
            wb.Close False
        Next

        ' delete initial sheets
        Application.DisplayAlerts = False
        For n = m To 1 Step -1
            wbMaster.Sheets(n).Delete
        Next
        Application.DisplayAlerts = True

        ' save master
        wbMaster.SaveAs FOLDER & "Master_" & k & ".xlsx", _
               FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
        wbMaster.Close False
    Next
    ' end
    Application.ScreenUpdating = True
    MsgBox dict.Count & " master files created", vbInformation

End Sub

A: Convert your current sub to accept the letter pattern and call it by a main one feeding all wanted letters
Sub Merge()
    Const letters As String = "ABCDEFG" ' collect all wanted initial letters

    Dim iLetter As Long
        For iLetter = 1 To Len(letters) ' loop through letters
            MergeLetter String(4,Mid$(letters, iLetter, 1))
        Next

End Sub

and here's your original Merge() sub, I adapted for the task:
Sub MergeLetter(letter As String)

    Dim masterWb As Workbook
        Set masterWb = Workbooks.Add 'open a new "master" workbook

    Dim path As String
        path = "C:\Temp\"

        Dim fileName As String
            fileName = Dir(path & letter & "*.xlsx")

            Do While fileName <> vbNullString

                With Workbooks.Open(fileName:=path & fileName, ReadOnly:=True)
                    Dim sh As Worksheet
                        For Each sh In .Worksheets
                           sh.Copy After:=masterWb.Sheets(1)
                        Next
                        .Close
                End With

                fileName = Dir()

            Loop

            With masterWb
                .SaveAs fileName:=path & letter & ".xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
                .Close False
            End With
End Sub

as you see, I also adopted some stylistic changes, one of them being my personal code indentation pattern, which you may found userful or not

A: Merge Sheets from Multiple Workbooks to Master Workbooks

*

*The code should be located in a module of a file that is not inside the source folder path (FolderPath) or at least a file whose name has none of the prefixes.

*Not tested.

Option Explicit

Sub mergeSheets()

    Const FolderPath As String = "C:\Temp\"
    Const PrefixesList As String = "AAAA,BBBB,CCCC"

    Dim Prefixes() As String: Prefixes = Split(PrefixesList, ",")

    Dim swb As Workbook
    Dim dwb As Workbook
    Dim sh As Object
    Dim fName As String
    Dim n As Long
    Dim dshCount As Long

    Application.ScreenUpdating = False

    For n = 0 To UBound(Prefixes)
        fName = Dir(FolderPath & Prefixes(n) & "*.xlsx")
        dshCount = 0
        Do Until Len(fName) = 0
            Set swb = Workbooks.Open(FolderPath & fName, , True)
            For Each sh In swb.Sheets ' charts and what not included
                If dshCount = 0 Then
                    sh.Copy ' creates a new workbook containing one sheet
                    Set dwb = ActiveWorkbook
                Else
                    sh.Copy After:=dwb.Sheets(dshCount)
                End If
                dshCount = dshCount + 1
            Next sh
            swb.Close SaveChanges:=False
            fName = Dir
        Loop
        ' Maybe you wanna rather do '... & Prefixes(n) & ".xlsx",...'
        dwb.SaveAs "C:\Temp\File_" & dwb.WorkSheets(1).Range("A1") & ".xlsx", _
            xlOpenXMLWorkbook, , , , False
        dwb.Close
    Next n

    Application.ScreenUpdating = True

End Sub

A: Create a class Named WorkbookMerger and add the following code into it
Option Explicit
''Add/check Tools> Reference> Microsoft Scripting Runtime

Private FileSysObject As Scripting.FileSystemObject
Private Fullfolder  As Scripting.Folder
Private SingleFile As Scripting.File
Private dict As Scripting.Dictionary
Private ProccessedFolder As String

Private Const Delim As String = "_"
Private Const SaveInFolder As String = "ProccessedFiles"

Public Function Execute(ByVal BasePath As String) As Boolean
    Set Fullfolder = FileSysObject.GetFolder(BasePath)

    ProccessedFolder = FileSysObject.BuildPath(BasePath, SaveInFolder)

    Execute = False
    If Not FileSysObject.FolderExists(ProccessedFolder) Then
        FileSysObject.CreateFolder (ProccessedFolder)
    End If

    If ReadPatterns Is Nothing Then
        Exit Function
    Else
        ProcessFiles
    End If
    Execute = True
End Function

Private Function ReadPatterns() As Scripting.Dictionary
    For Each SingleFile In Fullfolder.Files

        Dim Pattern As String
        Pattern = Split(SingleFile.Name, Delim)(0) 'change delimeter

        On Error Resume Next
        If Not dict.Exists(Pattern) Then dict.Add Pattern, CStr(Pattern)

    Next SingleFile
    Set ReadPatterns = dict
End Function

Private Sub ProcessFiles()

    Dim key As Variant
    For Each key In dict
        'loop through all patterns in dict and process each file if it matches

        Dim masterWb As Workbook
        Dim masterwbName As String
        masterwbName = ProccessedFolder & "\" & key & ".xlsx"
        If FileSysObject.FileExists(masterwbName) Then
            Set masterWb = Workbooks.Open(masterwbName)
        Else
            Set masterWb = Workbooks.Add
        End If

        For Each SingleFile In Fullfolder.Files
            With SingleFile

                If .Name Like key & "*" Then

                    Dim Wsheet As Worksheet
                    Dim wb As Workbook
                    Set wb = Workbooks.Open(Fullfolder.Path & "\" & SingleFile.Name, ReadOnly:=True)
                    For Each Wsheet In wb.Worksheets
                        Wsheet.Copy after:=masterWb.Sheets(1)

                    Next Wsheet
                    wb.Close False
                    'close file without saving any changes
                End If
            End With

        Next SingleFile
        With masterWb
            .SaveAs masterwbName, xlOpenXMLWorkbook
            .Close True
        End With

    Next key
End Sub

Private Sub Class_Initialize()
    Set FileSysObject = New Scripting.FileSystemObject
    Set dict = New Scripting.Dictionary
End Sub

Now in any module add the following code
Public Sub Testing()
    Dim WMerger As WorkbookMerger
    Set WMerger = New WorkbookMerger
    On Error GoTo ErrorExit:
    With Application
        '.Calculation = xlCalculationAutomatic
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableCancelKey = xlInterrupt
    End With

    If WMerger.Execute("C:\Temp") Then MsgBox "Completed"

ErrorExit:

    With Application
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
        .StatusBar = False
    End With
End Sub

*

*The class takes basepath and based on constant SaveInFolder it creates a sub-folder under basepath where all processed files will be stored.

*Reads all file in basepath and retrieves unique patterns based on
the Delim.

*Loop through each key(unique pattern), Create file base don pattern
and process all filenames again to check if any of the file name
matches this pattern.

*If matches  it's worksheets will be copied in this new file and at
last this file will be saved in sub folder with Pattern name.

I tried with 20 different files with different patterns and it works as expected.
Let me now if it works.


text:
Q: Mac OS X 10.6 Setup for Apache/MySQL/Perl I just got a new Mac and have been trying to setup a local development environment for my perl applications for a few days now with no luck. I'm getting no where fast so I hope someone else who has done this successfully could help.
I started by installing MAMP which I thought would take care of everything for me but unfortunately it doesn't take care of some important perl modules. I used CPAN to install all our required modules except that it seems DBD::mysql doesn't install correctly through CPAN. After reading a lot online, lots of people reported problems with this and recommended using MacPorts to install the module which I have tried doing with no luck using the following command:
sudo port install p5-dbd-mysql

After what seems like a successful install of DBD::mysql, Apache continues to report the following error when trying to run any of our Perl scripts:
[Fri Apr 30 18:51:07 2010] [error] [client 127.0.0.1] install_driver(mysql) failed: Can't locate DBD/mysql.pm in @INC (@INC contains: /Library/Perl/Updates/5.10.0/darwin-thread-multi-2level /Library/Perl/Updates/5.10.0 /System/Library/Perl/5.10.0/darwin-thread-multi-2level /System/Library/Perl/5.10.0 /Library/Perl/5.10.0/darwin-thread-multi-2level /Library/Perl/5.10.0 /Network/Library/Perl/5.10.0/darwin-thread-multi-2level /Network/Library/Perl/5.10.0 /Network/Library/Perl /System/Library/Perl/Extras/5.10.0/darwin-thread-multi-2level /System/Library/Perl/Extras/5.10.0 .) at (eval 1835) line 3.
[Fri Apr 30 18:51:07 2010] [error] [client 127.0.0.1] Perhaps the DBD::mysql perl module hasn't been fully installed,
[Fri Apr 30 18:51:07 2010] [error] [client 127.0.0.1] or perhaps the capitalisation of 'mysql' isn't right.
[Fri Apr 30 18:51:07 2010] [error] [client 127.0.0.1] Available drivers: DBM, ExampleP, File, Gofer, Proxy, SQLite, Sponge.

I'm not sure where to go from here but my Mac isn't much of a development environment if Perl isn't able to talk to the database. I'd really appreciate any help and advice you might be able to provide in getting my system setup successfully. Thanks in advance!

A: I've spent near 4 days fighting with this issue and here's the setup that finally got me there:

*

*don't use macports

*use the stock perl, with a twist:

*

*Snow Leopard ships with 2 perls: 5.10.0 and 5.8.9 - switch to the earlier version like so:

% export VERSIONER_PERL_PREFER_32_BIT=yes
% defaults write com.apple.versioner.perl Prefer-32-Bit -bool yes
% defaults write com.apple.versioner.perl Version 5.8.9

*

*download the 32bit version of mysql from dev.mysql.com/downloads/mysql/ ("Mac OS X ver. 10.6 (x86, 32-bit)")

*

*Find the instructions on Google - I just put the extracted directory in /usr/local and linked /usr/local/mysql to that directory

*CPAN seems to prefer the 5.10.0-specific install locations, so I downloaded DBD::mysql from search.cpan.org and did the usual install:

% perl Makefile.PL
% make
% sudo make install

UPDATE:

*

*In order to get CPAN to get its config from the right perl version, and to get Apache to run perl CGIs with the right perl version, use the following command instead of the last one in the above list:

% defaults write /Library/Preferences/com.apple.versioner.perl Version 5.8.9

You'll have to be an admin to do this. After this, HUP apache and you'll be all set.

A: I've gone through the same headaches that Steve Ivy did, with the same solution.
In addition, because I'm using mod_perl2, I also had to build mod_perl manually -- if you download it from CPAN, then issue:
    $ cd ~/.cpan/build/mod_perl-2.*

    $ export ARCHFLAGS="-arch i386 -arch x86_64"
    $ export CFLAGS="-arch i386 -arch x86_64"

    $ perl Makefile.PL
            # (will prompt for where apxs is:
            /usr/sbin/apxs

    $ make -j8
            # make test will fail ... had to modify a file:

    $ vi t/response/TestAPI/access2.pm
            # around line 117, comment out the line:

            AuthGroupFile @DocumentRoot@/api/auth-groups

            # (I have no idea *why* this is failing, though)

    $ make test
            # in my case, it failed a couple of tests ... 5 out of 238
            # most were because we're running older versions of
            # modules, or the pure-perl varient (you'll see 'PP' in
            # the module name, or it complains about (something)XS)

            # If you're concerned, see t/logs/error_log

    $ sudo make install

... and then force Apache2 down to 32 bit, by following Michael Cramer's advice


text:
Q: php write subdirectories' contents into separate text files I am trying to list files in subdirectories and write these lists into separate text files.
I managed to get the directory and subdirectory listings and even to write all the files into a text file.
I just don't seem to manage to burst out of loops I am creating. I either end up with a single text file or the second+ files include all preceeding subdirectories content as well.
What I need to achieve is:

*

*dir A/AA/a1.txt,a2.txt >> AA.log

*dir A/BB/b1.txt,b2.txt >> BB.log

*etc.

Hope this makes sense.
I've found the recursiveDirectoryIterator method as described in PHP SPL RecursiveDirectoryIterator RecursiveIteratorIterator retrieving the full tree being great help. I then use a for and a foreach loop to iterate through the directories, to write the text files, but I cannot break them into multiple files.

A: Most likely you are not filtering out the directories . and .. .
$maindir=opendir('A');
if (!$maindir) die('Cant open directory A');
while (true) {
  $dir=readdir($maindir);
  if (!$dir) break;
  if ($dir=='.') continue;
  if ($dir=='..') continue;
  if (!is_dir("A/$dir")) continue;
  $subdir=opendir("A/$dir");
  if (!$subdir) continue;
  $fd=fopen("$dir.log",'wb');
  if (!$fd) continue;
  while (true) {
    $file=readdir($subdir);
    if (!$file) break;
    if (!is_file($file)) continue;
    fwrite($fd,file_get_contents("A/$dir/$file");
  }
  fclose($fd);
}

A: I thought I'd demonstrate a different way, as this seems like a nice place to use glob.
// Where to start recursing, no trailing slash
$start_folder = './test';
// Where to output files
$output_folder = $start_folder;

chdir($start_folder);

function glob_each_dir ($start_folder, $callback) {

    $search_pattern = $start_folder . DIRECTORY_SEPARATOR . '*';

    // Get just the folders in an array
    $folders = glob($search_pattern, GLOB_ONLYDIR);

    // Get just the files: there isn't an ONLYFILES option yet so just diff the
    // entire folder contents against the previous array of folders
    $files = array_diff(glob($search_pattern), $folders);

    // Apply the callback function to the array of files
    $callback($start_folder, $files);

    if (!empty($folders)) {
        // Call this function for every folder found
        foreach ($folders as $folder) {
            glob_each_dir($folder, $callback);
        }
    }
}

glob_each_dir('.', function ($folder_name, Array $filelist) {
        // Generate a filename from the folder, changing / or \ into _
        $output_filename = $_GLOBALS['output_folder']
            . trim(strtr(str_replace(__DIR__, '', realpath($folder_name)), DIRECTORY_SEPARATOR, '_'), '_')
            . '.txt';
        file_put_contents($output_filename, implode(PHP_EOL, $filelist));
    });


text:
Q: How to include js parts of code inside another js file with code. [Prepros] Prepros has useful feature:
//@prepros-prepend filename.js

which includes js file at the beginning of current one, but I need to include files inside jquery document.ready statement, which would look like so:
$(function(){
  //@prepros-include code1.js
  //@prepros-include code2.js
  //@prepros-include code3.js
  //@prepros-include code3.js
  ...
});

Is that somehow possible, or have you any other solution how to concatenate a lot of js-fragments which would be bound inside jquery $(function(){...}); wrapper?
[edit] Ps. I don't want to write $(function(){...}); inside of each partial-file.

A: Well if you use google the first link wil be this one of jquery home page
But if you want to include in your js file other js files use this.
$.getScript( "ajax/test.js" )
  .done(function( script, textStatus ) {
    console.log( textStatus );
  })
  .fail(function( jqxhr, settings, exception ) {
    alert("No file found");
});

ofcourse you can easily easy a line like this.
$.getScript( "ajax/test.js" );


text:
Q: Automount using AutoFS and AFP permission issue I have a FreeNAS server of which I'd like to mount volumes on my Mac.
I'm using afp and mounting via Autofs following this tutorial. The folder / mountpoints on which I mount the drives are located in ~ (in my case ~/Data).
After setting up and using automount -vc, everything runs fine. When I reboot and try to access the drives again, I get permission errors. These problems are usually solved my using umount ~/Data (the volume) (which, I guess, unmounts and then automounts it correctly and therefore somehow solving the permission issue). This is kind of a annoying workaround, hence I'm looking for a solution.
The mountpoint on my Mac has these permissions:
drwxr-xr-x    2 Frank  staff         68 Aug  1 15:26 Data

The mounted folder on my Mac has these permissions:
drwx------@   1 Frank  staff        264 Jan 10 14:33 Data

The volume in FreeNAS is owned by the same user as I'm logged in on my Mac.
Could anyone help me out?

A: I have the same issue. But finally now solution yet.
If you look with command sudo mount, then you will see in case of failure the the mount point was not mounted by any user.
In case of working your user will have mounted it


text:
Q: Sometimes Play icon on status bar disappear while using AVQueueplayer I want to show the play icon on status bar in iOS while app is playing audio. I use AVQueuePlayer to play audio items. All works well but problem I am facing is play icon doesn't show on status bar sometimes.
The app has to support play/pause. When user taps on pause, I  pause the queue player and tapping on play button will start playing the queue again. When user taps on play again, I do seeking of the player item so that it will be in sync with what it is supposed to be played at that time. But some times after tapping on play again, the queue seeks to proper time and plays but play icon doesn't show up in the status bar.
I tried by commenting out the seek code and just did play/pause. The play icon shows/hides correctly, but I am not sure what is happening with seekTime API. If I use this to seek, sometimes the icon doesn't show time.
Is this something issue happening in seekTime: API? I am using the following code for seek
[self.player.currentItem seekToTime:seekTime];
Please help me on this issue.
Thanks

A: I don't use AVQueuePlayer but I had a similar problem. I'm using AVAudioPlayer only and when the application starts I play an audio which is then repeated constantly. For some reason, at different times, the play icon disappears but the audio is still playing.
My solution was to apply the response of "One Man Crew" in How to display playing indication icon on status bar?
But, in addition, every time I play again, I use the following:
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];

I don't know if it is correct, I am new in ios development, but currently is working to me.
Please let me know if there is a better solution.
Diego.


text:
Q: How to find list of people whose age is between a range? I have this situation where I have date-of-birth stored in database eg. 1990/03/15. I want to find out info. of records whose age is between 20 & 30. How should I write this query?
I have tried this:
I get age of all candidates using this query:
SELECT TIMESTAMPDIFF(YEAR,dob,CURDATE()) as age FROM `profile`

How to use it to get list of all candidates between age 20 & 30?

A: The NOW() gives the current Date. Now, to get date 20 and 30 years older, we can do the following:
DATE_SUB(NOW(), INTERVAL 20 YEAR)
AND
DATE_SUB(date, INTERVAL 30 YEAR)

Now the remaining query is very simple.
That is,
SELECT * FROM Person
WHERE dateOfBirth BETWEEN DATE_SUB(NOW(), INTERVAL 20 YEAR)
                  AND DATE_SUB(date, INTERVAL 30 YEAR)


text:
Q: Disable Android Notification Bar in Full Screen (in SGIII) In Samsung Galaxy S3, even though my app is set to be full screen, and this makes the notification bar not to be visible, if I swipe from the very edge of the screen side, this action will make the notification bar to appear again, allowing the user to expand it over the full screen app.
Is there any way to disable this, or to cancel the expand of the notification bar?
The problem is that I have a listview covering the whole screen, and if I swipe to scroll the items, every time I do it from the very edge due to the instinctive action of scrolling faster, then the notification bar appears again.
I've tried tricks such as creating an overlay window on the edge, but not working at all for SG3.
Thanks

A: If you haven't tried already, you might attempt to use the View flag for hiding navigation, SYSTEM_UI_FLAG_HIDE_NAVIGATION, documented here.
However it may be important to note this found at the bottom of their description :

There is a limitation: because navigation controls are so important, the least user interaction will cause them to reappear immediately. When this happens, both this flag and SYSTEM_UI_FLAG_FULLSCREEN will be cleared automatically, so that both elements reappear at the same time.

which is probably related to what you're seeing. I find it hard to believe there's a way around this... I just tried and every fullscreen app I have on my S3 behaves this exact same way.
I suspect that if there was a way around it (assuming the above doesn't work, which I don't expect it to), it would be considered to be a bug by the Android team, and I would advise against it.


text:
Q: Möbius function - understanding of relations I am trying to understand Möbius function from the wikipedia article (and also few others that I have come across so far). This function is defined in posets and so the relations in Special elements section of the wikipedia article confuse me. So what do relations $=$, $\leq$, $<$ mean in this section? Do these have the traditional meaning or does these relations mean something different?

A: In the original number-theoretic case, $\leq$ would be replaced by $\mid$. The integers are partially ordered by divisibility and the Mobius function is the inverse of the zeta function, using the language of the general poset case.


text:
Q: Paypal integration with pocket PC application for Windows mobile 6.0 I'm developing a pocket PC application for Windows mobile 6.0 and I want to use Paypal.
Should i use Web Browser control for this. I need to know the entire process and flow to implement PayPal to my smart device application.

A: I'm not sure exactly what your requirements are, but I would start with the PayPal web services API.


text:
Q: Export blender lights to Unity I need help to Export Blender Lights to Unity, I created a Material with a light and need use this in Unity, but when I export this lights in .fbx, Unity not recognises this, only recognises the material
thanks for the help.

A: If you mean the light objects in blender, you can't export them to Unity. Rather, use Unity's built-in light objects to illuminate your scene.
You could try to bake the lightning information into the texture though, using either Blender or Unity to do so.

A: So you can not import lights from Blender to Unity or even if there is light information in the object Unity will not process it. There is actually a good reason for that since Unity has its own lighting system which is made with game performance in mind whereas Blender lights are made for aesthetics.
In Short: Use Unity lights!


text:
Q: ui-select selected not working in angularjs I'm currently using ui-select component in AngularJS.
<ui-select ng-model="tipData.category" search-enabled="false" name="category" required="required" class="orange-site-color-select custom-select">
  <ui-select-match>{{$select.selected}}</ui-select-match>
  <ui-select-choices repeat="tipcat in tipCategory"></ui-select-choices>
</ui-select>

I'd like to know how can I implement auto select value displayed in that ui-select as retrieving data (just id) from database and displayed in that ui-select?

A: try this

<select ng-model="selectedCountry">
<option value="">Select Account</option>
 <option ng-repeat="x in chooseCountries" value="{{x.countryId}}"  >{{x.name}}</option>
</select>

And script code
 var app = angular.module('main', []);
 app.controller('DemoCtrl', function ($scope) {
 $scope.chooseCountries=[
{countryId : 1, name : "France - Mainland", desc: "some description" },
{countryId : 2, name : "Gibraltar", desc: "some description"},
{countryId : 3, name : "Malta", desc: "some description"}
];
 $scope.selectedCountry =  $scope.chooseCountries[1].countryId.toString();
 });

A: You can use selected property.

  <select ng-model="selectedCountry">
<option value="">Select Account</option>
      <option ng-repeat="x in chooseCountries" value="{{x.countryId}}"  selected="{{x.name}}=Malta">{{x.name}}</option>
</select>


text:
Q: Using QDataStream to serialize custom class causes C2679 error I'm writing an application in which I need serialization to store some data in files. For serialization I want to use the QDataStream class.
I can't compile my code due to this compiler error:

Error 1   error C2679: binary '<<' : no operator found which takes a
  right-hand operand of type 'const CListItem' (or there is no
  acceptable conversion)    c:\qt\4.8.6\src\corelib\io\qdatastream.h    265

See the relevant code below. Anyone knows what's going on here?
There is a similar question which didn't help me. When I follow the steps described there, I get this (similar) error:

Error 1   error C2678: binary '<<' : no operator found which takes a
  left-hand operand of type 'QDataStream' (or there is no acceptable
  conversion)   c:\qt\4.8.6\src\corelib\io\qdatastream.h    265

This is my problem:
What I want to serialize is a class called CMPProject.
CMPProject holds

*

*CListModel* m_pData;

*QDateTime m_dateTimeCreated;
This is basically what should be serialized.
CMPProject has operators to stream its contents into a QDataStream.
MPProject.h:
#ifndef _MPPROJECT_
#define _MPPROJECT_

#include <QtCore/QString>
#include <QtCore/QFile>
#include <QtCore/QDateTime>

#include "ListModel.h"

class CMPProject
{
public:
    // ...

    friend QDataStream& operator <<(QDataStream& stream, const CMPProject& project);
    friend QDataStream& operator >>(QDataStream& stream, CMPProject& project);

private:
    static const quint32 m_streamHeader = 0x1329453;
    QFile* m_pFile;
    CListModel* m_pData;
    QDateTime m_dateTimeCreated;
};

#endif // _MPPROJECT_

The data stream operators in MPProject.cpp:
QDataStream& operator <<(QDataStream& stream, const CMPProject& project)
{
    return stream << project.m_dateTimeCreated << *(project.m_pData);
}

QDataStream& operator >>(QDataStream& stream, CMPProject& project)
{
    return stream >> project.m_dateTimeCreated >> *(project.m_pData);
}

m_pData is of type CListModel. CListModel contains the actual data stored as a QList<CListItem>.
To serialize the CListModel I added the according operators in ListModel.h:
#ifndef _LISTMODEL_
#define _LISTMODEL_

#include <QtCore/QAbstractListModel>
#include <QtCore/QList>
#include <QtCore/QStringList>

#include "ListItem.h"

typedef QMap<unsigned int, QString> TValueMap;

class CListModel : public QAbstractListModel
{
public:
    // ...

    template<typename T>
    friend void operator <<(QVariant& data, const QList<T>& target);

    template<typename T>
    friend void operator >>(const QVariant& data, QList<T>& target);

    friend QDataStream& operator <<(QDataStream& stream, const CListModel& listModel);
    friend QDataStream& operator >>(QDataStream& stream, CListModel& listModel);

private:

    QList<CListItem> m_items;
};

#endif // !_LISTMODEL_

and ListModel.cpp:
template<typename T>
void operator <<(QVariant& data, const QList<T>& target)
{
    QVariantList list;
    list.reserve(target.count());
    for (int i = 0; i < target.count(); i++) {
        QVariant item;
        item << target[i];
        list.append(item);
    }
    data = list;
}

template<typename T>
void operator >>(const QVariant& data, QList<T>& target)
{
    QVariantList list = data.toList();
    target.reserve(list.count());
    for (int i = 0; i < list.count(); i++) {
        T item;
        list[i] >> item;
        target.append(item);
    }
}

QDataStream& operator <<(QDataStream& stream, const CListModel& listModel)
{
    // ERROR C2679 does not occur when I change this line to "return stream;"
    return stream << listModel.m_items;
}

QDataStream& operator >>(QDataStream& stream, CListModel& listModel)
{
    return stream >> listModel.m_items;
}

In order to serialize the contents of listModel.m_items (objects of type CListItem) I implemented the according operators in ListItem.h:
#ifndef _LISTITEM_
#define _LISTITEM_

#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QDateTime>
#include <QtCore/QVariantMap>

class CListItem
{
public:
    // ...

    friend void operator <<(QVariant& data, const CListItem& target);
    friend void operator >>(const QVariant& data, CListItem& target);
private:
    QString m_name;
    QString m_domain;
    QString m_login;
    QString m_password;
    QDateTime m_LastModified;
};

#endif // !_LISTITEM_

and ListItem.cpp:
template<typename T>
void operator <<(QVariant& data, const T& target)
{
    data = QVariant::fromValue<T>(target);
}

template<typename T>
void operator >>(const QVariant& data, T& target)
{
    target = data.value<T>();
}

void operator <<(QVariant& data, const CListItem& target)
{
    QVariantMap map;
    map["name"] << target.m_name;
    map["domain"] << target.m_domain;
    map["login"] << target.m_login;
    map["password"] << target.m_password;
    map["dateModified"] << target.m_LastModified;
    data << map;
}

void operator >>(const QVariant& data, CListItem& target)
{
    QVariantMap map;
    data >> map;
    map["name"] >> target.m_name;
    map["domain"] >> target.m_domain;
    map["login"] >> target.m_login;
    map["password"] >> target.m_password;
    map["dateModified"] >> target.m_LastModified;
}

A: I fixed it.
The problem was that I didn't have operators to put my QList into a QDataStream. But I defined wrappers to store my list in QVariant, so (of course) I just should have used those.
QDataStream& operator <<(QDataStream& stream, const CListModel& listModel)
{
    QVariant var;
    var << listModel.m_items;
    return stream << var;
}

QDataStream& operator >>(QDataStream& stream, CListModel& listModel)
{
    QVariant var;
    stream >> var;

    var >> listModel.m_items;

    return stream;
}

A: It looks like here is no operator<< overloaded for arguments: QDataStream & and QList<CListItem> const&. In the reference here and here, there aren't any documented.
The second error addresses this, but there also should be QList<CListItem> argument mentioned. Was that the full error message?
Basically, you should be using this:
QDataStream& operator <<(QDataStream& stream, const CListModel& listModel)
{
    for(auto const& item : listModel.m_items)
        stream << item; // write elements one by one

    return stream;
}

This template might serve you for multiple types (or something akin to Pretty-print C++ STL containers):
template <typename Stream, typename Containter>
Stream& operator <<(Stream& stream, const Containter& container)
{
    for(auto const& item : container)
        stream << item;

    return stream;
}

Your code would be valid without making change to operator<< you defined. Hope that helps.


text:
Q: Using videojs with youtube.js Im using the videojs(http://videojs.com/) Plugin in combination with youtube.js(https://github.com/eXon/videojs-youtube) to play youtube videos in a custom player.
In the head im loading the css from video.js and this is the html body

   <video
     id="vid1"
     class="video-js vjs-default-skin"
     controls
     autoplay
     width="640" height="264"
     data-setup='{ "techOrder": ["youtube"], "sources": [{ "type": "video/youtube", "src": "https://www.youtube.com/watch?v=xjS6SftYQaQ"}] }'
   >
   </video>

So I have tried and the solution is replacing :

A: You need to place under your code, where you build your youtube a variable:
const youtube = require('videojs-youtube');

And also the require for your "videojs" e.g.
const videojs = require('video.js');
_player = videojs('#video-js');


text:
Q: Perl modules hierarchy and composition Reading more and more about Perl, I'm having doubts about how I organized my modules on my current project.
I have a main namespace - let's call it "MyProject".
In this project, the base data are graphs in which each object has a class. objects are linked with relations. Both objects and relations can have attributes.
There is a part of the project where I use a model to validate these graphs.
So I have a Model class that is composed of objects of class Class, Relation and Attribute.
Classes Class, Relation and Attribute are used by class Model only, so it made sense to me to organize the modules as follows:

*

*MyProject::Model

*MyProject::Model::Class

*MyProject::Model::Relation

*MyProject::Model::Attribute

But I'm starting to think that it will make sense to me only if I ever dare to relase parts of my project in CPAN. I think people will believe that Class, Relation and Attribute are inheriting Model and not composing it.
So: shall I reorganize my modules this way:

*

*MyProject::Model

*MyProject::Class

*MyProject::Relation

*MyProject::Attribute

Or maybe indicate that Class, Relation and Attribute are parts of Model by appending their names?

*

*MyProject::Model

*MyProject::ModelClass

*MyProject::ModelRelation

*MyProject::ModelAttribute

My question: What is the currently considered a best practices for module organization and naming when it comes to composition?
Cross-posted at Perlmonks

A: Your concern is correct. Typically, packages are named by either inclusion or inheritance. I'm going to make up a more realistic example. Let's say we are building an online shop.
Inclusion
You first pick a namespace for your project. In the business world, you often see namespaces with the company name first, to distinguish proprietary modules from CPAN ones. So the project's namespace could be:
OurCompany::Shop

Then probably the main class or module for the application is called the same, so we have a
OurCompany/Shop.pm

We will have a bunch of things that we need to make an online shop. If our project is MCV, there are controllers and models and stuff like that. So we might have these things:
OurCompany::Shop::Controller::ProductSearch
OurCompany::Shop::Controller::Cart
OurCompany::Shop::Controller::Checkout
OurCompany::Shop::Model::Database

All of those map to modules direcly.
OurCompany/Shop/Controller/ProductSearch.pm
OurCompany/Shop/Controller/Cart.pm
OurCompany/Shop/Controller/Checkout.pm
OurCompany/Shop/Model/Database.pm

But there is no OurCompany::Controller as a base class. That name is just a namespace to sort things into.
Then there are some things that are just there, and get used by OurCompany::Shop, like the Session engine.
OurCompany::Shop::Session

Those go on the first level after the project, unless they are very specific.
Now of course there is some kind of engine behind the session system. Let's say we are fancy and use Redis for our sessions. If we implement the communication ourselves (which we wouldn't because CPAN has done that already), we would stick that implementation into
OurCompany::Shop::Session::Engine::Redis

The only thing that uses this module is OurCompany::Shop::Session under the hood. The main application doesn't even know what engine is used. Maybe you don't have Redis on your development machine, so you are using plain files.
OurCompany::Shop::Session::Engine::File

Both of them are there, they belong to ::Session, but they don't get used by any other part of the system, so we file them away where they belong to.
Inheritance
We will also have Products1. The base product class could be this.
OurCompany::Shop::Product

And there is a file for it.
OurCompany/Shop/Product.pm

Just that this base product never gets used directly by the shop, other than checking that certain things have to have ::Product in their inheritance tree (that's an isa check). So this is different from ::Session, which gets used directly.
But of course we sell different things, and they have different properties. All of them have prices, but shoes have sizes and hard drives have a capacity. So we create subclasses.
OurCompany::Shop::Product::Shoe
OurCompany::Shop::Product::HardDrive

And those have their own files.
OurCompany/Shop/Product/Shoe.pm
OurCompany/Shop/Product/HardDrive.pm

We might also distinguish between a mechanical HardDrive and an SSD, so we make an ::SSD subclass.
OurCompany::Shop::Product::HardDrive::SSD

OurCompany/Shop/Product/HardDrive/SSD.pm

So basically things are put in the same namespace if they belong to each other. Here's a tree view of our lib.
.
└── OurCompany
    ├── Shop
    │   ├── Controller
    │   │   ├── Cart.pm
    │   │   ├── Checkout.pm
    │   │   └── ProductSearch.pm
    │   ├── Model
    │   │   └── Database.pm
    │   ├── Product
    │   │   ├── HardDrive
    │   │   │   └── SSD.pm
    │   │   ├── HardDrive.pm
    │   │   └── Shoe.pm
    |   ├── Product.pm
    │   └── Session.pm
    │   │   └── Engine.pm
    │   │       ├── File.pm
    │   │       └── Redis.pm
    └── Shop.pm

To sum up:

*

*For your main module, the file name is the last part of the project's package name. Everything else goes under there.

*Stuff that belongs together gets grouped under one namespace.

*Stuff that inherits from something goes under that something's namespace.

*Stuff that only gets used by one specific thing goes under that thing.

Never append things together like MyProject::AB to indicate that it belongs to MyProject::A. Always use namespace separators to organize your namespaces. Consider this, which looks just plain wrong:
OurCompany::ShopProductShoe

1) It might be that we also have a backoffice application that also uses the same product classes. In that case, we might have them as OurCompany::Product, and they get used by two different projects, OurCompany::Shop and OurCompany::BackOffice.


text:
Q: How to create popup image on top of other applications, while my application is running in the background? I have an Android application which in some stage run in the backgroung, and once some event happens, it takes over, and appears in the foreground.
now I want something more complex. when my activity is in the background, show small image at the bottom of the screen (like a popup ad), no matter what application is running.
is this possible? (it's not the case of writing application, and letting ads engine to insert ads into my application. I want kind of opposite, without any integration)

A: Like Jan said, you should be very careful with this as it can easily irritate users if not handled properly. Here is one way of showing a view overlay. You would need the owner of the phone to expressly grant you overlay permissions. You can then display views from a service class. You need to remember to handle the permissions correctly. You need to specify the following permission in your manifest -
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

Because this is a dangerous permission, the user has to manually give you permission in settings. You can then in your service class work with windowManager to handle view alignment, size and details. For example -
windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        params = WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                PixelFormat.TRANSLUCENT)

        params.gravity = Gravity.BOTTOM
        if (view.windowToken != null) {
          try {
            windowManager!!.addView(view, params)
        } catch (e: Exception) {
            Log.d("The exception is", e.toString())
        }

        }

A: You can do this, but it is very much against the design principles of Android itself, and people will probaly remove your app instantly.


text:
Q: Syntactic sugar for making new dictionary entries + other operations in Gforth I am a Forth newbie, trying to develop some (pseudo useful) toys to learn the language. I want to make the following operations condensed:
[ifundef] vehicles    2variable vehicles [then]
[ifundef] cars<       2variable cars<    [then]
vehicles 2@ s" cars "    s+ vehicles 2!
cars<    2@ s" vehicles" s+ cars<    2!

by the following (much more compact) instruction
-> vehicles cars

Or, in other words:

*

*"->" parse the two following names

*for the first name create a dictionary entry "vehicle" for a 2variable like structure, if it doesn't already exists, a string will be assigned to it

*for the second name create another entry "cars<" (note the <), if it doesn't already exists, also a 2variable

*then add (not replace) the string "cars" to variable vehicle

*and add the string "vehicles" to variable cars<

I made an hack to obtain just this behavior using strings manipulation and evaluating...
: space+ ( str -- ) s"  " s+ ;
\ use like: cars add alfa-romeo (first is a 2variable name, second a parsed name)
: add ( a "name" -- ) dup >r 2@ parse-name space+ s+ r> 2! ;

create _x 256 chars allot align
: _x@ ( -- ) _x count ;
: _x! ( -- ) _x place ;

create _y 256 chars allot align
: _y@ ( -- ) _y count ;
: _y! ( -- ) _y place ;

: init_x ( str -- ) 2dup s" [ifundef] " 2swap s+ s"  2variable " s+ 2swap s+ s"  [then]" s+ evaluate ;
: init_y ( str -- ) 2dup s" [ifundef] " 2swap s+ s" < 2variable " s+ 2swap s" <" s+ s+ s"  [then]" s+ evaluate ;

: make-dictionary-entries ( -- ) _x@ init_x    _y@ init_y ;
: add-strings-to-entries  ( -- ) _x@ s"  add "  s+ _y@ s+ evaluate
                                 _y@ s" < add " s+ _x@ s+ evaluate ;

: -> parse-name _x! parse-name _y!
     make-dictionary-entries
     add-strings-to-entries ;

\ CUSTOM TESTING to improve readability of the examples
: test( POSTPONE assert( ; immediate
: true! 0= throw ;
: false! throw ;
: same-string! str= true! ;

-> vehicles cars
test( vehicles 2@  s" cars "     same-string! )
test( cars< 2@     s" vehicles " same-string! )

-> vehicles trucks
-> vehicles dreams
test( vehicles 2@  s" cars trucks dreams " same-string! )
test( trucks< 2@   s" vehicles "           same-string! )

-> cars ferrari
-> cars lamborghini
-> dreams lamborghini
test( cars 2@          s" ferrari lamborghini " same-string! )
test( lamborghini< 2@  s" cars dreams "         same-string! )

I think another more direct, more elegant way exists, but this is the best I can do at this time. Any suggestions?

A: Some pieces of advice

*

*Start top-down decomposition from a pure postfix solution.

*Find some kind of ideal conceptual implementation of the top-level postfix solution.

*Implement the absent words and-or levels of your Forth-system.

NB: It is not the general rules, but some weak points from the code in the question.
One common rule is following.
In the plumbing part the postfix syntax should be only used. The prefix syntax (parsing words) may take place as sugar on the top level only. I.e. any parsing word should have a postfix variant.
A general postfix solution for the given problem is: S" content" S" name" update-var
The solution
\ reference implementations of some underlying words for testing purpose only
: s, ( d-txt -- ) here swap dup allot move ;
: s+ ( d-txt1 d-txt2 -- d-txt3 ) here >r 2swap s, s, r> here over - 0 c, ;
: s+! ( d-txt addr -- ) dup >r 2@ 2swap s+ r> 2! ; \ '+!' naming convention
: gs+ ( d-txt1 -- d-txt2 ) s"  " s+ ; \ add gap string ('space+' is too long)
\ some Forth-systems have these words as factors:
: created ( d-txt-name -- ) s" create " 2swap s+ evaluate ;
: obey ( i*x d-txt-name wid -- j*x true | i*x d-txt-name false )
  >r 2dup r> search-wordlist if nip nip execute true exit then  false
;

\ the solution itself

wordlist constant v \ for special auto-created variables

: make-var ( d-txt-name -- addr )
  get-current >r v set-current
  created here 0 , 0 ,
  r> set-current
;
: obtain-var ( d-txt-name -- addr )
  v obey if exit then  make-var
;
: update-var ( d-txt-content d-txt-name -- )
  obtain-var s+!
;
: -> \ "vehicles" "cars"
  parse-name parse-name
  2over gs+ 2over s" <" s+ update-var
  gs+ 2swap update-var
;

d- prefix in the stack notation symbols here means a two-cells value, and d-txt- prefix means a string (cell-pair).
s, ( d-txt -- ) stores given string into the data space as is (see also , and c,); NB: in Gforth it stores in counted string format (see 3.1.3.4 Counted strings).
created is a postfix variant of create (in a proper system the last should be defined via the first); regarding etymology see also the standard words included (postfix form) and include (prefix form, parsing word).
Also it is better to use a separate wordlist for these auto-created variables to avoid possible issues on clash names (e.g. what if you need -> here str). See the variant without a separate wordlist in the revision 8.
To write testcases the well-known ttester.fs library can be also used (in Gforth it is located in ./test/ directory). In this library -> word is defined for its own purpose, so the synonyms can be used to overcome undesired shadowing.


text:
Q: How to check if memory is accessible or not? I am trying to debug a crash issue where memcpy is trying to access a memory location which does not exist and fails. Following is a reduced version of the problem code:
void func_foo(int **a) {
   int *b, c;
   if (*a) {
       b = *a;
   }
   memcpy(&c, b, sizeof(int));//this crashes because address "b" is not accessible.
}

My question is: is there a way I can check if memory is accessible before attempting the memcpy, or is there another protection mechanism to prevent the crash here? Would not checking **a cause a crash as well in this case?

A: There is no, portable way, to programmatically test if a pointer is pointing to valid accessible memory.
This is one reason for the highly recommended practice of always setting your pointers to NULL when the memory they were pointing to was freed and at initialization, so you have something to test against.
Would not checking **a cause a crash as well in this case?
Correct, all you're doing here is assigning the passed-in value to a local variable then attempting to access it. If the local is bad, it's because the passed-in value is bad. Garbage in, garbage out.

To address the code you provided:
   if (*a) {
       b = *a;
   }
   memcpy(&c, b, sizeof(int));//you really shouldn't be executing this at all unless
                              // you're setting b, so it should be within the if check
                              // and only executed after b=*a

A: If someone passes you a garbage pointer in *a there's no way of checking (not platform independent anyway) if that can be accessed.
But if someone is passing a==NULL or *a==NULL you could at least check for that (Eric mentioned that first in his comment to the other answer):
void func_foo(int **a)
{
   int *b= NULL, c;

   if (a!=NULL) {
       b = *a;
   }

   if (b!=NULL) {
       printf("about to access memory at address 0x%p\n", b);
       memcpy(&c, b, sizeof(int));//this crashes because address "b" is not accessible.
       // btw same as c= *b  or  c= **a;
   }
   else {
       printf("someone passed us a null pointer either in a or *a\n");
   }
}

Just for fun, a simplified version would be:
void func_foo(int **a)
{
   int c;

   if (a!=NULL && *a!=NULL) {
       c = **a;
   }
   else {
       printf("someone passed us a null pointer either in a or *a\n");
   }
}


text:
Q: hive execution engine -- Spark -- NoClassDefFoundError - SparkCounters I am trying to run a simple select count(*) from table on hive. However i get an error after the state changes to STARTED.
Hadoop Version -- 2.6.2
Spark Version  -- 1.6.2
Hive Version   -- 2.0.1
The following is the complete flow
hive> select count(*) from customers;
Query ID = hadoop_20170302215442_6493f265-3121-4eaf-b2d6-eea5b08ae591
Total jobs = 1
Launching Job 1 out of 1
In order to change the average load for a reducer (in bytes):
  set hive.exec.reducers.bytes.per.reducer=<number>
In order to limit the maximum number of reducers:
  set hive.exec.reducers.max=<number>
In order to set a constant number of reducers:
  set mapreduce.job.reduces=<number>
Starting Spark Job = b22ec8e6-4b11-49fe-9fdd-001aa7248084
state = SENT
state = SENT
state = SENT
state = SENT
state = SENT
state = SENT
state = SENT
state = STARTED
state = STARTED
state = STARTED

Query Hive on Spark job[0] stages:
0
1

Status: Running (Hive on Spark job[0])
Job Progress Format
CurrentTime StageId_StageAttemptId: SucceededTasksCount(+RunningTasksCount-    FailedTasksCount)/TotalTasksCount [StageCost]
2017-03-02 21:55:02,526 Stage-0_0: 0(+1)/1      Stage-1_0: 0/1
state = STARTED
2017-03-02 21:55:03,537 Stage-0_0: 0(+1,-1)/1   Stage-1_0: 0/1
state = FAILED
Status: Failed
FAILED: Execution Error, return code 3 from     org.apache.hadoop.hive.ql.exec.spark.SparkTask

In the Yarn Log file i see the following error..
Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent failure: Lost task 0.3 in stage 0.0 (TID 3, slcag034.us.oracle.com): java.lang.NoClassDefFoundError: Lorg/apache/hive/spark/counter/SparkCounters;
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2583)

I have set the spark.driver.extraClassPath in hive-site.xml
<property>
        <name>spark.driver.extraClassPath</name>
        <value>file:///***/***/binary/apache-hive-2.0.1-bin/lib/hive-exec-2.0.1.jar</value>
    </property>

Can someone tell me what could have gone wrong please.
Regards
Bala


text:
Q: How would one integrate $\sin\left(\pi t^2\right)$ from 0 to 1? I got this problem on my final exam and was completely lost on how to solve it. It's pretty short as problems go but it was surprisingly difficult. Does u-sub work here?
$$ \int_{0}^{1}\sin(\pi t^2) dt $$
Thanks for your help!

EDIT:
I'd appreciate if a mod could delete this. I appear to have remembered the problem incorrectly and it would be impossible to solve using things learned in Calc 1.

A: Since you're in the range $[0,1]$ you can deal with Taylor Series
$$\sin(\pi t^2) = \sum_{k = 0}^{+\infty} \frac{(-1)^k (\pi t^2)^{2k+1}}{(2k+1)!}$$
Hence
$$\int_0^1 \sum_{k = 0}^{+\infty} \frac{(-1)^k (\pi t^2)^{2k+1}}{(2k+1)!} = \sum_{k = 0}^{+\infty} \frac{(-1)^k \pi^{2k+1}}{(2k+1)!}\int_0^1 t^{2(2k+1)}\ \text{d}t$$
The integral is trivial and you get at the end
$$\sum_{k = 0}^{+\infty} \frac{(-1)^k \pi^{2k+1}}{(2k+1)!} \frac{1}{4k+3}$$
If you are in search of numerical approximation then you can develop the series term by term:
$$\frac{\pi}{3} - \frac{\pi^3}{42} + \frac{\pi^5}{1212} - \frac{\pi^7}{10900} + \ldots $$
Numerical result:
$$0.5048545941136863...$$

A: This is likely asking for a numerical approximation or you didn't write it correctly. The exact answer is $\frac{\operatorname{S}(\sqrt{2})}{\sqrt{2}}$ where $\operatorname{S}(x)$ is the Sine Integral function, which is cannot be represented in terms of elementary functions (the basic functions you'll see in a calculus class). A numerical approximation is $0.504855...$

A: I believe you are looking at Fresnel's integral, particularly,
$$S(x)=\int_0^x\sin(t^2)\ dt$$


text:
Q: Under which circumstances does iOS call -accessibilityScroll:? I implemented all accessibility action methods in my table view and added the "adjustable" trait. I made custom control with UITableView to select an item by scrolling. It does not have typical rows to select. It is intended for scrolling and a marker shows what is selected. Similar to UIPickerView or the selector in Weightbot. It is a custom date picker control to select event date.
But iOS never calls my accessibility action methods. A flick up or down in the table view Voice Over does not react properly. It wildly jumps around.
Must I set a delegate or data source for voice over? How can I get it to correctly scoll my table view up / down when user flicks up / down like in UIPickerView?
It would help a lot to understand how exactly Apple made UIDatePicker accessible with VoiceOver. It uses UITableView for each column. You can drag between columns to select column. Then you can flick up down to increase or decrease.
EDIT: Dumped recursively info about UIDatePicker to see how it is set up.
 UIDatePicker:
     _UIDatePickerView:
         UIView:
         _UIOnePartImageView:
         _UIPickerWheelView:
         _UIPickerViewSelectionBar:
         UIPickerTableView:; contentOffset: {0, 2.19991e+06}>
             UIPickerTableViewWrapperCell:
                 UITableViewCellContentView:
                 UIDatePickerWeekMonthDayView:
                     UILabel: {label = 28. Jul} {traits = staticText } {accessibilityIncrement} {accessibilityDecrement} {accessibilityScroll:} {accessibilityPerformEscape} {accessibilityPerformMagicTap}

It prints ALL available accessibility related things when set / implemented. Like you can see, strangely the UILabel of the table view cells implement the scroll method. This doesnt make sense to me. Why is this? Why not the UIPickerTableView itself? and also there is no trait saying adjustable in the entire UIDatePicker.
This is code I use to dump this information. I call it initially on UIDatePicker after 2 second delay just to be sure. I put this code in category on UIView.
- (NSString *)description {
    NSString *className = NSStringFromClass([self class]);

    NSMutableString *str = [NSMutableString stringWithFormat:@"%@: ", className];

    if (self.isAccessibilityElement) {
        if (self.accessibilityLabel) {
            [str appendFormat:@"{label = %@} ", self.accessibilityLabel];
        }

        UIAccessibilityTraits traits = self.accessibilityTraits;
        [str appendString:@"{traits = "];
        if (traits & UIAccessibilityTraitAdjustable) {
            [str appendString:@"adjustable "];
        }
        if (traits & UIAccessibilityTraitAllowsDirectInteraction) {
            [str appendString:@"interaction "];
        }
        if (traits & UIAccessibilityTraitButton) {
            [str appendString:@"button "];
        }
        if (traits & UIAccessibilityTraitCausesPageTurn) {
            [str appendString:@"pageTurn "];
        }
        if (traits & UIAccessibilityTraitHeader) {
            [str appendString:@"header "];
        }
        if (traits & UIAccessibilityTraitImage) {
            [str appendString:@"image "];
        }
        if (traits & UIAccessibilityTraitKeyboardKey) {
            [str appendString:@"kbKey "];
        }
        if (traits & UIAccessibilityTraitLink) {
            [str appendString:@"link "];
        }
        if (traits & UIAccessibilityTraitNone) {
            [str appendString:@"none "];
        }
        if (traits & UIAccessibilityTraitNotEnabled) {
            [str appendString:@"notEnabled "];
        }
        if (traits & UIAccessibilityTraitPlaysSound) {
            [str appendString:@"sound "];
        }
        if (traits & UIAccessibilityTraitSearchField) {
            [str appendString:@"search "];
        }
        if (traits & UIAccessibilityTraitSelected) {
            [str appendString:@"selected "];
        }
        if (traits & UIAccessibilityTraitStaticText) {
            [str appendString:@"staticText "];
        }
        if (traits & UIAccessibilityTraitSummaryElement) {
            [str appendString:@"summaryElement "];
        }
        if (traits & UIAccessibilityTraitUpdatesFrequently) {
            [str appendString:@"updatesFreq "];
        }
        [str appendString:@"} "];

        if ([self respondsToSelector:@selector(accessibilityIncrement)]) {
            [str appendString:@"{accessibilityIncrement} "];
        }
        if ([self respondsToSelector:@selector(accessibilityDecrement)]) {
            [str appendString:@"{accessibilityDecrement} "];
        }
        if ([self respondsToSelector:@selector(accessibilityScroll:)]) {
            [str appendString:@"{accessibilityScroll:} "];
        }
        if ([self respondsToSelector:@selector(accessibilityPerformEscape)]) {
            [str appendString:@"{accessibilityPerformEscape} "];
        }
        if ([self respondsToSelector:@selector(accessibilityPerformMagicTap)]) {
            [str appendString:@"{accessibilityPerformMagicTap} "];
        }
    }

    return str;
}


text:
Q: Is it possible/legal to return reference to input temporary arguments which are passed by reference My question is : is it legal to return a reference to an input variable which is passed by reference.
I borrow the example from C++: Life span of temporary arguments?  and return by rvalue reference
#include <iostream>

#include <string>

class MatrixClass
{
public:
int m_value;

std::string m_str;

MatrixClass(int a)
{
    m_value = a;
    std::cout << "hello: " << m_value << '\n';
}

MatrixClass(const MatrixClass& A)
{
    m_value = A.m_value;

    std::cout << "hello: " << m_value << '\n';

    if (A.m_str == "temp_in_*")
    {
        std::cout << "string: " << "copied from temp_in_*" << '\n';
    }

}

void operator=(const MatrixClass& A)
{
    m_value = A.m_value;

    std::cout << "hello: " << m_value << '\n';

    if (A.m_str == "temp_in_*")
    {
        std::cout << "string: " << "copied from temp_in_*" << '\n';
    }
}

~MatrixClass()
{
    std::cout << "bye: " << m_value << '\n';

    if (m_str == "temp_in_*")
    {
        std::cout << "string: " << "temp_in_*" << '\n';
    }
}

};

MatrixClass& operator+(MatrixClass& tempClassA, MatrixClass& tempClassB)
{
    tempClassA.m_value += tempClassB.m_value;
    return tempClassA;
}

MatrixClass operator*(MatrixClass& tempClassA, MatrixClass& tempClassB)
{
    MatrixClass Temp(101010);
    Temp.m_value = tempClassA.m_value * tempClassB.m_value;

    Temp.m_str = "temp_in_*";

    return Temp;
}

int main()
{
    MatrixClass A1(2);
    MatrixClass A2(3);
    MatrixClass A3(10);
    MatrixClass A4(11);
    MatrixClass A5(12);

    std::cout << "start of expression " << '\n';

    MatrixClass A6(0);

    A6 = A1 * A2 + A3 * A4 + A5 * A6;

    std::cout << "end of expression " << '\n';

    std::cout << "A6.m_value: " << A6.m_value << '\n';

    std::system("pause");
}

the operator return a reference to its input which is a temporary variable, and pass
it to another operator:  operator*(A1, A2) return a temporary variable, also operator*(A3, A4), operator*(A5, A6)
Is there any problem with the lifetime of the temporary variables ? I am developing a Matrix class.
What happens if the expression is more complicated, such as:
    (A+B*C)*((A*B + C)*A)

A general question is (take from return by rvalue reference)
is this possible:
change
A compute(A&& v)
{
  (do something to v)

  return v;
}

to
A& compute(A& v)
{
  (do something to v)
  return v;
}

A: Yes, it is legal for a function to return references to input parameters, in the sense that it will compile and there are many uses where it will work without problems.  The lifetime of any temporaries created in an expression is the lifetime of the full expression or statement, so as long as the reference is not used beyond the expression, the usage should work fine.  It is somewhat risky, though, because the caller may not be aware of the reference propagation the function does, and the special rules for extension of temporary lifetimes don't generally apply when the reference is passed through an intermediary function.
Your examples involve modifying and returning a reference to non-const lvalue instance.  These types of uses, in general, will be harder to run into the pitfalls than references to const or references to rvalues.  A reference to non-const lvalue can't be bound to a temporary (at least not without going through some hoops to trick the compiler), so you will generally have to pass an actual l-value (non-temporary) named variable (or other long-lived object) into them.  When that reference is then passed out of the function as a return value, it will refer to whatever long-lived object was passed in.  (You can still get into trouble if you don't properly manage lifetimes, of course, but at least the lifetimes we're talking about in this case are generally more than a single statement/expression.)
If you pass rvalue references through your function, and especially if they get translated to a non-const lvalue somewhere down the expression tree (which is somewhat easy to do since the language, as a safety feature, decays rvalues into lvalues whenever they're bound to a name), the temporary nature of the reference can be lost and it is easier to accidentally bind the reference to a long-lived reference, which would outlive the temporary that it is bound to (which generally won't live beyond the statement/full-expression in which it is created).  This is why I generally favor returning (and usually passing) r-values by value rather than by reference.  Then, the compiler is more aware of the lifetime issues and the usages are generally more foolproof.  In many cases, the compiler can elide the move constructions anyway, and when it can't, moves are generally cheap.


text:
Q: Reverse Proxying Google Cloud Storage public URL fails / 404s I'm trying to load some assets from Google Cloud Storage (GCS) onto a website, but I want to use a proxy so if I visit mysite.com/page/asset.html I want it to load the content from http://storage.googleapis.com/my-bucket/directory/asset.html without redirecting.
In my apache configs, I am utilizing mod_proxy
ProxyPass "/page/asset.html" "http://storage.googleapis.com/my-bucket/directory/asset.html"
ProxyPassReverse "/page/asset.html" "http://storage.googleapis.com/my-bucket/directory/asset.html"

If I visit /page/asset.html I get a 404 NoSuchBucketThe specified bucket does not exist.
I'm using HTTP as its just the development environment - I tested this by replacing the GCS URL with a URL from another development environment and that worked. I am thinking that there is some config that I've missed out for proxying GCS.
Note that the GCS URLs are public and can be visited without authentication.

A: For anyone else that comes across this issue
The problem is that I had ProxyPreserveHost On as it was serving some of my other proxies, but to access GCS we want to switch that off.
Now I can access the assets fine.
So my code looks like:
ProxyRequests Off
ProxyPreserveHost On
ProxyPass /first/proxy https://external.com/fproxy/
ProxyPassReverse /first/proxy https://external.com/fproxy/
ProxyPreserveHost Off
ProxyPass "/page/asset.html" "http://storage.googleapis.com/my-bucket/directory/asset.html"
ProxyPassReverse "/page/asset.html" "http://storage.googleapis.com/my-bucket/directory/asset.html"


text:
Q: Base case for printing String using recursion when the String length is an odd number my program uses recursion to print a String in the form of a triangle:
Sample input: "abcdefghij"
Sample output:
aj
abij
abchij
abcdghij
abcdefghij

Sample input: "abcdefghi"
Sample output:
    a
   abi
  abchi
 abcdghi
abcdefghi

Issue is this works only when String length is even. Please how do i adjust the base case to print the very middle character?
Here is my code:
public class DisplayTriangle
{
  public static void main(String[]parms)
  {
    print ("abcdefghij");
  }
  public static void print(String str)
  {

    int mid = str.length()/2;
    String first="";
    String last="";
    print(str,0,str.length()-1,first,last);
  }

  public static void print(String str, int start, int end,String first, String last)
  {
    if( start >= end ||  end <=start )
    {
      return;
    }
    first+=str.charAt(start);
    last =  str.charAt(end)+last;
    System.out.println( first+ last );
    print(str, (start+1), (end-1), first, last);
  }
}

A: This will do it, without excessive string concatenation, and with correct indentation:
private static void print(String str) {
    if (! str.isEmpty())
        print(str, (str.length() - 1) / 2, 1, (str.length() - 1) | 1);
}
private static void print(String str, int indent, int leftLen, int rightIdx) {
    for (int i = 0; i < indent; i++)
        System.out.print(' ');
    System.out.println(str.substring(0, leftLen) + str.substring(rightIdx));
    if (leftLen < rightIdx)
        print(str, indent - 1, leftLen + 1, rightIdx - 1);
}

Output
    aj
   abij
  abchij
 abcdghij
abcdefghij

    a
   abi
  abchi
 abcdghi
abcdefghi

Explanation
The second print method should be pretty obvious: Print indent spaces, print leftLen character from str, and all character starting at rightIdx. If not done, recurse with one less indent, one more from left, and one character earlier from right.
Looking at the sample output, the value of indent should be 4 for both length 10 and length 9, so (str.length() - 1) / 2 will calculate that.
First call should always print 1 character from the left, so that's simple.
Now, the initial value of rightIdx should be 9 for the even length 10, so the j will be printed, and should also be 9 for the odd length 9, so nothing will be printed. So, for lengths 10/9 we subtract 1 to get 9/8, then set lowest bit (| 1) to make it 9/9.

A: Please check below modified version of your print function
public static void print(String str, int start, int end,String first, String last)
  {
  if( start > end ||  end <start )
  {
    return;
  }
if(start==end){
    first+=str.charAt(start);
    last =  str.charAt(end+1)+last;
    System.out.println( first+ last );
    return ;
}
first+=str.charAt(start);
last =  str.charAt(end)+last;
System.out.println( first+ last );
print(str, (start+1), (end-1), first, last);
}

A: Try to do with 2 methods
1. for even , e.g,

    if(string.length()%2==0)

    {
    //Method for Even
    }

2. for odd , e.g,

    else

    {
    //Method for odd
    }