Can't keep the php session more than 30 mins

Question: I tried following other posts to use these instructions at the begin of the script:
ini_set('session.gc_maxlifetime',24*60*60);
ini_set('session.gc_probability',1);
ini_set('session.gc_divisor',1);
session_cache_expire(24*60*60);

but always seeing session expires after 30 minutes. the session_start() is called after that instructions.
PS: I'm using an Ubuntu LAMP remote server.
Comment: call `session_start` before `session_cache_expire(24*60*60);`
Comment: Also, make sure the session cookie is set to expire after the desired amount of time. (Session cookie lifetime http://php.net/manual/en/function.session-set-cookie-params.php)
Comment: I'm trying both the methods now. i'll keep you updated, thanks.
Comment: No, it doesn't works. I still lose my session before 24h. I've both tried the set_cookie_params and session_cache_expire after session_start.
Answer: You have you change those configurations from the ini, otherwise they do not stay that way after the page has been executed, so therefore as the user continues using the website, they hit the php.ini's session max lifetime: session.gc_maxlifetime
you would have to edit php.ini to contain:
session.gc_maxlifetime = 86400


I'm trying to convert the time of day from military time to a 12-hour format using call by reference

Question: so, I'm new to calling by reference but from what I understand, its used for void functions to supply the main method with values. This is what I have.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdio>

using namespace std;
void convert12Format(int& hrs, int& minutes, int& time, string& ampm);
int main() {
    int length, width, time, hrs, minutes;
    string ampm;

    convert12Format(hrs, minutes, time, ampm);

    string timeOfDay = hrs + ":" + minutes + ampm;

    cout << timeOfDay;

    return 0;
}
void convert12Format(int& hrs, int& minutes, int& time, string& ampm){

    cout << "Please enter the time in military time (hhmm): ";
    cin >> time;

    hrs = time / 100;
    minutes = time % 100;
    if (hrs < 12) {

        ampm = " AM";
    }
    else {

        hrs = hrs - 12;
    ampm = " PM";
    }
}

when inserting a time in the form (hhmm): 1233
I get an output:
PM
I was expecting:
12:33 PM
Comment: `hrs + ":"` does not do what you think it does. If you add `4` to `":"` you don't get `"4:"`. You do not add an integer value to a string, and somehow end up concatenating the two. C++ simply does not work this way, that's all. Can you explain what led you to believe this is how string concatenation works? How does your C++ textbook explain the correct approach for concatenating text strings, the the correct approach for converting integers to strings?
Comment: If you want to concat numbers and strings, either convert the numbers to `std::string` using `std::to_string()`, or else write the values to a `std::ostringstream` first, and then extract a `std::string` from it via its `str()` method. Or, in C++20 and later, you can use `std::format()` to create formatted strings from input values.
Comment: On a side note, `main()` doesn't use `time` for anything, so there is no reason for `convert12Format()` to have an `int& time` parameter at all. `time` should be a local variable inside of `convert12Format()` only.
Comment: I'm an idiot.  I for some reason was trying to concatenate the string like in java.

thanks everyone for the help. I appreciate the answer posted.
Comment: *"I'm new to calling by reference"* -- that  could explain why you called it "calling by reference" instead of "passing by reference". Not that this question has anything to do with pass-by-reference. (Test one thing at a time. Verify the values you get back with*out* trying to format them. `std::cout << hrs << '\n'; std::cout << minutes << '\n'; std::cout << ampm << '\n'; std::cout << time <<'\n';`. Add labels if desired.)
Answer: The problem is on this statement:
string timeOfDay = hrs + ":" + minutes + ampm;

You are invoking pointer arithmetic, not string concatenation.
You are adding an int (hrs) to a const char[2] array (":"), which decays into a const char* pointer.  So, you are advancing the pointer in memory by however many characters the int specifies.  Which, in this case, will lead to undefined behavior for any int value other than 0 or 1.
Try this instead:
#include <iostream>
#include <string>
using namespace std;

void convert12Format(int& hrs, int& minutes, string& ampm);

int main() {
    int hrs, minutes;
    string ampm;

    convert12Format(hrs, minutes, ampm);

    string timeOfDay = to_string(hrs) + ":" + to_string(minutes) + " " + ampm;
    cout << timeOfDay;

    // alternatively:
    // cout << hrs << ":" << minutes << " " + ampm;

    return 0;
}

void convert12Format(int& hrs, int& minutes, string& ampm){
    int time;

    cout << "Please enter the time in military time (hhmm): ";
    cin >> time;

    hrs = time / 100;
    minutes = time % 100;

    if (hrs < 12) {
        if (hrs == 0) hrs = 12;
        ampm = "AM";
    }
    else {
        if (hrs > 12) hrs -= 12;
        ampm = "PM";
    }
}

Comment: I think you need a separate check for `hrs == 12`, or else your noon would look funny.
Comment: @VladFeinstein Same with midnight, too. I've updated my example.


How to show the full image in circle image view without streching?

Question: I am new in android,I need to display the image in circular form but some images which have more than width and height from custom circular image view then displaying the image as streching form, But I want to show the image with reduce the size of image and show in circle.  I am using universal image loader for loading the images.Please help me How to do this.
Thanks in advance
Comment: try to use  .displayer(new RoundedBitmapDisplayer(px)) in universal image loader
Comment: Already used this one with size but still issue is producing. I am getting size as 309*99 and i need to show in size as 150*150.
Comment: use http://square.github.io/picasso/ to load images
Answer: in the build.gradle file , put this line in the dependencies:
compile 'de.hdodenhof:circleimageview:2.0.0'

this is a library for the circular imageView. then in the xml you can use it like:
<de.hdodenhof.circleimageview.CircleImageView
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:id="@+id/profile_image"
     android:layout_width="60dp"
     android:layout_height="60dp"
     android:scaleType="centerCrop"
     android:src="@drawable/male_profile_image"
     app:civ_border_width="0dp"/>

Answer: You can achieve this by using a circle image view library
implementation 'de.hdodenhof:circleimageview:2.2.0'

Next, You'll add it to your layout
<de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/ptv_pic"
            android:layout_width="120dp"
            android:layout_height="100dp"

            android:src="@drawable/ptv" />

Lastly, create a drawable file to match the src stated above "ptv" (Give it any name you'd like of course)
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item
    android:drawable="@mipmap/yourImage" (Here is where you'll add the image)
    android:width="50dp"  (Adjust the width and height here)
    android:height="50dp"
    />

</layer-list >


Second state in JQuery impromptu flashes and closes?

Question: I am working on a web based application using jquery impromptu dialogs . I am using this code:
var statesdemo = {
        state0 : {
            title : 'here',
            html : 'Name <input type="text" id="fname" name="fname" value="1">
',
            /* + '<input type="text" name="lname" onclick="iconPrompt()" value="Change Image">
', */

            buttons : {
                ChangeImage : -1,
                Delete : -2,
                Save : false,
                cancel : true
            },
            focus : 0,

            submit : function(e, v, m, f) {
                console.log(f);

                if (v == -2) {
                    $('.1' ).remove();
                    $.prompt.close();
                }

                if (!v) {
                    $('#pos')
                            .append(
                                    $('
"'
                                            + document
                                                    .getElementById('fname').value
                                            + '"

'));

                    $.prompt.close();
                } else if (v) {

                    $.prompt.close();
                }

                if (v == -1) {
                    $.prompt.goToState('changeImage');
                }

                return false;
            }
        },
        changeImage : {
            title : "Choose Image",
            html : '
'
                    + '

'
                    + '

'
                    + '

'
                    + '

',

            buttons : {
                Done : 1
            },
            focus : 2,

            submit : function(e, v, m, f) {
                /* console.log(f);

                e.preventDefault();
                if (v == 1)
                    {
                    $.prompt.goToState('state0');}
                return false; */

            }
        },

    };

It runs fine until I press the ChangeImage Button in first state . The Second state flashes and closes in a second of time. What am I doing wrong please help . I am stuck for hours.
Comment: This would be easier to troubleshoot if we had some HTML markup to look at. Why don't you create a jsFiddle?
Answer: You probably forgot return false; within the if (v) { .. }
EXAMPLE:
state0: {
  title: 'this is the title',
  html: '
this is the html',
  submit: function(e,v,m,f) {
    if (v) {
      //validation here

      return false;
    }
  }
},
state1: {
 ......
}

Answer: sorry to ressurect this query, but probably what is missing (and I had the same problem because I copied and tested from their example) is the else statement before the next ifs
let's say you wanted it to match the first IF and the code succeded (and that's why it flashes'. when the execution jumps to the next line it finds another if to evaluate. but the condition is not correct and it goes to this if's else. got it?
example:
input is 2
if(input == 2){...} //matched
if(!input){...}
else{...} //matched again because previous `if` didn't match


Selection of tableview cell's index path

Question: I have a question regarding the selection of table cells.
I have three grouped tables which are used as forms, only one of which should be in view at a time. So in the nav controller I have a button which presents another table in a popover with the title of all three forms and will control which form is currently available. So to show only one at a time manually is easy enough, but how do I go about detecting the selection of a certain cells indexPath upon selection and communicate that selection with another view controller?
Answer: You are getting it as part of
<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
</code>
for the table view delegate.
Also, it might be worth considering using a segmented control for the selection.


Taking a list of items and displaying a value from each item as a string

Question: I have a function that takes a list of items i.e. [item_1, item_2] etc.
Each item itself is a dictionary on another page. i.e. item_1 {key: value, etc}
I want to display the value of the key (called "name") for each item in the list.
For example if the input to the function, list_of_items() is [item_1, item_2]
Should return 'name of item 1, name of item 2' as a string separated by commas.
new_list = []
for i in items:
    new_list.append(i["name"])

return str(new_list).strip('[]')

This code returns "'name of item 1', 'name of item 2'" and it is the closest I have gotten.
How can I return the string I want?
Answer: You can use str.join() to join the list of strings into a single string. Example -
new_list = []
for i in items:
    new_list.append(i["name"])

return ','.join(new_list)

This can be simplified using the below list comprehension -
return ','.join([i['name'] for i in items])

Demo -
>>> items = [{'name':'a'},{'name':'b'},{'name':'c'}]
>>> ','.join([i['name'] for i in items])
'a,b,c'

Comment: Thank you very much, exactly as I wanted.
Comment: Glad I could be helpful! :-)
Answer: The answer from @AnandSKumar is perfect. In addition, note that you don't actually have a function in the code that you provided. A function in python begins with the def statement. So copying some code from @AnandSKumar, you have the following function:
def dictsName2str ( listOfDicts ) :
    return ','.join([i['name'] for i in listOfDicts])

Then you can call your function with the following code:
>>> items = [{'name':'a'},{'name':'b'},{'name':'c'}]
>>> myStr = dictsName2str( items )


Find the Possible solution for the differential equation

Question: determine by inspection at least one solution of the given differential equation. That is, use your knowledge of derivatives to make an intelligent guess. Then test your hypothesis:
$xy'+ y = 3x^2$
When I tried I observed that there are product rule and power rule so I approached it backward but am stuck.
I feel like there is a concept I am unable to recall.
It would be nice to have some guidance.
Thanks in advance
This is what I have done after various approaches .
Comment: For some basic information about writing mathematics at this site see, *e.g.*, [here](/help/notation), [here](//math.meta.stackexchange.com/q/5020), [here](//meta.stackexchange.com/a/70559) and [here](//math.meta.stackexchange.com/q/1773).
Comment: @AnotherUser thanks for the advice
Answer: What you did looks good:
$$xy'+ y = 3x^2$$
$$(xy)' = (x^3)'$$
You have derivatives on both sides. Integrate.
$$xy = x^3+C$$
For the solution by introspection try $y=cx^2$ as a possible solution.
Comment: I addes a line you were almost there @PriyankaJangra
Comment: Thank you so muchヾ(^-^)ノ     Can't believe I hve been messing up the integration
Comment: You're welcome @PriyankaJangra


Can I play LOTRO on Nvidia ION based netbook running 64bit linux?

Question: I have a ASUS Eee PC 1215N netbook, from the Seashell series.
It has a Nvidia ION graphic processor.
I'm running 64bit Ubuntu Linux (11.10 Oneiric Ocelot) on it.
I've tried to install LOTRO on it following the HOWTO on
But the game fails to run with one of:

Game Error [105], "Could not initialize Direct3D. Please ensure that
DirectX 9.0c [Dec 2005] or higher is installed."
Game Error [129], "Hardware texture compression support was not detected. This video card feature is required to run the game."

The PyLotro wine output contains eiter

err:wgl:has_opengl Failed to load libGL: libGL.so.1: cannot open shared object file: No such file or directory
  err:wgl:has_opengl OpenGL support is disabled.
err:d3d_caps:WineD3D_CreateFakeGLContext Can't find a suitable iPixelFormat.
err:d3d:InitAdapters Failed to get a gl context for default adapter
Direct3D9 is not available without OpenGL.

Or a repeating errors ending in

ERROR: ld.so: object 'libdlfaker.so' from LD_PRELOAD cannot be preloaded: ignored.
ERROR: ld.so: object 'librrfaker.so' from LD_PRELOAD cannot be preloaded: ignored.
Xlib:  extension "NV-GLX" missing on display ":2".
  Xlib:  extension "NV-GLX" missing on display ":2".
err:winediag:X11DRV_WineGL_InitOpenglInfo Direct rendering is disabled, most likely your OpenGL drivers haven't been installed correctly
Comment: I think that Codemaster's support can help you more than we, you should try to post on their forum aswell, if you haven't done that already.
Comment: Thanks for the comment. I've made this question to answer it myself with information I've gathered from the several fora out there.  On Mac OS Leopard, I ended up using Crossover Games. I'll probably buy a licence for that; they contribute a lot back to the wine-project as well.
Comment: And you probably mean [Code*Weavers*](http://www.codeweavers.com/products/cxgames/) not Code*masters*.
Answer: Running software using the ION processor will require extra software. Windows 7 Nvidia supplies Optimus. On linux there's a project called Bumblebee.
To recap the several sources on the web for 64bit Oneiric:
Install LOTRO roughly following the howto
sudo apt-get install wine winetricks
export WINEPREFIX=$HOME/.wine-lotro
winetricks vcrun2008
winetricks d3dx9
cd /wherever/you've/downloaded/the/game
wine LOTROSetup.exe

This will have created a wine environment (sometime revered to as 'bottle') in .wine-lotro in your home directory and installed the game there, including some native windows dll's that the game needs.
To launch the game from wine you'll need the special launcher called PyLotro. Normally on Ubuntu you do
sudo add-apt-repository ppa:ajackson-bcs/ppa
sudo apt-get update
sudo apt-get install pylotro

But there's no Oneiric version in the ppa yet. So just get the source version (not the 'Stand-alone Version' exe one).
To have it use the Nvidia processor, you install Bumblebee
sudo add-apt-repository ppa:bumblebee/stable
sudo apt-get update
sudo apt-get install bumblebee

And since wine is 32-bit, and 64-bit Oneiric uses multiarch, you install the 32-bit version of some libraries like this
sudo apt-get install virtualgl-libs:i386

without it you'll see those LD_PRELOAD errors.
To have the pylotro launcher use optirun to run wine, I made a tiny wrapper script like this
mkdir $HOME/bin
cat << EOF > $HOME/bin/optiwine
#! /bin/sh
optirun wine \$@
EOF
chmod +x $HOME/bin/optiwine

In pylotro  /Tools/Options, tick the Advanced Options and set /home/{username}/bin/optiwine as the Wine Program. And of course set the right WINEPREFIX et al.
Comment: I have followed your instruction and I am able to use pylotro with your wrapper, but I still get the "Hardware texture compression support was not detected." error. Did I miss something? Is there anything you can help me to fix this issue. I will also check the codeweaver forum to see if I can find anything there.
Comment: Very hard to say from what you tell. Is there any difference in the wine output when you run the game with the wrapper instead of wine?


BLE gatttool reading serial data from bluno?

Question: I am trying to send data over BLE from Bluno to a Raspberry Pi (Raspian), bluez 5.50.
Whilst the connection seems to be fine. I am struck in a point where am unable to retrieve serial data from notification handle.
Below is what I tried.
pi@raspberrypi:~ $ sudo gatttool -b <BLE-MAC-ADDRESS> -I
<BLE-MAC-ADDRESS>[LE]> connect
Attempting to connect to <BLE-MAC-ADDRESS>
Connection successful
[<BLE-MAC-ADDRESS>][LE]>
Notification handle = 0x0025 value : 32
Notification handle = 0x0025 value : 32
Notification handle = 0x0025 value : 32
Notification handle = 0x0025 value : 32
[<BLE-MAC-ADDRESS>][LE]>char-read-hnd 0x0025
handle : 0x0025 value : 01
Notification handle = 0x0025 value : 32
Notification handle = 0x0025 value : 32
[<BLE-MAC-ADDRESS>][LE]>

So the problem here is , Notification handle listener 'listens' to the serial data and returns the value( 2 -> Hex:32) every 1 second from Bluno  (as programmed in Adurinosketch).
But when I try to retrieve this value through the command char-read (tried both by handle & uuid) it always returns 01 ?!!!
Ultimately I want to retrieve this value in my Python code (am using Pexpect for this)
Any help / directions appreciated.
Answer: Ok , Here is what I ended up doing in my Python code to retrieve the value
`
child = pexpect.spawn("sudo gatttool -b <BLUNO-MAC-ADDR> -I")
# Connect to the device.
print("Connecting to Bluno...")
child.sendline("connect")
child.expect("Connection successful", timeout=5)
print(" Connected!")

while True:
    child.expect("Notification handle = 0x0025 value: ", timeout=10)
    child.expect("\r\n", timeout=10)
    resp = child.before
    print(process_my_data(bytearray.fromhex(resp.decode("utf-8")).decode()))

`


Does VB.NET support Promises/Deferreds?

Question: I'm interested in something similar to jQuery's Deferred object.  The below link seems to be  thread oriented.  With Javascript running in a single timeshared thread the model is quite different.
http://www.codethinked.com/net-40-and-systemthreadingtasks
Comment: Are you familiar with delegates and events?  I'm not familiar with jQuery, but from what I just read, it sounds roughly equivalent to delegates and events (events are a special kind of delegate).
Comment: In ASP.NET MVC you can do async type stuff. Not exactly the same as the jQuery object. But I am not sure what the context is for your question. Here is link if this helps: http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4
Answer: Take a look at Asynchronous Programming with Async and Await (C# and Visual Basic) available with .NET 4.5 and Visual Studio 2012.  It builds on the infrastructure laid by the Task Parallel Library that is the topic of the link you provided above.
Comment: Looks to have promise (no pun intended).  I see they opted to expound upon the language rather than building asynchronous constructs from existing structures ala jQuery.
Comment: You can build something just like jQuery Deferred by using `Task`, `TaskCompletionSource`, `ConfigureAwait`, and of course `async` and `await`. E.g., see Stephen Toub's blog post on [implementing `then` with `await`](http://blogs.msdn.com/b/pfxteam/archive/2012/08/15/implementing-then-with-await.aspx).

Does VB.NET support Promises/Deferreds?


How to concatenate N' strings on insert in SQL

Question: I'm trying to insert strings into a NVARCHAR as I was having problem with characters not going into the db properly.
e.g. I have strings I want to put into my db but to get the special characters to show up it seems I need the N' to store Unicode.
N'I used tö like SQL'

But sometimes these string already have single quote in them.
e.g.
"I dön't anymore"

How do I concatenate these strings so that the still store the Unicode. I thought something like this would work but I'm having no luck.
(N'' + "I dön't anymõre")

Any help would be appreciated thanks!
Comment: Which dbms are you using?
Comment: Double the single quote in a literal, like `N'I dön''t anymõre'`.
Comment: Is it possible that you think the type indicator is `N'`? It is just `N`. So if double quoting is also allowed in your RDBMS, what about `N"I dön't anymore"`?
Answer: To include an apostrophe in an SQL string you need to double the apostrophe, as in:
N'I dön''t anymore'

String concatenation, on the other hand, performed with the || operator as in
N'This is the first substring' || N' and here''s the secönd substring'

will produce
This is the first substring and here's the secönd substring

db<>fiddle here
Comment: Not the concatenation operator is the question, but you showed properly that each string must have an `N`.
Comment: Well, since the title of the question says `How to concatenate...` and the user wasn't using the correct SQL concatenation operator I thought it would be a good idea to give an example.
Comment: Without the RDBMS there is no `correct concatenation operator` - try your example in SQL Server.
Answer: Generally to store quotes you simply double them up:
declare @string nvarchar(50)
set @string=N'I dön''t anymõre'
print @string

Edit - You don't state a particlar platform however I'm assuming SQLServer, doubling single quotes works on most platforms.
Comment: Very product specific answer to a question with no dbms specified. At least tell us which dbms this is for.
Comment: @jarlh . .. The answer is not product specific.  Doubling the single quote is the SQL standard way of inserting a single quote.  Of course, the `declare` and `print` are product specific, but those are secondary to the answer.


Analytic function is constant.

Question: I looked around the site and  I couldn't seem to find a similar question. But, I came across this question:
Let $f$ be analytic from the unit disc to the complex plane with the property that $|f(z)|\leq |f(z^2)|$ for all $z \in D.$ Show $f(z)$ is constant.
I did a similar problem where we assume we $f(z)$ is an entire map and that  was straight forward since we could write $f(z) = c f(z^2),$and play around with the taylor coefficients. But now, I don't have any intuition for this problem. I want to use the maximum modulus theorem  but I can't apply it, since we are not continuous  on the closure. I also tried defining a few functions, such as the  difference of the two $f(z)-f(z^2),$ but I seem to be coming up short in either case. Am I missing something? Is there some trick I don't see?
Comment: Use maximum modulus theorem on $|z|\leq r$ for $r<1$
Comment: see as well : https://math.stackexchange.com/q/2739812
Answer: Following @RodrigoDias, let $r <1$ and consider the restriction of $f$ to $B(0;r)$. If $f$ is non-constant on $B(0;r)$, then there exists $z_0 \in \partial B(0;r)$ such that $z \in B(0;r) \implies |f(z)| \leq |f(z_0)|$. But since $|z_0^2|<|z_0|$,$z_0^2 \in B(0;r)$ and by hypothesis, $|f(z_0)| \leq |f(z_0^2)|$. This is a contradicts the maximum modulus principle. Therefore, $f$ must be constant.
Answer: Notice that $|f|$ has a maximum in $z=0$. In fact, for $|z|<1$, we have
$$|f(z)|\leq|f(z^2)|\leq|f(z^4)|\leq|f(z^8)|\leq\dots \leq\left|f\left(z^{2^n}\right)\right|\to |f(0)| \text{ for }n \to +\infty$$
where all the inequalities are applications of the given property, and the convergence at the end uses the fact that $|z|<1$, thus $z^{2^n}\to 0$.
If $f$ wasn't constant, it wouldn't have a maximum (by the maximum principle).

Analytic function is constant.


How to identify the module supposed to claim a device by vendor/product ID only?

Question: Suppose I know the numerical product/vendor IDs of hardware I don't have here and I want to know if there's support for me in the kernel, I can do this (USB bluetooth receiver example):
modinfo btusb
filename:       /lib/modules/3.7.5-030705-generic/kernel/drivers/bluetooth/btusb.ko
[...]
alias:          usb:v0A5Cp*d*dc*dsc*dp*icFFisc01ip01in*
alias:          usb:v0489p*d*dc*dsc*dp*icFFisc01ip01in*
alias:          usb:v413Cp8197d*dc*dsc*dp*ic*isc*ip*in*
[...]

From this I can see which devices are to be claimed by btusb and it requires me to know the module name on beforehand. In some cases however, I don't have a clue about the module(s) name(s) supporting such a device.
Networking hardware is one of those categories which seems very hard to find out about. Also, the lspci and lsusb names are sometimes inconclusive or simply wrong. I'm currently grepping through the whole kernel source tree, which is not that elegant.

Is there a way to list all modaliases of all modules (including built-in to the kernel) in one go so I can find a match?
Or, alternatively, is there a way to query the kernel to provide me the kernel modules claiming such a device I don't actually own?

Use cases:

Users asking questions here which I can answer/dupe with by actually verifying that "support is in if you upgrade to..." or "Try rmmod module1; modprobe module2 as module2 seems to support your device as well."
Checking support before buying hardware with prior knowledge of the IDs. Additional to searching with the IDs, I can then look for bug reports on the kernel module itself.
Comment: There isn't really an easy way to get this information. Not all USB devices are claimed based on their IDs. Class based devices (storage, HID, and many serial and networking devices) are identified based on what interface they provide.
Comment: maybe usb-modeswitch can help with that. if you not have it: `sudo apt-get install usb-modeswitch`
Comment: type lsusb and you will see ID
Comment: from your question i just saw that you want to see id and change it, am i wrong?
Comment: now i really not understand you. please explain your question than i can understand it better and see if i actually can help you
Comment: I don't see how this answers my question either. I'm not looking for a way to change modes of USB devices. Please re-read my question and give an example if you think this *does* answer my question.
Answer: If you restate the problem as "How can I run modinfo on all (or some) modules and select some of the output for further use?", you could use this trick (I've left the commands I used to figure out how to get to the final result):
ls /lib/modules
ls /lib/modules/$(uname -r)
ls /lib/modules/$(uname -r)/kernel
find  /lib/modules/$(uname -r)/kernel -type f -name '*.ko' -print
for i in $( !! ) ; do
for i in $( find  /lib/modules/$(uname -r)/kernel -type f -name '*.ko' -print ) ; do
   j=${i##.*/}
   j=${j%%.ko}
   echo $j
   modinfo $i | egrep 'filename:|alias:'
   echo ""
   done

This trick can be used elsewhere, have fun!


How to create silverlight app with vwd 2008 sp1?

Question: I've installed Visual Web Developer express 2008 sp1 and Silverlight 3 Tools.
But I only have two new VS templates "Silverlight Script Web" and "WCF Service".
How do I create a Silverlight application?
I have c#, vb.net, vwd express editions and visual studio 2005.
Please Help.
Thanks
Answer: Web Developer Express is the preferred method of Silverlight development. You don't need the C# or VB.NET express editions.
Make sure that you're running the latest (SP1 included) Visual Web Developer Express 2008. After installation, install the Silverlight Tools (v3). Confirm that you also have the Silverlight SDK and all that on your machine.
It just works, and you'll find the project templates under the language of choice - Visual C# or Visual Basic, for instance.
Answer: Larry also make sure you are choosing New Project instead of New Web Site.


Field creation AP efficiency

Question: Should I create two fields with one link or should I create one field at a time? It seems like I get 2.8k AP from 2 fields with one link, and 1.5k from just one field per link. So it would seem like creating them one at a time would be the most efficient method, but I see people telling me to create links that would establish two fields at a time. Any benefits to either of these?
Answer: The answer to your question depends on what you're trying to achieve. If you're trying to gain as much AP as possible, creating one field at a time (two fields with two separate links) is best. Here's the math:
<code>313 AP per link established
1250 AP per field created
---
2 fields with 2 separate links > 2 fields with one link
313*2 + 1250*2 > 313*1 + 1250*2
3126 > 2813
</code>
However, there are a few reasons for why you might want to create two fields with one link.

If you're short on time, this can be the fastest way to gain a relatively large amount of AP.
If you're running short on keys or know you want to establish other links with your existing keys, one link creating two fields gets you almost the same amount of AP (313 less).

Hope this helps.
Comment: This answer is completely wrong. It profits from a primitive fact that `626 + 2500` is more than `313 + 2500`, but the reasoning behind it is off the wall. If you are alone in a situation with 4 portals, no links and 5 keys it DOESN'T MATTER AT ALL if you first create the border links and then one through the middle createing 2 fields at a time, or if you create field after field. The CORRECT math is: `313+313+313+313+(313+2x1250) = 4065` and `313+313+(313+1250)+313+(313+1250) = 4065`.
Comment: Just add, that sometimes there's no other way to do. I mean, with 1 link, create 2 fields, for example dividing a posible inner triangle.
Comment: So if you are ever in a situation where you can create TWO fields with ONE link, there is NO POSSIBILITY WHATSOEVER to create two links, thereby the comparament (`626 > 313`) is not real in such situation. There is NO such situation which the answerer describes. Either you HAVE to create two links to create fields, or you HAVE to create one link to create fields. It's not up to you, it's the current situation. There is a special case of linking though. It is called `onion fields`. Search more about it.
Answer: The one case where creating two fields at a time is beneficial is layering. You can create fields on top of existing fields by linking from an "outside" portal to an "inside" portal. Here's a video that shows how:

This will give you more total AP than you could have obtained by creating fields one-at-a-time.
Comment: Just for the record, it is called `Onion Fields`.
Answer: It depends on the situation at hand, on the time you have at the moment, on the topology of the area, etc. There can't be an all around answer to this question.
Suppose you're on a neutralized farming area and you want to improve your fielding stats or just gain the most possible AP. You should build as much fields as possible, meaning that you  would certainly at some point build two adjacent fields with one link. Or if you wanted to improve your linking stats, too, then you would develop a completely different strategy.
The loss of just 313 AP is not such a big thing.

Field creation AP efficiency


Absolute value of a negative number

Question: I was reading 'The method of Coordinates - Gelfand' and in the section about the absolute value of a number, it is stated what follows :
if x > 0, then |x| = x,
if x < 0, then |x| = -x,
if x = 0, then |x| = 0
"Since the points a and -a  are located at the same distance from the origin of coordinates, the numbers a and -a have the same absolute value: |x| = |-x|."
I don't understand the second statement : if x < 0, then |x| = -x.
Why is the absolute value of a negative number negative if a distance between 2 points, I suppose, can't be negative ? Plus, the author contradicts himself by saying that |x| = |-x|, because if |x| = x and |x| = |-x|, then |-x| = x. Is it a typing error or am I missing something ?
Comment: `if x < 0, then |x| = -x` Replace $x$ with $-1$ and see what you get for $|-1|$. Hint: it's *not* negative.
Comment: If x = -1, then |-1| = -(-1) = 1. So the author actually could not say that if x < 0, then |x| = x because that would mean, as x is a negative number, that it's modulus is a negative number (because x = -something), which is false. Now I understand, thanks for your help.
Comment: Because $-x> 0$ if $x < 0$
Comment: $-x$ isn't necessarily negative, it's just $-1\cdot x$.
Answer: You can define the absolute value by
$$|x|=\max(x,-x)$$
if $x<0$, $-x$ is bigger than $x$.
Comment: What is max(x, -x) ? Is it the biggest value between x and -x ?
Comment: @CylianBarichard Yes. {}{}{}{}

Absolute value of a negative number


About the position of "for all" quantifier

Question: I'm not expert in logic, but as far as I know, quantifiers comes before the predicates they refer to. Still, if written in english, there are statements which sounds better when you don't put all the quantifiers before. For example, the definition of a sequence of functions $f_n:\mathbb{R}\to\mathbb{R}$ converging uniformly to some function $f:\mathbb{R}\to\mathbb{R}$:

For all $\varepsilon > 0$, exists $n_0\in\mathbb{N}\ $ such that $\ n>n_0 \implies |f_n(x) - f(x)| < \varepsilon$ for all $x\in\mathbb{R}$

I have seen teachers writing this as

$$\forall\varepsilon > 0,\ \ \exists n_0\in\mathbb{R}\ \  \text{ such that } \ \ n>n_0 \implies |f_n(x) - f(x)| < \varepsilon,\ \ \forall x\in\mathbb{R}$$

Maybe an even more simple example, from probability. It's not hard to find  something like

$$P[X_n=Y_n, \forall n\in\mathbb{N}]$$

where $(X_n)_{n\in\mathbb{N}}$ and $(Y_n)_{n\in\mathbb{N}}$ are collection of random variables.
I understand the motivation: if you talk about this probability, you probably will say the probability of have $X_n=Y_n$ for all $n$, and not the probability of, for all $n$, have $X_n=Y_n$. The same reasoning applies for the statement about uniform convergence. That last for all quantifier will fit better at the final of the sentence if you have to say it in words.
So my question is: are this "informal" formulas just wrong (in the formal logic point of view)? Or the formal language of logic can handle this kind of writing?
Thanks.
Comment: The informal approach becomes ambiguous (and that's really a problem) as soon as statements of the form $\exists x\; \Phi(x,y)\;\forall y$ occur
Answer: The informal, natural language examples are neither right nor wrong form the formal viewpoint, because the informal examples are not written in a formal way.
The general rule is that the "last quantifier" in natural language becomes the innermost quantifier in formal language. Here are some common examples of informal phrasings and their formal counterparts:

A sequence $(x_n)$ converges to $L$ if for all $\epsilon > 0$ there is an $N$ such that $|x_n - L| < \epsilon$ for $n > N$. Formally:
$$(\forall \epsilon > 0)(\exists N)(\forall n)[ n > N \to |x_n - L| < \epsilon]$$
A function $f$ is continuous at a point $x$ if for every $\epsilon > 0$ there is a $\delta > 0$ such that $|f(x) - f(y)| < \epsilon$ for all $y$ with $|y-x| < \delta$. Formally:
$$
(\forall \epsilon> 0)(\exists \delta > 0)(\forall y)[|x-y| < \delta \to |f(x) - f(y) | < \epsilon].$$

This is something that is rarely mentioned explicitly in textbooks, but which you have to learn as a student in order to read informal mathematics correctly.  But that does not make the informal mathematics "wrong" and the formal mathematics "right". They are simply different ways of approaching the same topic.
Comment: The convergence definition would be probably more coherent with the informal phrasing if you write it this way: $$(\forall \epsilon > 0)(\exists N)(\forall n > N)\,[\,|x_n - L| < \epsilon\,]$$
Comment: @CiaPan: thanks. I did write it that way at first, but then I decided I liked to see the $\to$ in both of the formulas, so I changed it. So I agree that the formula you wrote is appealing as a translation of the informal phrasing.
Answer: I think you're correct that in precise logical statements the quantifier should come first, and the more colloquial mathspeak is an abuse. This bothered me for a while when I went from my first logic class to my first analysis class.
Comment: This can be a problem sometimes, I guess. Because this abuse makes sense for some people (who speakes english or other language with similar grammar), but not for all. Japanese grammar, for instance, is very different. I'm not sure if a japanese student would translate this formulas in native language and understand why the change of position of the quantifier. Basically that's what this abuse is: a translate of native language in logic formulas (ignoring the fact that the formulas are formally wrong).
Answer: Carl Mummert's answer is very good, but I'd like to refer specifically to the examples you have given.
Examples such as

$$\forall\varepsilon > 0,\ \ \exists n_0\in\mathbb{R}\ \  \text{ such that } \ \ n>n_0 \implies |f_n(x) - f(x)| < \varepsilon,\ \ \forall x\in\mathbb{R}$$

are perfectly fine on a blackboard: writing on it takes time, and it is a dynamic process (you see it being written), probably assisted by the lecturer's comments. Actually spelling everything out in words would take up too much time and blackboard space, and the "dynamic" plus the commentary make the text completely understandable (hopefully).
Things are very different with a stand-alone mathematical text. In there, you should (as a rule of thumb) either spell out quantifiers (and logical connectives!) in words, as in

For all $\varepsilon > 0$, there exists $n_0\in\mathbb{N}\ $ such that whenever $\ n>n_0$, we have that $\lvert f_n(x) - f(x)\rvert < \varepsilon$ for all $x\in\mathbb{R}$.

(and this is preferable), or spell everything out purely formally, like:

$$\forall\varepsilon > 0\ \ \exists n_0\in\mathbb{N}\ \ \forall n\in {\mathbb N} \   \left( n>n_0 \implies \forall x\in\mathbb{R}\ \ |f_n(x) - f(x)| < \varepsilon,\right).$$

(In the latter case, you should also probably avoid writing the formal part inline (unless it is very short).)
You can, of course, use various notational shorthands for formal writing, like writing $\forall n>n_0$ or similar, and likewise, when writing in natural language, there is also some wiggle room: for instance, you could write "for all real $x$" instead of "for all $x\in {\mathbb R}$", so there is some wiggle room in how much to spell out and how formal to be, but mixing formal language and natural language too much is bad form IMHO, makes the text harder to read and easier to write sloppily.
Comment: Hi tomasz, thank you for your response. I totally agree about the dynamics in the lectures. I see a lot this kind of notation in blackboards and it really makes sense, but I see very few books following this style. Yet there is some books which mimics this notational *style*. This is one of the reasons which motivated me do create this question. Besides that, I have a doubt: what you meant by *you should also probably avoid writing the formal part inline* ? What is to write inline?
Comment: I mean, you should write it separately (as you would a longer equation), not within a paragraph of text. Usually, the only reasons for using such formal notation that I can think of are when you want to a) highlight the *structure* of a statement or b) express it in an unambiguous way (this can be difficult to do in natural language at times). In both cases, you would want the formal part to be clearly distinct, and besides, you have better control over alignment and line breaks this way).
Comment: @tomasz, just expressing a doubt that came up during my study : I know that the usage of $\forall$ means that the condition/statement holds for all values in the domain under consideration, but what happens if I use $\not\forall$ ? For example, $x \in X\cap Y \not\forall x \in X$ ? Does it mean literally that not every element in $X$ belongs to $X \cap Y$?
Comment: @Spectre: I don't know. I've never seem anyone write $\not\forall$ before, it seems highly nonstandard, and honestly a bit sketchy.
Comment: @tomasz so basically I use Enlgish?
Comment: @Spectre: Sorry, I don't understand the question.
Comment: @tomasz I meant, instead of using that sketchy and non-standard symbol, should I prefer writing it out?
Comment: Writing things out is *usually* preferable to using symbols in general. If you *do* need to write this sort of thing symbolically, you can write $\neg  \forall x\in X(x\in X\cap Y)$ (or some other combination of spaces/parentheses you like). Of course, simpler is almost always better, so in this particular case, it'd be much better to write $X\not\subseteq Y$.
Answer: Strictly in terms of formal logic, quantifiers are at the beginning of any formula.  However, no one gives a proof that is written in the formal language.  Even simple proofs would be very long and unreadable.  The point is that statements like the probability example you gave can be written in the formal language.
Comment: Yes, this is a good point. But it shouldn't be surprising.  One advantage of a formal language is that it is unambiguous.  Anyone, regardless of what natural language they speak, will interpret a sentence in the formal language in the same way.  The price for this clarity of course is readability.  Natural languages, because of their inherent ambiguity, are subject to many more limitations.  But remember, formal languages have their limitations as well.  Most notably, the Godel Incompleteness Theorem.
Comment: I understand what you say. But about the uniform convergence example? That formula only makes sense if you know english (or other language with similar grammar), for it is just a translation of words to logic symbols. In this sense, this makes the mathematics communication less universal and more arbitrary.
Answer: The proper usage of a formal notation or of a more informal one depends particularly on the context of presentation. It is essential to whom we communicate an idea and this should guide us to use a suitable level of formal notation.
Here is an excerpt from P.R. Halmos' instructive paper How to write Mathematics regarding the aspect:
What about the usage of logical symbols?

P. R. Halmos: Here is a sample :
"Prove that any complex number is the product of a non-negative number and a number of modulus $1$."
...
One way to recast the sample sentence of the preceding paragraph is to establish the convention that all "individual variables" range over the set of complex numbers and then write something like
  $$\forall z\exists p\exists u [(p=|p|) \wedge (|u|=1) \wedge (z=pu)]. $$
I recommend against it. The symbolism of formal logic is indispensable in the discussion of the logic of mathematics, but used as a means of transmitting ideas from one mortal to another it becomes a cumbersome code. The author had to code his thoughts in it (I deny that anybody thinks in terms of $\exists, \forall, \wedge$, and the like), and the reader has to decode what the author wrote ; both steps are a waste of time and an obstruction to understanding. Symbolic presentation, in the sense of either the modern logician or the classical epsilontist, is something that machines can write and few but machines can read.

Hint: You might also have a look at the related question Why there is no sign of logic symbols in mathematical texts?
Comment: I can attest that, after years of training and practice, it *is* possible to learn to think directly in terms of $\exists$, $\forall$, and the like, but this is only likely to happen in a very few specialties of mathematical logic where we work with such things on a daily basis. When I teach analysis or abstract algebra, I switch back to the normal, informal treatment of quantifiers.  I think that even most people who work in formal logic would agree with Halmos. For example, in our published papers, we only use formal notation when strictly necessary, and avoid it otherwise.
Comment: @Markus Scheuer It's fine to keep the comments, thanks.
Comment: @CarlMummert: Many thanks for your contribution. Good to see, that you essentially agree based upon your personal, professional practicing and teaching experience.
Comment: *How to write Mathematics* seems to be a good reading, thanks for recommending. Also I will take a look at the another question.
Comment: About Halmos example, I must say that I think he exaggerated a little. Would be better to not consider all variables ranging over the complex and write something like $$\forall z\in\mathbb{C},\ \exists p\in\mathbb{Z}_{\geq 0},\ \exists u\in\mathbb{C},\ (|u|=1,\ z = pu)$$

This is still readable.
Comment: @diff_math: Good to see you like the reference to Halmos' paper. And regarding your last comment: I think, you see the point. While your proposal seems to be perfectly adequate for an analysis lecture, it's presumably not rigid enough for a lecture in formal logic. It's the context which matters. ($p$ should be a non-negative *real* number in your example.)
Comment: @Markus Scheuer Thank you for your response. I got a little distracted about $p$ and have no idea why I made it an integer.
Comment: @diff_math: You're welcome and don't worry. Since we could already exchange the essential information we can discard our comments if you like.
Answer: I think that, at this point, it's useful to point out what "formal logic" actually is.  Formal logic is reasoning based on the form of the statement, i.e., its syntax. For example, the statement $(X\land Y)\rightarrow X$ is true not because you know something about the individual meaning of $X$ and $Y$ but because all statements of that form are true.
In formal logic, we use a fixed syntax, to make this reasoning based on form simpler.  In particular, this syntax places quantifiers ahead of the thing being quantified over: we write "$\forall x\,\varphi$" not "$\varphi,\, \forall x$".
When writing informally (and, here, informal really means "casual", rather than "not based only on the form of the sentence"), this order is often reversed because, everyday English is more flexible than the syntax of first-order logic.


Blinking, bouncing and flashing elements

Question: I'm responsible for the UI/UX in a software development company.
During my absence, some developers decided to implement a "bounce" effect on a button of a website that they think should have more visibility.
Basically you will see this button jumping every 10 seconds, drawing your attention. The button points to the help content of the software.
I am usually against intrusive and annoying animations, but I would like to know more about this topic. I personally think that this solution is very intrusive and distracting.
How should I deal with blinking, bouncing, rotating, and zooming effects? Are there best practices?
Comment: This is a bad idea
Comment: "Users don't read instructions" - Steve Krug. I wouldn't even worry about the bouncing button pointing to the help section because the fundamental goal is already wrong.
Comment: It depends so much in the context and what you want to achieve, that it is extremely difficult to just *discuss* about it. There is no right or wrong. Maybe the question should be more specific.
Comment: Movement, rotation, and zooming might have serious accessibility ramifications for your application. Users with vertigo, for example, might not handle it so well.
Comment: You are right, it's not so easy to discuss about this topic.  I just think that before using an animation (to draw attention) the developer should think about more simple solutions (work on positionig, contrast and proportions of the elements)
Comment: JoJo, it depends on the manual.. The help section we created links to tutorials and video guides that are very handy to understand complex workflows. The help in this case is more "conceptual" then practical.
Comment: @Rdpi: If we've answered your question, you can select the best solution so that if anyone comes across the same problem in the future, they know the course of action.
Comment: Some good answers here. Just to add if you are having to draw attention to the help of your software then the software itself could probably do with some work.
Answer: In my book, all animations of control elements must be triggered only by user actions. For example, in large forms or full-screen workflows animations can be used as additional visual cues for the next step once something has been completed. If This Than That (ifttt.com) is a good example here - the page auto-scrolls to the next step when you click Next.
Random animations distract users from the current task and break their mental flow. This especially concerns elements that have no effect on the workflow of the task at hand (like the help button in your example).
Comment: I totally agree.
Comment: How exactly does my logic allow for animations on a "useless screen"? Any animation will distract the user.
Comment: Thank you for the answer. You shared some very useful thoughts.
Comment: When a software needs my attention in both MacOs and Windows the system uses animation to get my attention and Im totally fine with it. But if a web site uses animation for a large portion of a page our banner blindness kicks in and we dont look at it. If the web site is more entertainment oriented animation could enhance the experience but if the visitor needs to solve problems the site should be more subtle.
Comment: A little animation around the next button for a 'useless' screen or some unimportant step in a wizard would be acceptable following this logic.
Answer: As JoJo said in the comments, there is something fundamentally wrong if you need to draw your users attention to a button that link to the help system. The fact that you have a prominent button - not just a link - to help pages is an indication of problems in the user experience, and the fact that someone feels it needs to be more prominent - jiggling like a teenager needing Ritalin - indicates that somewhere, something is critically broken.
In terms of the wider question, yes movement is a valid attention grabber - I did implement a winking button, to draw some attention to it, in one case. However the problem of banner blindness is crucial here - most regular web users assume that a jiggling button is an advert, and so do not click on it. And the same applies to a lot of "clever" animation techniques - they may be very good and appropriate, but the user expectation is that they must be advertising something.
IMO, where a valid and appropriate link to help - or rather, further relevant information to the task at hand - needs to be highlighted, using a different colour or size, or even changing the colour briefly is probably better suited to the purpose.
Answer: I mostly agree with dnbrv, but I think perhaps there is a place for un-triggered animation if the personality of the product is "alive", or frenetic and uncontrolled. You might have a next page button in an animated children's book that looks like it's breathing or twitching if it's appropriate to the scene, for instance, or maybe on a site for a kids' game show involving a lot of frantic movement and distraction. In those cases it may not distract from the mental flow because it's actually adding to the ambient character of the product. I almost certainly wouldn't put it on a help button, though, except maybe a small, subtle twitch if there's a good reason to think the user might be stuck and there are other aspects of the interface with personality--not once every 10 seconds.
Answer: At very least make it stop bouncing around after the user has clicked on it once.  It gives users the chance to stop it if it is a distraction to them.
Although, I can't imagine anything in the help content being so important that you would need everyone to click on it.  If there is something that everyone needs to read, why not just put it right on the page?
Comment: Yes, the user should be able to stop it, or he will end up being really annoyed by this eye-catcher trick...
Answer: It all depends. I can imagine scenario in which slightly bouncing button can be appropriate.
There are three basic psychological mechanisms that can help to draw attention to a specific UI element:

sudden movement
contrast
size

We're well aware of the last two... why not to use the first one in some cases?
Which one is right for your case? This is question for both qualitative and quantitative tests. I wouldn't reject it basing just on assumptions and stereotypes.
Answer: just to complement the above answers, animated UI elements can be discreet!, I was listening Paul Boag's Podcast on how Boagworlds uses almost unperceivable CSS animations and found the Podcast quite interesting
Comment: You linked to the main page without giving any specifics about the podcast. Your post sounds spammy.
Comment: @dnbrv I guess Paul Boag has a debt with me then :P, edited! thanks for the feedback


Hybrid apps fullScreen

Question: I've fouded this plugin to get the Immersive Android view on a Hybrid app (GitHub)
But the navbar is attached into the StatusBar

i've tried with css ..
.platform-android.has-translucent-status-bar.app-header-bar{ padding-top:25px!important; }

Any suggestion?
Answer: If you want to completely hide the status bar:
$ionicPlatform.showStatusBar(false);

Make sure to inject $ionicPlatform to the service/controller. Also make sure to install the Cordova Statusbar Plugin.
ionic plugin add cordova-plugin-statusbar
If you only want to push the content down a bit, you can do this:
body {
    padding-top: 25px !important;
}

Hybrid apps fullScreen


Azure functions - When do we need to use out for output bindings?

Question: In azure functions there is multiple ways to do output bindings.

For Blob storage, I can declare it as a binding with no additional constructs.
For CosmosDb , I need to specify it as an out parameter.
For a queue ,I can specify it as  return in the attribute.

I have a sample code below for the above three scenarios
<code> public static class myblobtestfunc
    {
        [FunctionName("myblobtestfunc")]
        [return: Queue("samplequeue", Connection = "storageconnection")]
        public static string Run([BlobTrigger("functiontestblob/{name}.txt", Connection = "storageconnection")]Stream myBlob,
                               [Blob("copyblob/{name}", FileAccess.Write)]Stream copyBlob,
                               [CosmosDB(databaseName: "testfiledb", collectionName: "testfilecoll", ConnectionStringSetting = "cosmosdbconnectionstring")]out dynamic document,
                               string name,
                               ILogger log
                               )
        {
            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
            myBlob.CopyTo(copyBlob);

            document = new { Description = name, id = Guid.NewGuid() };

            return name;
        }
    }
</code>
Can output bindings use any of the three ways to do it? i.e. Can I use the return with CosmoDb binding?
Why have such a wide choice of output binding styles?
Comment: You cant use the return in a method signature anyway. This code isn't valid. As to why you can do things more than one way? well because its convenient
Comment: Thanks @TheGeneral. Makes Sense but binding expressions and the several ways of returning data while convenient, introduces an additional element to think through especially out and non out binding parameters.
Answer:
Can output bindings use any of the three ways to do it? i.e. Can I use
the return with CosmoDb binding? Why have such a wide choice of output
binding styles?

Such a wide choice of output binding styles comes from the support ticket continuously launched by the Azure function community.
In fact, for specific output binding, these three are not necessarily all feasible. Please refer to official doc. The designs of these three are based on the corresponding SDK package, so in most cases, it is equivalent to writing the code based on corresponding SDK in the function body.


Calendar Control in WPF weird behavior

Question: I am trying Bind the "DisplayDate" of the calendar to make the control notify whenever there is change in date.
Here is my xaml
<Window x:Class="CalenderControl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
            <Calendar x:Name="_calendar" DisplayMode="Year"  DisplayDate="{Binding Display}"/>
    </Grid>
</Window>

and my ViewModel
    public class ViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string PropertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
        }

        private DateTime _displayDate;

        public DateTime Display
        {
            get { return _displayDate; }
            set { _displayDate = value; OnPropertyChanged("Display"); }
        }

    }

CASE 1:
After all this.  I have assigned the datacontext with viewmodel.
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new ViewModel() { Display = DateTime.Parse("10/10/2015") };
        }

This is how it looks after binding.

CASE 2:
Then, I tried without assigning the DataContext with ViewModel.
        public MainWindow()
        {
            InitializeComponent();
            // --- Commenting out ---
            //this.DataContext = new ViewModel() { Display = DateTime.Parse("10/10/2015") };
        }

This is how it looks without binding

Why the width goes weird when I assign the DataContext?  Is there anything I'm doing wrong. .
Comment: it should be  OnPropertyChanged("Display"); not  OnPropertyChanged("DisplayDate");  in the setter.(not related to width problem)
Comment: @Nikita. . Yes. Updated now.  Thanks for that.
Answer: For an unknown reason the issue seems to be related to DisplayMode="Year"
I can suggest you to do the following steps, seems working in my test app.
1) Remove DisplayMode from your Xaml
2) After setting the DataContext, append this:
  Action act = delegate()
  {
    _calendar.SelectedDate = ((ViewModel)DataContext).Display;
    _calendar.DisplayMode = CalendarMode.Year;
    _calendar.SelectedDate = null;
  };
  Dispatcher.BeginInvoke(act, DispatcherPriority.ApplicationIdle);

Seems weird but it should work. You couldn't set SelectedDate back to null if you need it.
Added: The SelectedDate tricks seems necessary to set your Calendar Date to 2015, in your screenshot is year 1 ;-)
Comment: Hurray. .  Its working as expected. . Thanks alot.  Still it I am perplexed about the behavior.
Comment: Very very strange....but this seems to do the trick! Feel free to accept the answer if helped you.
Answer: It is not the DisplayDate binding that is causing the Calendar control to stretch; it is setting the DisplayMode to "Year". It looks like a bug in the Calendar control.

Calendar Control in WPF weird behavior


Python - How can I call methods of super class from child class instance?

Question: When child class has a method with same name with the method in parent class, the method of child class overrides the method of parent class.
In the definition of child class, it is possible to access the method of parent class by super().
Then, Does it possible to access the method of parent class from child class Instance?
class Person:
    def print(self):
        print("Message from Person")

class Student(Person):
    def print(self):
        print("Message from Student")\

s = Student()
# Method of Student Class Instance
s.print()  # Output: "Message from Student"

# I want to call method "print" of Person
# from student Instance
# How can I call it?
s.super().print()  # ERROR
super(s).print()  # ERROR

Comment: If you want both methods to be easily accesible, why override them? Just give them different names.
Comment: can you paste the error so we understand better?
Comment: @mapf Thanks for your help. I know that it could be solved easily as you said. But, I just wonder whether it is possible or not. thanks
Answer: If there is absolutely no way to access the parent class in any other way, I guess you could do this, but I would absolutely not recommend it:
class Person:
    def print(self):
        print("Message from Person")

class Student(Person):
    def print(self):
        print("Message from Student")

s = Student()
# Method of Student Class Instance
s.print()  # Output: "Message from Student"
s.__class__.__base__.print(s.__class__.__base__)  # Output: "Message from Person"

You have to understand that this is super hacky, and that you are not calling the method of an instance, as it is the case with s.print(), but you are calling the method of an uninstantiated class, a method that is not a classmethod (or staticmethod for that matter) and pass it the class as an argument (i.e. the self argument). It's very different syntax.
And again, it makes much more sense to give the methods different names instead of overriding them.


VS Team Services git Dependency Build

Question: I am new to Team Services (web based) build process. Previously I asked a different question for a solution with using TF for version control. Thanks to a great individual that problem was solved. I am now experimenting with git for version control and ran into a similar situation.
I have a Solution 1 with Project A and B where B is dependent on A (common code). Project A is under a different Solution 2 but was added to Solution 1 via "Add...Existing Project". Both solutions and projects are under different git repo. I use submodule for Project B to pull in Project A and that part works. However, Project A is pulled in under "d:\a\1\s\ProjectA" and
when the build agent attempts to build Project B, it is looking at "d:\a\1\s\ProjectB....\ProjectA\" for the dependency. How do I change this part to tell the build agent the location of Project A? Or how can I tell the submodule to pull Project A to "d:\a\1\s\ProjectB....\ProjectA\"?
Thank you!
Answer: Since you added ProjectA as submodule for the ProjectB, so you should add dependent for ProjectB by selecting ProjectA in submodule (not solution 2). So you should remove the projectA you added, and then use Add -> Existing Project -> select projectA from submodule -> OK.
Then commit/push changes to VSTS git repo. And build your ProjectB, it should find the dependent in the submodule path.
Or if you want the submodule located in root/ProjectB/.../ProjectA, in your local repo, you should go to the directory root/ProjectB/..., and use git submodule add <URL for the repo including ProjectA>. Then the submodule will located in root/ProjectB/.../ProjectA.
Comment: Thank you, thank you! I was using the 2nd route anyway. Previously I was tripped up twice by when I loaded the submodule at different folder structure (up in the root, and then 1 level above the solution file). I loaded the submodule at the Project B level at my local repo and it worked, but not before I had to manually change .gitmodules. Questions - why was the path in the .gitmodules a relative path (I had to change it to a local path to make it work), and why where there 2 entries in it? One was [Project A], the other is [Project B/ProjectA].
Comment: `.gitmodules` use the relative path so that git will find it easily which directory is submodule. Actually there is only one entry which was the path you selected for the reference you added (It seems you added the reference by selecting `ProjectB/.../ProjectA`), for `projectA/`, it just the submodule you added in projectB, the build will only find the reference you specified in `ProjectB/.../ProjectA`.

VS Team Services git Dependency Build


PayPal API does not support Items?

Question: PayPal does not support API to read/update Items? -as in the Items being sold. I see API for Payments, Vaults, sale Transactions, Orders, ...
I also checked PayPal Here SDK, I could not find one. Please let me know if I am looking at the wrong place. Where do I find the API to read Items - such as name of Item, Item Id, Item Price ...
Please refer to this image, pulled from Paypal website-
How is the list of items managed -what you see on the right is the list of items/services offered by the merchant. What you see on the left is the Transaction? My question is given the list of Items (on the right), how was it managed?
So when the merchant enters the information at the POS hardware it just remains local on the system or maybe on the cloud and PayPal does not expose API to manage/Read/GET the List? (sorry for the rhetorical question - could not frame it any other easy way)
Comment: That looks like [PayPal Here](https://www.paypal.com/us/webapps/mpp/credit-card-reader-how-to)
Comment: To my knowledge there is no API to manage those items.  It's all local to the app.
Comment: I had previously browsed through  https://github.com/PayPal-Mobile/android-here-sdk-dist/blob/master/docs/DeveloperGuide_Android.pdf. There is no reference to reference to Item List. Item only exists in the context of an Invoice, as in "Add Items to the Invoice".
Comment: OK  - so the merchant has a native application that informs the PayPalHere SDK about the Item as the invoice is being prepared. What confused me was that this example picture at a bicycle merchant had the app with a title as "PayPal" - it made me believe it is a PayPal provided app / webpage / ...  Thank you
Answer: Why would it?
Paypal is only interested in taking payment for an item.  You can send through a reference and a description, but paypal doesnt care about your items, so it doesnt provide an API.
Comment: @Abhi You're not missing something, you're assuming Paypal manages your store - which it does **not**. Paypal is a **payment** option. You send it some total you want paid. That total represents "something" - an item or set of items. Therefore _you_ have to manage your own pricing, calculations and such _before_ you send it for payment.
Comment: Without Items Management I wonder how will a merchant enter Item pricing information - another system for Pricing, also how about online store? I guess I am missing something big here!
Comment: @EdSF - thank you - please refer to the Question - I revised it.
Answer: Are you referring to the details of the item(s) on an order that was paid with PayPal?
If I understand you correctly then the GetTransactionDetails API would give you what you're after.  It returns an details for any items that were included on the original payment request.
Comment: That would be handled in whatever shopping cart system you are using.  PayPal doesn't have a way to manage items directory, however, you could use the PayPal Button Manager to create hosted buttons for individual items.  Have you looked into that?
Comment: Yes, details similar to "Payment Item Fields". Is this information available outside a transaction?  I am trying to get access to this information before transaction occurs. Without Items Management I wonder how will a merchant enter Item pricing information. I guess I am missing something big here.
Comment: thank you - please refer to the Question - I revised it. The Hosted Solution might be a way to do what I want - I need to look at it better.

PayPal API does not support Items?


Cannot convert unicode to utf-8 in python

Question: It must be a trivial task but I can't handle it.
I have json that looks like this.
        {'
          city': u'\\u0410\\u0431\\u0430\\u043a\\u0430\\u043d',
        'language':{
          u'\\u0410\\u043d\\u0433\\u043b\\u0438\\u0439\\u0441\\u043a\\u0438\\u0439': 5608,
          u'\\u0418\\u0442\\u0430\\u043b\\u044c\\u044f\\u043d\\u0441\\u043a\\u0438\\u0439': 98
        }
    },

I'm trying to convert the unicode strings into utf-8.
string=u'\u0410\u0431\u0430\u043a\u0430\u043d'
string.encode('utf-8')

I've got
'\xd0\x90\xd0\xb1\xd0\xb0\xd0\xba\xd0\xb0\xd0\xbd'

Instead of:
u'Абакан'

What am I doing wrong?
Comment: You're seeing the `repr` of the byte string, which doesn't try to show the actual characters. Try `print`ing it.
Comment: Your sample JSON is not really JSON. If those are Python values, you have double-encoded `\u` unicode escapes in those unicode strings. Is that really what you have or did you type this out by hand?
Comment: Your `string` sample value is a proper `unicode` object, which you could just directly print (`print string`), and the same applies to the encoded value (`print string.encode('utf8')`). You are getting confused by the *string representation* echoed by the Python interactive interpreter or used to show the contents of containers like a dictionary or a list. Representations are ASCII-safe debugging values.
Answer:
What am I doing wrong?

Not printing it.
When you just evaluate a string in Python REPL, you will get its repr. This is '\xd0\x90\xd0\xb1\xd0\xb0\xd0\xba\xd0\xb0\xd0\xbd'. When you print it, you will get Абакан.
print(string.encode('utf-8'))

Comment: that was... silly) Thank you. Even though, I've got another problem when I try to save the json as file I've got
`u'\\u0410\\u043d\\u0433\\u043b\\u0438\\u0439\\u0441\\u043a\\u0438\\u0439'`

How to convert it into cyrillic letters?

`with open('file_to_save.txt', 'w') as outfile:
    json.dump(json_var, outfile)'`
Comment: `u'\\u0410\\u043d\\u0433\\u043b\\u0438\\u0439\\u0441\\u043a\\u0438\\u0439'` is not valid JSON. (note the quotes.) `u'"\\u0410\\u043d\\u0433\\u043b\\u0438\\u0439\\u0441\\u043a\\u0438\\u0439"'` is valid JSON. With this latter value, `import json; print(json.loads(x))` prints `Английский`.
Answer: As @Amadan said, you just need to print your string.
But why printing string resolves the problem?
The answer is that if you type string + Enter this will lead to display the representation of repr() the of the object string; while running print string (or print (string) in Python 3.x) you will get a human readable string representation -str()- of string.
>>> converted = string.encode('utf8')
>>> converted
'\xd0\x90\xd0\xb1\xd0\xb0\xd0\xba\xd0\xb0\xd0\xbd'
>>> print converted
Абакан
>>> print repr(converted)
'\xd0\x90\xd0\xb1\xd0\xb0\xd0\xba\xd0\xb0\xd0\xbd'
>>> print str(converted)
Абакан
>>>

Further reading: Difference between __str__ and __repr__ in Python
Comment: `str` of string gives the string itself; `print(str(x))` == `print(x)`, and `print(repr(x))` is pretty much the same as `str(x)` in REPL (as `str(x)` will be again displayed using `repr`).


Mathematica Maximization, Won't maximize a * 0.3

Question: I'm Having a problem maximizing this function in mathematica:
Maximize[a + 0.3 * b, 0 < b < 10, a]

I just get the above back again as output when I run the code, Not helpfull
However when I maximize the equivalent function:
Maximize[a + (3/10) * b, 0 < b < 10, a]

I get a solution?!?
What is going on here? why does mathematica do this?
Answer: If you compare these results you see that the first one switches to use NMaximize due to 0.3 being Real, whereas the second attempts to solve symbolically using Maximise due to 3/10 being Rational.  This accounts for the different behaviour.

Map[Head, {0.3, 3/10}]

{Real, Rational}
Comment: This seams to explain the issue, but why does mathematica not try to do this on its own is beyond me. And the lack of debugging output is worrying


SOLR OR query PHP

Question: The code I currently have looks like this:
$query -> addFilterQuery(array(
    'key'=>feature,
    'query'=>'Features:1,7 Ghz',
    'tag'=>'include'
))

What I need is both the results for 1,7 Ghz and 2,0 Ghz.
Adding another filter query uses an AND operator, but what I need is an OR operator.
I've read that the setQuery() function does use an OR operator, but I cannot figure out how to work that out with multiple values.
I've been looking for this for a while, but I can't find any documentation on this.
If anything is unclear please let me know (not my native language)
Answer: Using plain Lucene syntax should work fine, depending on the escaping performed by the Solr library you're using:
'query' => 'Features:("1,7 Ghz" OR "2,0 Ghz")'

This can also be combined as multiple separate statements referring to a field:
'query' => 'Features:"1,7 Ghz" OR Features:"2,0 Ghz"'

Comment: Tried something similar before, but I guess the syntax wasn't right. This works like a charm, thanks!

SOLR OR query PHP


Telnetlib read server response without telnet commands

Question: I'm using telnetlib to connect to a remote telnet server and parse it's response, however, all telnetlib's read_* methods return its raw response - including raw telnet command bytes (starting with 0xFF) - which is undesirable for my purpose.
For example, when calling read_all:
desired output - b'Hello'
output returned by telnetlib - b'\xff\xfd\x18\xff\xfdHello'
Is there a way to make telnetlib exclude those special telnet control bytes from its output?
Answer: As far as I can tell from your question you need to convert the string into UTF-8. This may be your solution.
https://www.tutorialspoint.com/python/string_decode.htm
Comment: No, those are telnet control characters and they are not part of the server's shell response and trying to decode such byte sequences would probably result in an invalid unicode string or it would contain unwanted data.
Comment: In that case there is a question already answered about removing control characters. http://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python
Comment: Those are not ANSI escape sequences, this is **telnet** control bytes, which is something completely different.


SQL Server Questions

Question: How do I rename a database in Server Explorer on Visual Studio 2008? I changed the filename using Rename on the context menu, but that just changed the filename, not the name in SQL Server (2005 Express).
Also, is there an easy-to-use management tool like PHP MyAdmin that I can use? Or is it easier to just use VS 2008 Server Explorer?
Thanks!
Answer: Find SQL Management Studio Express 2005 for all your common tasks in dealing with the database. You'll find it more fully-featured than Visual Studio, and provides the functionality you're used to from PhpMyAdmin.
To rename your database, create a new query, either in VS or SSMS:
<code>EXEC sp_renamedb 'oldDB_Name', 'newDB_Name'
</code>
Comment: I was able to rename it through SQL Management Studio Express 2005.

SQL Server Questions


Articulate Scorm 2004 Cms compliance

Question: I wrote a JavaScript file for launching Scorm courses; it's working good for Scorm 1.2. But in the case of Scorm 2004, 'Unable to find an API adapter' alert is coming when I launch my course.
Unable to locate the LMS's API Implementation. LMSInitialize was not successful. What changes need to be done in my JavaScript file to make my LMS work properly for Scorm 2004.
Answer: Are you sure your LMS supports SCORM 2004 as well? You would see that error if you tried to deploy a 2004 course in a 1.2 environment.
Comment: Hi Mike,My LMS is not supporting Scorm 2004....its actually working for scorm 1.2 ....Will u please tell the modifications i have to do to make my LMS supporting Scorm 2004....'Unable to find an API adapter' alert is coming when i launch my course created in Scorm 2004...'Unable to locate the LMS's API Implementation.
LMSInitialize was not successful'....How can i fix this problem....
Comment: Hi Mike,Actually i wrote an javascript file for launching Scorm  courses...its working good for Scorm 1.2...But in the case of Scorm 2004 ...'Unable to find an API adapter' alert is coming when i launch my course....Unable to locate the LMS's API Implementation. LMSInitialize was not successful...What changes need to be done in my javascript file to make my LMS work properly for Scorm 2004....Its very urgent ....Please help me to fix the same....
Answer: First, your JS code should look for API_1484_11 object instead of  API object.
Second, you need to call SCORM 2004 API calls, for example Initialize, SetValue, GetValue instead of LMSInitialize, LMSSetValue, LMSGetValue.
Third, if your LMS does not support SCORM 2004, you need to upgrade your system to SCORM 2004.
Comment: Thanks ,Actually i changed my js code as u mentioned and all the data model changes mentioned in the Scorm 2004 documentation...i successfully launched some courses using Scorm 2004 package,for example course created using LECTORA....but its not working in the case of Articulate Scorm 2004...what changes must be done to make my CMS compatible with course created by Articulate using Scorm 2004...Please help me to fix it out....Regards ,Arun KG
Comment: Could you please send me your js code and the imsmanifest file? My email is: email@example.com. If your LMS recognized other SCORM 2004 courses, then the problem is either with the mainifest or the JS code.
Comment: Hi,I have mailed my JS file and manifest.Please look into it and suggest the changes needed for the code to work properly...Regards Arun KG
Comment: The manifest file and JS code are compatible with SCORM 2004. I'm afraid your LMS does not support SCORM 2004. You can do nothing about that unless you awnt to upgrade your system to a version which supports 2004.
Comment: Hi Fadel,
Thanks for helping me out.
Actually its my own LMS and there is no vendor.So when i upload a Scorm 1.2 its working properly and the code for that was created by me .So when the case of all Scorm 2004 its not working .There is addscormcourse.php file where i am doing all the things needed for scorm(xml parsing and  all).I am launching it from launchcourse.php where i include ths JS file which i mailed you earlier.If it is necessary i will mail you the the 2 files mentioned in the mail.....

Otherwise please tell me how can in upgrade my LMS to Scorm 2004...

Waiting for your reply...

Articulate Scorm 2004 Cms compliance


reshape dataframe based on string values

Question: I want to melt a dataframe into long format based on the unique values in a string variable. Some example data:
df1 <- structure(list(lllocatie = structure(c(3L, 13L, 5L, 10L, 4L, 32L, 10L, 10L, 22L, 4L, 36L, 37L, 31L, 15L, 23L, 20L, 34L, 8L, 35L, 24L, 19L, 19L, 2L, 29L, 26L, 25L, 25L, 30L, 8L, 22L, 9L, 20L, 19L, 12L, 16L, 38L, 6L, 27L, 7L, 11L, 17L, 33L, 14L, 2L, 21L, 18L, 9L, 28L, 32L, 1L), .Label = c("Annen", "Appingedam", "Assen", "Eleveld", "Emmen", "Farmsum", "Froombosch", "Garrelsweer", "Garsthuizen", "Geelbroek", "Hellum", "Hoogezand", "Hooghalen", "Huizinge", "Langelo", "Leermens", "Meedhuizen", "Onderdendam", "Oosterwijtwerd", "Overschild", "Roodeschool", "Roswinkel", "Sappemeer", "Sint Annen", "Slochteren", "Startenhuizen", "Steendam", "Stitswerd", "t-Zandt", "Ten Post", "Tjuchem", "Toornwerd", "Tripscompagnie", "Westerbroek", "Westerwijtwerd", "Winneweer", "Woudbloem", "Zandeweer"), class = "factor"), lat = c(52.992, 52.928, 52.771, 52.952, 52.965, 53.358, 52.953, 52.956, 52.831, 52.961, 53.32, 53.21, 53.294, 53.084, 53.16, 53.285, 53.177, 53.305, 53.316, 53.315, 53.333, 53.336, 53.332, 53.363, 53.368, 53.208, 53.202, 53.294, 53.306, 52.833, 53.37, 53.279, 53.323, 53.17, 53.345, 53.39, 53.316, 53.275, 53.194, 53.226, 53.294, 53.156, 53.359, 53.335, 53.423, 53.324, 53.372, 53.365, 53.351, 53.061), lon = c(6.548, 6.552, 6.914, 6.575, 6.573, 6.657, 6.572, 6.562, 7.032, 6.57, 6.74, 6.747, 6.868, 6.465, 6.805, 6.795, 6.685, 6.793, 6.65, 6.66, 6.837, 6.808, 6.848, 6.765, 6.675, 6.812, 6.82, 6.753, 6.777, 7.045, 6.72, 6.807, 6.805, 6.747, 6.808, 6.68, 6.962, 6.828, 6.798, 6.835, 6.95, 6.823, 6.682, 6.852, 6.77, 6.613, 6.743, 6.577, 6.628, 6.698), mag.cat = c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 3L, 3L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 3L, 2L, 2L, 3L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 3L, 2L, 2L, 3L, 3L), names = structure(c(3L, 4L, 9L, 2L, 2L, 11L, 2L, 8L, 10L, 2L, 21L, 29L, 1L, 19L, 1L, 24L, 28L, 1L, 1L, 1L, 23L, 23L, 1L, 27L, 12L, 1L, 15L, 17L, 16L, 10L, 1L, 24L, 1L, 1L, 20L, 14L, 1L, 25L, 1L, 1L, 1L, 1L, 18L, 1L, 22L, 7L, 13L, 26L, 6L, 5L), .Label = c("", "Amen,Assen,Deurze,Ekehaar,Eleveld,Geelbroek,Hooghalen,Marwijksoord,Vredenheim", "Amen,Assen,Deurze,Ekehaar,Eleveld,Geelbroek,Taarlo,Ubbena", "Amen,Ekehaar,Eleveld,Geelbroek,Hooghalen", "Annen,Gasteren,Nieuw Annerveen,Oud Annerveen,Schipborg,Zeegse,Zuidlaren","Bedum,Eppenhuizen,Garsthuizen,Huizinge,Kantens,Middelstum,Onderdendam,Rottum,Sint Annen,Startenhuizen,Stedum,Stitswerd,Tinallinge,Toornwerd,Uithuizen,Usquert,Warffum,Westeremden,Westerwijtwerd,Zandeweer", "Bedum,Huizinge,Kantens,Lellens,Middelstum,Onderdendam,Rottum,Sauwerd,Sint Annen,Stedum,Stitswerd,Thesinge,Tinallinge,Toornwerd,Westeremden,Westerwijtwerd,Wetsinge,Winsum", "Eleveld,Geelbroek", "Emmen", "Emmer-Compascuum,Roswinkel", "Eppenhuizen,Garsthuizen,Huizinge,Kantens,Middelstum,Oldenzijl,Onderdendam,Rottum,Startenhuizen,Stedum,Stitswerd,Toornwerd,Uithuizen,Westeremden,Westerwijtwerd,Zandeweer","Eppenhuizen,Garsthuizen,Huizinge,Kantens,Middelstum,Oldenzijl,Rottum,Startenhuizen,Toornwerd,Westeremden,Zandeweer", "Eppenhuizen,Garsthuizen,Oldenzijl,Startenhuizen,t-Zandt,Westeremden,Zeerijp,Zijldijk", "Eppenhuizen,Oldenzijl,Startenhuizen,Uithuizen,Zandeweer", "Froombosch,Hellum,Noordbroek,Sappemeer,Schildwolde,Slochteren", "Garrelsweer", "Garrelsweer,Overschild,Ten Post,Winneweer", "Huizinge,Startenhuizen", "Langelo", "Leermens,Oosterwijtwerd", "Loppersum,Winneweer", "Oosteinde,Roodeschool", "Oosterwijtwerd", "Overschild", "Steendam", "Stitswerd", "t-Zandt,Zeerijp", "Westerbroek", "Woudbloem"), class = "factor")), .Names = c("lllocatie", "lat", "lon", "mag.cat", "names"), class = "data.frame", row.names = c(NA, -50L))

