Q:

Limit data values displayed in MATLAB histogram

I have a vector that I want to print a histogram of of data for. This data ranges from -100 to +100. The amount of data around the outer edges is insignificant and therefore I don't want to see it. I am most interested in showing data from -20 to +20.
1.) How can I limit that window to print on my histogram?
The amount of data I have at 0 outnumbers of the amount of data I have anywhere in the dataset by a minimum of 10:1. When I print the histogram, the layout of element frequency is lost because it is outnumbered by 0.
2.) Is there a way that I can scale the number of 0 values to be three times the number of -1 entries?
I am expecting an exponential drop of this dataset (in general) and therefore three times the frequency of -1 would easily allow me to see the frequency of the other data.

A:

1) You can limit the histogram range you see on the plot by just setting the X axes limits:
xlim([-20 20])

Setting bins in hist command is good, but remember thatall the values outside the bins will fall into the most left and right bin. So you will need to set the axes limits anyway.
2) If there is a big difference between values in different bins, one way is to transform values on Y axes to log scale. Unfortunately just setting Y axes to log (set(gca,'YScale','log')) does not work for bar plot. Calculate the histogram with hist or histc (depending on whether you want to specify bins centers or edges) and log2 the values:
[y, xbin] = hist(data);
bar(xbin, log2(y) ,'hist')


Q:

How to mask a email id without masking its domain name and the dots in oracle SQL?

I have multiple email ids in a table. But I need mask all the email ids using oracle SQL. Below are some examples of masking email ids,
Input : Output :

alex.hales@gmail.com = ****.hales@*****.com
Joeroot.eng@yahoo.co.in = *****ot.eng@*****.**.in

I want to:
First Part:
For each email ids first 5 charters from the left hand side of @ should be masked with *, but if a . is coming within the first character then it should not be masked it will remain same.
Second Part:
right hand side from @ will be masked with *, again if a . is there then it will remain same and the domain name like .com, .in should be as is.
I have tried:
enter code here

Declare
v_id Varchar2(100):= 'abc.defghijklmnop@qrst.uv.wxyz';
v_id1 Varchar2(100);
v_id2 Varchar2(100);
v_id3 Varchar2(100);
v_id4 Varchar2(100);
v_id5 Varchar2(100);
v_id6 Varchar2(100);

Begin
Select v_id,
instr(v_id,'.'),
instr(v_id,'@'),
Case When instr(v_id,'.') >=6
   Then '*****'|| substr(v_id,6,(instr(v_id,'@')-5))
Else
rpad(lpad('.',instr(v_id,'.'),'*'),6,'*') || substr(v_id,7,(instr(v_id,'@')- 6))
End testing
Into v_id1,v_id2,v_id3,v_id4
From dual;

dbms_output.put_line(v_id1);
dbms_output.put_line(v_id2);
dbms_output.put_line(v_id3);
dbms_output.put_line(v_id4);
End;

o/p:::
abc.defghijklmnop@qrst.uv.wxyz.
4
18
***.**fghijklmnop@

SELECT REGEXP_REPLACE (substr(instr('abc.defghijklmnop@qrstname.uv.wxyz','@')+1),'^[.].'*')
FROM dual;

Output:
abc.defghijklmnop@****.**.****

I am not able to unmasked the domain name as well as unable to do the whole thing together.

A:

You should search for something like Oracle Data Masking and Subsetting.

Using only text operations:
WITH test_data AS
(
        SELECT 'alex.hales@gmail.com' AS email FROM dual
        UNION ALL
        SELECT 'Joeroot.eng@yahoo.co.in' FROM dual
        UNION ALL
        SELECT 't.e.s.t.ex.ampl.e@do.ma.i.com' FROM dual
        UNION ALL
        SELECT 't1@z.a' FROM dual
)
SELECT z.email,
    CASE WHEN INSTR(part1_masked, '*',1, 5) > 0
          THEN SUBSTR(part1_masked,1,INSTR(part1_masked, '*',1, 5))
               || SUBSTR(part1, INSTR(part1_masked, '*',1, 5)+1)
            ELSE part1_masked
    END || '@'
    || SUBSTR(part2_masked,1,INSTR(part2_masked, '.',-1)-1)
    || SUBSTR(part2,INSTR(part2, '.',-1,1)) AS masked_email
FROM
(
    SELECT
      email
     ,SUBSTR(t.email, 1, INSTR(t.email, '@')-1) AS part1
     ,SUBSTR(t.email,INSTR(t.email, '@')+1) AS part2
     ,regexp_replace(SUBSTR(t.email, 1, INSTR(t.email, '@')-1),
                            '[[:alnum:]]', '*') AS part1_masked
     ,regexp_replace(SUBSTR(t.email,INSTR(t.email, '@')+1),
                            '[[:alnum:]]', '*') AS part2_masked
    FROM test_data t
) z

LiveDemo
Output:
╔═══════════════════════════════╦═══════════════════════════════╗
║             EMAIL             ║         MASKED_EMAIL          ║
╠═══════════════════════════════╬═══════════════════════════════╣
║ alex.hales@gmail.com          ║ ****.*ales@*****.com          ║
║ Joeroot.eng@yahoo.co.in       ║ *****ot.eng@*****.**.in       ║
║ t.e.s.t.ex.ampl.e@do.ma.i.com ║ *.*.*.*.*x.ampl.e@**.**.*.com ║
║ t1@z.a                        ║ **@*.*                        ║
╚═══════════════════════════════╩═══════════════════════════════╝

How it works:

SUBSTR(t.email, 1, INSTR(t.email, '@')-1) AS part1 - split email (@ is delimiter)

regexp_replace(SUBSTR(t.email, 1, INSTR(t.email, '@')-1),    '[[:alnum:]]', '*') AS part1_masked - replace all alfanumeric characters with *

INSTR(part1_masked, '*',1, 5) > 0 - check if exists at least 5 * in masked string

Concatenate part up to 5 stars from masked string and the rest from unmasked

EDIT:
WITH test_data AS
(
        SELECT 'alex.hales@gmail.com' AS email FROM dual
        UNION ALL
        SELECT 'Joeroot.eng@yahoo.co.in' FROM dual
        UNION ALL
        SELECT 't.e.s.t.ex.ampl.e@do.ma.i.com' FROM dual
        UNION ALL
        SELECT 't1@z.a' FROM dual
)
SELECT z.email,
     CASE WHEN INSTR(part1, '.')-1 < 0 THEN part1_masked
          WHEN INSTR(part1, '.')-1 <=5
          THEN SUBSTR(part1_masked,1, INSTR(part1, '.'))
               || SUBSTR(part1, INSTR(part1, '.')+1)
           ELSE SUBSTR(part1_masked, 1, 5) || SUBSTR(part1, 6)
      END
    || '@'
    || SUBSTR(part2_masked,1,INSTR(part2_masked, '.',-1)-1)
    || SUBSTR(part2,INSTR(part2, '.',-1,1)) AS masked_email
FROM
(
    SELECT
      email
     ,SUBSTR(t.email, 1, INSTR(t.email, '@')-1) AS part1
     ,SUBSTR(t.email,INSTR(t.email, '@')+1) AS part2
     ,regexp_replace(SUBSTR(t.email, 1, INSTR(t.email, '@')-1),
                            '[[:alnum:]]', '*') AS part1_masked
     ,regexp_replace(SUBSTR(t.email,INSTR(t.email, '@')+1),
                            '[[:alnum:]]', '*') AS part2_masked
    FROM test_data t
) z

LiveDemo2
Ouptut:
╔═══════════════════════════════╦═══════════════════════════════╗
║             EMAIL             ║         MASKED_EMAIL          ║
╠═══════════════════════════════╬═══════════════════════════════╣
║ alex.hales@gmail.com          ║ ****.hales@*****.com          ║
║ Joeroot.eng@yahoo.co.in       ║ *****ot.eng@*****.**.in       ║
║ t.e.s.t.ex.ampl.e@do.ma.i.com ║ *.e.s.t.ex.ampl.e@**.**.*.com ║
║ t1@z.a                        ║ **@*.a                        ║
╚═══════════════════════════════╩═══════════════════════════════╝


Q:

i m trying to play mp3 from tableview while user select table row song need to play

//i have take 2 song 's array
nsmutablearray *  enrique = [[NSMutableArray alloc]init];

        [enrique addObject:@"add.mp3"];
        [enrique addObject:@"hero.mp3"];

// this section of uitableview didselectrow

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
             cell = [tableView cellForRowAtIndexPath:indexPath];

      cellText = cell.textLabel.text;

      lbl.text=cellText;

     player=[passarray objectAtIndex:indexPath.row];

       NSLog(@"mp3 %@",player);
      //  [passarray indexOfObject:player];
        [self.player prepareToPlay];
       // [player play];

         }

A:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [audioPlayer stop];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    songNumber = indexPath.row;
    [self loadPlayer:songNumber];
}

-(void)loadPlayer:(int)songIndex
{
    if(songIndex <= 0)
    {
        [previousButton setEnabled:NO];
    }
    else
    {
        [previousButton setEnabled:YES];
    }
    if(songIndex+1 >= self.arySongsList.count)
    {
        [nextButton setEnabled:NO];
    }
    else
    {
        [nextButton setEnabled:YES];
    }
    if(songIndex < self.arySongsList.count)
    {
        NSURL *audioFileLocationURL;
        audioFileLocationURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",[self.arySongsList objectAtIndex:songIndex]]];
        NSString *str = [[[NSString alloc]initWithFormat:@"%@",audioFileLocationURL]autorelease];
        str = [str lastPathComponent];
        str = [str stringByReplacingOccurrencesOfString:@"%20" withString:@" "];
        str = [str stringByReplacingOccurrencesOfString:@"%5B" withString:@"["];
        str = [str stringByReplacingOccurrencesOfString:@"%5D" withString:@"]"];
        NSError *error;
        if(songIndex == self.arySongsList.count)
        {
            NSURL *url = [NSURL URLWithString:@"http://sound18.mp3pk.com/pop_remix/ebodf11/ebodf11-15(www.songs.pk).mp3"];
            NSData *data = [NSData dataWithContentsOfURL:url];
            audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];
        }
        else
        {
            audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
        }
        [audioPlayer setNumberOfLoops:0];
        [audioPlayer setDelegate:self];
        if (error)
        {
            NSLog(@"%@", [error localizedDescription]);
            [[self volumeControl] setEnabled:NO];
            [[self playPauseButton] setEnabled:NO];
            [[self alertLabel] setText:@"Unable to load file"];
            [[self alertLabel] setHidden:NO];
        }
        else
        {
            [[self alertLabel] setText:[NSString stringWithFormat:@"%@ has loaded", str]];
            [[self alertLabel] setHidden:NO];
            //Make sure the system follows our playback status
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
            [[AVAudioSession sharedInstance] setActive: YES error: nil];
            //Load the audio into memory
            [audioPlayer prepareToPlay];
        }
    }
    if (!self.audioPlayer.playing)
    {
        [self playAudio];
    }
    else if (self.audioPlayer.playing)
    {
        [self pauseAudio];
    }
}


Q:

ASCIIEncoding.ASCII.GetBytes() Returning Unexpected Value

This C# code...
string s = "\u00C0";
byte[] bytes = ASCIIEncoding.ASCII.GetBytes(s);
Trace.WriteLine(BitConverter.ToString(bytes));

produces the following output:
3F

Why is the output not C0?

A:

Because \u00c0 is not ASCII ( 0-127 range). As result it is encoded as if it is question mark - ? (0x3F).
See MSDN article on ASCIIEncoding:

ASCIIEncoding corresponds to the Windows code page 20127. Because ASCII is a 7-bit encoding, ASCII characters are limited to the lowest 128 Unicode characters, from U+0000 to U+007F. If you use the default encoder returned by the Encoding.ASCII property or the ASCIIEncoding constructor, characters outside that range are replaced with a question mark (?) before the encoding operation is performed.

A:

It seems that you want a byte sequence that represents a string of Unicode characters. Obviously, the bytes will depend on the encoding. Since you expect C0 to be one of the bytes, it narrows the options down a bit. Here is UTF16LE, which of course is two bytes since \u00c0 completely represents a BMP character:
string s = "\u00C0";
byte[] bytes = Encoding.Unicode.GetBytes(s);
Trace.WriteLine(BitConverter.ToString(bytes));

You should read The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
by Joel Spolsky


Q:

Не с прилагательными в краткой форме

Подзабыла правило: "цели неясны", но"цели пока не ясны" - или я ошибаюсь?

A:

Всё зависит от того, утверждаете ли вы отрицательный признак (тогда слитно) или отрицаете положительный (тогда раздельно). Это общий принцип правописания НЕ с чем бы то ни было, он очень помогает не запутаться в многочисленных правилах и избавляет от зубрежки. Собственно, все правила и следуют из этого принципа.
В обоих ваших примерах возможно как слитное, так и раздельное написание. Многое зависит от контекста.
Нужно также смотреть, есть ли вообще слово с НЕ в языке. Например, слово неширок, безусловно, есть, а вот неузок нету.


Q:

Find current Windows 8 desktop background

When I had Windows 7, I used this thread to add a functionality that lets me right click the desktop and click to find the background that is currently being used. However, ever since updating to Windows 8.1 I have not been able to add the same functionality by using the same technique.
I've navigated in regedit to HKEY_CURRENT_USER\Control Panel\Desktop\Wallpaper, which gives me the following path: C:\Users\UserName\AppData\Roaming\Microsoft\Windows\Themes\TranscodedWallpaper. When I put this path into FileExplorer it asks me to open the image using one of my image editors/viewers. When I do, it is the correct image, but that's not what I'm looking for. I'm looking for the actual image's filepath so that I can delete the original photo. TranscodedWallpaper seems to update with each background change.
I know for a fact that all the backgrounds are found in D:\Users\MyUser\Pictures\Backgrounds (Windows is on the C drive), but there are about 1.4k images so looking through them each time for the image would be too much of a hassle.
So, how can I add this functionality back to my setup? At the very least, how can I get the file path of the current background image?

A:

I have found a website that has a script you can download and run on your machine, it gives you a popup for the location and name of the image running on your background. The reason you can't get your Windows 7 tweak to work is because the information is stored differently in the registry in Windows 8. In Windows 7 it's in plain text (plain English) and in Windows 8 it is stored in raw binary
01010100 01101000 01100101 00100000 01100001 01101110 01110011 01110111 01100101
01110010 01110011 00100000 01110100 01101111 00100000 01100001 01101100 01101100
00100000 01101111 01100110 00100000 01111001 01101111 01110101 01110010 00100000
01110001 01110101 01100101 01110011 01110100 01101001 01101111 01101110 01110011
00100000 01100001 01110010 01100101 00100000 01101111 01101110 00100000 01000111
01101111 01101111 01100111 01101100 01100101 00101110 01100011 01101111 01101101
00101110 00101110 00101110

You can find the script here

A:

Although this is now an old question, I thought it still worth making the following post. Until recently I’ve been running Windows 7 and a few years ago as an exercise had written a simple program running with a system tray icon to discover the path to the current desktop background image. When I upgraded to Windows 10 this no longer worked of course, so I went looking and found Ramesh Srinivasan's blog and John Dangerbrooks' scripts. As a result, I’ve updated my program to work for Windows 8 and beyond and to work for different images for multi-monitor environments, while also maintaining backwards compatibility with Windows 7.
I’m sharing this program with the wider community in case anyone else likes the idea of having this as a system tray tool. It is written in C# and requires .Net framework v4, and is available as separate .zip files for x86 (32-bit) and x64 (64-bit) environments. There’s no installer, it’s just a simple executable with a readme file. Personally I start it automatically using the HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run key, but I leave that detail to you. More details are in the readme.
The zip files are located here https://onedrive.live.com/redir?resid=B2EA2CF6592EC937!839&authkey=!AMNZgrGbt9raflQ&ithint=folder%2czip. (The old short link http://1drv.ms/1OoQRti appears not to work any more - has Microsoft removed the ability to generate short links for OneDrive folders?)


Q:

Exclude public pages from access control list

I have application in Symfony2 with 2 roles: ROLE_ADMIN and ROLE_PARTNER. Also I have some public pages. All public pages starts with URL "/public/". I want to protect all application excluded these public items.
My current config:
access_control:
    - { path: /.*, role: ROLE_PARTNER|ROLE_ADMIN }
    - { path: /public/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }

But it works wrong (looping redirection).

A:

Change the order:
access_control:
    - { path: ^/public/, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/, role: ROLE_PARTNER|ROLE_ADMIN }

The second option is to turn off security for the public section completely:
firewalls:
    public:
        pattern: ^/public/
        security: false

A:

Add:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }

See "Common Pitfalls" in http://symfony.com/doc/current/book/security.html#using-a-traditional-login-form


Q:

What does M15 mean?

Does anyone know what M15 means in the following context?
"And we are again at war albeit with an unseen enemy whose poisonous tentacles have the potential to reach into every corner of our world. At the time of writing, according to M15, the current UK threat level for international terrorism is "severe" – which means that an attack is likely."
The paragraph above is from this article: http://www.telegraph.co.uk/news/uknews/terrorism-in-the-uk/12109626/Its-time-to-bring-back-national-ID-cards.html
In case you need more context
I can't find anything useful on the internet.
Thanks!

A:

I believe that this is most likely a typo, meaning to say MI5.
The fact that the UK Terror Threat levels are shown on the MI5 website shows that this was most likely a typo. Also, a Google search for M15 returns with nothing, as you specified in your question.


Q:

What Does This Command Do? Should i be worried?

So I was debugging my code when I see these few lines in my log:
GET /cgi/common.cgi 302 8.015 ms - 23
GET /stssys.htm 302 2.928 ms - 23
GET / 200 134.922 ms - 9896
POST /command.php 302 33.826 ms - 23
GET /language/Swedish${IFS}&&echo${IFS}610cker>qt&&tar${IFS}/string.js 302 1.049 ms - 23

Could this affect me or my system? What can I do to protect against this? I'm not using CGI or PHP.

A:

It's an attempt at command injection. IFS is basically a space in this situation, and && executes multiple commands. So you have:
/language/Swedish && echo 610cker > qt && tar /string.js

Which tries to execute three commands:
/language/Swedish   <-- where the injection takes place
echo 610cker > qt   <-- write 610cker to file qt
tar /string.js      <-- compress file string.js (but the command is invalid)

The commands do not really make sense and are not used to exploit your system, but likely used to test if it is vulnerable.
If you google 610cker you will find some reports about an exploit on a D-Link router (although the payload looks slightly different) and other systems (see eg here, using the same payload).
As with all log entries of this type, it is almost certainly a scanner. If your system is not vulnerable and there are no other signs of intrusion, I wouldn't worry about it.


Q:

How can I skip values of the foreach loop?

I am using C# and developing and Application in Windows Form, my objective is compiler a chat with MySQL connection, where all the messages are save in a database and then in the computer, in a TXT.
Then, I will make a dynamic label which make a label for each line of the TXT.
sql.sqlcmd("SELECT COUNT(*) FROM chat");
int count = int.Parse(sql.sqlcmd_answ);

foreach (string line in File.ReadLines("mac.txt"))
{
    int i = 0;
    int p = 62;
    while (i < count)
    {
        Console.WriteLine(line);
        Label lb = new Label();
        lb.Text = line;
        lb.Location = new Point(58, p);
        p = p + 30;
        panel1.Controls.Add(lb);
        ++i;
    }
}

The files has these lines:

1222
22222
Chat...
fxckxd
fxckxd
fxck
ffff
cambio
Chat...heya
22222
Xd
Xd
DDDD3EEEE
DDDD

You can see that the foreach always print the first value, my TXT has 15 values, I would like that the TEXT of each label, were each line of the TXT.

A:

This is simply because the value of line is the same for the entire life-time of the inner while loop. I can't see why do you even need the while loop. Simply iterate over the values in the file:
int p = 62;
foreach (string line in File.ReadLines("mac.txt"))
{
    Console.WriteLine(line);
    var lb = new Label()
    {
       Text = line,
       Location = new Point(58, p)
    };
    panel1.Controls.Add(lb);
    p = p + 30;
}


Q:

What SharePoint 2013 Development can be done in Visual Studio 2010?

It looks like the tools for developing SharePoint 2013 customizations are mostly in Visual Studio 2012 and "Napa for Office 365."
If you've tried developing solutions for SharePoint 2013 in Visual Studio 2010, what has worked for you?

A:

To add to Hugh's answer, almost anything you can do in VS 2010 for SP10 works in SP13 (event receivers, web parts, etc.), but nothing new, or not much of the new features work in VS2010 because much of them are new templates and data techniques such as the app model, remote event receivers, etc.
The App model requires the ability to do remote development which is built into VS 2012, but not 2010 and the SharePoint add on for VS is for 2012, not 2010.
By the way, it is Visual Studio 2012, not 2013, confusing, I know.
A positive push for VS 2012 is that remote development and deployment is allow, which matches Microsoft's push towards SharePoint online (office 365).

A:

It seems to work for the most part, but I am not confident about things like workflows as I have had two not work now which work on 2010.
We are in the middle of upgrading visual studio now though, as a company we don't believe the risks of incompatibility outweigh the costs.


Q:

Design advice when daisy-chaining multiple JTAG devices

I know that JTAG was specifically developed to support daisy-chaining of multiple devices, but I am still worried that my board will show up and I won't be able to talk to one of the devices because I did something wrong.  Does anyone have any advice on what the common pitfalls are or what precautions should be taken when implementing more than 1 device on the JTAG bus?

A:

1) Don't put very many devices on one bus.
2) If there's something for which jtag is really critical, and you need jtag extensions for firmware download or debug, put it on it's own separate bus so electrical issues on a longer one don't force you to run at a painfully slow clock rate.
3) See (instead or as well) if you can design end-to-end functional tests that would detect assembly or component errors, thus including coverage of the parts that don't have jtag capability.


Q:

Changing Query Parameter for jQuery UI's Autocomplete

I'm using version 1.8.13 of jQuery UI's Auto complete and by default jQuery is using the query parameter of "?term=" by default, while my app is using "?q=" in the string it is creating. I COULD change the variable to be "term" on the backend, but I'd rather just tell jQuery what the server is trying to send it. Is there a way to change this?
Right now I just have something like this and it works if I change the variable to "term" on the backend, but like I said I wanted to change it to "q" and I can't find any info online about setting the parameter (that works):
$( "#input-search").autocomplete({
   source: "/search/autocomplete/"
});

A:

You could use the callback form of source and handle all the interaction with the server yourself. Something like this:
$("#input-search").autocomplete({
    source: function(request, response) {
        $.get('/search/autocomplete', { q: request.term }, function(data) {
            response(data.split('\n'));
        });
    }
});

A:

The answer above is a great simple example and helped me get to this result on my app which generates an unordered list from the response data which displays the autocomplete results:
$("#input-search").autocomplete({
   source: function(request, response) {
      $.ajax({
         url: "/search/autocomplete",
         dataType: "json",
         data: {
            q: request.term
         },
         success: function(data) {
            response(data);
         }
      });
   },
}).data("autocomplete")._renderItem = function(ul, item) {
    $(ul).attr('id', 'search-autocomplete');
       return $("

")
       .data( "item.autocomplete", item )
       .append(""+item.title+"").appendTo(ul);
    };


Q:

Loadable/Unloadable django apps

I wanted to make an application which could handle other applications as plugins, that the user could download and load/unload at any time. I read all the django documentation, and there doesn't seem to be a proper way to do it apart from installing the app by hand a doing a syncdb, with no possibility of unloading.
A good example of what I want to do could be the wordpress plugins. I wanted something like that for my django project, downloadable "plugins" that the user can load and unload at any time.
Is there any way to accomplish this?

A:

I don't think it's possible. Django loads all its .py files only once, when its *cgi process is started. So to updating your urls.py or models.py requires restarting cgi, and I don't think you want to allow your users doing this. :-)


Q:

Jenkins Multibranch pipeline: How to select a build node?

Jenkins multibranch pipeline always performs checkout on master node. In my case I want to make my build on another node. My script in Jenkinsfile looks like this:
node('osx') {
    ...
}

I'm forced to checkout env.BRANCH on my node myself again to perform a build. It will be much better to perform pipeline build on selected node from the beginning, but I can not find how to do it.

A:

Do you have checkout scm in your Jenkinsfile on the branch?
Like so:
node('osx') {
    checkout scm
    ...
}


Q:

Want to put a method into a QThread

How to add a method within the class to a thread to execute?
I do not want to put "Pup" into a seperate class that inherits QThread as this is just an abstraction of some Legacy code I am working on.
void Dog::Pup()
{
     printf("pup");
}

void Dog::Init()
{
     QThread *dogThread = new QThread();
     Pup->moveToThread(dogThread); //this is all wrong
     Pup->connect(dogThread, ?, Pup, SLOT(Pup), ?)
     dogThread.start();
}

A:

Try this:
void Dog::Init()
{
     QThread *dogThread = new QThread;
     connect(dogThread, SIGNAL(started()), this, SLOT(Pup()), Qt::DirectConnection);
     dogThread->start();
}

It basically creates a new QThread named dogThread and connects it's started() signal to the method you want to run inside the thread (Dog::Pup() which must be a slot).
When you use a Qt::QueuedConnection the slot would be executed in the receiver's thread, but when you use Qt::DirectConnection the slot will be invoked immediately, and because started() is emitted from the dogThread, the slot will also be called from the dogThread. You find more information about the connection types here: Qt::ConnectionType.


Q:

Sorting mysql results on the basis of relevance to query

I'm searching mysql database using user's query with php via html form.
SELECT * FROM Collection WHERE `Name` LIKE '%$query%';

I want to sort the results with the row having highest matching score on the top in decreasing order with matching score.
How to do this?

A:

You must take a look at FULLTEXT search in Boolean mode.
Boolean Full-Text Searches


Q:

How to access service destination from approuter?

It seems that I configured my approuter successfully:
Approuter
I gave a destination to my service in SCP Cockpit:
destination config in SCP Cockpit
And I maintained the destination in the xs-app.json:
    {
  "welcomeFile": "/webapp/index.html",
  "authenticationMethod": "route",
  "logout": {
    "logoutEndpoint": "/do/logout"
  },
  "routes": [
    {
      "source": "/destination",
      "target": "/",
      "destination": "service-destination"
    }
  ]
}

My question is now how can I access my service destination via approuter?
Shouldn't it be something like this:
https://qfrrz1oj5pilzrw8zations-approuter.cfapps.eu10.hana.ondemand.com/webapp/index.html/destination
Accessing service via Approuter
...it returns Not found.
Any idea what I'm doing wrong here?
This is my mta.yaml (if relevant):
    ID: oDataAuthorizations
_schema-version: '2.1'
version: 0.0.1
modules:
  - name: oDataAuthorizations-db
    type: hdb
    path: db
    parameters:
      memory: 256M
      disk-quota: 256M
    requires:
      - name: oDataAuthorizations-hdi-container
  - name: oDataAuthorizations-srv
    type: java
    path: srv
    parameters:
      memory: 1024M
    provides:
      - name: srv_api
        properties:
          url: '${default-url}'
    requires:
      - name: oDataAuthorizations-hdi-container
        properties:
          JBP_CONFIG_RESOURCE_CONFIGURATION: '[tomcat/webapps/ROOT/META-INF/context.xml: {"service_name_for_DefaultDB" : "~{hdi-container-name}"}]'
      - name: xsuaa-auto
  - name: approuter
    type: html5
    path: approuter
    parameters:
      disk-quota: 256M
      memory: 256M
    build-parameters:
      builder: grunt
    requires:
      - name: dest_oDataAuthorizations
      - name: srv_api
        group: destinations
        properties:
          name: service-destination
          url: '~{url}'
          forwardAuthToken: true
      - name: xsuaa-auto

resources:
  - name: oDataAuthorizations-hdi-container
    type: com.sap.xs.hdi-container
    properties:
      hdi-container-name: '${service-name}'
  - name: xsuaa-auto
    type: org.cloudfoundry.managed-service
    parameters:
      path: ./cds-security.json
      service-plan: application
      service: xsuaa
      config:
        xsappname: xsuaa-auto
        tenant-mode: dedicated
  - name: dest_oDataAuthorizations
    parameters:
      service-plan: lite
      service: destination
    type: org.cloudfoundry.managed-service

A:

You have two hosts:

approuter
srv

The problem:

https://approuter/destination/ will proxy to https://srv/
Notice the root path in the URL. You see the path segment of your destination is ignored by the approuter. Instead it looks for the routes[0].target declaration of your xs-app.json file.

The symptom:

https://srv/ redirects (307) to /odata/v2. So does https://approuter/destination/
https://approuter/odata/v2/ does not exist (404), no route was defined in your xs-app.json
https://approuter/destination/odata/v2/ gives you the expected response.

The solution:
Adapt your xs-app.json to correctly refer the target endpoint path:
  "routes": [
    {
      "source": "/destination",
      "target": "/odata/v2",
      "destination": "service-destination"
    }

Follow up
Since your srv application statically references links to absolute path /odata/v2, you would either have to update each link in srv to use relative paths, or use "/odata/v2/" as your approuter route source to mirror the target. For the latter case you would miss out on the "/destination" path.


Q:

pywikipedia login.py socket.error: (10060, 'Operation timed out')

I'm totally new to python, so hopefully someone can help if I'm doing something obviously wrong. I'm trying to create and run a simple pywikipedia bot on vocabularies.referata.com, a semantic mediawiki site. I downloaded the pywikipedia distro and created a family file:
import config, family, urllib         # REQUIRED

class Family(family.Family):          # REQUIRED
    def __init__(self):               # REQUIRED
        family.Family.__init__(self)  # REQUIRED
        self.name = 'explicator'        # REQUIRED; replace with actual name

        self.langs = {                # REQUIRED
            'en': 'vocabularies.referata.com',  # Include one line for each wiki in family
        }

I've created a user, wikibot, and run:
python generate_user_files.py

as per instructions on:
http://meta.wikimedia.org/wiki/Using_the_python_wikipediabot

When I try to run:
python login.py

I'm getting the following error:
C:\pywikipedia>python login.py
Password for user wikibot on explicator:en:
Logging in to explicator:en as wikibot
Traceback (most recent call last):
  File "login.py", line 376, in <module>
    main()
  File "login.py", line 372, in main
    loginMan.login()
  File "login.py", line 261, in login
    cookiedata = self.getCookie(api)
  File "login.py", line 178, in getCookie
    response, data = self.site.postData(address, self.site.urlEncode(predata))
  File "C:\pywikipedia\wikipedia.py", line 4915, in postData
    conn.endheaders()
  File "C:\Python25\lib\httplib.py", line 860, in endheaders
    self._send_output()
  File "C:\Python25\lib\httplib.py", line 732, in _send_output
    self.send(msg)
  File "C:\Python25\lib\httplib.py", line 699, in send
    self.connect()
  File "C:\Python25\lib\httplib.py", line 683, in connect
    raise socket.error, msg
socket.error: (10060, 'Operation timed out')

Is their something stupid/apparent that I need to check or am doing wrong? I'm behind a firewall, would this be the problem? (and if so what steps do I need to take to fix it).
thanks for any help
Stuart

A:

I'm not familiar w/ pywikipedia =p, but the problem is at least about connection rather than python: the socket connection fails to be established at the beginning.

Is the post url, address in the login.py L178 , correct? Any typo or misconfiguration?
Is the url accessible? You could try to directly visit the url in browser and see if there is any http response. If the server is reachable, you could check whether it's listening on certain port like 80, by netstat -ant, netstat -anptcp or similar. On windows, a firewall w/ default settings may block communication, you could see whether there is any warning dialog waiting for confirm, or check the fireware log. Also, you need to have Administrator privilege to use port 80.


Q:

Why is glGenVertexArrays undefined in PyOpenGL when using GTKGLArea

I have the below test code below where I am trying to get a basic opengl Gtk3 GLArea example working.
The error below is currently my sticking point, from what i have read this potentially means the features are not availabale to the context but reading about GLArea it does not seem to let you pick the context and sounds like it should default to the correct one.
The issue could be with GLArea or PyOpenGL unfortunately all examples i can fine are currently in C be great to get a basic example working in python.
Anyway spent a lot of time trying to figure this issue out so would be great-full if anyone can help get past at least this error.
Traceback (most recent call last):
File "gtkglarea.py", line 91, in on_configure_event
self.vertex_array_object = glGenVertexArrays(1)
File "/usr/lib/python3/dist-packages/OpenGL/platform/baseplatform.py", line 407, in call
self.name, self.name,
OpenGL.error.NullFunctionError: Attempt to call an undefined function glGenVertexArrays, check for bool(glGenVertexArrays) before calling

Example, its also on a gist https://gist.github.com/olymk2/5b3e49ac83130e580bd9983f2e5d49c3
#!/usr/bin/python
import os
import sys

from OpenGL.GLU import *
from OpenGL import GLX
from OpenGL import GL as GL
from ctypes import *
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk

from OpenGL.arrays import vbo
from OpenGL.GL import shaders
from OpenGL.raw.GL.ARB.vertex_array_object import glGenVertexArrays, \
                                                  glBindVertexArray

from numpy import array
import numpy as np

VERTEX_SHADER = """
    #version 330
    in vec4 position;
    void main()
    {
        gl_Position = position;
    }"""

FRAGMENT_SHADER = """
    #version 330
    out vec4 fragColor;
    void main()
    {
        fragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }
    """

class application_gui:
    """Tutorial 01 Create and destroy a window"""
    # glwrap = gtkglarea()
    def __init__(self):
        self.window = Gtk.Window()
        self.canvas = Gtk.GLArea()
        self.canvas.set_required_version(3, 3)
        self.test_features()

        self.vertices = [
            0.6,  0.6, 0.0, 1.0,
            -0.6,  0.6, 0.0, 1.0,
            0.0, -0.6, 0.0, 1.0]

        self.vertices = np.array(self.vertices, dtype=np.float32)

        self.canvas.connect('realize', self.on_configure_event)
        self.canvas.connect('render', self.on_draw)
        self.canvas.set_double_buffered(False)

        self.window.connect('delete_event', Gtk.main_quit)
        self.window.connect('destroy', lambda quit: Gtk.main_quit())

        self.window.add(self.canvas)
        self.window.show_all()

        self.on_configure_event(self.canvas)

    def test_features(self):
        print('Testing features')
        print('glGenVertexArrays Available %s' % bool(glGenVertexArrays))
        print('Alpha Available %s' % bool(self.canvas.get_has_alpha()))
        print('Depth buffer Available %s' % bool(self.canvas.get_has_depth_buffer()))

    def on_configure_event(self, widget):
        print('realize event')

        widget.make_current()
        # widget.attach_buffers()
        context = widget.get_context()

        print('is legacy context %s' % Gdk.GLContext.is_legacy(context))
        print('configure errors')
        print(widget.get_error())

        vs = shaders.compileShader(VERTEX_SHADER, GL.GL_VERTEX_SHADER)
        fs = shaders.compileShader(FRAGMENT_SHADER, GL.GL_FRAGMENT_SHADER)
        self.shader = shaders.compileProgram(vs, fs)

        self.vertex_array_object = glGenVertexArrays(1)
        GL.glBindVertexArray( self.vertex_array_object )

        # Generate buffers to hold our vertices
        self.vertex_buffer = GL.glGenBuffers(1)
        GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vertex_buffer)

        # Get the position of the 'position' in parameter of our shader and bind it.
        self.position = GL.glGetAttribLocation(self.shader, 'position')
        GL.glEnableVertexAttribArray(self.position)

        # Describe the position data layout in the buffer
        GL.glVertexAttribPointer(self.position, 4, GL.GL_FLOAT, False, 0, ctypes.c_void_p(0))

        # Send the data over to the buffer
        GL.glBufferData(GL.GL_ARRAY_BUFFER, 48, self.vertices, GL.GL_STATIC_DRAW)

        # Unbind the VAO first (Important)
        GL.glBindVertexArray( 0 )

        # Unbind other stuff
        GL.glDisableVertexAttribArray(self.position)
        GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)

        print('errors')
        print(widget.get_error())

        return True

    def on_draw(self, widget, *args):
        print('render event')
        print(widget.get_error())
        #Create the VBO

        widget.attach_buffers()

        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
        GL.glUseProgram(self.shader)

        GL.glBindVertexArray( self.vertex_array_object )
        GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3)
        GL.glBindVertexArray( 0 )

        GL.glUseProgram(0)
        glFlush()
        return True

