text:
Q: Why is this code concatenating the empty string and an integer? What does this snippet of code mean?
int value;
if (value > 0)
 String input = "" + value;

A: String input = "" + value; value is an integer type. adding it to empty string-"" just making it a  string. Suppose value = 3, then ""+value will be "3"
Edit: Forgot to mention about String.valueOf(val) function, another static utility method to convert almost all primitive type to String.

A: It is converting value to a string.  "" + value is very similar to value.toString().  The "" means the compiler is looking for a string after the +, so when it sees value in that space, it automatically calls value.toString() to produce the string result.

A: Compiler know how to add an integer with some string value. So in the code rather calling directly the integer to string conversion method. The coder generates an constant string ""(having no value in it) and then call concatenation operator(+) overloaded method to add and cast the integer into string value.


text:
Q: PHP Parse error: syntax error, I keep getting the following error when building an array:
PHP Parse error:  syntax error, unexpected ';', expecting ')'

for the following code:
$fetchResult=$PubMedClient->run_eFetch(array(
'db'=>'pubmed',
'id'=>(count($searchResult->IdList->Id)>1 ? join(",",$searchResult->IdList->Id) : $searchResult->IdList->Id)));

I've tried to break this up in many ways, but it does not work. As usual, I'm sure it is something simple that I'm just not seeing.
Anyone have an idea?
Many thanks

A: It would be slightly easier to read if you broke out the ternary operation into a variable like so:
$getID = count($searchResult->IdList->Id) > 1 ? join(",", $searchResult->IdList->Id) : $searchResult->IdList->Id;

$fetchResult = $PubMedClient->run_eFetch(
    array(
        'db'=>'pubmed',
        'id'=> $getID
    )
);

The above should work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to publish binaries and copy to server in TFS 2017 We were using xaml builds earlier now we migrated to TFS2017. I am not able to publish the build files and how can we copy them.
My Build runs file it does not publish files. I see only the code files.

A: You need to add Copy Files task and Publish Build Artifacts task in your build definition, to copy and publish files:

A: Maybe you may create the publish profile for you web project and use it in build process. I use this way for the web site project:

*

*Create the publish profile for project to package: https://msdn.microsoft.com/en-us/library/dd465323(v=vs.110).aspx

*Add publish args for the build step. In my case:

/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactstagingdirectory)\Test" /p:PublishProfile="shdemowebtest - Web Deploy"

*Then copy drop artifact

In your case you may create profile to publish on the file system. Then add build args to publish and redirect the destination folder: MsBuild publish website without using publish profile
Steps for publish to local folder (on VSTS and local build agent):

*

*Add new profile to your project (destination bin\release\PublishOutput):

*I use first build step to build additional project with tests.

*Add step to publish with default folder path.
MS Build Args:

/p:DeployOnBuild=true  /p:PublishProfile="FolderProfile"

3.1. Then I use standard step to copy results to staged directory:

 3.2. And publish to drop artifact:

 3.3. Then you can use that artifact to deploy with release management:

*Add step to publish to custom path:
MS Build Args:

/p:DeployOnBuild=true  /p:PublishProfile="FolderProfile" /p:publishUrl="C:\temp\Output"

4.1. The result of this step:


text:
Q: Change Parameter Value with a Filter I got the task to build a report, that shows the information of three different months on one page. The current month, current -1 and current -2.
The challenge is, that i have @month already in my Dataset1. This cannot be changed.
I have another Dataset for the month-parameter:
WITH Kalender
AS (SELECT DateAdd(m,-2,DateAdd(d,1-DAY(DateAdd(d,-1,Convert(date,GETDATE()))),DateAdd(d,-1,Convert(date,GETDATE())))) AS [Datum]
    UNION ALL
    SELECT DATEADD(m, 1, [Datum])
    FROM Kalender
    WHERE DATEADD(m, 1, [Datum] ) <= DateAdd(d,-1,Convert(date,GETDATE()))
   )

Select Monat = convert(varchar(4),Year([Datum])) + right('00' + convert(varchar(2),Month([Datum])),2)
FROM Kalender
ORDER BY Monat desc

The month format should look like this: 202102 - that's how the date is converted in the query of Dataset1.
I wanted to create three different tablix, one for each month. Is there any possible way, to set a filter on each tablix that changes the month-parameter value?
Thanks in advance.


text:
Q: Why doesn't this xargs command work? I wanted to delete all .sh extensions so did this:
ls *.sh | xargs -I {} mv {} `basename {} .sh`

However it doesn't work, it behaves like basename returns unchanged file name.
Why is it behaving that way ?
For instance, this works:
ls *.sh | xargs -I {} echo `basename {}.jpg .jpg`;

EDIT:
Solution: single quote prevents `basename ...` evaluation by the shell before the command is run.
ls *.sh | xargs -I {}  sh -c 'mv {} `basename {} .sh`'

A: I'm unsure about your question, are you actually asking why your first line doesn't work?  Or are you looking for a proper method to rename all the .sh files?
Assuming it's the cleanest method, I prefer to prepare command options before xargs.
For removing a .sh file extension, I often consider this approach,
 find -maxdepth 1 -type f -iname '*.sh'  | sed 'p;s_.sh$__' | xargs -L2 mv

A: Because the basename command is run before the pipeline is run. To make this work you need xargs to execute basename and you can do that with sh -c, e.g.:
ls *.sh | xargs -L1 sh -c 'basename $1 .sh' dummy

Notes:

*

*If you don't tell xargs where to insert the file names they will be added at the end of the command line.

*You should use the -L1 switch or its equivalent, so xargs only passes one argument to sh.

*Using the output of ls may have unwanted effects.

Edit
Removed deprecated options, thanks TechZilla


text:
Q: Magnific Popup - Index error I can't get my Magnific Popup working with index option. My goal is to make the gallery open on index of clicked image. In my HTML I have this for each image:

then my JS looks like this:
$(function(){
  $('.open_gallery_index').click(function(){
    var i = Number($(this).data("id"));
    $.magnificPopup.open({
      items: g_items,
      gallery: {
        enabled: true
      },
      type: 'image'
    },i);
  });
})

But when clicking the image I get an error

Uncaught TypeError: Cannot read property 'parsed' of undefined

Though if I set the variable i manually to let's say 5, everything works fine, so the problem must be in this
var i = Number($(this).data("id"));

but I have tried everything with no success, thanks for any help.

A: Update your data-id attribute like this.

A: I think $.magnificPopup.open requires an src property. Not really sure what g_items is in your code, but try something like this:
$.magnificPopup.open({
  items: {
    src: '.open_gallery_index',
    type: 'image'
  }
  gallery: {
    enabled: true
  },
},i);

A: $.magnificPopup.open({
  items: g_items,
  gallery: {
    enabled: true
  },
  type: 'image'
},i);
i--;
i++;

it worked with me this way and I don't know why


text:
Q: How to execute "reformat code" of PyCharm via command line (no GUI)? Is there a way to script PyCharm to do reformat code without a GUI?
I have a lot of legacy python code, and I would like to clean it automatically.

A: You can run format.bat or format.sh from the IDE installation directory. See the documentation for more details on supported options.


text:
Q: FullCalendar.js: Event callbacks not firing for added events that get resized/clicked/dropped? After adding an event and then changing it again, nothing happens, // * no callback. I even used fullCalendar('refetchEvents') still no luck. Am I missing something? Here is the code:
$('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'agendaWeek'
        },
        defaultDate: '2015-04-20',
        editable: false,
        eventLimit: true,
        firstDay: 1,
        defaultView: 'agendaWeek',
        timeFormat: 'HH:mm',
        lang: 'de',
        columnFormat: 'dddd D.M.',
        allDaySlot: false,
        slotDuration: '00:30:00', // default is 30 min
        minTime: '12:00:00',
        // maxTime: '23:00:00',
        contentHeight: 600,
        events: [
            {
                title: '',
                start: '2014-09-01T18:00:00',
                end: '2014-09-01T20:00:00',
                dow: [1], // repeat same weekday
                rendering: 'background',
                color: '#6BA5C2'
            },
            {
                title: '',
                start: '2014-09-02T20:00:00',
                end: '2014-09-02T22:00:00',
                dow: [2], // repeat same weekday
                rendering: 'background',
                color: '#6BA5C2'
            },
            {
                title: 'Event',
                start: '2015-04-24 13:00:00',
                end: '2015-04-24 14:00:00',
                color: '#F77'
            },
        ],
        // * no callback
        viewDisplay: function (element) {
            alert(element);
        },

        // adding an event
        selectable: true,
        selectHelper: true,
        select: function(start, end) {
            var title = prompt('Deine E-Mail:');
            var eventData;
            if(title) {
                eventData = {
                    title: title,
                    start: start,
                    end: end,
                    color: '#00AA00',
                    editable: true,
                    eventDurationEditable: true,
                    // * no callback
                    eventResizeStop: function(event, jsEvent, ui, view) {
                        alert('end');
                    },
                    // * no callback
                    eventClick: function(calEvent, jsEvent, view) {
                        alert('clicked');
                    },
                    // * no callback
                    eventDrop: function(event, delta, revertFunc, jsEvent, ui, view) {
                        alert('dropped');
                    },
                    // * no callback
                    eventResize: function(event, delta, revertFunc, jsEvent, ui, view) {
                        alert(event.title + ' end is now ' + event.end.format());
                    },
                };
                $('#calendar').fullCalendar('renderEvent', eventData, true); // stick = true
                $('#calendar').fullCalendar('refetchEvents');
                // not helping either
                $('#calendar').fullCalendar('rerenderEvents');
            }
            $('#calendar').fullCalendar('unselect');
        },

    });

Visible proof:

A: Those callbacks are not properties of the events. They are top level fullcalendar options. Each section of the docs represents one FC top level option. Some options can also be specific to certain events, but they are mentioned as such in the docs. If you look at event object you see that there is no eventResize property, for example.
So the fix is to just move the callbacks to the top level:
$('#calendar').fullCalendar({
    /*...other options*/
    eventResizeStop: function (event, jsEvent, ui, view) {
        alert('end');
    },
    // * no callback
    eventClick: function (calEvent, jsEvent, view) {
        alert('clicked');
    },
    // * no callback
    eventDrop: function (event, delta, revertFunc, jsEvent, ui, view) {
        alert('dropped');
    },
    // * no callback
    eventResize: function (event, delta, revertFunc, jsEvent, ui, view) {
        alert(event.title + ' end is now ' + event.end.format());
    },
    events: [{
        title: '',
    /*... etc*/

Here's a JSFiddle with it working.


text:
Q: Clarification on Measure Theory My text book says that the Lebesgue measure on Borel $\sigma$-algebra of $\mathbb{R}$ is not complete . I am looking for such a Borel set which has measure $0$ but its subset is not a Borel set. Such set must exist or else it will be a complete measure space. Correct me if I am wrong.

A: Yes, indeed, such sets will exist. You don't even need measure theory to show this!

*

*It's not too hard to show (caveat: you do need a small amount of the axiom of choice here, namely that the union of countably many countable sets is countable; surprisingly, this is not provable in ZF alone) that there are continuum-many Borel sets of reals, while there are $2^{2^{\aleph_0}}$-many subsets of any set of reals of size continuum. Combining these facts, a counting argument shows that there must be some non-Borel subset of the Cantor set, which is Borel (indeed, closed) and has measure zero.

*This doesn't produce a specific example, unfortunately. Explicit examples are possible, but they're somewhat harder to describe. My personal favorite is as follows. There is a natural way to represent an element of the Cantor set as an infinite sequence of 0s and 1s (via ternary expansion), and there is a natural way to represent a binary relation $R$ on $\mathbb{N}$ as an infinite sequence of 0s and 1s (a 1 in the $2^m3^n$th bit exactly when $R(m, n)$ holds, and zeroes elsewhere). Thus, letting $W$ be the set of points in the Cantor set which are the codes of well-ordered relations on $\mathbb{N}$, we get a reasonably definable set of reals. Perhaps surprisingly, this set is not Borel!


text:
Q: Cannot access to the Grub menu and cannot connect as "root" Being a total newbie in this domain, I've recently tried to install Ubuntu on my Chromebook using this guide: https://itsfoss.com/install-linux-chromebook/ and it works, at first.
I was able to login on Ubuntu and navigate a little before closing my session but when I came back, I wasn't able to connect via crosh ("sudo startxfce4" not working) or via the "Ctrl+Alt+Shift+Forward" terminal (this one was asking a login and a password I don't know.)
I tried connecting as "root" but it doesn't seem to work and it always tells me that my login is incorrect.
I've been looking everywhere on the Internet and the Grub menu doesn't appear wherever I hold shift or esc when starting the chromebook so I'm really lost.


text:
Q: ActionBarSherlock Missing libary.jar I was trying to add the actionbarsherlock libary moet I'm getting the following error:
The project cannot be built until build path errors are resolved            Unknown Java Problem

When I look into the tab 'Builth path' I see libary.jar is missing. But there isn´t a file called libary.jar?
I've already set the compiler to Java 1.6, but it's still not working. The target SDK of both projects is Android 4.0
I hope anyone can help!

A: I tried to switch to Java 1.7 and let Android fix my project properties. (I got a message). After that, it worked for me!


text:
Q: Why is fs.readFile triggering "Error: EMFILE: too many open files" and how can I fix it? I've been using this load method on a file manager class:
const fs = require('fs')
const path = require('path');
const isJson = require.main.require('../js/funcs/is-json.js');
let fileCount = 0;
module.exports = class {
  constructor() {
    this.cache = {};
  }
  // .. snip ..
  load(pathName, raw = false, cache = false) {
    if (!raw) pathName = "." + pathName + ".js";
    return new Promise((resolve, reject) => {
      if (cache && this.cache[pathName]) {
        //console.log("returned memory cached file", pathName);
        resolve(this.cache[pathName]);
      } else {
        fileCount++;
        fs.readFile(pathName, (err, data) => {
          console.log("files read", fileCount);
          if (err) {
            throw err;
          } else {
            //console.log("loaded file", pathName)
            if (isJson(data)) {
              let parsed = JSON.parse(data);
              if (cache) this.cache[pathName] = parsed;
              resolve(parsed);
            } else {
              //console.log("ignored bad JSON", data);
              resolve(false);
            }
          }
        });
      }
    });
  }
  // ... snip ...
}

And now I'm getting the error:
files read 8774
C:\Users\jonat\.. proj path ..\js\classes\storage.js:55
            throw err;
            ^

[Error: EMFILE: too many open files, open 'C:\Users\jonat\.. proj path ..\cache\v1\markets\myfilename1.json'] {
  errno: -4066,
  code: 'EMFILE',
  syscall: 'open',
  path: 'C:\\Users\\jonat\\.. proj path ..\\cache\\v1\\markets\\myfilename1.json'
}

And as you can see in the logs and code, I added a fileCounter variable to iterate on each fs.readFile call and see if I'm opening some massively high number of files, but the count appears to be at just 5 (Edit: 8774 once I moved the iterator to before the file is actually read) when the error gets logged. Also, I thought fs.readFile would close the files when done reading, so I shouldn't have a large number of files opened at once. What's going on here and how can I better debug / fix this?
Edit: see changes to iterator count.

A: I know just-library solutions are usually frowned upon here, but hostly, the graceful-fs node.js module was the perfect fix here. https://github.com/isaacs/node-graceful-fs
Just installed it and replaced
const fs = require('fs')

with
const fs = require('graceful-fs')

And my code magically worked again


text:
Q: Member function of a templated class can't return a pointer to member structure? This code doesn't compile (gives errors C2059, C2065, C2072, C2143, C2146, C2447, C2470, C4430)
But does if you change B* to an inbuild type like int.
Any ideas?
template <typename T>
class A
{
private:
    struct B
    {
        T key;
    };

    B* foobar(T key);

};

template <typename T>
B* A<T>::foobar(T key)
{
    B* ptr = new B;
    B->key = key;
    return ptr;
}

int main()
{}

A: You have a few errors in your method.
1) the return type's scope must be properly qualified.
2) You have to set the key if a A::<T>::B instance, not a B.
Try this:
template <typename T>
typename A<T>::B* A<T>::foobar(T key) // fix error 1)
{
    B* ptr = new B();
    ptr->key = key;  // fix error 2)
    return ptr;
}

A: The return type should be typename A<T>::B*, not just B*:
template<typename T>
typename A<T>::B* A<T>::foobar(T key)
{
   //..
}

Note also typename keyword in the return type.


text:
Q: Why does pip install winshell not work on Python v3.4.2? Install winshell with pip:
C:\Users\jonc>pip install winshell
Downloading/unpacking winshell
  Downloading winshell-0.6.zip
  Running setup.py (path:C:\Users\jonc\AppData\Local\Temp\pip_build_Jonc\winshell\setup.py) egg_info for package winshell

Installing collected packages: winshell
  Running setup.py install for winshell

Successfully installed winshell
Cleaning up...

Try and import it:
C:\Users\jonc>python
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import winshell
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python34\lib\site-packages\winshell.py", line 30, in <module>
    import win32con
ImportError: No module named 'win32con'

Why does this fail?
Pip version is as follows:
C:\Users\jonc>pip -V
pip 1.5.6 from C:\Python34\lib\site-packages (python 3.4)

A: you will need to install pywin32 to get the missing file.
it must be installed separately (i.e. it cannot be installed with pip).  for more information see this post.


text:
Q: Mac Os X 10.10 Yosemite disable usb ports I am struggling to disable USB ports on macs with the new Yosemite
My original intention was to give read only access to USB drives but it seems impossible, so I decided to go for the complete removal of the USB access
I followed the instructions on the osX manual but won't work
I tried this, posted here in the forum: link but it won't work
What I get now is this error link

(kernel) Can't remove kext com.apple.iokit.IOUSBMassStorageClass; services failed to terminate - 0xdc008018.
Failed to unload com.apple.iokit.IOUSBMassStorageClass - (libkern/kext) kext is in use or retained (cannot unload).

It may be because I removed the file from the extensions folder first, but if that was the case, why usb is still working?
Hope you can help somehow.
Cheers

A: Unload it first with
kextunload /System/Library/Extensions/IOUSBMassStorageClass.kext/
However having said that removing and even deleting this kext in Yosemite doesn't seem to prevent USB working again on reboot. In fact you now lose the ability to unload the kernel extension once loaded.

A: I'd like to improve the previous answer but I cannot comment on it, so I will add it here.
I am having the same problem and to solve it I confirm that you should unload the driver with
kextunload /System/Library/Extensions/IOUSBMassStorageClass.kext/

In order to keep this setting at reboot, I added a call to the root crontab (since this won't be modified by updates nor other users)
to become root
sudo su -

modify root crontab
crontab -e

add the line to the file and close it
@reboot kextunload /System/Library/Extensions/IOUSBMassStorageClass.kext/

I hope this helps

A: You need to unload the AppleUSBCardReader and AppleUSBODD drivers as they load IOUSBMassStorageClass. Run the following commands in the terminal:
sudo kextunload -b com.apple.driver.AppleUSBCardReader

sudo kextunload -b com.apple.driver.AppleUSBODD

sudo kextunload -b com.apple.iokit.IOUSBMassStorageClass


text:
Q: Set front-facing camera in iPhone SDK I would like to have my app open the camera (presently UIImagePickerController ) front-facing if available.  (Iphone SDK).
How can I do that?

A: Try this method of UIImagePickerController:
 + (BOOL)isCameraDeviceAvailable:(UIImagePickerControllerCameraDevice)cameraDevice

This is a class method and UIImagePickerControllerCameraDevice can take two values:
  - UIImagePickerControllerCameraDeviceRear
  - UIImagePickerControllerCameraDeviceFront
  Example code:

        if([UIImagePickerController isCameraDeviceAvailable: UIImagePickerControllerCameraDeviceFront ])
        {
        // do something
        }

A: It's right there in the documentation:
picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;

Of course, you'll need to check first if the front camera is actually available. It's also only available starting with iOS 4.0.


text:
Q: How to handle when user return back to app without login from google using Google iOS sdk? I am using Google-iOS SDK for login.How to know when user tries to authenticate to the google, but changes mind and without login returns back to app. Is there any method which gets invoked on this event on google ios sdk?
For facebook there is :
[FBAppCall handleDidBecomeActive];

which is called from applicationDidBecomeActive method of app delegate.
With Facebook-SDK if user returns to the app without signing in, the session gets closed.
Method named:
sessionStateChanged: state: error:

get called.
Is there anything like this in Google-SDK for iOS?


text:
Q: jQuery: Optional datepicker-field? i have a field like this:
<input name=devtime class=devtime>

and jQuery like this:
<script>$(".devtime").datepicker();</script>

If a user click inside the field (or it gets the focus) the datepicker appears.
How can i change the code so the users also can enter normal text and not just digits and numbers?
I'm looking for a common text field with "a datepicker option".
Thanks!

A: Datepicker has the constrainInput option:
http://api.jqueryui.com/datepicker/#option-constrainInput
This is true by default but if false you can put what you want in input.

A: You can use bootstrap date picker for the same when you click on icon date picker will appear else you can text in the text box.
Reference Link
Note :- This is not advisable to use like this but this can be fulfil your requirement.

A: you can change your markup with the below code
<input type="text" class="devtime">


text:
Q: Convex hull of sets in Minimax theorem Suppose $X\subseteq\mathbb{R}^n$ is a convex and compact set, and $Y\subseteq\mathbb{R}^m$ is a nonconvex bounded set. Consider
$$
\min_{x\in X}\max_{y\in Y}x^TAy.
$$
Is this equivalent to
$$
\min_{x\in X}\max_{y\in conv(Y)}x^TAy,
$$
where $conv$ is the convex hull? It seems to make sense, since for any fixed $x$, the objective is linear in $y$.
Then, suppose $X$ is a standard simplex, and $Y$ is a set of all $m$ dimensional elementary vectors (zero vector except for one being 1). Does it mean that optimal $y^*$ is also an elementary vector, i.e., pure strategy?

A: Yes, the maximum of a linear map over any set is equal to the maximum over the convex hull of the set.


text:
Q: How do I generate reports in Jenkins if my shell script fails? Is there a plug in? I have a jenkins job that will do a deployment in my CentOS machine by running the docker-compose file. This is how my shell script looks ?
    #!/bin/sh

# Post steps for deployment

# Navigate to deployment scripts
cd /deployment/scripts/v1.0.784

#Execute the uninstall script
./dit_undeploy_all.sh

set +e
#Remove all docker images and containers
docker container rm $(docker ps -a -q) -f
docker rmi $(docker images -a -q)
docker volume rm $(docker volume ls -q)
set -e

#Remove and clear out the folder structure
rm -rf *.*

#Gets all the latest files from Artifactory by reading from teh input file
wget -B https://artifactory.gue.com -i /deployment/scripts/inputFile.txt

# Gives rea/write access
chmod +x *.*

# Execute docker compose file to get all the latest containers
./dit_deploy_all.sh

#Add wait time for the services to be up and running
sleep 60s #Wait 15 sec

# Need to update the URL
./dit_create_policies.sh

#Verify URL Status Code of 200
cd /deployment/scripts

sleep 60s #Wait time 60s
./verifyHttpCode

The script ./verifyHttpCode does the following:
    #!/bin/bash
while read LINE; do
        curl -o /dev/null --silent --head --write-out '%{http_code}' "$LINE"
        echo " $LINE"
        done < url-list.txt

So basically after the deployment it will verify the http status code...What's the equivalent of testNG in shell script that I can use in Jenkins to verify the http status code and generate reports ??

A: Have you tried this plugin : Audit2DB
https://wiki.jenkins.io/display/JENKINS/Audit+To+Database+Plugin
It will log all required job details into a DB. When you want to create a report, it will fetch it from DB.
So in this case, you'll need to fail the job (non-zero exit) on script failure. Also you can set $http_code as env variable on completion of your job and log the same into DB.


text:
Q: Indicating Required Fields in PHP I'm trying to create a PHP file of a process form that indicates the required fields when processed. The code that I have is:

    <?php
    if(isset($_POST['fullname']) && $_POST['fullname'] != "") {
        $fullname = $_POST['fullname'];
    }
    if(isset($_POST['email']) && $_POST['email'] != "") {
        $email = $_POST['email'];
    }
    if(isset($_POST['feedback']) && $_POST['feedback'] != "") {
        $text= $_POST['feedback'];
    }

    $nameErr = $emailErr = "";
    $name = $email = "";

    if ($_SERVER["REQUEST_METHOD"] == POST) {
        if (empty($_POST["fullname"])){
            $nameErr = "Name is required";
        } else {
            $name = test_input($_POST["fullname"]);
        }
        if (empty($_POST["email"])) {
            $emailErr = "Email is required";
        } else {
            $email = test_input($_POST["email"]);
        }
    }
    ?>

Customer Feedback

        <p1>Please tell us what you think</p1>

        <form method='POST' action='<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>' >
            <p1>Your name:</p1>

            <input type="text" name="fullname" value="<?php echo $fullname; ?>">

            <p1>Your email address:</p1>

            <input type="text" name="email" value="<?php echo $email; ?>">

            <p1>Your feedback:</p1>

            <textarea rows="5"  cols="50" name="feedback"><?php echo $text;?></textarea>

            <input type="submit" Value="Send Feedback">

            <?php
                error_reporting(E_ALL);

                $name = $_POST['fullname'];
                $email = $_POST['email'];
                $feed = $_POST['feedback'];

                if (empty($name))
                {
                    echo "Please enter your name, email and feedback.";
                }
                if (empty($email))
                {
                    echo "Please enter your email and feedback.";
                }
                if (empty($feed))
                {
                    echo "Please enter feedback.";
                }
                if (!empty($name) && !empty($email) && !empty($feed))
                {
                    echo "You have inserted the correct data";
                }
            ?>
        </form>

However, when I run it on Chrome, I got a server error 500 saying that

The website encountered and error while retrieving process_4.php. It maybe down for maintenance or configured incorrectly.

The other PHP files that I've made leading up to this point have all worked correctly and I don't know why this one isn't.


text:
Q: How to give Ubuntu 14.04 more disk space My original OS was / is W7 and whenever I installed Ubuntu 14.04 LTS it gave me 17GB of space but now I want to expand it for certain applications.

I kinda am new to the whole disk and partitioning thing so GOOD help would be appreciated.
I also installed Ubuntu alongside W7.

A: To give more space to Ubuntu, you'll need to do a few things:

*

*Shrink /dev/sda2

*Resize the extended partition (/dev/sda3) to include the space freed up by the previous step.

*Decide whether the space is for system applications (those installed by apt-get, Software Centre, etc.) or user applications (those installed by you from source, precompiled binaries, etc.

*If the former, resize root (/dev/sda5); if the latter, make a partition in the free space and mount it somewhere convenient. I'll cover the former for now, and the latter if anybody requests it.

To accomplish the first step, you have two options:

*

*Shrink using GParted or

*Shrink using the Disk Management section in Windows' Computer Management.

With GParted, you can shrink to free up as much space as available, but the operation will be slow. With Windows, shrinking will be very fast, but you may not be able to free up as much space as is shown to be unused. This is because the Windows utility only shrinks upto the last used sector, whereas GParted moves around files. I recommend that you see how much Windows is willing to free up, and if it is satisfactory, use it, or else use GParted. And if you do choose to use GParted, use a live CD/USB to do so. I'll assume a live environment for any Linux operations henceforth.

*

*To shrink in Windows, right click My Computer and select Manage. Go to the Disk Management section, select the C: partition, right click it and choose Shrink Volume:

*To do so in GParted: Unmount the partition first if it is mounted (the key icon shows it is mounted) by right clicking /dev/sda2 and selecting Unmount. Choose Resize/Move, and drag the right end of the slider (or enter in values manually) until enough free space is shown at the end of the partition.

*Right click the root partition and select Information. You'll get a window that looks like this:

Copy the UUID to somewhere (open a file in gedit and paste it there, if you will).

*Repeat the above step with the extended partition and the root partition, but this time dragging the slider to fill up the free space at the beginning.

*Click on the green tick to apply.

Once the operations have finished, you'll probably have to change the UUID values of the partitions (as used in /etc/fstab, GRUB, etc.).  For this, we will set up a chroot. But first, repeat step 2 to get the new UUID of the root partition. If they are the same, no worries, skip the next section. You are done. If not:
Now open a terminal and do the following steps:
sudo mount /dev/sda5 /mnt
sudo mount -o bind /dev /mnt/dev
sudo mount -t devpts none /mnt/dev/pts
sudo mount -t proc none /mnt/proc
sudo mount -t sysfs none /mnt/sysfs

sudo chroot /mnt /bin/bash -l

Now, you will be inside a chroot environment in your installed Ubuntu, as opposed to the live Ubuntu used to get there. We must replace the UUID value for root in /etc/fstab, so use your choice of editor to open it and change the value to the one you copied a few steps ago (if you aren't familiar with vi, use nano):
vi /etc/fstab

(You are root within the chroot, so you don't need sudo.)
Or use the sed command:
sed -i 's/OLD_UUID/NEW_UUID/' /etc/fstab

(Replace OLD_UUID and NEW_UUID with the appropriate values.)
Finally, update GRUB:
update-grub

If this finished without errors, you can exit the chroot (exit) and reboot. Done!


text:
Q: $\{a_n\}$ is a sequence of real numbers defined by $a_1=1$, $a_2=2$, $a_3=3$ and $a_n=2a_{n-1} - a_{n-3}$ Image of problem: http://d2vlcm61l7u1fs.cloudfront.net/media%2F901%2F9010d0fd-aeea-43bb-a993-9327afc7df9e%2FphpiKWhi5.png
Text of problem: $\{a_n\}$ is a sequence of real numbers defined by $a_1=1$, $a_2=2$, $a_3=3$ and $a_n=2a_{n-1} - a_{n-3}$ for $n \geq 4$.  Prove that $a_n=a_{n-1} + a_{n-2}$ for every integer $n \geq 3$.
I've gotten this far and I'm not sure where to go from here. Please guide me in the right direction? This is a Strong Principle of Mathematical Induction problem.
We show that $a_{k+1} = a_k + a_{k-1}$.
If $k = 2$ then $a_3 = a_2 + a_1 = 3$. Since $a_3 = 3$, it follows that $a_{k+1} = a_k + a_{k-1}$ when $k = 2$. Hence we may assume that $k \geq 2$. Since $k + 1 \geq 3$, it follows that
$a_{k+1} = 2a_k - a_{k-2} = 2a_{k-1} + 2a_{k-2} - a_{k-3} - a_{k-4}$.

A: We do the induction step.
Suppose that we know that for a certain $k$ we have $a_{k-1}=a_{k-2}+a_{k-3}$. We show that $a_k=a_{k-1}+a_{k-2}$.
By the induction hypothesis, $a_{k-1}=a_{k-2}+a_{k-3}$, and therefore $$a_{k-3}=a_{k-1}-a_{k-2}.$$
Thus
$$a_k=2a_{k-1}-a_{k-3}=2a_{k-1}-(a_{k-1}-a_{k-2})=a_{k-1}+a_{k-2}.$$


text:
Q: what is the largest unsigned integer that is valid to store in the size field of a tar archive header In the GNU specs for POSIX tar archive format here, the header structure is defined as:
struct posix_header
{                              /* byte offset */
  char name[100];               /*   0 */
  char mode[8];                 /* 100 */
  char uid[8];                  /* 108 */
  char gid[8];                  /* 116 */
  char size[12];                /* 124 */
  char mtime[12];               /* 136 */
  char chksum[8];               /* 148 */
  char typeflag;                /* 156 */
  char linkname[100];           /* 157 */
  char magic[6];                /* 257 */
  char version[2];              /* 263 */
  char uname[32];               /* 265 */
  char gname[32];               /* 297 */
  char devmajor[8];             /* 329 */
  char devminor[8];             /* 337 */
  char prefix[155];             /* 345 */
                                /* 500 */
};

The size field of the header is defined as a char array of length 12, and the byte length of the field appears to be 12 bytes (inferred by the byte offset comment). This in theory provides 12 bytes (=96 bits) of space to store an unsigned integer. However, I suspect this is not the case.

*

*Is the max size value equal to just 12 digits (999,999,999,999)? Or

*Since this size value represents the number of bytes in the file, does that mean the size value might not be completely accurate since the data size might equal a number of bits that isn't divisible by 8? Or do files always get saved in increments of 8 bits (with unused bits padded out to fill an entire byte), and thus the data length of bits will always be divisible by 8?

A: According to the standard documentation

The name, linkname, magic, uname, and gname are null-terminated character strings. All other fields are zero-filled octal numbers in ASCII.
  For historical reasons, a final NUL or space character should also be used.

Therefore, 11 bytes give you 11 octal digits (0..777777777778, or 0..0x1FFFFFFFF range), which your program needs to convert to binary representation in a way that you find suitable - for example, like this:
uint64_t size;
sscanf(header->size, "%" SCNo64 "", &size);

Demo.

A: Each of the fields in the header are stored as null terminated strings.  In the case of the file size, it is stored as an octal string.
So you have a total of 11 octal characters (leaving room for the null byte) meaning 33 bits for the file size, or up to 8GB.


text:
Q: what's the efficient technique to build a crud form using asp.net mvc I'm just start digging into mvc asp.net stack, I've Been for two days trying to submit a form to action controller I find myself in a very narrow choices, for instance in web form approach we can submit a form with multiple actions and we can use all possible elements to achieve that (buttons, a tag, ...)
Questions :
1 - Is asp.net mvc a OneForm-OneAction process ?
2 - How can we implement a CRUD actions in one form ? (according to question 1)

A: MVC is not really designed to enable one view for multiple actions.
To answer your first question, yes, MVC is designed so that each action corresponds to a specific view or partial view. Partial views are an interesting area because using them you can combine the output of multiple actions into one overall view.
In terms of CRUD operations, I would rely initially on the scaffolding features in Visual Studio as they will create fairly decent Controllers, Actions and Views based on your model which will do all the of the CRUD operations via Entity Framework. Right click your project > Add > New Scaffolded Item > MVC 5 controller with views using Entity Framework

A: You can easily post data from your view (form is not a must) to your controllers using jquery-ajax:
<input type="text" id="name" />
<input type="button" id="send" value="Save" onclick="SendName()" />

<script>
     function SendName() {
        var name= document.getElementById("name").value;

         $.ajax({
            type: "POST",
            url: "/GetName",
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({
                  "Name": name,
           }),
           success: function () {
             alert("Ok");
            },
            error: function () {
                alert("error");
              }
        });
         return true;
    }
 </script>


text:
Q: protocols & viewControllers, passing info using protocols on the same action Func Swift 3 & 4 I have this code to pass info between viewControllers using protocols, I have my models and with the first protocol work perfectly but the second one I have some issues, the data pass nil, or do nothing, already use tabBarController & UINavigationBar... the protocols... I create one in my ViewController(RecordViewController) and have the button & action and one protocol, this is:
 protocol RecordViewProtocol {

func newTrackInstrument(item: SampleCarouselsRecord)
func newInstrumentTrackCell(item: SampleTrackCellRecord)

  }

  extension RecordViewController: RecordViewProtocol {

func newTrackInstrument(item: SampleCarouselsRecord) {
    self.sampleCarouselItemsRecord.append(item)

    let indexOnPath = NSIndexPath(row: self.sampleCarouselItemsRecord.count - 1, section: 0)
    self.instrumentCarousel.insertItems(at: [indexOnPath as IndexPath])
}

func newInstrumentTrackCell(item: SampleTrackCellRecord) {
    self.sampleTrackRecord.append(item)

    let indexOnPath = NSIndexPath(row: self.sampleTrackRecord.count - 1, section: 0)
    self.trackInstrument.insertItems(at: [indexOnPath as IndexPath])
   }
}

the other protocol, on another ViewController(MixerViewController):...
  protocol MixerViewProtocol {
func newCarouselItem(item: SampleCarouselMixer)

}
  extension MixerViewController: MixerViewProtocol {
    func newCarouselItem(item: SampleCarouselMixer) {
    self.sampleCarouselMixer.append(item)

    let indexOnPath = NSIndexPath(row: self.sampleCarouselMixer.count - 1, section: 0)
    self.mixerCarouselInstrument.insertItems(at: [indexOnPath as IndexPath])
}

}
so, when wanna go the view and put the info to my models.. I put this code in the action Button to go into the view where is the function to put the info models:
   @objc func goToAddView() {

    let addTrackViewController = AddNewTrackView()

    let addTrackView = UINavigationController(rootViewController: addTrackViewController)
    addTrackViewController.recordViewControllerProtocol = self as RecordViewProtocol

    present(addTrackView, animated: true, completion: nil)
}

and work good with the first protocol.. but with to the other protocol nothing.. I don't know why or I don't know wath I have to do... look, I have the delegate protocols inside on the AddNweTrackView:
  var recordViewControllerProtocol: RecordViewProtocol?
  var delegateMixerView: MixerViewProtocol?  <- this is I think, put into the action button like the firstone:

here on the same action where the first protocol already is
  @objc func goToAddView() {

let addTrackViewController = AddNewTrackView()

let addTrackView = UINavigationController(rootViewController: addTrackViewController)
addTrackViewController.recordViewControllerProtocol = self as RecordViewProtocol

  addTrackViewController.delegateMixerView = MixerViewController.self as? MixerViewProtocol

present(addTrackView, animated: true, completion: nil)
 }

but return nil... and I try with diferents forms.. I try put this:
  let mixerViewController = MixerViewController()

  addTrackViewController.delegateMixerView = mixerViewController as? MixerViewProtocol

and try with this but the error Is obvious:
  addTrackViewController.delegateMixerView = self as MixerProtocol

and the same... I think, here at this point, it's where Im failing .. someone can help?


text:
Q: Present UIViewController I know this is extremely silly.
I have a view controller that scans a QR code. I create it in the AppDelegate (didFinishLaunchingWithOptions), and I also set my AppDelegate as a delegate for the the view controller which will call a method when he finishes scanning the code. In that method, that I have implemented in the AppDelegate I want to present a UINavigationController. The problem is that it is not presenting my navigation controller. This is my code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    reader=[ZBarReaderViewController new];
    reader.readerDelegate=self;
    reader.supportedOrientationsMask=ZBarOrientationMaskAll;
    ZBarImageScanner *scanner=reader.scanner;
    [scanner setSymbology:ZBAR_I25 config:ZBAR_CFG_ENABLE to:0];

   [self.window addSubview:reader.view];
   [self.window makeKeyAndVisible];
   return YES;
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    RootViewController *rootViewController=[[RootViewController alloc] init ];  //create root view controller

    UINavigationController *navigationController=[[UINavigationController alloc] initWithRootViewController:rootViewController];  // create and init navigation controller with viewController
    [navigationController setValue:[[GradientBar alloc] init] forKey:@"navigationBar"];

    rootViewController.title=@"mTLU";
    [reader presentModalViewController:navigationController animated:NO];

}

A: Seems like you forgot to set self.window.rootViewController in didFinishLaunchingWithOptions:
Try:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   // Override point for customization after application launch.
   self.reader=[ZBarReaderViewController new];
   self.reader.readerDelegate=self;
   self.reader.supportedOrientationsMask=ZBarOrientationMaskAll;
   ZBarImageScanner *scanner=reader.scanner;
   [scanner setSymbology:ZBAR_I25 config:ZBAR_CFG_ENABLE to:0];

   self.window.rootViewController = self.reader;

   [self.window addSubview:reader.view];
   [self.window makeKeyAndVisible];
   return YES;
}

This code assumes reader is property of AppDelegate. If it's only iVar you should ommit self. (or consider making it a property).


text:
Q: Getting the right CBOR output I have a little code snippet, where I try to serialize a map, kind of a JSON object into a CBOR ByteArray. But I can not get the same output as in the CBOR playground cbor.me
The thing I want to serialize to CBOR is this:
{
123: [22,67,2] ,
456 : [34,22,1]
}

If I serialize this in cbor.me I get:
A2          # map(2)
   18 7B    # unsigned(123)
   83       # array(3)
      16    # unsigned(22)
      18 43 # unsigned(67)
      02    # unsigned(2)
   19 01C8  # unsigned(456)
   83       # array(3)
      18 22 # unsigned(34)
      16    # unsigned(22)
      01    # unsigned(1)

My code looks like this:
val mapper = CBORMapper()
val map = HashMap<Any,Any>()
map[123] = intArrayOf(22,67,2)
map[456] = intArrayOf(34,12,1)
val cborData = mapper.writeValueAsBytes(map)
println(cborData.toHex())
val deserialized = mapper.readValue(cborData, HashMap<Any,Any>().javaClass)

The output from the print is this:
bf-19-01-c8-83-18-22-0c-01-18-7b-83-16-18-43-02-ff

TLDR
How can I get the same output as in the CBOR playground?


text:
Q: SQL Server XML.value context node I give users, of the tool we work on, the possibility to have calculate variables. Values are calculated by a given XPath expression. In .Net, with Saxon library, it is possible to calculate the value by executing the XPath expression in the context of the value to be calculated.
Example XML:
@data = '<Object>
  <Parameters>
    <Parameter Name="a">2</Parameter>
    <Parameter Name="b">5</Parameter>
    <Parameter Name="c"/>
  </Parameters>
</Object>'

Example XPath expression in context of Parameter with name "c":
../Parameter[@Name="a"]/text() + ../Parameter[@Name="b"]/text()

This wil result in 7 ;)
I like to execute the XPath expression on the SQL Server, but have now idea how to change the context node of a XML type?
A possibility would be that I add a XPath in front of the expression that changes the context, but have not found if this is possible. Query could than look like:
/<go to node variable "c" and make this the context node>

../Parameter[@Name="a"]/text() + ../Parameter[@Name="b"]/text()

Does someone have good ideas?

A: Using SQL Server's XQuery, you can declare XQuery variable, say $p to reference target parent element i.e <Parameters> where child element with attribute Name="c" is found. Then you can do further XPath/XQuery processing while using $p as context element :
declare @data XML = '<Object>
  <Parameters>
    <Parameter Name="a">2</Parameter>
    <Parameter Name="b">5</Parameter>
    <Parameter Name="c"/>
  </Parameters>
</Object>'

SELECT @data.value('
    let $p := /Object/Parameters[Parameter/@Name="c"]
    return ($p/Parameter[@Name="a"])[1] + ($p/Parameter[@Name="b"])[1]
','int') AS Result

sqlfiddle demo
output :
7

A: What you want is - AFAIK - not possible...
Try to define a working query with your XPath expression:
Btw: Your example is wrong in two ways: Attributs within the XML do not have the @-mark and the closing Parameters-tag is missing its final "s"...
DECLARE @data XML=
'<Object>
  <Parameters>
    <Parameter Name="a">2</Parameter>
    <Parameter Name="b">5</Parameter>
    <Parameter Name="c"/>
  </Parameters>
</Object>';

--This will not work, because your parts are not singleton
--SELECT Context.Node.value('../Parameter[@Name="a"]/text() + ../Parameter[@Name="b"]/text()','int')
--FROM @data.nodes('/Object/Parameters/Parameter[@Name="c"]') AS Context(Node);

--This works, because I framed both parts with (...)[1]
SELECT Context.Node.value('(../Parameter[@Name="a"]/text())[1] + (../Parameter[@Name="b"]/text())[1]','int')
FROM @data.nodes('/Object/Parameters/Parameter[@Name="c"]') AS Context(Node);

But there might be a workaround, but it's quite hacky and not reliable:
A Stored Procedure creates a dynamic sql statement built up from your parameters and executes this.
Your must-not-be-changed XPath expression will be changed in the way, that a + with a blank to the left and to the right (as well as -, * and /) is replaced in the way, that there is a singleton expression returned. I do not know how complex calculations might be. Check it out...
CREATE PROCEDURE dbo.CalculateXPathExpression
(
     @data XML
    ,@XPathContextNode VARCHAR(MAX)
    ,@XPathCalculation VARCHAR(MAX)
)
AS
BEGIN
    DECLARE @Return INT;
    DECLARE @CalcSingleton VARCHAR(MAX)='(' + REPLACE(REPLACE(REPLACE(REPLACE(@XPathCalculation,' + ',')[1] + ('),' - ',')[1] + ('),' * ',')[1] + ('),' / ',')[1] + (') + ')[1]';
    DECLARE @Cmd NVARCHAR(MAX)=
    'SELECT @Return = Context.Node.value(''' + @CalcSingleton + ''',''int'')
    FROM @data.nodes(''' +  @XPathContextNode + ''') AS Context(Node);';

    EXEC sp_executesql @Cmd, N'@data XML, @Return INT OUTPUT',@data=@data, @Return=@Return OUTPUT;

    SELECT @Return;

    RETURN;
END
GO

DECLARE @data XML=
'<Object>
  <Parameters>
    <Parameter Name="a">2</Parameter>
    <Parameter Name="b">5</Parameter>
    <Parameter Name="c"/>
  </Parameters>
</Object>';

DECLARE @XPathContextNode VARCHAR(MAX)='/Object/Parameters/Parameter[@Name="c"]';
DECLARE @XPathCalculation VARCHAR(MAX)='../Parameter[@Name="a"]/text() + ../Parameter[@Name="b"]/text()';

EXEC dbo.CalculateXPathExpression @data, @XPathContextNode, @XPathCalculation;
GO

DROP PROCEDURE dbo.CalculateXPathExpression;
GO


text:
Q: How to change focus on buttons up, down, left and right relative to the button that is selected? I'm new in programming.
I don't know how to explain well!!.
How can i make my WinForms application understand the button location,
for example imagine a number of buttons positioned and that one of them is select
button1- button2 -button3
button4-(button5)-button6
button7 -button8- button9
how can i press down on the keyboard and jump to (button8) and not to (button6), or press upkey and go from (button2).
how can i make visual studio understand which button is up or down or left and right relative to the button that is selected?

A: You can add your Buttons to a TableLayoutPanel, so each Button's position is determined by the TableLayoutPanel's (Column:Row) coordinates.

*

*Create a TableLayoutPanel (in the below, named tlpButtons) with enough Rows and Columns to contain your Buttons. You can add/remove Rows and Column at run-time, if needed.

*Select all your Buttons and subscribe to the PreviewKeyDown, using the PropertyGrid in the Form Designer, so that you have just one event handler for all your Buttons (in this code, the event handler is named buttons_PreviewKeyDown).

*When the Key.Up or Keys.Down are pressed, the PreviewKeyDown handler of the Buttons is invoked. The sender argument references the control that triggered the event, so we cast sender to Control (since only a Control type reference is needed, we don't use any property specific to a derived type, like Button)

*If we handle the Key pressed, we have to set IsInputKey, otherwise the event is passed on to the control and processed (causing the normal selection to trigger)

*The TableLayoutPanel's GetPositionFromControl() returns the Row/Column position of this Control.

*We just set the Row value ± 1, depending on what cursor Key has been pressed (while checking whether the new value is in the [0 : RowsCount] range).
The GetControlFromPosition() method returns the reference of the control in the new position: we use this reference to set the current ActiveControl.

This is the result:

Note:
the buttons_PreviewKeyDown event handler is the same for all Buttons/Controls.
tlpButtons is the name of the TableLayoutPanel used as container for the Buttons/Controls
Updated to also work with a Numeric Pad when either active or inactive.

private void buttons_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    var btn = sender as Control;
    var pos = tlpButtons.GetPositionFromControl(btn);
    bool moveFocus = false;

    switch (e.KeyCode) {
        case Keys.NumPad8:
        case Keys.Up:
            pos.Row = (pos.Row > 0) ? pos.Row - 1 : tlpButtons.RowCount - 1;
            moveFocus = true;
            break;
        case Keys.NumPad2:
        case Keys.Down:
            pos.Row = (pos.Row < (tlpButtons.RowCount - 1)) ? pos.Row + 1 : 0;
            moveFocus = true;
            break;
        case Keys.NumPad4:
            if (pos.Column > 0) {
                pos.Column -= 1;
            }
            else {
                pos.Column = tlpButtons.ColumnCount - 1;
                pos.Row = pos.Row > 0 ? pos.Row - 1 : tlpButtons.RowCount - 1;
            }
            moveFocus = true;
            break;
        case Keys.NumPad6:
            if (pos.Column < (tlpButtons.ColumnCount - 1)) {
                pos.Column += 1;
            }
            else {
                pos.Column = 0;
                pos.Row = (pos.Row < tlpButtons.RowCount - 1) ? pos.Row + 1 : 0;
            }
            moveFocus = true;
            break;
    }
    if (moveFocus) {
        e.IsInputKey = true;
        var ctrl = tlpButtons.GetControlFromPosition(pos.Column, pos.Row);
        if (ctrl != null) this.ActiveControl = ctrl;
    }
}

A: I'm assuming you are talking about buttons within a Form.
Put them in a List like that
List<Button> buttons = new List<Button>() {Button1, Button2...}

Now you know what button you are on and going up means you need to take the current index and substract 3* from it (Button6 -> Button3) and just use that as the new index for the list.
For down you add 3* and left/right are minus/plus 1.
Now you just have to define your edge cases:
What if you press down or right when you are on Button9?

*This value changes based on the amount of columns. 3 columns => +/-3; 4 col => +/-4


text:
Q: MapActivity - width and height must be > 0 i created an app using mapActivity and MapView and encounter the wierd message:
" E/AndroidRuntime(4276): java.lang.IllegalArgumentException: width and height must be > 0 "
that message is not always shows up. I backtraced the situation it shows up and found out this:
1) If it's been long time since i touch the app and then run it, the crash wills show up, note that if after the crash i reopen the app then there is NO crash again.
2) if I delete the memrey (RAM) then after i run the app it will crash.
3)if I run dibugg mode then i never encounter the crash...
from my point of view i think the crash related to something that Android did not yet misured but still trying to display it.
still i do not touch the mapview misure parameters so why should i ever get this crash?
anyways, i have no idea what to do since the debugg mode can't realy help here.
i will display my onCreate() here:
/********************************  Methods  *****************************************
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);  //get rid of the title bar of the window, NOTE: we have to do this BEFORE we call "setContentView()"
    //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);  //this line is use to remove the uppermost bar in the window (the one with the time , etc.)

    setContentView(R.layout.create_map);
    mMapView = (MapView)findViewById(R.id.mapview);
    moveDotBtn = (Button)findViewById(R.id.movedot);
    finishBuildBtn = (Button)findViewById(R.id.finish);

    mapController = mMapView.getController();
    mMapOverlays = mMapView.getOverlays();
    mMapView.setBuiltInZoomControls(true);
    mMapView.setSatellite(false);
    mMapView.setStreetView(false);

    whereAmI = new MyCustomLocationOverlay(this, mMapView,mapController);
    mMapView.getOverlays().add(whereAmI);
    //mMapView.postInvalidate();    //without that call the overlay "where_m_i" will not show.

    sensor_mgr = (SensorManager) getSystemService(Context.SENSOR_SERVICE); //activate for compass
    sensor = sensor_mgr.getDefaultSensor(Sensor.TYPE_ORIENTATION); //activate for compass, and orientation

    powerManager =(PowerManager)getSystemService(Context.POWER_SERVICE);    //to make always on, and never looked
    wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");

    locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    lastLocation = null;

    Touchy t = new Touchy();
    mMapOverlays.add(t);

    iconItems = getResources().getStringArray(R.array.icons);
    RES = getResources();
    mIconOverlays = new IconItemizedOverlay(RES.getDrawable(R.drawable.ic_bench));
    mMapOverlays.add(mIconOverlays);

    mapController.setZoom(17);
}

@Override
public void onResume()
{
    wakeLock.acquire(); //make your phone awake at all times.

    locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0 , whereAmI);
    locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0 , whereAmI);
    whereAmI.enableMyLocation();
    whereAmI.enableCompass();
    findLastKnownLocation();
    sensor_mgr.registerListener(sensorEventListener , sensor ,SensorManager.SENSOR_DELAY_NORMAL);
    super.onResume();
}

A: i think i got the answer, but i'm not sure, only time can tell with buggs like thoes. it seems as if i should not touch the screen on the onCreate while using google maps, so if i want to do ZoomIn or setZoom(SOME_NUMBER) then i should do it on the onResume() and not the onCreate. hope this will help someone, some day :)
btw:
if someone has an idea if it is realy the problem or is it just a temporery solution then i would like to hear, casue it seem to work fine with my solution :)

A: You should do your changes in onWindowFocusChanged since you are not alloted screen height/width before that.
 @Override
   public void onWindowFocusChanged(boolean hasFocus) {
      if (hasFocus) {
             setOverlay(); //Your code should come here
         }
      }
      super.onWindowFocusChanged(hasFocus);
   }


text:
Q: How to get query created by the prepare statement in PDO We can use prepare method to get the query prepared for multiple time use in PDO.
But i want to know that can we see all the queries executed at the DB.
For e.g see below:
<?php

    // Cosidering DB connection already set here. With $db.
    // using named placeholder

    $db->prepare("select * from user where id=:id");
    $db->bindParam(':id',$id);

    for($i=1;$i<=5;$i++)
    {
       $id=$i;
       $db->execute();
    }

?>

OK now we can see that this code will run 5 queries.
So how can i get these queries which is executed by this execute() statement???
Hope I am clear to all.

A: Afaik, unless you extend the PDO class, I don't think its possible. You possibly can enable a log on your (development) database however. Don't use it in production.


text:
Q: How do I tell cmake which version of python to use? I want to use use python 3.7 instead of python 2.7 when building with cmake.
This is the error I get:
enter image description here
How do I tell cmake which python to use?
Text version of my error -
-- Building local IBM Accelerator simulator.
-- Found PkgConfig: /usr/bin/pkg-config (found version "0.29.1")
-- Found UUID: /usr/include
-- Found Python: /usr/bin/python2.7 (found version "2.7.17") found components: Interpreter Development
-- Found Python version 2.7.17. Version must be greater than 3.0.0, skipping Python API build.
-- Configuring done
-- Generating done
-- Build files have been written to: /home/cades/dev/envs/xacc/build

A: Assuming you are using a recent version of CMake and that you are developing the build system of the project you discussed above, you could do the following:
find_package (Python3 COMPONENTS Interpreter Development)

See https://cmake.org/cmake/help/latest/module/FindPython3.html#module:FindPython3
Now, if you are building an existing project, you would have to check if the project support using a newer version of python.


text:
Q: How do I get the real font used by a Windows Form? When displaying text in a Windows Form (like a TextBox for example) I can enter Chinese characters in it if I want, and they will get displayed correctly. However, the font used by the Form is not actually capable of rendering Chinese. As a result, if I try to use the Form's font in order to create a PDF file containing the text, it won't work:
myPdf.RenderText(myForm.Font, myForm.Text);

In this case in Windows 10, myForm.Font is just Microsoft Sans Serif (or Arial in older Windows versions,) which does not support Chinese (or CJK in general) and as a result the PDF won't render correctly when embedding the Arial font in it.
So, how do I find out which font is really used to render text in a Windows Form? It can't be what the Font property says it is. In this particular case, it's probably "SimSun" or some other system font that supports Chinese characters, but there doesn't seem to be any way whatsoever to find out.
How do I deal with this? If it's not possible to get the true font of a Form, then could I somehow detect what font (or combination of fonts) Windows would use to render a piece of text on a Form before actually displaying the text on that Form?


text:
Q: How to get dummies and groupby I have dataframe below
   Q  A
A  a  h
A  b  i
A  c  j
B  d  k
B  a  l
B  b  m
C  c  n

I would like to get dummy and groupby
    a   b   c   d    e   f   g
A   h   i   j  nan  nan nan nan
B   l  nan nan nan  k   nan nan
C  nan nan  n  nan  nan nan nan

col=df.Q
I must apply get_dummiesandgroupby.but I couldnt figure out.
How can I get this result ?

A: It seems you need reset_index with pivot:
df = df.reset_index().pivot(index='index', columns='Q', values='A')
print (df)
Q         a     b     c     d
index
A         h     i     j  None
B         l     m  None     k
C      None  None     n  None

And then if neccessary reindex_axis and replace:
cols = list('abcdefg')
print (df.reindex_axis(cols, axis=1).replace({None:np.nan}))
Q        a    b    c    d   e   f   g
index
A        h    i    j  NaN NaN NaN NaN
B        l    m  NaN    k NaN NaN NaN
C      NaN  NaN    n  NaN NaN NaN NaN

EDIT:
If duplicates in data better is groupby with join:
print (df)
   Q  A
A  a  h
A  b  i
A  c  j
B  d  k
B  a  l
B  b  m <-duplicates B b
B  b  t <-duplicates B b
C  c  n

df = df.reset_index().groupby(['index','Q'])['A'].apply(','.join).unstack()
print (df)
Q         a     b     c     d
index
A         h     i     j  None
B         l   m,t  None     k
C      None  None     n  None

Another possible solution with pivot_table:
#aggfunc='first' - get only first value, another values are lost
df1 = df.reset_index().pivot_table(index='index', columns='Q', values='A', aggfunc='first')
print (df1)
Q         a     b     c     d
index
A         h     i     j  None
B         l     m  None     k
C      None  None     n  None
Q         a     b     c     d

#aggfunc='sum' - summed data, no separator
df2 = df.reset_index().pivot_table(index='index', columns='Q', values='A', aggfunc='sum')
print (df2)
index
A         h     i     j  None
B         l    mt  None     k
C      None  None     n  None
Q         a     b     c     d

#aggfunc=','.join - summed data with separator
df3 = df.reset_index().pivot_table(index='index', columns='Q', values='A', aggfunc=','.join)
print (df3)
index
A         h     i     j  None
B         l   m,t  None     k
C      None  None     n  None


text:
Q: Next.js: react-color - Warning: Prop `style` did not match
I'm using Next.js framework & I'm getting a warning when I use react-color in my index.js.
Here is index.js:
import SketchPicker from 'react-color';

const index = () => {
    return <SketchPicker />
}

export default index;

A: You're getting that error because the style prop generated from SSR does not match the client-side one. You could solve it by only loading SketchPicker on the client with Next.js dynamic import.
You also need to pass a state  setter to onChangeComplete
and state variable to color to properly handle the color picking.
import dynamic from 'next/dynamic';

const SketchPicker = dynamic(
  () => import('react-color').then((mod) => mod.SketchPicker),
  { ssr: false }
);

const Index = () => {
    const [color, setColor] = useState();
    const handleChange = (color) => setColor(color);

    return <SketchPicker color={color} onChangeComplete={handleChange} />;
}

export default Index;

A: Hide the Color picker initially and it renders on any further user interaction.
Refer sample code here, where it is hidden using state.displayColorPicker.


text:
Q: path function for URL throwing error when we want to capture an integer or slug paramter I am a beginner in django 2.2.4. I was trying to the following the urls.py file.
from firstapp import views
from django.contrib import admin
from django.urls import re_path, path

urlpatterns = [
    re_path(r'^admin/$', admin.site.urls),
    re_path(r'^$', views.index),
    path('articles/2003/', views.index),
    path('articles/<int:year>/', views.index),
]

I see that the url http://127.0.0.1:8000/articles/2003/ executes the views.index. However, when I run the url http://127.0.0.1:8000/articles/2005/ ,there is an error.
Request URL:    http://127.0.0.1:8000/articles/2005/
Django Version: 2.2.4
Exception Type: TypeError
Exception Value:
index() got an unexpected keyword argument 'year'

Why is this not working?
As above.It was expected this ur would be matched by the line
path('articles/<int:year>/', views.index).

A: Your views.index should take a parameter called year, something like:
def index(request, year):
    ...

Right now it must be only
def index(request):
    ....

And /articles/2003/ is working because you have an explicit path set for in your url conf:
    path('articles/2003/', views.index), # matches articles/2003/, calls views.index(request) with no year param
    path('articles/<int:year>/', views.index), # matches articles/2005/, calls views.index(request, year=2005), throws error

Remove the explicit path for articles/2003/, add the year param to views.index and then things should work.


text:
Q: Converting doc to docx using python I am trying to convert .doc documents to .docx documents using python. Getting inspiration from this post, I have tried the following code :
import subprocess
import glob
import os

root = "//xxx/"
data_path = root + '/data2/'

os.chdir(data_path)

for doc in glob.iglob("*.doc"):

    print(doc)
    subprocess.call(['soffice', '--headless', '--convert-to', 'docx', doc], shell = True)

But unfortunately litterally nothing happens, i.e. I get no error message, the code is running, the docs are detected (which I check thanks to print) but I don't get any result. Any idea how I may troubleshoot this ?
EDITS :

*

*I am running on Windows, hence shell = True

*I have tried double quotes : '"

*I have tried without spaces in the names

*When I execute the subprocess command on one file alone, I get 1as output, which I don't knowhow to interpret...


text:
Q: How do I display special characters in ncurses with Linux? I'm trying to make a code where I make Lenny jump,  but lenny's face this: ( ͡° ͜ʖ ͡°)
When compile & run the code (g++ -o Lenny main.cpp), I get the output "( ͡° �~\�~V ͡°)".  Is there a way I can get it to display ( ͡° ͜ʖ ͡°)?

A: You are dealing with Unicode characters. You can use this libray: ICU.
See more here:

A: Linux has good Unicode support, you don't need any special libraries if all you're doing is output:
#include <iostream>
int main()
{
    std::cout << "( ͡° ͜ʖ ͡°)\n";
}

online demo: http://ideone.com/UUS6Il
Or, you could not rely on Linux's built-in UTF-8 and be explicit about it:
#include <iostream>
#include <locale>
int main()
{
    std::locale::global(std::locale("en_US.utf8"));
    std::wcout.imbue(std::locale());
    std::wcout << L"( ͡° ͜ʖ ͡°)\n";
}

online demo: http://ideone.com/EhTfB9
EDIT: Based on your code in the comment, your question is actually about the ncurses library I/O, not about C++. To get your program work as expected,

*

*Add the line setlocale(LC_ALL, "en_US.utf8"); near the beginning of your main() (and add #include <clocale> accordingly)

*change your linkline to use -lncursesw as opposed to -lncurses if that's what you're using.


text:
Q: How can I get raster layers to display when I switch to them, even if the zoom is too high for them? I am using OpenLayers 3.15 and have an application that mostly does what I want it to do. However I do have a little issue with displaying some layers when I first switch to them.
You can see it if you go to http://mapping4ops.org/ShowMapsDev/M4OPS-index.html?OPS=HcN&Layer1=No%20layer, and zoom in 4 times. Now switch the base layer to eg Bartholemew, 1897-1907, and that layer does not display. I presume it is something to do with maxResolution and maxZoom for the layer, but I do not really understand these.
If you now zoom out 4 times, the layer displays, and if you zoom back in 4 times the layer remains displayed (fuzzily). I would like the layer to display when you first switch to it, even though it is fuzzy.
To do the switch in js I am using:
thismap.getLayers().removeAt(layerindex);
thismap.getLayers().insertAt(layerindex,layer);

I get the same problem with all of my raster layers (some served by tileserver on my own server, and others from geo.nls.uk), when the map is at too high a zoom level. They all appear when I zoom out enough and then remain when I zoom back in.
I have considered various ways to force the layer to display when I first switch to it, but not found one that works. I see applications that do not seem to have this problem, so how do I solve this?


text:
Q: How to get latest RMP data? In Realm Browser and in my App I can watch how rows get deleted, modified and created when I log in with a Sync User, like it is getting synced slowly, when I login my app I would like to know when this sync ends, or better, get only the latest data at once and not the whole history of it.
I don't know if is a setting in Realm Object Server (Ubuntu) or in my App (iOS Swift)

A: Realm Mobile Platform syncs your data automatically in background, it allows you to work with the Realm url the same way you work with the local one.
So you can just use any type of Notifications to handle any data changes.


text:
Q: Trying to return a value from switch case to a switch case but doesn't work Firstly, I'd just like to clarify that this is my first time on this site and, i'm very new to coding in general. This is my first language :') My code is probably extremely messy and could be done a lot better, so please go easy on me...!
i've got a switch case within an int function.
The problem is:
I'm trying to make it so that whatever seat is taken is memorized, and the seat can not be taken again. I have tried returning 'result' from the function to go through the switch case but unfortunately, it doesn't seem to be returning correctly as I keep getting the default of that statement, which returns an error message to me.
Any help would greatly be appreciated!

A: you have two possibilities to recover the result,
1) The first approach you have to get the result of the function like this:
result = standardType(type, snumber, result, s1, s2, s3, s4, s5);

With this approach you did not need to pass in parameter the result, you can directly return "return 1 or other value"
2) The second approach (pass the address of the result variable as a parameter of the function)
void standardType(char type, int snumber, int* result, int s1, int s2, int s3, int s4, int s5)
{
...
*result = 1;
...
}

// in main
 int main()
{
    char choice, type;
    int snumber, cont=1, result;
    int s1, s2, s3, s4, s5;

while (cont != 0)
{

    printf("\n\nWelcome to Cinema System.\n        Choose 'S' for Standard Type, 'G' for Gold Type and 'X' to exit:\n\n");
    scanf(" %c", &choice);

    switch(choice){

case 'S':
     standardType(type, snumber, &result, s1, s2, s3, s4, s5);

...
}

In this example, you directly modify the value of the result variable via the address of the variable.
The variable symbol &var gives the address of the variable in memory and the variable symbol *var gives access to the value via the address.


text:
Q: Convert array data into Excel I am converting array data into Excel using PHPExcel. When Excel file is created, data is stored row wise but I want to store data column wise. My array is given below:
array (size=3)
  0 => string '8801755568952' (length=13)
  1 => string '8801755556987' (length=13)
  2 => string '8801755587985' (length=13)

My array to Excel conversion code is:
$objPHPExcel->getActiveSheet()->fromArray($csv_data, null, 'A1')
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    return $objWriter->save($xls_output_path);

My output is:
8801755568952 8801755556987 8801755587985

My desired output is:
8801755568952
8801755556987
8801755587985

A: If you pass a simple 1-dimensional array to the fromArray() method, then PHPExcel assumes that it is a single row, which is what you're seeing.
Either convert your array to a 2-dimensional array
As PHPExcel will treat these values as numeric, and they're larger than the limit for a 32-bit signed integer in PHP (and you're probably running 32-bit PHP), they'll be cast to float, and you'll potentially lose accuracy, so I wouldn't use this approach myself.
If you do want to convert the array to a 2-dimensional array, then use:
$csv_data = call_user_func_array(
    'array_map',
    array_merge(array(NULL), [$csv_data])
);

Or just loop over it writing to each row individually
$row = 1;
foreach($csv_data as $cellData) {
    $objPHPExcel->getActiveSheet()->setCellValueExplicit('A'.$row++, $cellData);
}

The use of setCellValueExplicit() will force the values to be treated as a string, so nothing will be cast to float, so no loss of precision


text:
Q: Absorbing Markov chain when less transient states than absorbing states I  have a probability matrix:
   1    2    3
1  0.5  0.3  0.2
2    0    1    0
3    0    0    1

I understand that:
$$
Q = \left(\begin{array}{c} 0.5 \end{array} \right) \\
R = \left(\begin{array}{c} 0.3 & 0.2 \end{array} \right) \\
I = \left(\begin{array}{cc} 1 & 0 \\ 0 & 1\end{array} \right)
$$
I calculated the fundamental matrix $ N $ to be:
$$
N = (I - Q)^{-1} = \left(\begin{array}{cc} 1 & 0 \\ 0 & 2 \end{array} \right)
$$
But when I try to calculate the probability matrix, I can't do the multiplication because it's a $ 2 \times 2 $ matrix against a $ 1 \times 2 $ matrix. =S
$$
B = \left(\begin{array}{cc} 0.5 & 0 \\ 0 & 1\end{array} \right)
\left(\begin{array}{c} 0.3 & 0.2\end{array} \right)
$$

A: So, as @Arkamis pointed out, what I had wrong is that $ (I-Q)^{-1} $ shouldn't be a $ 2 \times 2 $ matrix.
I started with a mistake in $ I - Q $ like this, which is wrong:
$$
I - Q= \left( \begin{array}{cc} 1 & 0 \\ 0 & 1 \end{array} \right) - \left( \begin{array}{cc} 0.5 & 0 \\ 0 & 0 \end{array} \right)
$$
One isn't to "expand" $ Q $ to fit $ I $. Instead, it should make $ I $ whatever the size of $ Q $:
$$
I - Q = (1) - (0.5)
$$


text:
Q: Customization of Mage_Adminhtml_Block_Sales_Order_Create_Items_Grid I want to add a custom 'gift wrap' column under 'Items Ordered' so that I can add gift wrapping cost to the subtotal of the product. The page is present at admin panel->sales->orders->create new order->create new customer. The file to this page is present at (app\code\core\Mage\Adminhtml\Block\Sales\Order\Create\Items\Grid.php) Please find the screen shot of what I intend to do. I am unable to do this,please help

A: This is the similar work I am just doing now.
You will need to change/overwrite following file:
design/adminhtml/default/default/template/sales/order/create/items/grid.phtml
Learn how to override template:
Basically you are adding  in
 and  in
 section.
Hope this helps.
Update
In that file
add <col width="80" /> in <col> section.
and change

                    <?php echo $this->helper('sales')->__('Product') ?>
                    <?php echo $this->helper('sales')->__('Price') ?>
                    <?php echo $this->helper('sales')->__('Qty') ?>
                    <?php echo $this->helper('sales')->__('Subtotal') ?>
                    <?php echo $this->helper('sales')->__('Discount') ?>
                    <?php echo $this->helper('sales')->__('Row Subtotal') ?>

                    <?php echo $this->helper('sales')->__('Action') ?>

To

                <?php echo $this->helper('sales')->__('Product') ?>
                <?php echo $this->helper('sales')->__('Price') ?>
                <?php echo $this->helper('sales')->__('Qty') ?>
                <?php echo $this->helper('sales')->__('Gift wrap') ?>
                <?php echo $this->helper('sales')->__('Subtotal') ?>
                <?php echo $this->helper('sales')->__('Discount') ?>
                <?php echo $this->helper('sales')->__('Row Subtotal') ?>

                <?php echo $this->helper('sales')->__('Action') ?>

and change
 <input name="item[<?php echo $_item->getId() ?>][qty]" class="input-text item-qty" value="<?php echo $_item->getQty()*1 ?>" maxlength="12" />

to
<input name="item[<?php echo $_item->getId() ?>][qty]" class="input-text item-qty" value="<?php echo $_item->getQty()*1 ?>" maxlength="12" />
<input name="item[<?php echo $_item->getId() ?>][gift_wrap]" class="input-text item-gift-wrap" value="<?php echo $_item->getGiftWrap() ?>" />

Important
echo $_item->getGiftWrap() is coming from database table sales_flat_quote_item, so you must have a column named gift_wrap.
You can add that column like this (in your setup/sql file)
<?php
$installer = $this;

$installer->startSetup();
$installer->getConnection()
    ->addColumn($installer->getTable('sales_flat_quote_item'),
        'gift_wrap',
        array(
            'type' => Varien_Db_Ddl_Table::TYPE_TEXT,
            'nullable' => true,
            'comment' => 'Gift Wrap'
        )
    );
$installer->endSetup();


text:
Q: ASP.NET MVC 5 concurrent requests are queued even with disabled Session Before thinking about downvoting or telling me "google it", please read the problem more carefully. This is old/classic problem but old/classic solution is no longer working. Here is very simple scenario to reproduce in Visual Studio 2013/2015:
1) Create ASP.NET Web application using MVC template:

2) Open Controllers\HomeController.cs and add attribute to controller and "Sleep" action:
[SessionState( System.Web.SessionState.SessionStateBehavior.Disabled)]
public class HomeController : Controller
{
    public ActionResult Sleep(int? time)
    {
        System.Threading.Thread.Sleep(time ?? 3000);
        return Content("OK");
    }

    public ActionResult Index()
    {
...

3) Open file: Views\Home\Index.cshtml and add/replace content html with the following :

<script>
    function ReqClick() {
        var startTime = Date();

        $.ajax("/Home/Sleep")
        .success(function () {
            var log = $("#log");
            var endTime = Date();
            log.text(log.text() + "Start: " + startTime.toString() + "  === " + endTime.toString());
        });
    };
</script>

<button type="button" onclick="ReqClick();">
    Request
</button>
<div>
    <textarea id="log" style="width:640px; height:480px"></textarea>
</div>

4) Run it (does not matter if you're using IIS or IIS Express or Vs Dev Server) - Open Home/Index. Click F12 to open dev tool, open network tab. On the Home page click "Request" button twice fast. You can see that second request takes almost 6 seconds:

In Debug mode in controller you can see that Session is null:

Cookies are totally empty (ASP.NET Session Id is absent)

Please let me know what I'm missing?
Adding the setting below to web.config does not help either:

<sessionState mode="Off"/>
<pages enableSessionState="ReadOnly"/>

A: Concurrent parallel requests worked for me when I decorated my controller with this attribute
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]

It works better than the above disabling session state and was added back in MVC 3.  More info here

A: I spent a lot of time on this issue and found much of the information that you saw above also did not correct the issue.  My parallel requests were always queuing, I saw this in Internet Explorer as well as Firefox.
I found this article related to am using an MVC application this article
This shows that you can use Disabled [SessionState(SessionStateBehavior.Disabled)] instead of setting it to ReadOnly.
I moved my code that was performing the AJAX GET call to its own controller since I had other code in the current controller that used Session via TempData.  This corrected my issue and my $.get() call to the controller with session disabled would process in parallel with the $.post() to the other controller that used session.


text:
Q: Python tools won't open when clicked on I am creating a python toolbox within ArcGIS 10.3 and I am having issues opening it up in ArcMap. I have been editing it, saving it, and running it within ArcMap this whole time to test it little by little, and now when I double click on the tool within the toolbox it won't respond. I checked to make sure that I do not have multiple scripts running, or that I am not hiding the pop up window for the tool behind other things open on my screen. This leads me to believe that there is something wrong with my python script (below).
import arcpy

class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "Toolbox Label Property"
        self.alias = "Toolbox Alias Property"

        # List of tool classes associated with this toolbox
        self.tools = [WiFi_Buffer]

class WiFi_Buffer(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Buffer WAP"
        self.description = "This python script tool will buffer WAPs"
        self.canRunInBackground = False

    def getParameterInfo(self):
        """Define parameter definitions"""
        param0 = arcpy.Parameter(
        displayName="Wireless Access Points",
        name="wap_pts",
        datatype="GPFeatureLayer",
        parameterType="Required",
        direction="Input")

        param1 = arcpy.Parameter(
        displayName="Obstruction Layer",
        name="obstructions",
        datatype="GPFeatureLayer",
        parameterType="Required",
        direction="Input")

        params = [param0, param1]
        return [params]

##    def isLicensed(self):
##        """Set whether tool is licensed to execute."""
##        return True
##
##    def updateParameters(self, parameters):
##        """Modify the values and properties of parameters before internal
##        validation is performed.  This method is called whenever a parameter
##        has been changed."""
##        return
##
##    def updateMessages(self, parameters):
##        """Modify the messages created by internal validation for each tool
##        parameter.  This method is called after internal validation."""
##        return
##
##    def execute(self, parameters, messages):
##        """The source code of the tool."""
##        return

I have left the parts that I have not reached yet commented out, and it has been running the first parameter just fine, it wasn't until trying to create the second parameter (param1) that the tool wouldn't run. I don't see anything wrong with the code, but I am new to building python tools so there could be something obviously wrong with it. Any ideas on how I can get the tool to run again?

A: I figured it out. Rather than setting up a new variable "params" and holding the multiple parameters to be returned through that, I just simplified it to return the parameters directly as shown below.
    return [param0, param1]

Now it loads the tool up when clicked on with both of the parameters correctly displayed. I guess it's best to keep it simple sometimes. Thanks for the input all.


text:
Q: How to access files on a USB-connected NTFS disk removed from a Win7 notebook? My daughter seems to have fried her motherboard in her Lenovo Notebook. The disk seems to be fine. I removed the disk and used a universal disk-to-USB kit to attach it to another computer. The disk is recognized fine and I can peruse it in Windows Explorer. The problem is that the files she would like to recover from it are located in places that Windows refuses to let me access. When I try, for example, to enter the directory "Documents and Settings" it gives me an "Access is denied" error. Same thing when I try to go into the various User directories and other locations.
I thought to try creating a Ghost image & retrieve the files from that, but Ghost seems to croak when I  try to run it - apparently it doesn't like accessing the disk via a USB connection (even though I've told it to install the drivers for USB).
Any other ideas about how to get to the files I need, either through Windows or perhaps some other OS that I could boot from a CD that can read an NTFS disk? Thanks, Yosh

A: Firstly, you can try to take ownership of the folder with windows itself. You must be an administrator for this to work! So, here goes.

*

*Right-click on the folder and click on "Properties"

*Go to the "Security" tab.

*Click on the "Edit..." button

*

*Click on "Add..." and enter your username in the textbox

*Click on "Check Names", just to be on the safe side, and then click on "OK". Your account has appeared in the list of users.

*Click on your account and then select the necessary permissions (basically: select "Full control")

*Tada! That's done. You might have to repeat this process for other folders. If this doesn't work, please follow the next set of steps.

*Instead of clicking on "Edit...", click on "Advanced" in the properties window.

*

*Click on "Change" next to "Owner:" at the top.

*Enter your username, click on "Check Names" and then on "OK".

*Select "Replace all child object permissions (...)" and click on "OK" again. And again... Tadah

*If this also didn't work, click on "Add" instead of "Change" (step 4.1).

*

*Click on "Select a principal", enter your username, etc...

*Select "Full control".

*Select "This folder, subfolders and files" next to "Applies to:"

*Click on "OK", "OK", "OK"...

*This is all you can do with Windows itself.

You might want to use a 3rd-party program for some reason.
For this, please follow the instructions here: Add "Take Ownership" to Explorer Right-Click Menu in Win 7,8 or Vista - How-To Geek.
After installing the mentioned tool, right-click on the folder and select "Take Ownership" as shown on the picture below:

Or you can use the program you mentioned yourself: Ownership Changer - Software created by our members - Neowin Forums
As a 'last resort', you can use a LiveCD of a Linux distro (Ubuntu, for example) to copy the files from the external HDD.
Or you can use GParted (yes, its main purpose is managing partitions, but as you can see here, (other) manipulation of hard drives is also possible)
btw, I assume you mean the "Users" folder? "Documents and Settings" isn't used anymore since Windows Vista. Well, nevermind, doesn matter.

A: OK, first of all, make sure you are able to access the correct directories. In Windows 7, in my user directory C:\users\[username]\, I see two "My Documents" but one is like a symlink or something and doesn't let even me "open" it.

In the above screenshot, the selected "My Documents" is the directory that lets me get to all my files. The second one (with the shortcut symbol on it) doesn't seem to work for even me. So make sure you're trying to get to the right directory.
Also, a modern Linux distro can access NTFS and iirc, will ignore NTFS permissions and allow you to copy files off as necessary.


text:
Q: I can't read a sector from a CD-ROM in x86 assembly I'm trying to load the second stage bootloader from my ISOSYS bootloader for my OS32 operating system, but I can't seem to do it. CF seems to always be set. This is to be booted from a CD/DVD and I'm using Debian GNU/Linux 7.6 (Wheezy)
Here's isosys.asm:
;===============================================================
;
;               ISOSYS v1.0 in isosys.asm
;
; Program for booting OS32 and OS32-based systems from CD/DVDs
; using the ElTorito boot standard.
;
; By Omar, 2014
;
; ===============================================================

; set up bios...
bits 16
org 0x7c00

; beginning of sector 1, byte 0:

; jump over functions block
jmp Start

;
; Print()
;      prints a string to standard output
; AL = 0 : terminate
;

Print:
   lodsb            ; grab a byte from SI and place it in AL
   cmp al, 0         ; is AL = 0?
   jc PrintDone         ; yep, we're done so return
   mov ah, 0eh
   int 0x10         ; nope, print the character
   jmp Print         ; loop until no more characters to be printed
PrintDone:
   ret            ; return to wherever we were!

;
; Start()
;      bootloader entry point
;

Start:
   mov si, creditmsg
   call Print         ; print the first message
   mov dh, 1         ; read 1 sector

.ReadSector:
   cli            ; disable interrupts
   push dx            ; push this stack value
   sti            ; re-enable interrupts

   mov ax, 0x1000         ; read sector into address 0x1000
   xor bx, bx         ; read sector into offset 0x0
   mov ah, 0x02         ; read sector function
   mov al, dh         ; read 1 sector
   mov ch, 0x0         ; must be 0x0 to read sector
   mov dh, 0         ; reading head 0
   mov cl, 0x02         ; start reading from sector 2 to load the second stage

   mov [CDDriveNumber], dl      ; store our drive number is variable CDDriveNumber
   cli            ; disable interrupts
   pusha            ; save the stack
   sti            ; enable interrupts

   int 0x13         ; INT 13h
   jc Error         ; handle error because Carry Flag is set

   pop dx            ; Restore DX

.ExecuteSector:
   ; now that our sector was loaded into address 0x1000:0x0, let's execute it!
   jmp 0x1000:0x0         ; jump to execute the sector
;
; Error()
;      handles errors when carry is set
;

Error:
   mov si, errmsg
   call Print         ; print an error message

   cli            ; disable interrupts to prevent problems
   hlt            ; halt the system... :(

; data section

creditmsg db "ISOSYS v1.0 by Omar Mohammad, Init...", 0
errmsg db "Cannot load the second stage. (File not found maybe?)", 0
CDDriveNumber db 0

times 2048 - ($-$$) db 0      ; fill in 2048 bytes with zeroes

; end of sector 1! :D Any more code here would take bytes 2048 and 2049 but we don't    need that...

This is boot.asm, the second stage:
bits 16
org 0x1000

Main:
   xor bx, bx
   mov ah, 0eh
   mov al, 'A'
   int 0x10

   cli
   hlt

times 2048 - ($-$$) db 0

I compiled with nasm -f bin isosys.asm -o ISOSYS and nasm -f bin boot.asm -o BOOT
Then I did mkdir iso and then cp ISOSYS iso/ then cp BOOT iso/ and then generated ISO:
genisoimage -no-emul-boot -boot-load-size 4 -eltorito-boot ISOSYS -o boot.iso iso/
I run it in VirtualBox but all it says is Cannot load the second stage (file not found maybe?) which means that Carry Flag is set but I can't seem to find the error.
Any help anyone?  Help would be greatly appreciated! :*

A: Your stack handling is totally off. You push dx (why?) inside a cli‥sti block (WHY?), then pusha but don't popa.
You're also missing a mov es,ax after the mov ax, 0x1000 to actually set the segment register to where you want your code to be loaded at.
You cannot read ISOs with the CHS function (AH=02h), you must use the LBA function (AH=42h) with a parameter block. Have an example.


text: Q: How to grab an adjacent maps image in google maps static API I'm using the Google Maps static API to retrieve an image. I'm trying to figure out a way to grab the image that would be directly to the north, essentially the next tile if it were a map. I know it will be based on the zoom, but I really can't figure out where to start. Any suggestions?


text:
Q: PHP Case-Insensitive LTRIM? I have an array of data I'm iterating through containing a Title and a Description. Each description currently begins with the corresponding title, so I want to ltrim() it off. Unfortunately, not all Titles were written in the same case format as used at the beginning of the description. I was going to use:
ltrim($description,$title)

but the case problem has stopped that.
Data EG:
array(
    array("title" => "Hello World", "description" => "Hello World This is a description"),
    array("title" => "Hellow world", "description" => "Hellow World This is a description"),
    array("title" => "Hello again", "description" => "HELLO AGAIN This is a description"));

ltrim($description,$title) would clean the first, but leave the others alone.
I didn't create the data I'm cleaning up btw, I've just taken over the job.
Anyway, ltrim() is case-sensitive (yes?) so I'm at abit of a loss as to how to go about this. Is there any other way of doing this?
edit
Forgot to mention, the Title DOESN'T ALWAYS appear in the description, just 90% of the time

A: ltrim is not the function you want in the first place. The second argument to ltrim is a charlist, so it will keep removing from the left of the string as long as one of the characters is encountered.
If every title is in every description you could use str_ireplace. And replace the title with nothing, and set the count to 1.
The better alternative is to use regular expressions.
preg_replace('/^'.preg_quote($title, '/').'\s*/i', '', $description);

This will replace the title if it is the first thing in the description, followed by any whitespace (so spaces/newlines will be removed if they come after the title. preg_quote is important to protect the regular expression incase the title contains any regex characters.

*

*preg_replace

*preg_quote


text:
Q: Is a PriorityQueue appropriate for this case? I've got a class which is little more than a pair (double, int). I need to keep two collections of these objects, both sorted by the double, one in ascending order and the other in descending order.
Example:
asc: [(4.0, 10), (4.5, 8), (5.2, 13), (6.0, 1)]
des: [(32.0, 20), (27.5, 2), (13.65, 4), (6.0, 100)]

The main usage pattern will be:

*

*Client enters with a pair (d, i);

*Check the head of one of the collections (depends on the client) for a pair lower (resp. higher), with respect to d, than the given pair;

*If it exists, either remove it or perform some calculations, based on the value of i;

*If it doesn't exist, or it wasn't removed, insert the given pair in the other collection, in the appropriate place.

So, the main operations are:

*

*Insert in order;

*Retrieve head;

*Remove head.

Example:

*

*Client enters with (4.2, 12) and wants to look at asc;

*asc has a pair with 4.0, which is lower than 4.2;

*Remove head of asc and look at the new head;

*The new head is higher than 4.2, so the client inserts the pair in des, at the tail, since 4.2 is lower than 6.0.

Since no client wants to traverse the collection, but rather process the current head, and since insertions have to be in order and quite fast, I'd say a PriorityQueue is the tool for the job.
Am I right, or is there a better data-structure in Java (no external libraries) that I'm not aware of?
An ArrayList, for instance, sounds terrible for this task, since insertions would happen at a random index, as opposed to inserting at the tail.

A:

*

*Insert in order

PriorityQueue.add() does that.

*

*Retrieve head

PriorityQueue.peek() does that.

*

*Remove head

PriorityQueue.poll() or PriorityQueue.remove() does that.
Seems like a perfect fit to me.


text:
Q: can build using visual studio ide but cannot build using devenv.com i'm using VS 2008. I can compile my solution using the IDE successfully. However, when I try to build it using devenv.com, it fails saying that "ERROR: Cannot find outputs of project output group '(unable to determine name)'.  Either the group, its configuration, or its project may have been removed from the solution." while building a .vdproj setup project.
A similar problem is here
any ideas to fix this?
thx
Edit: Actually cruisecontrol.net tries to build the solution using devenv.com. Here is the devenv section i use in ccnet.config:
<devenv>
      <solutionfile>xxxxx.sln</solutionfile>
      <configuration>Debug</configuration>
      <buildtype>Build</buildtype>
      <executable>C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.com</executable>
      <buildTimeoutSeconds>60000</buildTimeoutSeconds>
      <version>VS2008</version>
    </devenv>

A: It sounds like you have an invalid argument in the command line you pass to devenv.com.
Does it work ok if you create a new solution with a simple hello world project?
Cheers,
Sebastiaan

A: Have you tried using the MSBuild task instead of VisualStudio? I have always had better results with MSBuild, especially as it means you do not need VisualStudio installed on your Build Machine.
Here is a generic config based off what I use:
<msbuild>
    <executable>C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable>
    <workingDirectory>D:\dev\your\path\</workingDirectory>
    <projectFile>xxxx.sln</projectFile>
    <buildArgs>/v:m /noconlog /p:Configuration=Debug</buildArgs>
    <targets>Build</targets>
    <!--<logger>C:\Program Files\CruiseControl.NET\server\Rodemeyer.MsBuildToCCNet.dll</logger>-->
    <!-- If you dont have that logger for CruiseControl, you should try it :) -->
</msbuild>

If this does not work, you can also run it from a command line:
>cd "D:\dev\your\path\"
>D:
>C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe /v:m /p:Configuration=Debug xxxxx.sln

You can change the v (Verbosity) flag to something higher to get more output if you need (see msdn article on MSBuild here).