The observations where the names column is empty, need to be excluded from the new dataframe. When you look for example at the first row:
lllocatie    lat   lon mag.cat                                                     names
    Assen 52.992 6.548       3 Amen,Assen,Deurze,Ekehaar,Eleveld,Geelbroek,Taarlo,Ubbena

In the reshaped dataframe this row should result in the following desired output:
lllocatie    lat   lon mag.cat     names
    Assen 52.992 6.548       3      Amen
    Assen 52.992 6.548       3     Assen
    Assen 52.992 6.548       3    Deurze
    Assen 52.992 6.548       3   Ekehaar
    Assen 52.992 6.548       3   Eleveld
    Assen 52.992 6.548       3 Geelbroek
    Assen 52.992 6.548       3    Taarlo
    Assen 52.992 6.548       3    Ubbena

The observations where the names column is empty, need to be excluded from the reshaped dataframe. Any ideas how to do this?
Comment: This is a kind of geocoded data. Your melted dataframe will have a lat, long and mag.cat for each location? for a single row, all places will have shaded coordinates. Is that what you are looking for?
Comment: @Henrik That does indeed give an answer to my question. On the other hand, the answer of jlhoward gives a nice alternative solution. As jlhoward's approach is easier to understand, I think this question & answer is a valuable addition to SO.
Answer: library(data.table)
dt <- data.table(df1)
result <- dt[,strsplit(as.character(names),",",fixed=T),
              by=list(lllocatie,lat,lon,mag.cat)]