application = application_gui()
Gtk.main()

A:

For me, the problem seemed to be related to running under Wayland. It seems like if PyOpenGL is running under Wayland and there's an X11 server running, it will use GLX rather than Wayland's EGL support. Something about how GtkGLArea sets up the GL context means that GLX works but doesn't have any GL extensions, which includes VAOs. This seems like a bug in PyOpenGL.
There's two ways to work around this:

Set PYOPENGL_PLATFORM to force PyOpenGL to use EGL instead of GLX.
E.g. before importing OpenGL:
if 'WAYLAND_DISPLAY' in os.environ and 'PYOPENGL_PLATFORM' not in os.environ:
    os.environ['PYOPENGL_PLATFORM'] = 'egl'

Unset WAYLAND_DISPLAY to force Gtk to use GLX instead of EGL.
E.g. before importing Gtk:
if 'WAYLAND_DISPLAY' in os.environ:
    del os.environ['WAYLAND_DISPLAY']


Q:

Failing to authorize connection to own GAE endpoints API with service account

I've been beating my head against the wall trying to successfully authorize an API hit on the Google App Engine (GAE) project I'm running from a python script using OAuth2 and a service account.
I've created the service account, added the service account id to the allowed client ids in the api file, converted the private key from a .p12 to a .pem, and authorized the httplib2 call. I've tried passing the credentials using the .authorize() method and by loading the credentials as JSON and adding the access_token parameter to the headers manually --     {"Authorization": "Bearer " + token_string}.
Every call too the API yields "Invalid Token".
One strange thing I have been noticed in that when I first call SignedJwtAssertionCredentials, there is no access token in the credentials -- "access_token" is None. However, the access token does show up when I retrieve the credentials from the .dat file in storage.
Following are the GAE endpoints_api.py file, the python_test.py file, and the 401 response.
Any ideas would be hugely appreciated.
First the app engine endpoints server file:
# endpoints_api.py running on GAE

import endpoints
import time
from protorpc import messages
from protorpc import message_types
from protorpc import remote

SERVICE_ACCOUNT_ID = 'random_account_id_string.apps.googleusercontent.com'
WEB_CLIENT_ID = 'random_web_client_id_string.apps.googleusercontent.com'
ANDROID_AUDIENCE = WEB_CLIENT_ID

package = "MyPackage"

class Status(messages.Message):
    message = messages.StringField(1)
    when = messages.IntegerField(2)

class StatusCollection(messages.Message):
    items = messages.MessageField(Status, 1, repeated=True)

STORED_STATUSES = StatusCollection(items=[
    Status(message='Go.', when=int(time.time())),
    Status(message='Balls.', when=int(time.time())),
    Status(message='Deep!', when=int(time.time())),
])

@endpoints.api(name='myserver', version='v1')
class MyServerApi(remote.Service):
    """MyServer API v1."""

    @endpoints.method(message_types.VoidMessage, StatusCollection,
                  allowed_client_ids=[SERVICE_ACCOUNT_ID,
                                      endpoints.API_EXPLORER_CLIENT_ID],
                  audiences=[ANDROID_AUDIENCE],
                  scopes=[endpoints.EMAIL_SCOPE],
                  path='status', http_method='GET',
                  name='statuses.listStatus')
    def statuses_list(self, unused_request):
        current_user = endpoints.get_current_user()
        if current_user is None:
            raise endpoints.UnauthorizedException('Invalid token.')
        else:
            return current_user.email(), STORED_STATUSES

APPLICATION = endpoints.api_server([MyServerApi])

next the local python script:
# python_test.py file running from local server

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import SignedJwtAssertionCredentials
import httplib2
import os.path
import json

SERVICE_ACCOUNT_EMAIL = "service_account_string@developer.gserviceaccount.com"
ENDPOINT_URL = "http://my-project.appspot.com/_ah/api/myserver/v1/status"
SCOPE = 'https://www.googleapis.com/auth/userinfo.email'
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))

f = file('%s/%s' % (SITE_ROOT, 'pk2.pem'), 'rb')
key = f.read()
f.close()

http = httplib2.Http()
storage = Storage('credentials.dat')
credentials = storage.get()

if credentials is None or credentials.invalid:
    credentials = SignedJwtAssertionCredentials(
        SERVICE_EMAIL, key, scope=SCOPE)
    storage.put(credentials)
else:
    credentials.refresh(http)

http = credentials.authorize(http)
headers = {'Content-Type': 'application/json'}

(resp, content) = http.request(ENDPOINT_URL,
                           "GET",
                           headers=headers)

print(resp)
print(content)

Finally, the console output:
{'status': '401', 'alternate-protocol': '443:quic,p=0.002', 'content-length': '238', 'x-    xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'transfer-encoding':     'chunked', 'expires': 'Sun, 14 Sep 2014 23:51:36 GMT', 'server': 'GSE', '-content-encoding': 'gzip', 'cache-control': 'private, max-age=0', 'date': 'Sun, 14 Sep 2014 23:51:36 GMT', 'x-frame-options': 'SAMEORIGIN', 'content-type': 'application/json; charset=UTF-8', 'www-authenticate': 'Bearer realm="https://accounts.google.com/AuthSubRequest"'}
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Invalid token.",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid token."
 }
}

A:

Thank you for the help. There are a couple things I did wrong above.
Firstly, I needed to reference the app engine project id in the allowed ids list.
API_ID = 'project-id-number.apps.googleusercontent.com'

@endpoints.method(message_types.VoidMessage, StatusCollection,
              allowed_client_ids=[API_ID, SERVICE_ACCOUNT_ID,
                                  endpoints.API_EXPLORER_CLIENT_ID],
              audiences=[ANDROID_AUDIENCE],
              scopes=[endpoints.EMAIL_SCOPE],
              path='status', http_method='GET',
              name='statuses.listStatus')

I had incorrectly come to the assumption that the build() method would only work with official google APIS, but it turned out I was referencing my project incorrectly. With the project id in place, I could use build() instead of writing my own httplib2 call in the server side file (which didn't work).
Erasing the code beneath 'http = credentials.authorize(http)' I replaced it with the following:
myservice = build('my-service', 'v1', http=http, discoveryServiceUrl=discoveryServiceUrl)
data = myservice.my-path().endpoint-name()
results = data.execute()

This successfully authorizes my account and calls the endpoint. Woot! If anyone else has questions about this, or if my solution isn't clear, please feel free to comment. This was a painful process I don't wish upon anyone else.


Q:

How do I convert this function to not use the Promise constructor antipattern

I asked this question and was told to avoid the Promise constructor anti-pattern. I read through the article linked but I am unsure how to not use the anti pattern. This is the function:
db.getUserCount = function () {
    return new Promise (function (resolve, reject) {
    db.users.count().then(function (result) {
        resolve (result);
    }, function(e) {
        reject (e);
    });
});

I have all my database queries coded like the one above. This is my attempt to not use the anti-pattern but as I don't totally understand it I don't think this way is correct either:
db.getUserCount = function () {
    return new Promise (function (resolve, reject) {
        db.users.count().then(function (result) {
            return (result);
        }).then(function(result) {
            resolve(result);
        }).catch(function(err) {
            reject(err);
        });
    });
};

As I want to be writing good code, if someone could take a minute to show me an example of using the above function by not using the anti-pattern that would be great.

A:

Since db.users.count() seems to return a promise already, you can just do this:
db.getUserCount = function () {
    return db.users.count();
});

There's not need to wrap it in an additional promise (using new Promise(...)).

A:

If the db.users.count() function is an asynchronous operation, then what you've written is not an anti pattern. The "anti pattern" comes in when the method is synchronous, and a promise is returned for the sake of using the Promise Pattern.
The key here is from a quote from another Stack Overflow question linked to in the question you reference:

... promises are about making asynchronous code retain most of the lost properties of synchronous code such as flat indentation and one exception channel.

(emphasis, mine)
If the code is not asynchronous, then returning a promise is an anti pattern.
As for returning new Promise(...) being an anti pattern? If that's the case then returning new Anything() is an anti pattern. Using the Promise constructor is fine.


Q:

Managing multiple versions in cruise-control, team city, etc

In my shop (as I expect it is in most), you have multiple releases of different software components (let's call them foo-client and bar-service).  In my cc.net configuration, I currently have one "project" for foo-client at trunk, one project for foo-client version 1.0 and another for foo-client version 1.1.
What I'd really like to see at the dashboard level is something like:

foo-client

bar-server

With the ability to drill down into either foo-client or bar-server.  The rollup would show the status of the last continuous build and I could review and/or force a new build for an existing tagged version.
What are you guys doing and under what build management framework?

A:

You might want to take a look at Hudson (which supports MSbuild's via a plugin) - it can be deployed to a Java application server (recommend: Glassfish or Tomcat).
It takes about 5-15 minutes to download, unzip, and deploy - and then you are ready to begin defining project builds.
There are quite a large number of plugins to extend the basic functionality - and the development team seems to release new features / bug fixes on a 3-4 day release schedule - so the code vitality is very high.
http://hudson-ci.org/
Within the Glassfish dashboard - you can organize your projects via a tab specific to the project root name that you might want to define - and then you can easily achieve the organizational structure you appear to want.


Q:

Which integers $a, b, c$ satisfy the equation $a \sqrt 2 − b = c \sqrt5$?

This is a non-calculator question:

Which integers $a, b, c$ satisfy the equation $a \sqrt 2 − b = c \sqrt5$?

I've tried solving it through trial and error and the only solution I seem to be getting is $0,0,0$.

A:

Let us assume there are $a,b,c \in \mathbb{Z},ac \neq 0$ such that $a \sqrt 2 − b = c \sqrt5$
$$b=a\sqrt{2} -c\sqrt{5}$$
$$b^2=2a^2+5c^2-2ac\sqrt{10}$$
$$\sqrt{10}=\frac{2a^2+5c^2-b^2}{2ac}$$
$$\implies \sqrt{10} \space \text{is rational (contradiction)}$$
EDIT: As suggested by A.P., we will need to rule out the cases when $a=0$ and when $c=0$ for a complete solution.
When $a=0$,
$$\sqrt{5}=-\frac b{c} \space \Rightarrow\Leftarrow$$
When $c=0$,
$$\sqrt{2}=\frac b{a} \space \Rightarrow\Leftarrow$$

A:

Hint: square both sides of the equation and remember that $\sqrt2$ and $\sqrt5$ are irrational.


Q:

Xceed DataGrid QueryableSource and DbContext

I'm trying implement DataGridVirtualizingQueryableCollectionViewSource like documentation: http://doc.xceedsoft.com/products/xceedwpfdatagrid/Xceed.Wpf.DataGrid.v4.5~Xceed.Wpf.DataGrid.DataGridVirtualizingQueryableCollectionViewSource.html
Using ObjectContext API everything is normal.
However when using DbContext API, the cells content aren't showed.
Does anyone know anything about this?
/// <summary>
/// WITH THIS WORKS.
/// </summary>
public partial class AdventureWorksEntities : ObjectContext

/// <summary>
/// WITH THIS DOES NOT WORK.
/// </summary>
public partial class AdventureWorksEntities : DbContext

My source below:
<Grid xmlns:xcdg="http://schemas.xceed.com/wpf/xaml/datagrid">
    <Grid.Resources>

        <xcdg:DataGridVirtualizingQueryableCollectionViewSource
            x:Key="cvs_queryableSource"
            QueryableSource="{Binding Path=QueryableSource}"/>

    </Grid.Resources>
    <xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource cvs_queryableSource}}">
    </xcdg:DataGridControl>
</Grid>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        this.DataContext = this;
        InitializeComponent();
    }

    public IQueryable QueryableSource
    {
        get
        {
            if (m_queryable == null)
            {
                m_northwind = new AdventureWorksEntities();
                m_queryable = m_northwind.Contact;
            }
            return m_queryable;
        }
    }

    private AdventureWorksEntities m_northwind;
    private IQueryable m_queryable;
}