head(result,10)
#     lllocatie    lat   lon mag.cat        V1
#  1:     Assen 52.992 6.548       3      Amen
#  2:     Assen 52.992 6.548       3     Assen
#  3:     Assen 52.992 6.548       3    Deurze
#  4:     Assen 52.992 6.548       3   Ekehaar
#  5:     Assen 52.992 6.548       3   Eleveld
#  6:     Assen 52.992 6.548       3 Geelbroek
#  7:     Assen 52.992 6.548       3    Taarlo
#  8:     Assen 52.992 6.548       3    Ubbena
#  9: Hooghalen 52.928 6.552       3      Amen
# 10: Hooghalen 52.928 6.552       3   Ekehaar

Comment: I edited my question. Hopefully it describes what I want to achieve better now.
Comment: I edited my response. Compliments to @BrodieG for making me aware of this really neat feature of data.tables.


Triggering An Event At Certain Dates Android

Question: i am currently developing an auction app. each item will have a time frame before the auction ends on that item. i was wondering if anyone can give me an idea on how to listen to each item and check if the auction time has ended on that given item.
should i use a Service and build in it a trigger every second that checks each item in the database?
thank you in advance.
Answer: What I did for a previous app to solve a similar issue was to include the date/timestamp of the end date, and then implement a handler to implement a countdown until that date/time.
    UpdateDisplay();

    handler.removeCallbacks(updateTimeTask);
    handler.postDelayed(updateTimeTask, 1000);
    }

    private Runnable updateTimeTask = new Runnable() {
    public void run() {
    UpdateDisplay();
    handler.postDelayed(this, 1000);
    Log.i(TAG, "End of updateTimeTask");
    }
    };

And inside UpdateDisplay() I kept the code for updating the UI, based on some logic subtracting the current time from the time remaining to show a second hand ticking down.
Comment: so i fetch all the items ending date into an array for example and in this handler i check every second if the current date is equal to any of the dates in the array?


Java export a folder next to jar in eclipse

Question: I want to make it so, that when I export my project, Eclipse would create .jar file as well as folders and other files I desire on the same path. I am making a game and I rely a lot on external files, be it animation images or scripts, and it is very annoying copy pasting same stuff over and over again, additionally to making the "run" option not viable.
Comment: I would suggest you drop using the Export facility of Eclipse and use a real build tool like Apache Maven or Gradle. Such tools allow easily what you're trying to do.
Answer:
You can use Eclipse File sync Plugin to solve your problem, basically
  this plugin synchronizes your eclipse workspace files to any external
  folder you configured:
FileSync plugin for Eclipse is a file synchronisation tool. The main
  goal is to keep files outside of Eclipse projects in-sync with Eclipse
  project files. The plugin works as builder in Eclipse and will
  synchronize all changes on Eclipse project files with mapped external
  folders. E.g. if a file is created, changed or deleted in Eclipse,
  then the mapped (external) file will be created, changed or deleted
  too.

http://marketplace.eclipse.org/content/filesync