Thank you!

A:

I don't know why, but a simple OrderBy on my query resolves the problem.
public IQueryable QueryableSource
{
    get
    {
        if (m_queryable == null)
        {
            m_northwind = new AdventureWorksEntities();
            m_queryable = m_northwind.Contact.OrderBy(p => p.SomeField);
        }
        return m_queryable;
    }
}

Thanks again!


Q:

Fullcalendar manually adding new events

I'm adding events manually which lately will be edited.
The problem I'm having is when I add an event and insert it into the allDay events. If I drag the event to the timeline zone three issues popup:

It adds a text called 'Object object'
If I resize the event the event disappears and lots of errors appears on console
The date-start is null so is date-end (by looking at html code)

You can checkout the problem at this fiddle.

A:

Solved.
The problem was the timeFormat object. It should be timeFormat: 'H:mm'.


Q:

Jquery ajax login redirect

I' have a simple popup login, which returns status into div(if pass is not correct) or redirect to the main page.
Here is code for handling request:
$.ajax({
     type: "POST",
     url: "login.html",
     cache: false,
     data: formData
     success: function(data){
        var $response=$(data);
        $('#response').text($response.find('#response').text());
        if($('#response').text().length<=0)
        {
            window.location="main.html";
        }
     }
 });

I'm using spring MVC for handling request. Login.html returns String(pass not correct). But when I get redirect from Spring nothing happens. So I temporary added client code for redirect.
Is this approach correct? Cause I get success on both ways(wrong or correct password)

A:

See when you redirect from Spring ,how your page will be redirected..because your doing an ajax submission..when you redirect and return home page from spring then you can see home page html in variable data of ajax call.
Rule is simple..when you do ajax..browser normal submission wont interfere ..in ideal case when there is normal submission server will send HTTP code as 302 and your page will be redirected to new location(means new page opens).
you can try this approach:
$.ajax({
     type: "POST",
     url: "login.html",
     cache: false,
     data: formData
     success: function(data){
       document.open();
       document.write(data);//home page from server after authentication..dont forget to add redirect logic at spring
       document.close();
     }
 });

I hope you are not using Spring-security for authentication..hence you may need to write lots of filter approach of your own.
Also instead of ajax try using normal submission approach from authetication..because in ajax you may need to set browser cookie with session id..of your own which would be taken care easily in normal authentication process..thanks


Q:

Out-of-process COM server migrated to in-process COM server causes callbacks to block

We have an existing network messaging server that implements a custom communications protocol that we are migrating to an in-process COM object.  The server is implemented as a free threaded out-of-process COM server.  The clients can register with the server (think publish-subscribe) to receive messages.
After migration we noticed several dead locks when calling GUI related functions, e.g. SetWindowPos, RedrawWindow, EnumWindows, etc.  After doing some research I found that this was due to callbacks happening on a thread other than the main GUI thread (message pump).  The callbacks are custom COM callbacks that derive from IUnknown, so we are not using connection points.
What's interesting is if a create a simple MFC dialog project, everything works.  But in our main application it fails.  Our main application (20+ years old and doing things now it was never designed for) is an MFC dialog project.  In response to a message, the MFC dialog project loads a DLL that, in turn, creates an MFC dialog and registers with the COM server for messages.  When the DLL dialog receives a message it calls one of the three example GUI related functions above, and blocks.
This use to work for an out-of-process COM server, so I know there is a way to get the callback to be within the context of the clients main GUI thread but have been unable find the 'magic' code to make it work.  I did stumble upon SendMessageCallback but can't get the asynchronous callback function to be called.
The COM callbacks into the client are handled via a thread inside the in-process COM server.  The thread is initialized with CoInitialize, which from my research means STA.  I've tried changing this to CoInitializeEx and tested with MTA.  I've also tried changing the COM server threading model to STA, MTA, Both, and Free.  As you can see, I'm really starting to throw darts. here.
Any help would be appreciated.
I did order the Don Box books, Essential COM and Effective COM, but they will not arrive until later this week.
EDIT:
Our main application:
Inside of CApp derived class' InitInstance

AfxOleInit()

Inside of CDialog derived class' OnInitDialog

CoCreateInstance (Messaging COM Object)
Allocate callback pointer.  The client callback is an interface that derives from IUnknown.  Then a callback class derives from the client callback and implements the AddRef/Release interfaces.  When the client creates the callback the client passes a pointer to itself so the callback can call the client.
MessageComObject->Register(callback pointer)

Inside MessageCOMObject:

MessageComObject adds the callback to the GIT and saves the cookie.
MessageComObject starts a thread to 'send' callbacks to the client.

Some point in time later the main application receives a 'message' via the callback pointer.  The callback is initiated from within the MessageComObject.
Inside the MessageCOMObject:

MessageComObject gets the callback from the GIT using the cookie
MessageComObject calls a function on the callback interface

Inside the callback interface's derived class:

Calls the client callback function

Inside the CDialog derived class' callback handler:

Calls LoadLibrary on a DLL (what gets loaded is data driven)
Calls exported function from DLL.

Inside DLL's exported function:

Create CWnd object
CoCreateInstance (Messaging COM Object)
Allocate callback pointer (same as above)
MessageCOMObject->Register

Inside MessageCOMObject:

MessageComObject adds the callback to the GIT and saves the cookie.
MessageComObject starts a thread to 'send' callbacks to the client.

Some point in time later the DLL receives a message:

MessageComObject gets the callback from the GIT using the cookie, GIT returns 'Catastrophic Failure'

Code
Declaring the callback in the IDL file:
[
    object,
    uuid(...),
    pointer_default(unique)
]
interface IMessageRouterCallback : IUnknown
{
   ...
};

[
    object,
    uuid(...),
    pointer_default(unique)
]
interface IMessageRouter : IUnknown
{
    ...
};

[
    uuid(....),
    version(1.0),
]
library MessageRouterCOMLib
{
    importlib("stdole2.tlb");
    [
        uuid(....)
    ]
    coclass MessageRouter
    {
            [default] interface IMessageRouter;
    };
};