Control SNES emulator from different machines

Question: Say I have 3 machines connected to the same network, M1, M2 and M3. I want to do the following:

Run a SNES emulator on M1
Setup M2 so that it can control player 1 on the emulator running on M1 via keyboard (e.g. by executing a connectToEmulator binary)
Setup M3 so that it can control player 2 on the emulator running on M1 via keyboard (e.g. by executing a connectToEmulator binary)

Something like:
    +---------------+
    |       M1      |
    |               |
    | SNES Emulator |
    +---------------+
     ^             ^
     |             |
+----------+    +----------+
|    M2    |    |    M3    |
|          |    |          |
| Player 1 |    | Player 2 |
+----------+    +----------+

Is there an easy way to accomplish this?
Comment: You should look into a network KVM like [Synergy](https://symless.com/synergy). You could bind different controls for p1 and p2 on the keyboard, and configure the remote PCs to fire those buttons on the networked system.
Comment: I think some emulators might be able to do this out-of-the-box. Which emulator are you using? Or are you open to suggestions?
Comment: I'm not using any particular emulator. Anything that runs on a raspberry pi would be fine!
Answer: Parsec seems to accomplish what you want through streaming video and allowing for control passthrough.
Parsec is typically used to stream and play a couch co-op PC game that doesn't support network play. It streams the video to anyone who connects to the computer while allowing remote computers to use their controllers and keyboards. It works with any application on your computer, including emulators.
You'll want to host Parsec on M1 and have M2 and M3 connect to it. You'll have the option to enable keyboards or controllers for each client that connects. Once you're connected, you should be able to stream your emulator from M1 and control it from M2 or M3. As a bonus, this is not restricted to just working on your local network.
Since this is streaming video over the network, it's more resource intensive than if an emulator has network play features built in, but this is a guaranteed way to have this multiplayer support on your emulator if it's missing support.


Android Facebook event request

Question: I'm building an app, which should request events from Facebook.
I get the Message:

{Response: responseCode:200, graphObject: null, error{HttpStatus:-1, errorCode:-1, errorType:null, errorMessage:com.facebook.FacebookException:Session provided to a Request in un-opened state.}, isFromCache:false}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.event, container, false);

    requestData();

    eventName = (TextView) view.findViewById(R.id.eventName);
    eventOrt = (TextView) view.findViewById(R.id.eventOrt);
    eventZeit = (TextView) view.findViewById(R.id.eventZeit);
    eventBeschreibung = (TextView) view.findViewById(R.id.eventBeschreibung);

    return view;

}