The in-process COM DLL
class ATL_NO_VTABLE CMessageRouter :
    public CComObjectRootEx<CComMultiThreadModel>,
    public CComCoClass<CMessageRouter, &CLSID_MessageRouter>,
    public IMessageRouter
{
public:

DECLARE_GET_CONTROLLING_UNKNOWN()

BEGIN_COM_MAP(CMessageRouter)
    COM_INTERFACE_ENTRY(IMessageRouter)
    COM_INTERFACE_ENTRY_AGGREGATE(IID_IMarshal, m_pUnkMarshaler.p)
END_COM_MAP()

    CComPtr<IUnknown> m_pUnkMarshaler;

    DECLARE_PROTECT_FINAL_CONSTRUCT()

    DWORD callbackRegistrationId;

    HRESULT FinalConstruct()
    {
        //- TODO: Add error checking
        IUnknown *unknown;
        DllGetClassObject(IID_IMessageRouterCallback, IID_IUnknown, (void**)&unknown);
        CoRegisterClassObject(IID_IMessageRouterCallback, unknown, CLSCTX_INPROC_SERVER, REGCLS_MULTIPLEUSE, &callbackRegistrationId);
        CoRegisterPSClsid(IID_IMessageRouterCallback, IID_IMessageRouterCallback);

        return CoCreateFreeThreadedMarshaler(GetControllingUnknown(),
    }

    void FinalRelease()
    {
        if (callbackRegistrationId)
            CoRevokeClassObject(callbackRegistrationId);
        callbackRegistrationId = 0;

        if (m_pUnkMarshaler)
            m_pUnkMarshaler.Release();
    }
}

Where callback is registered:
boost::lock_guard<boost::mutex> guard(callbacksMutex);

//- callback is the raw interface pointer from the client
//- The class Callback contains a pointer to the raw client callback
//- and the global process ID.  The raw pointer is AddRef/Release in
//- the Callback class' constructor and destructor.
ptr = Callback::Pointer(new Callback(callback));
DWORD callbackId = 0;

HRESULT result = globalInterfaceTable->RegisterInterfaceInGlobal(callback, IID_IMessageRouterCallback, &callbackId);
if (SUCCEEDED(result))
{
    ptr->globalCallbackId = callbackId;
    callbackMap[callback] = ptr;
    //- NOTE: uses raw pointer as key into map.  This key is only
    //-       ever used during un-register.
    //- callbackMap is a std::map of Callback instances indexed by the raw pointer.
}

Callback thread:
CoInitialize(NULL);

while (processCallbackThreadRunning)
{
    QueueMessage message = messageQueue.Pop();
    if (!processCallbackThreadRunning)
        break;

    //- Make a copy because callbacks may be added/removed during
    //- this call.
    CallbackMap callbacks;
    {
        boost::lock_guard<boost::mutex> guard(callbacksMutex);
        callbacks = callbackMap;
    }

    for (CallbackMap::iterator callback = callbacks.begin(); callback != callbacks.end(); ++callback)
    {
        try
        {
            IMessageRouterCallback *mrCallback = NULL;
            HRESULT result = globalInterfaceTable->GetInterfaceFromGlobal(callback->second->globalCallbackId,IID_IMessageRouterCallback,(void **) &mrCallback);
            if (SUCCEEDED(result))
            {
                result = mrCallback->MessageHandler((unsigned char*)message.messageBuffer->Data(), message.messageBuffer->Length(), message.metaData.id, message.metaData.fromId, CComBSTR(message.metaData.fromAddress.c_str()));
                if (FAILED(result))
                {
                    ... log debug
                }
            }
            else
            {
                ... log debug
            }
        }
        catch (...)
        {
            ... log debug
        }
    }

    MessagePool::Push(message.messageBuffer);
}

CoUninitialize();

Client's implementation of the callback:
template <class CALLBACKCLASS>
class CMessageRouterCallback :
    public CComBase<IMessageRouterCallback>
{
    CMessageRouterCallback( CALLBACKCLASS *pCallbackClass = NULL) :
        m_pCallbackClass(pCallbackClass)
    {
        AddRef();   //- Require by CComBase.  This makes it so that this
                    //- class does not get automatically deleted when
                    //- Message Router is done with the class.
    }

    STDMETHODIMP MessageHandler( UCHAR *szBuffer, int nSize, DWORD dwTransCode, DWORD dwSenderID, BSTR bstrFromIP )
    {
        if ( m_pCallbackClass != NULL )
        {
            m_pCallbackClass->MessageHandler( szBuffer, nSize, dwTransCode, dwSenderID, bstrFromIP );
        }

        return S_OK;
    }
}

CComBase implements the IUnknown interface:
template < class BASE_INTERFACE, const IID* piid = &__uuidof(BASE_INTERFACE) >
class CComBase :
    public BASE_INTERFACE
{
protected:
    ULONG   m_nRefCount;

public:

    CComBase() : m_nRefCount(0) {}

    STDMETHODIMP QueryInterface(REFIID riid, void** ppv)
    {
        if (riid == IID_IUnknown || riid == *piid )
            *ppv=this;
        else
            return *ppv=0,E_NOINTERFACE;
        AddRef();

        return S_OK;
    }

    STDMETHODIMP_(ULONG) AddRef()
    {
        return ++m_nRefCount;
    }

    STDMETHODIMP_(ULONG) Release()
    {
        if (!--m_nRefCount)
        {
            delete this;
            return 0;
        }
        return m_nRefCount;
    }

    virtual ~CComBase() {}

};

The client then uses it:
class Client
{
    CMessageRouterCallback<Client> *callback;

    Client(IMessageRouter *messageRouter)
    {
        callback = new CMessageRouterCallback<this>();

        messageRouter->Register(..., callback);
    }

    void MessageHandler(...) { ... }
}

A:

There's something wrong with how those callbacks are being registered.  Possible causes may be:

A direct pointer to the callback manager's interface in the GUI thread, so you're providing direct pointers to STA objects to the callback manager too.
Your Callback instance in the code you added seems to be doing exactly this, it can't blindly call the raw pointer's Release when destroyed.
Your server objects are marshaled with CoCreateFreeThreadedMarshaler (not much different).
With the FTM, you must never use raw pointers, and you must always marshal interface pointers you intend to keep and unmarshal interface pointers you previously kept, preferrably using the GIT.  And I mean always, if you intend to keep things safe.

I recommend you keep your server objects in MTA (ThreadingModel="Free") or NA (ThreadingModel="Neutral"), make sure you're accessing them somehow in the GUI thread through CoCreateInstance[Ex] or CoGetClassObject and IClassFactory::CreateInstance (or any other object activation API), and let the "magic" happen.  This is as transparent as it can get without using the GIT or manually marshaling things between threads.


Q:

Overflow in Lambda function in C++

I was solving a question on leetcode. The question is, Given a list of non-negative integers, arrange them such that they form the largest number. I have got the algorithm to write the comparator function and sort the list based on that. I had written the following,
 string largestNumber(vector<int>& nums) {
    auto comp = [&] (string &a, string &b){
       return a+b>=b+a;
    };
    vector<string>s;
    for(auto x:nums)    s.push_back(to_string(x));
    sort(s.begin(),s.end(),comp);
    string ans="";
    for(auto x:s)   ans+=x;
    if(ans[0]=='0') return "0";
    return ans;
}

I was getting a Runtime error saying that,
Line 431: Char 55: runtime error: pointer index expression with base 0xbebebebebebebebe overflowed to 0x7d7d7d7d7d7d7d7c (basic_string.h)
But I found that in the return statement of lambda function to compare two strings, if I replace '>=' by '>'  I got the correct answer and it got accepted. Can I know what is wrong with comparing by the sign '>=' ? I understand that '>' operator compares strings and outputs them in decreasing order but I am curious to know the cause of error.

A:

If you open the documentation on std::sort, you'll see following:

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );

...
Type requirements

Compare must meet the requirements of Compare.

And the Compare requirements say:

Establishes strict weak ordering relation with the following properties

For all a, comp(a,a)==false

Your comparator doesn't conform to this requirement, because if you pass two equal strings to it, it'll return true rather than false.

Also note that the first link says that using T & as a comparator parameter is not allowed. You should use const T &.


Q:

Why is the size of results from FFT half the size of the input, while that is not the case in image processing?

When dealing with real data, Fourier Transform produces symmetric results and FFT algorithms discards half of it. An input with 1024 points will yield only 513 points in the output.
However, in image processing, when Fourier Transform is calculated, the size of the output image is same as that of the input image. Assume that the images are 2D. The (pixel) value of image function f(x, y) is still real. So, why do we still have an output image size same as input?

A:

No.
Size of FFT in 1D is not half of the signal length. It's still the signal length (assuming FFT length was of the signal length). However for real data, due to conjugate symmetry, half of this is redundant and can be dicarded to reduce storage. Note however that, when it's required to process the FFT data, you have to construct the full length from the half and proceed.
This is also the reason why spectral analysis software display only positive frequencies for real data; i.e, negative frequencies will be a mirror copy (of the magnitude) of positive frequencies.
But you don't have to discard the half. You can just retain it.
For image processing, the symmetry of FFT for real input data again exist and if you wish you can also dicard half of the image FFT data. Whether this will be employed or not depends on the intentions of the package.


Q:

Python 3.6 Bitwise operations on byte datatype (>>, <<, |, & ) throws error:

I am a beginner and I am trying to perform bit wise operations on an element from 'byte' array
Example code:
step1_result[i] = (bytes((seedrandom[i] >> 3)) | bytes((seedrandom[i] << 5)))

>>> TypeError: unsupported operand type(s) for >>: 'bytes' and 'bytes'

step1_result and seedrandom is a list with 'byte' type elements
Is there a specific method to apply bitwise operations on a byte in Python?

A:

Python's bitwise operators only operate on integers, so you need to convert each byte to an int before performing a bitwise operation.
import sys
b1, b2 = [b'\x77', b'\x88']
int.from_bytes(b1, sys.byteorder) << int.from_bytes(b2, sys.byteorder)

Note that explicit conversion is not necessary if your bytes are in an actual bytearray, because indexing on a bytearray returns ints.
ba = bytearray(b'\x77\x01')
ba[0] << ba[1]

Likewise if the bytes are in a composite bytes object
bs = b'\x77\x01'
bs[0] << bs[1]


Q:

Graphing the binomial coefficients: appearances?

Is it appropriate to describe the function
$$f(x) = \binom{x}{2}$$ as parabolic?
How does it vary over $c$:
$$f(x) = \binom{x}{c}?$$
And, is there any intuition behind these graphs? For example, their resemblance to the polynomials of degree $c?$
I tried inputting one into wolfram alpha and it spat out a continuous function, which confused me. This is what prompted me to ask the question.

A:

Yes, you can generalise the factorial, choose function, etc. to not whole numbers too.
$$\binom{x}{k}=\frac{x!}{k!(x-k)!}$$
$$=\frac{x(x-1)\dots(x-k)!}{k!(x-k)!}$$
$$=\frac{x(x-1)\dots(x-k+1)}{k!}$$
So for $k=2$ you will get:
$$\binom x2=\frac{x(x-1)}{2!}=\frac{x^2-x}{2}$$
And for $k=3$:
$$\binom x3=\frac{x(x-1)(x-2)}{3!}=\frac{x^3-3x^2+2x}{6}$$
And so on.


Q:

Why is parent's public member only accessible within a method definition but not the class that derived from it?

If I have these two classes
class Car
{
    public int maxSpeed;
}

class Minivan : Car
{
    maxSpeed = 100; //error

    public void Test()
    {
        maxSpeed = 100;//ok!
    }
}

Why it's only permitted to use the public  member of the base class within a method not the class body?

A:

Why it's only permissible to use public member of the base class within a method not the class body?

You are thinking about this the wrong way.
It is not the accessibility rules that make this illegal; it would be illegal regardless of the accessibility.
The rule you are violating is that a statement must appear within the body of a method, property, constructor, destructor, indexer, operator or event.  In your first code sample the statement appears outside of all of those, and in the second, it appears inside a method.
Again, this rule has nothing whatsoever to do with accessibility. It's a grammatical rule of the language that you are violating, not a semantic rule.
That should answer your question, but let's take a look at your code. The better way to write this would be:
abstract class Car
{
  public abstract double MaximumSpeed { get; }
}
class Minivan : Car
{
  public override double MaximumSpeed { get { return 100.0; } }
}

Why is this better?

Public fields are a bad idea. Represent things that are logically properties as properties.
The property is now read-only. You don't want just anyone to be able to change the value!
Use good naming conventions.
Car is abstract, so you cannot create a vehicle that is just a car.
The maximum speed is a "physics" quantity, so it should be double, not int. There is no requirement that speed be quantized to an integer.


Q:

Getting another controllers instance class

I have learned how to pass and instance of a class to another class, but I have yet to understand how to do it the other way arround.
Example:
Lets say that we are in rootViewController and in the didSelectRowAtIndexPath we pass the instance of playlist to someviewcontroller like this:
SomeViewController *someViewController = [[SomeViewController alloc] initWithNibName:nil bundle:nil];

playlist = [arr objectAtIndex:indexPath.row];
someViewController.playlist = playlist;

Now this works perfectly for passing the class instance forward, but lets instead say that Im in the someViewController and want rootViewController playlist.
How would I go about achieving this using a similar technique? Thanks for helping!

A:

You should check out the delegation pattern: https://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/Delegation.html
Also check out Apple's CoreDataRecipes sample code:
http://developer.apple.com/library/ios/#samplecode/iPhoneCoreDataRecipes/Listings/ReadMe_txt.html
You can see in the sample code that the RecipeListTableViewController is a delegate of the RecipeAddViewController so that when the RecipeAddViewController is done RecipeListTableViewController can show the recipe in the RecipeDetailViewController.
Delegation also helps with your object graph because the reference to the delegate is a weak link which means that it won't retain your delegate. So by using the delegation pattern you ensure that you don't create any retain cycles and ARC will take care of memory management for you.


Q:

.htaccess with two parameters redirects to a 404 page

I want to redirect /index.php?id=1&time=10 to /first-10.
.htaccess:
RewriteEngine On
RewriteCond %{QUERY_STRING} id=1&time=10
RewriteRule ^index\.php$ /first-10/? [L,R=301]

when I access /index.php?id=1&time=10 redirects to /first-10/, but it's a 404 page. Please notice last slash also.
Where is the problem?

A:

You need to internally rewrite it back to its old-original format.
You must use THE_REQUEST to avoid an infinite loop
RewriteEngine On

RewriteCond %{THE_REQUEST} \s/(?:index\.php)?\?id=1&time=10\s [NC]
RewriteRule ^ /first-10? [R=301,L]