private void requestData(){

    Request request = new Request(
            Session.getActiveSession(),
            "/0keepyourself/events",
            null,
            HttpMethod.GET,
            new Request.Callback() {

                @Override
                public void onCompleted(Response response) {
                    // TODO Auto-generated method stub
                    Object obj = response;
                    Toast toast = Toast.makeText(getActivity(), (CharSequence) response.toString(), Toast.LENGTH_LONG);
                    toast.show();
                }
            });
    request.executeAsync();
    String test = (String) request.getParameters().get("name");
    Toast.makeText(getActivity(), test, Toast.LENGTH_LONG).show();

}

Comment: Have you seen my answer ?
Comment: Yeah sorry, Thank you it works :)
Answer:
Session provided to a Request in un-opened state

You need to call openForRead() first, check if the state of the access token is OPENED and then call request.executeAsync().

Android Facebook event request


How to avoid radio button deselected automatically.

Question: There are two radio button. when select any radio button its automatically deselected.
Following are the snippet which is not working properly.

$('.radio_pmt').click(function(){
alert('click');
var payment_mode =$(this).attr('ownid');

 var type = typeof payment_mode;
 if(payment_mode == 'undefined' | payment_mode == null){
  alert("Please select payment method");
 }
 else
 {
  if(payment_mode == "paypal")
  {
   $('input:radio[name="payment_mode"][ownid="paypal"]').attr('checked', true);
   $('input:radio[name="payment_mode"][ownid="paypal"]').val('paypal');
   $("#paypal_form").submit();
  }
  else
  {
   $('input:radio[name="payment_mode"][ownid="braintree"]').val('braintree');
   $('input:radio[name="payment_mode"][ownid="braintree"]').attr('checked');
   $("#braintree_details").slideDown("slow");

  }
 }
 return false;
});

<form method="post" id="frm_choose_plan" name="frm_choose_plan">
Choose Payment method:
<input type="radio" class="radio_pmt" ownid="paypal" name="payment_mode" value="Paypal">Paypal
<input type="radio" class="radio_pmt" ownid="braintree"  name="payment_mode" value="braintree" id="credit_cardpmt">Credit card
</form>
Comment: remove the `return false;` line. also when using radio button it is better to use change event
Comment: @guradio : You are right...
Comment: @guradio : add your suggestion in answer so you will get credit for this solution..
Comment: @guradio - I would never use the change event on radios. It may trigger on off change too and in some browsers on blur only. We only want to capture the click event
Comment: @DiniZx i wll put it in answer mate
Answer: Your main problem was the "return false" which prevents the default event.
My Suggestion

$('.radio_pmt').click(function(){
  var $input = $(this);
  var inputType = $input.attr('ownid');

  if (inputType === 'paypal') {
     // do something if user clicked on paypal

     // your code
     $("#paypal_form").submit();

     $('#test').html('clicked paypal'); // remove this on live page
  }
  else if (inputType === 'braintree') {
     // do something if user clicked on baintree
     $("#braintree_details").slideDown("slow");

     $('#test').html('clicked Credit Card'); // remove this on live page
  }
  else {
    // nothing choosed! But i cant be reached because you choose the ".radio_pmt" selector to bind your click event which has both the "ownid"
  }
});