RewriteRule ^first-10$ /index.php?id=1&time=10 [L]

Both http://example.com/index.php?id=1&time=10 and http://example.com/?id=1&time=10 will redirect to http://example.com/first-10.
http://example.com/first-10 will internally rewrite it back to /index.php?id=1&time=10


Q:

GSM Sim300 response not Receive in atmega16

Am working on Sim300, trying to receive sms on atmega16  via serial communication.
When i send " *23# " sms to gsm modem from my mobile, gsm sends
" \r\n+CMGR:\s"REC\sUNREAD","+919762148043",,"14/03/13,23:04:32+22"\r\n*23#\r\n\r\nOK\r\n "
as response on serial port.
Am getting this data on atmega16, but only
" \r\n+CMGR:\s"REC\sUNREAD","+919762148043",,"14/03/13,23:04:32+22"\r "
this much of string where that " *23#" is my actual sms and am interested in "23".
my firmware looks like this,
while(Serial.available())
  {
    char tempChar = Serial.read();
    if(tempChar == '+')
    {
      isPreSms = true;
      lcd.print('+');
    }
    else if((tempChar == '\r') && (isPreSms == true))
    {
      isPreSms = false;
      lcd.print('r');
    }
    else if(tempChar == '*')
    {
      digitalWrite(OKLed, HIGH);
      isSms = true;
      lcd.print('*');
    }
    else if((tempChar == '#') && (isSms == true))
    {
      digitalWrite(powerLed, HIGH);
      isSms = false;
      lcd.print(sms);
    }
    else if(isSms)
    {
      digitalWrite(alertLed, HIGH);
      sms += tempChar;
    }
  }
  lcd.print('@');
}

Am expecting "+++r*23@" as output on lcd. I have checked, it receives '+' as well as '\r' but not '*' and further. Am stuck here, please help, what's going wrong.

A:

Now i solved it.
There is problem with size of serial buffer. I increased it's size to 128 bytes and its working fine now.


Q:

Jaxb - How to avoid "xsi:" at root element

Im using Java 7 and trying to create an xml from an xsd with jaxb.
I generated Java classes from xsd.
class1:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"vnr",
"meldungsart",
"teilnehmeranzahl",
"email",
"teilnehmer"
 })
@XmlRootElement(name = "Veranstaltung")
public class Veranstaltung {

@XmlElement(name = "VNR", required = true)
protected String vnr;
@XmlElement(name = "Meldungsart", required = true)
protected String meldungsart;
@XmlElement(name = "Teilnehmeranzahl")
protected int teilnehmeranzahl;
@XmlElement(name = "EMAIL")
protected String email;
@XmlElement(name = "Teilnehmer")
protected List<Teilnehmer> teilnehmer;

class 2
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"efn",
"punkteBasisJN",
"punkteZusatzLernkontrolleJN",
"punkteInteraktivitaetJN",
"punkteReferent"
})
@XmlRootElement(name = "Teilnehmer")
public class Teilnehmer {

@XmlElement(name = "EFN", required = true)
protected String efn;
@XmlElement(name = "Punkte_Basis_JN", required = true)
protected String punkteBasisJN;
@XmlElement(name = "Punkte_Zusatz_Lernkontrolle_JN", required = true)
protected String punkteZusatzLernkontrolleJN;
@XmlElement(name = "Punkte_Interaktivitaet_JN", required = true)
protected String punkteInteraktivitaetJN;
@XmlElement(name = "Punkte_Referent")
protected int punkteReferent;

Now I create a xml with JAXB:
    JAXBElement<eiv.Veranstaltung> tmp = ObjectFactoryNew
            .createEvent(event);
    JAXBContext jaxbContext = JAXBContext
            .newInstance(eiv.Veranstaltung.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "ISO-8859-15");
    jaxbMarshaller.setProperty("jaxb.noNamespaceSchemaLocation",
            "eiv-punktemeldung.xsd");
    jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);

    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.marshal(tmp, System.out);

ObjectFactory.java
@XmlRegistry
private static class ObjectFactoryNew {

    private static final QName EVENT_QNAME = new QName(
            "http://www.w3.org/2001/XMLSchema-instance", "Veranstaltung");

    private ObjectFactoryNew() {

    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}
     * {@link Veranstaltung } {@code >}
     *
     */
    @XmlElementDecl(namespace = "http://www.w3.org/2001/XMLSchema-instance", name = "Veranstaltung")
    public static JAXBElement<eiv.Veranstaltung> createEvent(
            eiv.Veranstaltung value) {
        return new JAXBElement<eiv.Veranstaltung>(EVENT_QNAME,
                eiv.Veranstaltung.class, null, value);
    }

}

Output:
<?xml version="1.0" encoding="ISO-8859-15" standalone="yes"?>
<xsi:Veranstaltung xsi:noNamespaceSchemaLocation="eiv-punktemeldung.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<VNR>2760012007000000289</VNR>
<Meldungsart>N</Meldungsart>
<Teilnehmeranzahl>1</Teilnehmeranzahl>
<EMAIL>lukas.mustermann@mailinator.com</EMAIL>
<Teilnehmer>
    <EFN>802760010002185</EFN>
    <Punkte_Basis_JN>J</Punkte_Basis_JN>
    <Punkte_Zusatz_Lernkontrolle_JN>N</Punkte_Zusatz_Lernkontrolle_JN>
    <Punkte_Interaktivitaet_JN>N</Punkte_Interaktivitaet_JN>
    <Punkte_Referent>0</Punkte_Referent>
</Teilnehmer>
</xsi:Veranstaltung>

How I can I avoid "xsi:Veranstaltung" ? What do Im wrong?

A:

It's correct in your case.
private static final QName EVENT_QNAME = new QName(
            "http://www.w3.org/2001/XMLSchema-instance", "Veranstaltung");

From QName documentation:

public QName(String namespaceURI,
       String localPart)
Parameters:
namespaceURI - Namespace URI of the QName
localPart - local part of the QName

So your root element <Veranstaltung> has namespace "http://www.w3.org/2001/XMLSchema-instance" (with alias xsi).
If you don't want this namespace, you should create QName with local part only.
private static final QName EVENT_QNAME = new QName("Veranstaltung");


Q:

RStudio does not see packages after update to R 3.4

I have Ubuntu 16.04 and after update of R to 3.4.1 version it does not see my packages even though they have also been updated:
> library(dplyr)
Error in library(dplyr) : there is no package called ‘dplyr’

Packages are there:
$ ls ~/R/x86_64-pc-linux-gnu-library/3.4/ | grep plyr
dplyr
plyr

My .libPaths:
> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"       "/usr/lib/R/library"

Setting .libPaths to desired path does the thing just for one session. I'd like it to be permanent.
I also tried to set the variables R_LIBS, R_LIBS_SITE and R_LIBS_USER to desired path as indicated here but it worked only in the console (didn't work in RStudio).

A:

Found the solution:
In the file /usr/lib/R/etc/Renviron there is a configuration of R.
In lines 43-45 there is:
# edd Jun 2017  Comment-out R_LIBS_USER
#R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}
##R_LIBS_USER=${R_LIBS_USER-'~/Library/R/3.4/library'}

I have uncommented R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}, restarted RStudio and now it works.
EDIT: Looking at the comments, it seems like a planned behaviour. Here is another solution.


Q:

Extract especific URL from String in java

I have a String like this:

.........e1.whatsapp.net..............>.ns1.p13.dynect..hostmaster.whatsapp.com.x:a>.......X..:....

And I need to extract the first URL:

e1.whatsapp.net

I was trying with the solution in this post but not working for me, maybe because the amount of dots. Maybe if I try with another pattern regex, but I know nothing about "regex".
Any sugestion?

A:

This code below may help you to extract the email with using regex.
class StringSeperator {

  public static void main(String args[]){
    String urlString = ".........e1.whatsapp.net..............>.ns1.p13.dynect..hostmaster.whatsapp.com.x:a>.......X..:....";
    String array[] = urlString.split("\\.\\.+");
    System.out.println(array[1]);
  }
}

Here I use regex as \\.\\.+ which means two or more dots. The string split using two or more dots.
If I further explain about regex. Here I use \\. for depicting the dot and use + for saying one or more occurrences of a dots. For more details about Java regex please follow below link.
https://www.tutorialspoint.com/java/java_regular_expressions.htm


Q:

Page not found (404) error happens

I got an error,Page not found (404)  when I put logout button in detail.html.
I wrote in header.html

WEB SITE

            SEE

              KNOW

              KNOW1

              KNOW2

      LOGOUT

I wrote in views.py
    @login_required
    def logout_view(request):
        logout(request)
        return redirect('regist')

    @login_required
    def regist(request):
        return render(request, 'registration/regist.html')

    @login_required
    def see(request):
        return render(request, 'registration/see.html')

    @login_required
    def nowknow(request):
        return render(request, 'registration/nowknow.html')

    @login_required
    def pastknow(request):
        return render(request, 'registration/pastknow.html')

   @login_required
    def detail(request):
        return render(request, 'registration/detail.html')

in urls.py
urlpatterns = [
    url(r'^product$', views.logout_view,name='logout_view'),
    url(r'^past_result$', views.see,name='see'),
    url(r'^privacy_policy$', views.nowknow,name='nowknow'),
    url(r'^privacy_policy$', views.pastknow,name='pastknow'),
    url(r'^detail$', views.detail,name='detail'),
]

I wrote in index.html

    <meta charset="UTF-8">

    <title>WEB SITE</title>

{% include '../header.html' %}

HELLO WORLD

When I acsess index.html and put LOGOUT link,logout is done accurately.But I wrote in detail.html

    <meta charset="UTF-8">

    <title>DETAIL</title>

{% include '../header.html' %}

HOGE

and put LOGOUT link,the error happens.In this time,Request URL is http://localhost:8000/accounts/detail/logout_view.I really cannot understand why this error happens.I wrote 2 html same way,so I cannot know why one of html is ok but another causes the error.How should I fix this?

A:

For some reason you have defined your URL for the logout_view view as "product", so that's the URL you need to use.
To avoid this sort of problem, you should always use the {% url %} tag to generate the URL, rather than hard-coding it in the template:
LOGOUT


Q:

Resistive Touchscreen Stands in Midway of the ADC in standby

In a resistive touchscreen I am trying to read x-y position. The schematics is as followed. The code works fine and when I press a point, it reads correct position well but the problem is in standby ( when no touch ).
The ADC shows the middle of the screen both for x and y instead of reading zero ( around 512 in a 10 bit ADC reading ).
I set a parallel 4.7 k resistor from X1 and Y1 to ground and the result is better ( it reads around 20 in standby) but I have not seen such design anywhere and dont know which value of the resistor is the best if this is the solution.
There is a good tutorial on resistive touchscreens by ATMEL here. In page 4, there is a table about the settings. I couldn't understand what Hi-Z stands for and I think the main result of my problem goes to that pull-up/int in the table for standby , but I couldn't find any sample code for setting a pull-up/int . What is that? should I clear SFIOR register PUD before reading and turning it off during the scan?
Schematics without resistor:

Schematics with resistor:

A:

Hi Z stands for "seemingly almost nothing connected", it acts as an open circuit, so you should take care of that situation if you want the other circuit to function properly.
Also, by the looks of it, 4.7k seems to be right in this scenario, as it would mean ~1mA at 5V, which is usually tolerable by most of the devices.
You should take a look at the uC datasheet on what resistance it uses for pulling down, and probably just set the port to pull down and the direction to input, but that might depend on what output impedance the touch module provides...
Copied form my comment below
According to the doc In stand-by mode one of the lines are connected to a level triggered interrupt in order to detect touch activity
It seems it stands for interrupt - if the device is touched, and goes out of standby, it pulls the line low to make the uC aware that it is touched. The uC has to switch mode of that pin to ADC at that time, and then it can detect the coordinate.