<form method="post" id="frm_choose_plan" name="frm_choose_plan">
Choose Payment method:
<input type="radio" class="radio_pmt" ownid="paypal" name="payment_mode" value="Paypal">Paypal
<input type="radio" class="radio_pmt" ownid="braintree"  name="payment_mode" value="braintree" id="credit_cardpmt">Credit card
</form>

Answer: Remove the return false; line and your code will work. It is deselecting because you are preventing the default action of radio button
Comment: Ah, converting the comment to answer. I see it now
Answer: Just remove return false; which blocks the selection

$('.radio_pmt').click(function(){
alert('click');
var payment_mode =$(this).attr('ownid');

 var type = typeof payment_mode;
 if(payment_mode == 'undefined' | payment_mode == null){
  alert("Please select payment method");
 }
 else
 {
  if(payment_mode == "paypal")
  {
   $('input:radio[name="payment_mode"][ownid="paypal"]').attr('checked', true);
   $('input:radio[name="payment_mode"][ownid="paypal"]').val('paypal');
   $("#paypal_form").submit();
  }
  else
  {
   $('input:radio[name="payment_mode"][ownid="braintree"]').val('braintree');
   $('input:radio[name="payment_mode"][ownid="braintree"]').attr('checked');
   $("#braintree_details").slideDown("slow");

  }
 }
});

<form method="post" id="frm_choose_plan" name="frm_choose_plan">
Choose Payment method:
<input type="radio" class="radio_pmt" ownid="paypal" name="payment_mode" value="Paypal">Paypal
<input type="radio" class="radio_pmt" ownid="braintree"  name="payment_mode" value="braintree" id="credit_cardpmt">Credit card
</form>


How do I add QtDeclarative to the pkg-config list

Question: I installed today the libqt5 and QtQuick development stacks.  In trying to also install the hsqml packages for Haskell, hsqml reports that QtDeclarative is not listed in pkg-config.  However, I have installed libqt5declarative5 and found both an i386 and x86_64 version of libQtDeclarative.so.4.8.1 on my filesystem.
So, how do I get pkg-config to add those files to the listing so that other applications can find them?
Answer: After more research, it would appear that the difference is that I have installed QT 5 in order to do development, and QtDeclarative has been subsumed into other components for QT 5.  The HsQML library is apparently designed for older versions of QT.  So the answer is that I should not be adding QtDeclarative to pkg-config at all, but should instead be looking to port HsQML to QT 5.