Q:

Reset the ID counter on a stored procedure in SQL Server

I'm developing a system that manages work orders for vehicles. The ID of work orders is composed as follows: OT-001-16.
Where OT- is a string, 001 is the counter, followed by - character and finally the number 16 is the current year.
Example:
If the current year is 2018, the ID should be OT-001-18.
The problem is when the year changes, the counter must restart from 001. I have a stored procedure to do that, but i think i'm doing a lot more work.
This is my stored procedure code:
CREATE PROCEDURE ot (@name varchar(100), @area varchar(100), @idate varchar(100), @edate varchar(100))
AS
BEGIN
  SET NOCOUNT ON;
  DECLARE @aux varchar(100);
  DECLARE @aux2 varchar(100);
  DECLARE @aux3 int;
  DECLARE @aux4 varchar(100);

  SELECT @aux = id_workorder FROM idaux;

  IF (@aux IS NULL)
    SET @aux = CONCAT('OT-000-', RIGHT(YEAR(GETDATE()), 2));

  SET
    @aux2 = SUBSTRING(
    @aux, CHARINDEX('-', @aux) + 1,
    LEN(@aux) - CHARINDEX('-', @aux) - CHARINDEX('-', REVERSE(@aux)));

  SET @aux3 = CAST(@aux2 AS int) + 1;

  SET @aux4 = @aux3;

  IF @aux3 < 1000
    IF @aux3 >= 10
      SET @aux4 = CONCAT('0', @aux4);
    ELSE
      SET @aux4 = CONCAT('00', @aux4);
  ELSE
    SET @aux4 = @aux4;

  DECLARE @f varchar(100);
  DECLARE @y varchar(50);

  SELECT TOP 1
    @y = id_workorder
  FROM workorder
  WHERE (RIGHT(id_workorder, 2)) = (RIGHT(YEAR(GETDATE()), 2))
  ORDER BY id_workorder DESC;

  DECLARE @yy varchar(10);

  SET
    @yy = RIGHT(@y, 2);
  DECLARE @yn varchar(10);

  SET
    @yn = RIGHT(YEAR(GETDATE()), 2);

  BEGIN
    IF @yn = @yy
    BEGIN
      DECLARE @laux varchar(20)
      SET @f = 'OT-' + @aux4 + '-' + RIGHT(YEAR(GETDATE()), 2);
      INSERT INTO workorder (id_workorder, name, area, initial_date, end_date)
        VALUES (@f, @name, @area, @idate, @edate);

      SELECT
        @laux = id_workorder
      FROM idaux

      IF (@laux IS NULL)
      BEGIN
        INSERT idaux (id_workorder) VALUES (@f);
      END
      ELSE
      BEGIN
        UPDATE idaux SET id_workorder = @f;
      END
    END
    ELSE
    BEGIN
      SET @f = CONCAT('OT-001-', (RIGHT(YEAR(GETDATE()), 2)));
      INSERT INTO workorder (id_workorder, name, area, initial_date, end_date)
        VALUES (@f, @name, @area, @idate, @edate);

      SELECT @laux = id_workorder FROM idaux;

      IF (@laux IS NULL)
      BEGIN
        INSERT idaux (id_workorder) VALUES (@f);
      END
      ELSE
      BEGIN
        UPDATE idaux SET id_workorder = @f;
      END
    END
  END

END

Basically, i created an auxiliar table to save the last Work Order ID, then from this table called idaux i take the ID and i compared to new possible ID by a string handling. Then if the year of the last ID saved are equal to the current year the counter increases, but if not the counter is restarted to 001, the new ID is updated in the auxiliar table and the Work Order is inserted to the table workorder.
My stored procedure works, but i need your help to optimize the stored procedure. Any question post on comments.

A:

Here is how I'd setup the stored procedure and the underlying table to keep track of your work orders:
create database tmpWorkOrders;
go

use tmpWorkOrders;
go

/*
    The work order ID (as you wish to see it) and the
    work order counter (per year) will be separated into
    two separate columns (with a unique constraint).
    The work order ID (you wish to see) is automatically
    generated for you and stored "persisted":
    http://stackoverflow.com/questions/916068/sql-server-2005-computed-column-is-persisted
*/
create table WorkOrders
    (
        SurrogateKey         int identity(1, 1) primary key not null,
        WorkOrderYear        int not null,
        WorkOrderCounter     int not null,
        WorkOrderID as
            N'OT-' + right(N'000' + cast(WorkOrderCounter as nvarchar), 3)
            + N'-' + right(cast(WorkOrderYear as nvarchar), 2)persisted,
        WorkOrderDescription nvarchar(200),
        constraint UQ_WorkOrderIDs
            unique nonclustered (WorkOrderYear, WorkOrderCounter)
    );
go

create procedure newWorkOrder
    (@WorkOrderYear int = null,
     @WorkOderCounter int = null,
     @WorkOrderDescription nvarchar(200) = null
    )
as
    begin
        /*
            If no year is given the the current year is assumed
        */
        if @WorkOrderYear is null
            begin
                set @WorkOrderYear = year(current_timestamp);
            end;
        /*
            If no work order counter (for the above year) is given
            then the next available one will be given
        */
        if @WorkOderCounter is null
            begin
                set @WorkOderCounter
                    = isnull(
                          (
                              select max(WorkOrderCounter)
                              from WorkOrders
                              where WorkOrderYear = @WorkOrderYear
                          ) + 1,
                          0
                            );
            end;
        else
        /*
                If a work order counter has been passed to the
                stored procedure then it must be validated first
            */
            begin
                /*
                    Does the work order counter (for the given year)
                    already exist?
                */
                if exists
                    (
                        select 1
                        from dbo.WorkOrders as wo
                        where wo.WorkOrderYear = @WorkOrderYear
                              and wo.WorkOrderCounter = @WorkOderCounter
                    )
                    begin
                        /*
                            If the given work order counter already exists
                            then the next available one should be assigned.
                        */
                        while exists
                            (
                                select 1
                                from dbo.WorkOrders as wo
                                where wo.WorkOrderYear = @WorkOrderYear
                                      and wo.WorkOrderCounter = @WorkOderCounter
                            )
                            begin
                                set @WorkOderCounter = @WorkOderCounter + 1;
                            end;
                    end;
            end;
        /*
            The actual insert of the new work order ID
        */
        insert into dbo.WorkOrders
            (
                WorkOrderYear,
                WorkOrderCounter,
                WorkOrderDescription
            )
        values
            (@WorkOrderYear,
             @WorkOderCounter,
             @WorkOrderDescription
            );
    end;
go

/*
    Some test runs with the new table and stored procedure...
*/

exec dbo.newWorkOrder @WorkOrderYear = null,
                      @WorkOderCounter = null,
                      @WorkOrderDescription = null;

exec dbo.newWorkOrder @WorkOrderYear = null,
                      @WorkOderCounter = 3,
                      @WorkOrderDescription = null;

exec dbo.newWorkOrder @WorkOrderYear = null,
                      @WorkOderCounter = 0,
                      @WorkOrderDescription = null;

exec dbo.newWorkOrder @WorkOrderYear = null,
                      @WorkOderCounter = 0,
                      @WorkOrderDescription = null;

exec dbo.newWorkOrder @WorkOrderYear = null,
                      @WorkOderCounter = 0,
                      @WorkOrderDescription = null;

/*
    ...reviewing the result of the above.
*/

select *
from dbo.WorkOrders as wo;

Note, that the "next available" work order counter is once given (1) as the maximum + 1 and once (2) increased until it does not violate the unique key constraint on the table anymore. Like this you have two different possibilities to go about it.


Q:

Listing answers for question(get_object_or_404) in for loop. How can I get each answer also as an object in one def?

I am sorry if my title doesn't make much sense for you. I have a problem and I have a problem with describing it. I will be very grateful if you could help me.
I have small voting system for my question objects. My questions have many answers that I am listing in "question_details" in for loop. I can of course access question model and therefore get informations about votes for question but I am unable to do the same for each answer. Maybe some code to better illustrate:
views.py:
def questiondetails(request, question_pk):
    question = get_object_or_404(Question, pk=question_pk)
    question_form_id = question
    total_voteup = question.total_voteup()
    total_votedown = question.total_votedown()
    is_voteup = False
    is_votedown = False
       if question.voteup.filter(id=request.user.id).exists():
           is_voteup = True
       if question.votedown.filter(id=request.user.id).exists():
           is_votedown = True

I can check about of votes, and I can check if user vote up or down.
in templates of questiondetails I am doing something like that:
{% for answer in question.answer_set.all %}
    {{ answer }}

    {% include 'main/partials/answer_voting_section.html' %}

{% endfor %}

And with that. I can click on my question, it will trigger "questiondetails" and bring me to it's page with question and answers coming from this for loop.
And my problem is, that I would like to access "total_voteup" (and other stuff) for each answer from that for loop.
How can I do it ? I am new at python at django so I only understand that I am able to do it with question and question details because I am PASSING a "question_pk". Can I in the same DEF also access answers associated with this question ? Or it is impossible because this data is "not yet visible" for django ?
@Edit:
My models:
class Question(models.Model):
    question = models.CharField(max_length=300)
    answered = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    datecompleted = models.DateTimeField(null=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    voteup = models.ManyToManyField(User, related_name='voteup', blank=True)
    votedown = models.ManyToManyField(User, related_name='votedown', blank=True)

    def __str__(self):
        return self.question

    def total_voteup(self):
        return self.voteup.count()

    def total_votedown(self):
        return self.votedown.count()

class Answer(models.Model):
    question_id = models.ForeignKey(Question, on_delete=models.CASCADE, blank=False, null=True)
    answer = models.TextField(max_length=1000)
    created = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    answer_voteup = models.ManyToManyField(User, related_name='answer_voteup', blank=True)
    answer_votedown = models.ManyToManyField(User, related_name='answer_votedown', blank=True)

    def __str__(self):
        return self.answer

    def total_answer_voteup(self):
        return self.answer_voteup.count()

    def total_answer_votedown(self):
        return self.answer_votedown.count()

A:

Although there's lots of redundancy on your code and your answer model doesn't need to use question_id field django will create id for you, the answer field is suppose to rather have the models.OneToMany relationship.
 but you can import answer model to the view and do something similar as you did for the questioniare upvote and downvote inside same view i.e
  answer_upvote = Answer.objects.filter(question_id=question).total_answer_voteup()
answer_downvote = Answer.objects.filter(question_id=question).total_answer_votedown()
The logic i am trying to use is getting all object related to each questions
but this way you can work around.


Q:

Write function for bsxfun with if/else

In my code, I need to divide each values of a matrix by the values of another. I could use A./B but some elements in B are 0. I know that if B(i,j) = 0 so A(i,j) = 0 too and I want to have 0/0 = 0. So I wrote a function div and I use bsxfun but I don't have 0, I have NaN :
A = [1,0;1,1];
B = [1,0;1,2];
function n = div(a,b)
   if(b==0)
      n = 0;
   else
      n = a./b;
   end
end
C = bsxfun(@div,A,B);

A:

Why not just replace the unwanted values after?
C=A./B;
C(A==0 & B==0)=0;

You could do C(isnan(C))=0;, but this will replace all NaN, even the ones not created by 0/0. If zeros always happen together then just C(B==0)=0; will do