text:
Q: wso2 api manager 2.6.0 Suspending endpoint : AnonymousEndpoint with address https://{uri.var.hostname}:{uri.var.portnum}/oauth2/token I am observing ocasional errors while invoking the token endpoint, I can't tell why sometimes it works fine an some others if fails.
The invocation is made using the JWT bearer grant to exchange JWT token for an access token.
The log shows:
Token endpoint suspension:
INFO {org.apache.synapse.mediators.builtin.LogMediator} - STATUS = Executing token 'fault' sequence, ERROR_CODE = 303001, ERROR_MESSAGE = Currently , Address endpoint : [ Name : AnonymousEndpoint ] [ State : SUSPENDED ] {org.apache.synapse.mediators.builtin.LogMediator}
...
WARN {org.apache.synapse.endpoints.EndpointContext} - Suspending endpoint : AnonymousEndpoint with address https://{uri.var.hostname}:{uri.var.portnum}/oauth2/token - current suspend duration is : 30000ms - Next retry after : Thu Feb 11 18:21:38 CET 2021 {org.apache.synapse.endpoints.EndpointContext}

What could be the reason why it fails? Advice to fix it?
UPDATE
I've located the token anonymous endpoint configuration in repository/deployment/server/synapse-configs/default/api/_TokenAPI_.xml:
<api xmlns="http://ws.apache.org/ns/synapse" name="_WSO2AMTokenAPI_" context="/token">
    <resource methods="POST" url-mapping="/*" faultSequence="_token_fault_">
        <inSequence>
            <property name="uri.var.portnum" expression="get-property('keyManager.port')"/>
            <property name="uri.var.hostname" expression="get-property('keyManager.hostname')"/>
            <send>
                <endpoint>
                     <http uri-template="https://{uri.var.hostname}:{uri.var.portnum}/oauth2/token">
                        <timeout>
                            <duration>60000</duration>
                            <responseAction>fault</responseAction>
                        </timeout>
                    </http>
                </endpoint>
            </send>
        </inSequence>
        <outSequence>
            <send/>
        </outSequence>
    </resource>
    <handlers>
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerCacheExtensionHandler"/>
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.common.SynapsePropertiesHandler"/>
    </handlers>
</api>

How can I turn it into a named endpoint and disable the suspension?

A: Seems like your token endpoint is created inside your Synapse configuration itself. It is configured as an anonymous endpoint.
The error code of 303001 indicates that your token Endpoint is not ready to connect. Thus the token endpoint is not active at all the time and getting inactive after some transactions.
It is not created as a separate endpoint and persisted in DB or File system. It is recommended to use a named endpoint instead of your anonymous one.
And disable the suspension of the endpoint.
<suspendOnFailure>
    <errorCodes>-1</errorCodes>
    <initialDuration>0</initialDuration>
    <progressionFactor>1.0</progressionFactor>
    <maximumDuration>0</maximumDuration>
</suspendOnFailure>


text:
Q: Multipart/form-data with raw request body sending document I'm trying to figure out how to send a PDF Document to a Server via Rest but I want to achive this with only raw request body in Postman:
RAW Body in Postman:
------verycreativeboundary
Content-Disposition: form-data; name="type"

144
------verycreativeboundary
Content-Disposition: form-data; name="parent_id"

1571844
------verycreativeboundary
Content-Disposition: form-data; name="name"

documentName25.pdf
------verycreativeboundary
Content-Disposition: form-data; name="file"; filename="documentName25.pdf"
Content-Type: application/pdf
Content-Transfer-Encoding: base64

{yourbase64}
------verycreativeboundary--

in the header:
Content-Type multipart/form-data;boundary=----verycreativeboundary

the base64 I'm sending in {yourbase64} looks like this

JVBERi0xLjYNJeLjz9MNCjI0IDAgb2JqCjw8L0ZpbHRlci9GbGF0ZURlY29kZS9GaXJzdCAyMS9MZW5ndGggMjY...

With this I managed to get the pdf to the server but the pdf only contains the base64 as a string. So the PDF is broken.
So something does not decode the base64 to pdf.

What am I missing that the pdf data gets correctly decoded in the pdf?
Maybe I am doing something wrong with Content-Transfer-Encoding?
The application I need to do this has only the RAW Body method availably so I can't use other methods.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Push Back This Pointer into private static Member Vector I want to push-back the object itself to the class's static member variable. However i get "unresolved external symbol". My Idea is to collect selected Objects in a Container.
class ActionClass
{
public:
    ActionClass();
    ~ActionClass();
    int addAction();

private:
    static std::vector<ActionClass* const> instances;
};

int ActionClass::addAction()
{
    instances.push_back(this);
    return 0;
}

ActionClass::ActionClass()
{
}

ActionClass::~ActionClass()
{
}

A: You have to define this static variable in one of cpp files:
std::vector<ActionClass* const> ActionClass::instances;


text:
Q: Regex pattern with variable not working The following regex correctly extracts the path between the quotes.
const value = 'image-width("image-path.jpg")';
const result = value.match(/image-width\(['"]?(.+?)['"]?\)/)[1];

console.log(result); // image-path.jpg

But I need to make it more DRY because image-width might not always be the same, so I've made a function to make it possible for image-width to be a variable
function getPath(value, wrapper) {
    const regexString = `${wrapper}\\(['"]?(.+?)['"]?\\)`; // deliberate double back slash
    const patternMatch = new RegExp(regexString, 'g'); // /image-width\(['"]?(.+?)['"]?\)/g (which is the same as the working regex value above
    return value.match(patternMatch)[1]; // undefined
}

const path = getPath('image-width("image-path.jpg")', 'image-width'); // undefined

This doesn't work and path is just undefined.

A: The problem was the use of match() with the g modifier
Broken using .match()
function getPath(value, wrapper) {
    const regexString = `${wrapper}\\(['"]?(.+?)['"]?\\)`;
    const patternMatch = new RegExp(regexString, 'g');
    return value.match(patternMatch)[1];
}

const path = getPath('image-width("image-path.jpg")', 'image-width'); // undefined

Fixed using .exec()
function getPath(value, wrapper) {
    const regexString = `${wrapper}\\(['"]?(.+?)['"]?\\)`;
    const patternMatch = new RegExp(regexString, 'g');
    return patternMatch.exec(value)[1]; // Use exec() instead
}

const path = getPath('image-width("image-path.jpg")', 'image-width'); // image-path.jpg


text:
Q: How do I know when to use parenthesis when chaining datetime functions in python? I am learning Python and was hoping someone here can help clear something up for me.
I have the following code:
import pandas as pd

ser = pd.Series(['01-01-2010', '02-02-2011', '03-03-2012', '04-04-2013'])
ser_ts = pd.to_datetime(ser)

ser_ts_daynum = ser_ts.dt.weekday.tolist()
ser_ts_dayname = ser_ts.dt.day_name().tolist()

print(ser_ts_daynum)
print(ser_ts_dayname)

Why do I need parenthesis in day_name() when defining ser_ts_dayname, but not for weekday within ser_ts_daynum? I get an error if I try the opposite.
I feel like I'm missing something about how to chain functions in Python. I'm very familiar with piping in R (%>%) but things don't seem to work the same way in Python. Greatly appreciate any insight!

A: There is no direct way of knowing. Here are a few pointers to try to determine what to do:
1. Check the documentation
pandas.Series.dt.day_name gives a use case, with parentheses, while pandas.Series.dt.weekday is without parentheses.
2. Check the type
Methods needs parentheses to be executed
>>> type(ser_ts.dt.day_name)
method

This is more tricky to identify properties (which do not need parentheses) as the type of the linked object will be returned:
>>> type(ser_ts.dt.weekday)
pandas.core.series.Series

3. Check the signature/docstring (interactive interpreter)
When using ipython/jupyter or any interactive interpreter, you can add a ? at the end of the name (without parentheses)
If a property, this is a reference to a inner object, you do not need parentheses.
>>> ser_ts.dt.weekday?
Type:        property
String form: <property object at 0x7fd0234d3770>
Docstring:
The day of the week with Monday=0, Sunday=6.
...

else, you have a signature, this is a method, you need parentheses.
>>> ser_ts.dt.day_name?
Signature: ser_ts.dt.day_name(*args, **kwargs)
Docstring:
Return the day names of the DateTimeIndex with specified locale.
...

4. Give parentheses a try ;)
>>> ser_ts.dt.weekday()
TypeError: 'Series' object is not callable

OK, looks like you did not need it


text:
Q: Firebase | How can I change the App Distribution's App Icon I migrated Fabric project to Firebase. But I can't find any options for an app icon in the App Distribution.
How can I change my app icon?

A: Sending a new build with a new app icon can be a solution.
Yesterday I sent wrong which belongs to another app and the app icon changed to the new build's app icon.


text:
Q: Why are menu, vote and 'add comment' clicks ignored on Stack Exchange sites on my mobile device? About a week ago, the mobile version of Stack Overflow was working as expected on my Windows Phone. Since then, the menu button at the top right of the screen, the voting buttons and the 'add comments' links have stopped responding - clicking them has no effect. In a comment to this question there is a report of similar behaviour on an iPhone.
Deleting my browsing history did not make any difference.
I first noticed this on my Windows Phone 7, but I have since been able to reproduce similar behaviour in Internet Explorer 9 on a PC. This can be accessed via the 'mobile' link at the bottom of the page.
The experience that I have on the PC (with the mobile site) is described below. I understand from the comments that the mobile version is not supported on the desktop, but I have included it because I feel that the problems may be related.
When I hover over the down arrow in the top right of the screen on the PC, the cursor changes to a text insertion point "the I bar" rather than the pointing finger which usually indicates that something is clickable. Clicking has no effect.
When I hover over a vote icon, although a tooltip is displayed, the cursor does not change to indicate that the icon is clickable. Clicking has no effect.
I have also noticed some strange behaviour related to the links at the bottom of the page that allow users to swap between the mobile and full versions of the site. The cursor changes to a text insertion point when I hover over them. Also, clicking on this link in the meta.stackoverflow.com site has no effect other than to refresh the page.
Is anyone else able to reproduce this behaviour? Is there anything I can try to help isolate the problem?

A: This will be fixed with the next build.
Basically, a javascript error was introduced that only affected IE and prevented most (if not quite all) of the click handlers for mobile to not be registered on Windows Phone devices.
The lack of a cursor on hover will not be fixed, since it only manifests on desktop browsers.  It'd be a waste of bytes to fix it, essentially.


text:
Q: How to mount a VirtualBox shared folder at startup? I have Ubuntu installed in Virtualbox. I want to mount my VirtualBox shared folder in Ubuntu automatically when I log in Ubuntu. I put the following line in my ~./bashrc and ~/.bash_profile:
sudo mount -t vboxsf windows_share /media/windows_share

where windows_share is the name I created with Virtualbox. But everytime I start my Ubuntu, it asks me for passwd since it needs sudo. Is there anyway to automatically mount Windows share without entering password every time I log in?

A: For newer systemd based systems you need alternative approaches - the simplest being one mentioned in another answer to another question - which basically says that you need to add a special comment option to the /etc/fstab entry:
src     /my_mount/src_host  vboxsf  auto,rw,comment=systemd.automount 0 0

However for the above to work on some systems you need to check the 'Auto-mount' box in  VirtualBox's Shared Folders->Add dialogue, which means you can end up with a few duplicate mounts of the directory.
For a cleaner mount - without duplicate directories nor the need for 'Auto-mount' - you need to use systemd's mount and automount directives. To do so create two entries in /usr/lib/systemd/system/ named after your desired mount point e.g. to match the fstab mount point above they would be named my_mount-src_host.mount and contain:
[Unit]
Description=VirtualBox shared "src" folder

[Mount]
What=src
Where=/my_mount/src_host
Type=vboxsf
Options=defaults,noauto,uid=1000,gid=1000

and my_mount-src_host.automount:
[Unit]
Description=Auto mount shared "src" folder

[Automount]
Where=/my_mount/src_host
DirectoryMode=0775

[Install]
WantedBy=multi-user.target

Then they need enabling:
sudo systemctl enable  my_mount-src_host.automount
sudo systemctl enable  my_mount-src_host.mount

They will now mount on boot. If you want mount them immediately (provided the Shared Folders have been created) you can do so:
sudo systemctl start  my_mount-src_host.mount

Note if you have directories with odd names or dashes (-) in them then use systemd-escape to find the appropriately escaped name.

A: After an exhausting morning trying all the above in Ubutntu 16.04 running in Virtualbox 5.0.20 unsuccessfully (particularly disappointed that the rc.local solution didn't work), it worked by:

*

*Registering from Shared Folders menu of Virtualbox GUI the required directory but NOT automounting it or permanent mounting from Virtualbox. Otherwise the host dir is mounted by root and it's a pain to access by non-root users even from the admin group.

*adding simple entry in fstab:
[VirtuablBoxNameOfMount] /media/[guestOSuser]/[mountSubdir]    vboxsf   rw, noauto   0     1

Note noauto option - otherwise boot loader fails as has been noted.

*Add corresponding line to /etc/sudoers as follows by using command visudo from within guest OS:
ALL ALL = NOPASSWD: /bin/mount /media/[guestOSuser]/[mountSubdir]/

This will allow non-root processes to specifically mount this (as fstab can't mount with 'user' option ...)

*Add corresponding line to .profile of user:
sudo mount /media/[guestOSuser]/[mountSubdir]/

Now the selected host subdir is ready-mounted for the selected user upon login!

A: I tried the rc.local solution but couldn't get it to work.
However I discovered the problem seems to be related to the folder you run the command from (no idea why).  So I added a line to change the directory to my home folder before the mount command, and now it works.
So, my windows share is called Dropbox, my mountpoint is /home/jamie/Dropbox, my user name is jamie, this is what I put in rc.local:
cd /home/jamie
mount.vboxsf /home/jamie/Dropbox Dropbox vboxsf
exit 0

A: *

*Edit /etc/rc.local
sudo -H gedit /etc/rc.local

*Before exit 0 type:
mount.vboxsf windows_share /media/windows_share vboxsf

*Save

*(Optional) Create a shortcut to the desktop or home folder:
ln -s /media/windows_share /home/freddy/Desktop

In order to boot without errors like pressing S to skip mount or press M to manually repair you may have to delete your entry in fstab

A: I do it of a very similar mode at was proposed above but these script create the required and mount or unmount the shared folder with the following script:
#!/bin/bash
#
# Mount automatically even shared folder on startup and unmount it at shutdown.
#
# VirtualBox (c) 2015 by Oracle Systems Inc.
#
####

# Check user privileges.
if [[ $EUID -ne 0 ]]; then
    echo -e "This script must run at ROOT user!" \
        "\nPlease, use 'sudo', 'visudo' or any other to run it."
    exit 1
fi

# Check paramas from caller.
if [[ $# -eq 0 ]]; then
    echo -e "Auto-Mount selected shared folder of VirtualBox machine." \
        "\nUsage:" \
        "\n    VBoxShared <drive_one> <drive_two> <...>"
    exit 2
fi

declare EVENT=          # This set the ACTION: -m OR -u
declare -a DRIVES=()

# Processing each param:
for arg in "$@"; do
    case "$arg" in
        "-m"|"--mount")
            if [[ -z ${EVENT} ]]; then
                EVENT=-m
            else
                exit 318        # parameters at conflict!
            fi
            ;;

        "-u"|"--umount")
            if [[ -z ${EVENT} ]]; then
                EVENT=-u
            else
                exit 318        # parameters at conflict!
            fi
            ;;

        *)
            DRIVES=("${DRIVES[@]}" "${arg}")
            ;;
    esac
done
unset arg

[[ -z ${EVENT} ]] && exit 1             # ERROR: No se ha establecido la acción a realizar.
[[ "${#DRIVES[@]}" -gt 0 ]] || exit 1   # ERROR: No se han indicado las unidades a manejar.

# Process each shared folder stored on '${DRIVES}' array
for drive in "${DRIVES[@]}"; do
    DEST="/media/sf_${drive}"

    case "${EVENT}" in
        "-m")
            [[ -d ${DEST} ]] || (mkdir ${DEST} && chown root:vboxsf ${DEST} && chmod 770 ${DEST})
            mount -t vboxsf ${drive} ${DEST}
            ;;

        "-u")
            if [[ `df --output=target | grep "${DEST}"` > /dev/null ]]; then
                umount -f ${DEST}
                rm -rf "${DEST}"
            fi
            ;;
    esac
    unset DEST
done
unset drive

unset EVENT
unset DRIVES
exit 0

Save it as /opt/.scripts/VBoxShared.sh.
Make sure that this can be runned. On shell type:
sudo chmod a+x /opt/.scripts/VBoxShared.sh

Now, we add a line that run this script on rc.local:
sudo nano /etc/rc.local

and we add these line before last line (exit 0):
. /opt/.scripts/VBoxShared.sh --mount <SharedFolder1> [<SharedFolder2> <SharedFolder3> ...]

Save (CtrlO) and close it (CtrlX)
At this point, we mount automatically all shared folder listed on <SharedFolder> at startup.
For unmount it, we only need type:
sudo nano /etc/rc6.d/K99-vboxsf-umount.sh
#!/bin/bash

. /opt/.scripts/VBoxShared --umount <SharedFolder1> [<SharedFolder2> <SharedFolder3> ...]

exit 0

Save (CtrlO) and close (CtrlX)
sudo chmod a+x /etc/rc6.d/K99-vboxsf-auto.sh

And that's all!

A: Here is a working solution.
As root (I.E. sudo su) Go to home folder (cd ~) and create a cron file:
vi cronjobs
Add the following
@reboot   sleep 15; mount -t vboxsf app /mnt/app

Save file
Note: replace app with your shared folder name and /mnt/app where you want to mount it.  In this case I created the folder app under mount (mkdir app) first.
To enable your cron as root (for above filename)
crontab cronjobs
Make sure cron is active:
crontab -l
reboot and it will be mounted.  15 second sleep allows enough time for everything to be ready for the mount.

A: To always mount a Virtual Box "shared folder" on booting an Ubuntu guest we have two options. It is up to personal preference which option works best in our setting.
1. Mount with fstab
To mount a shared folder using the vboxsf filesystem provided with Guest Additions we first need to make sure prerequisites are met. Then we may put the following line in our etc/fstab file:
<name_of_share>   /path/to/mountpoint   vboxsf   <options>  0   0

Replace name_of_share and /path/to/mountpoint with your individual setup (the directory for the mountpoint has to be created first). See the manpage for mount <options>. One possibility is to mount with defaults, or to give specific mount options (e.g. rw, suid, exec, auto, users).
On some systems the vboxsf kernel module is not yet loaded at the time fstab is read on boot. It may then help to append the vboxsf kernel module to /etc/modules.
Some systems may need option comment=systemd.automount in their fstab entry (source).
2. Mount with Virtual Box "automatic mounting":
In recent releases of Virtual Box we can also automatically mount shared folders on creation:

After a reboot of the guest this shared folder will be mounted to the guest directory /media/<username>/sf_<name_of_share> accessible to all users who had been made member of the group vboxsf.

A: (In my case, my host OS is Mac OS X and my guest OS is ubuntu)
None of the above solutions, and the solutions mentioned here and here worked for me. There was a problem with all of them.
Here is what I finally did to solve the issue:
1- I created a shared folder in VirtualBox UI, pointing to a folder named VMShares in my Mac OS, naming it wd
2- Then I installed Ubuntu Guest Addition tools (restart required)
3- Then I made a folder in my guest OS as the mount point (in my case the name was /home/fashid/host)
4- Then I ran:
sudo VBoxControl sharedfolder list

This was the command to be ensured that the share is available to the guest OS, meanwhile you still need to mount it in your guest OS to make it actually available.
It will show something like:
Shared Folder mappings (1):
01 - VMShares

This is the trick! It is showing the actual name you need to put in below command to actually mount it and make it available in your guest OS:
sudo mount -t vboxsf VMShares /home/farshid/myshares

Did you realize the point? I did not use wd anywhere later. In step 3, I needed to pickup the actual (host) folder name instead of the arbitrary name I asigned in GUI dialog box.
Via above steps, my issue was solved.

A: I recently encountered this thread when, after updating to Ubuntu LTS-18 (and making no changes whatever to VirtualBox, and after reinstalling the extensions and blah-de-blah), auto-mount stopped working.  The sf_xxx directories were present in /media/ but none of them were actually mounted.
Attempts to mount them in /etc/fstab (as suggested by VirtualBox's own documentation) didn't work:  the boot failed into "emergency mode," even when I had modified the /etc/modules file.
What did eventually work – although I regard it as a stinkin' hack – is the crontab trick described above.
To this day, I have no idea "what broke."

A: I was having an issue where I could see the shared folder, but there were no files in it.  So I did a hack similar to what was shown above:
I made sure that my user was in the correct group(s), and that there was an entry in fstab for mounting the share, and that the permissions were set correctly, and that auto-mount was on in VirtualBox settings, but still no files to be seen.
So I opened up the Startup Applications app in the Ubuntu 18.04 GUI and created a task that simply ran "sudo mount -a" right at startup.  For whatever reason the shared folder was not being mounted correctly when fstab was automatically parsed at boot, so re-mounting everything seemed to fix the problem.  Now I can see the files in the share.

A: I tried all of the solutions here and none worked.
What worked was to install supervisor and run a python script.
install supervisor
apt-get install supervisor
python script (mine was at /home/ubuntu/shared_folders.py)
import subprocess
import os
import time

shared_folder = '/home/ubuntu/shared'

file_count = len(os.listdir(shared_folder))

mnt_command = 'mount -t vboxsf -o rw,uid=1000,gid=1000 shared-folder ' + shared_folder
if file_count == 0:
        # mount
        subprocess.Popen(mnt_command, shell=True)

time.sleep(3600)

create config file for supervisor
nano /etc/supervisor/conf.d/sharedfolders.conf
[program:shared_folders]
command=python shared_folders.py
directory=/home/ubuntu
process_name=%(program_name)s_%(process_num)s
numprocs=1
numprocs_start=0
autostart=true
autorestart=true
startsecs=1
startretries=3
exitcodes=0,2
stopsignal=TERM
stopwaitsecs=10
;user=pavelp
redirect_stderr=true
stdout_logfile=/var/log/supervisor/qlistener-stdout.log
stdout_logfile_maxbytes=50MB
stdout_logfile_backups=10
stdout_capture_maxbytes=0
stdout_events_enabled=false
stderr_logfile=/var/log/supervisor/qlistener-stderr.log
stderr_logfile_maxbytes=50MB
stderr_logfile_backups=10
stderr_capture_maxbytes=0
stderr_events_enabled=false
environment=APPLICATION_ENV=development
serverurl=AUTO
open supervisorctl
sudo supervisorctl
read configuration
reread
add configuration
add shared_folders


text:
Q: SQL statement for Google Sheets QUERY function I'm trying to use Query to comb out Make and Model from a block of text on "Sheet2" by referencing from a larger "Sheet1". Also at the same time  finding out the average price purchased and also how many was purchased in the past.
On sheet1; the reference database of all goods purchased. With Col1 = Brand, Col2 = Model  etc etc...Col5 = Purchase Price. Here items with the same Make and Model could be purchased at various times at different prices.
i.e
Col1 Col2  ... Col5
Apple iPad3  ... $600
Apple iPad3  ... $500
Apple iPad3  ... $400
Sheet2, is the content of a catalogue from a supplier, with Col1 being the description of the products available.
An example of a cell (A5) could read...
"New Apple iPad3 with slightly damaged box"
B5 would return the found Make search "Apple".
C5 would return the found Model search "iPad3"
D5 would return the average price found in search array "$500"
E5 would return the the qty that was found "3"
The trouble I'm experience now is that I cannot get all the above (both Make Model and Avg Price and Count) to co-exist in a single query pass.
This Query is inserted into B5, it's results fills B5, C5, D5...
=QUERY(Sheet1!A:F,"select A,B,F where A<>'' and B<>'' and '"&B5&"' contains A and
'"&B5&"' contains B limit 1 Label A'', B'', F''")

...will return Make Model Price (the first found instance only). What we need is the above with average and count.
=QUERY(Sheet1!A:F,"select avg(F),count(F) where A<>'' and B<>'' and '"&A5&"' contains A
and '"&A5&"' contains B label avg(F)'',count(F)''")

The above works, at retrieving the average and count.
But as soon as I try to get make and model as well, it fails...
=QUERY(Sheet1!A:F,"select A,B,avg(F),count(F) where A<>'' and B<>'' and
'"&A5&"' contains A and '"&A5&"' contains B label A'',B'', avg(F)'',count(F)''")

Many thanks in advance.

A: You need to group your output by the dimensions you are aggregating on.
=QUERY(Sheet1!A:F,
"select A,B,avg(F),
count(F) where A<>'' and B<>'' and '"&A5&"' contains A and '"&A5&"' contains B
group by A,B label A'',B'', avg(F)'',count(F)''"
)


text:
Q: css style don't apply inside TextView for
* and
* in iOS I'm showing HTML data inside TextView, padding space for
 or
 is more than required but I can't adjust padding/margin using CSS (I would prefer to do using CSS) from HTML side, any suggestion how to achieve it?

Professionals are often vastly more comfortable solving analytical, convergent problems than those requiring more divergent thinking. In this article, Olivier Leclerc and Mihnea Moldoveanu share some strategies for stimulating truly novel thinking.
    They introduce five "flexons," which can be thought of as "languages" for shaping problems that help you bring diverse perspectives to problem solving:

Networks

Evolutionary

Decision-agent

System dynamics

Information-processing :

Decision-agent

System dynamics

Information-processing

Networks :

Decision-agent

System dynamics

This is HTML, ul,ol {padding-left:10px;} of CSS doesn't apply.
Function to converting HTML String to AttributeText
 extension NSAttributedString {
    convenience public init?(styled: String, textAlignment: NSTextAlignment = .center, color: UIColor = .black) {
        guard let data = styled.data(using: String.Encoding.unicode) else {
            return nil
        }
        do {
            let string = try NSMutableAttributedString(data: data,
                                                       options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = textAlignment

            string.addAttributes(
                [NSAttributedStringKey.foregroundColor: color],
                range: NSMakeRange(0, string.length)
            )

            self.init(attributedString: string.removingTrailingNewLine)
        } catch {
            return nil
        }
    }

    var removingTrailingNewLine: NSAttributedString {
        if string.hasSuffix("\n") {
            return attributedSubstring(from: NSRange(location:0, length: length - 1))
        }
        return self
    }
}

Image shows padding is a bit more than it should be, but can't adjust it.

A: There's already a computed padding and margin value for the ol and ul and what you're looking at is the margin, so change the margin-left to zero or less then the original value.
Check this code:

  ul,
ol {
  border: 1px solid red; /* for display only*/
  margin-left: 0;
  padding-left: 50px;/* change this value and see how it works */
}

Professionals are often vastly more comfortable solving analytical, convergent problems than those requiring more divergent thinking. In this article, Olivier Leclerc and Mihnea Moldoveanu share some strategies for stimulating truly novel thinking. They
  introduce five "flexons," which can be thought of as "languages" for shaping problems that help you bring diverse perspectives to problem solving:

Networks

Evolutionary

Decision-agent

System dynamics

Information-processing :

Decision-agent

System dynamics

Information-processing

Networks :

Decision-agent

System dynamics


text:
Q: Serialize incoming JSON with dynamically changing fields I have fields in the JSON response that change dynamically.
A part of the structure of the response remains constant so I can define a POJO for those fields, but I'm trying to serialize the rest of the response (that is within a JSON object with the key "fields") as a JSONObject. But when I log the JSONObject its always empty. The POJO is given below :
public class Project {

    @SerializedName("projectid")
    public String mProjectId;
    @SerializedName("parentgroupid")
    public String mParentGroupId;
    @SerializedName("projectname")
    public String mProjectName;
    @SerializedName("formid")
    public String mFormId;
    @SerializedName("state")
    public String mState;
    @SerializedName("priority")
    public int mPriority;
    @SerializedName("headers")
    public ArrayList<Header> mHeaders;
    @SerializedName("fields")
    public JSONObject mFields;
}

mFields is always returned as an empty JSONObject.
How do I serialize this dynamically changing JSONObject(Its key remains the same, but the contents change)?

A: Please use JsonObject instead of JSONObject and check.
as JsonObject can use the Object definition to directly create an object of the desired type and it is best for JSON parsing on Android, while JSONObject needs to be parsed manually.
For more details about its method and properties, please refer this JsonObject

A: If using Retrofit, use JsonObject instead of JSONObject.


text:
Q: Location Permission not working as expected on safari browser When we are trying to fetch the location in safari browser for my website(which is under development as of now). We are getting popup(allow, don't allow) for location permissions. When i am allowing it is working fine But when i am disallowing first and then change it after going into preferences and change location permission for the website to allow and trying to fetch location for the user again on button click but is not working without reload.
I have tried in console also using below commented code but there also i am getting error and not able to get the location without reload.
Expected is it should work without reload if we are giving locations permissions by going to preferences for a website on safari browser.


text:
Q: How to access Jamara 038300 qcr? I've got a Jamara 38300 qcr quadrocopter but not controller for it. I want to control it with a ps3 controller, an app or just via windows Bluetooth. How can I achieve this?
I know that the quadrocopter sends with a 2.4 GHz frequency and the on board microcontroller is a SMT8S005K6.
Can I just catch the signal from the transmitter so that I know which exact types of orders I have to send and try out some or do I have to connect to the microcontroller via a SL-Link which is used to program the SMT8 and get the code which is already on the micro (something like reverse engineering) ?
I don't really want to buy a "normal" controller for quadrocopter.


text:
Q: Creating a handout with the notes on a second screen How can I print slides and their accompanying note pages from a second screen as a handout? I try to accomplish this look:

(preferably 3 slides and their 3 note pages per page, the spaces between the slides are not important).

Now when using \pgfpagesuselayout{8 on 1} some slides are missing and the positioning is completely wrong:
\documentclass{beamer}
\usepackage{pgfpages}

\setbeameroption{show notes on second screen}

\pgfpagesuselayout{8 on 1}

\setbeamercolor{background canvas}{bg=gray}

\begin{document}

    \fontsize{60}{64}\selectfont

    \begin{frame}
         Slide 1
        \note{\fontsize{60}{64}\selectfont Note 1}
    \end{frame}

    \begin{frame}
        Slide 2
        \note{\fontsize{60}{64}\selectfont Note 2}
    \end{frame}

    \begin{frame}
        Slide 3
        \note{\fontsize{60}{64}\selectfont Note 3}
    \end{frame}

\end{document}

If possible I would like to keep \setbeameroption{show notes on second screen}, because of this Beamer section page and show notes for every page question

A: I would just use pdfnup for the task:
pdfnup --nup 1x3 --no-landscape --scale 0.9 --delta "0 1cm" --no-tidy slides.pdf

yields a file slides-nup.pdf that with the intended layout:

The pdfnup shell script is part of the pdfjam collection, which is included in most Linux distros. For MacOS it is available via MacPorts, fink, or brew. On Windows, it should work together with cygwin or mingw, but I haven't tested that.
However, as pdfjam is just a wrapper around pdflatex and the pdfpages LaTeX package, you could as well employ pdflatex for the task directly (using an extra LaTeX document):
\batchmode
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{pdfpages}

\begin{document}
  \includepdfmerge[nup=1x3,scale=0.9,delta=0 1cm]{slides.pdf,-}
\end{document}

A solution for a reusable template:
For a reusable, platform-independent template using only pdflatex and no external tools, we could improve the above to a generic handout-from-slides generator.
The following assumes that your presentation template is named with a -slides suffix, that is,  <presentation>-slides.tex, which will then compile to a file <presentation>-slides.pdf. The following code should be provided as <presentation>-handout.tex.
If one compiles <presentation>-handout.tex, it does the follwing:

*

*Checks if <presentation>-slides.pdf does exists and prints an error if not

*Generates <presentation>-handout.pdf with the respective nup setting.

*Checks if <presentation>-slides.pdf was recent, that is, not older than <presentation>-slides.tex. Otherwise, it prints a warning.

Users just need to rename <presentation>-slides.tex and <presentation>-handout.tex accordingly and compile them in the "right" order (which is anyway the "natural" oder, as handout production usually comes last...)
% http://tex.stackexchange.com/questions/141194/creating-a-handout-with-the-notes-of-a-second-screen/141294
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{pdfpages}

% We assume that this file is named
%
%    <presentation>-handout.tex
%
% and that the actual material stems from a file
%
%    <presentation>-slides.pdf
%
% which itself is compiled out of the source file
%
%    <presentation>-slides.tex
%

\newcommand{\jobbasename}{}
\newcommand{\setjobbasename}{%
  \def\split##1-##2!!!{\def\jobbasename{##1}}%
  \expandafter\split\jobname!!!%
}

% after: \jobbasename is <presentation>
\setjobbasename

\begin{document}
  % Check if <presentation>.pdf does exist, otherwise typeout an error message
  \IfFileExists{\jobbasename-slides.pdf}{%
    % Include the material
    \includepdf[nup=1x3,scale=0.9,delta=0 1cm,pages=-]{\jobbasename-slides.pdf}
    % Check if <presentation.pdf> is older than <presentation.tex> and typeout a warning
    \ifnum\pdfstrcmp{\pdffilemoddate{\jobbasename-slides.pdf}}{\pdffilemoddate{\jobbasename-slides.tex}}<0%
      \typeout{}
      \typeout{WARNING: \jobbasename-slides.pdf seems to be out of date!}
      \typeout{\space\space\space\space\space\space\space\space\space Consider recompiling \jobbasename-slides.tex.}
      \typeout{}
    \fi
  }{%
    \typeout{}
    \typeout{ERROR: \jobbasename-slides.pdf not found!}
    \typeout{\space\space\space\space\space\space\space You need to compile \jobbasename-slides.tex first.}
    \typeout{}
  }
\end{document}


text:
Q: How to add items to page list using javascript I want to add pages on pages list, when btnAddPage is clicked opens a dialog with two inputs, addPageTitle and addPageTags but I don't know how to create those pages. I've already created Items to a custom list I've made and I've tried using the same function but it didn't work. Does anyone know how to add those two fields on a new item on pages list?
Update:
I've made some research and manage to find this code:
function createFile(resultpanel) {
   var clientContext;
   var oWebsite;
   var oList;
   var fileCreateInfo;
   var fileContent;

   clientContext = new SP.ClientContext.get_current();
   oWebsite = clientContext.get_web();
   oList = oWebsite.get_lists().getByTitle("Pages");

   fileCreateInfo = new SP.FileCreationInformation();
   fileCreateInfo.set_url("title.aspx");
   fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
   fileContent = "The content of my new file";

   for (var i = 0; i < fileContent.length; i++) {

       fileCreateInfo.get_content().append(fileContent.charCodeAt(i));
   }

   this.newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);

   clientContext.load(this.newFile);
   clientContext.executeQueryAsync(
       Function.createDelegate(this, successHandler),
       Function.createDelegate(this, errorHandler)
  );

function successHandler() {
    resultpanel.innerHTML =
        "Go to the " +
        "document library " +
        "to see your new file.";
}

function errorHandler() {
    resultpanel.innerHTML = "Request failed: " + arguments[1].get_message();
}
}

That works perfectly but still can't add anything to a field Tags.
Update 2:
The answer below indeed adds a page but a blank one, the whole document(site) is blank. So I went through Rest Api check what was wrong and found that was missing some attribute:
<d:PublishingPageLayout m:type="SP.FieldUrlValue">
  <d:Description>Basic Page</d:Description>
<d:Url>http://deliveryoffice.telecom.pt/_catalogs/masterpage/EnterpriseWiki.aspx</d:Url>
</d:PublishingPageLayout>

Does anyone knows how to add this?

A: Use set_item to set the associated field data for the page item and create with a page layout in master page Gallery like below:

This is the page layout in Master Page Gallery and the id is 7

This is the result, it will create a publishing page based on the default layout:

Reference Demo from here:
Create A Publishing Page In SharePoint Using Javascript Object Model


text:
Q: Create model for existing database table in django I have an old table in the database. And I want to create a model in Django application.
After creating a model and I used migrate command then it created a new table with its own name.

A: Django provides a utility to auto-generate models from an existing database via inspectdb command.
You can create models by introspecting an existing database by executing following command
python manage.py inspectdb

The above command will output all the models Django can create from the existing database to stdout. You can save this as a file by using standard Unix output redirection
python manage.py inspectdb > models.py # or pass the app_name.models.py if you want to generate them inside models.py file of specific app

The output file will be saved to your current directory. Move that file to the correct app and you have a good starting point for further customization.
you can refer https://docs.djangoproject.com/en/4.1/ref/django-admin/#django-admin-inspectdb for more information.

A: You can specify the table name by setting table on the model's Meta class. Set managed = False to prevent Django from creating the table.
class ExistingModel(models.Model):
    ...

    class Meta:
        table = 'existing_table'
        managed = False

After making these changes, I would revert the previous migration, remove the migration file, then run makemigrations again.


text:
Q: I want to create a data.frame with the values that I print of this loop in R When I run this Loop I can print the results and I want to create a data frame with this data but I cant. Until now I have this:
filenames <- list.files(path=getwd())
numfiles <- length(filenames)
for (i in 1:numfiles) {
  file <- read.table(filenames[i],header = TRUE)
  ts = subset(file, file$name == "plantNutrientUptake")
  tss = subset (ts, ts$path == "//plants/nitrate")
  tssc = tss[,2:3]
  d40 = tssc[41,2]
  print(d40)
  print(filenames[i])
}

A: This is not the most efficient way to do this, but it takes advantage of what code you've already written. First, you'll create an empty data frame with the columns you want, but filled with NA. Then, in each iteration of the loop, you'll fill one row of the data frame.
filenames <- list.files(path=getwd())
numfiles <- length(filenames)

# Create an empty data.frame
df <- data.frame(filename = rep(NA, numfiles), d40 = rep(NA, numfiles))

  for (i in 1:numfiles){
    file <- read.table(filenames[i],header = TRUE)
    ts = subset(file, file$name == "plantNutrientUptake")
    tss = subset (ts, ts$path == "//plants/nitrate")
    tssc = tss[,2:3]
    d40 = tssc[41,2]

    # Fill row i of the data frame
    df[i,"filename"] = filenames[i]
    df[i,"d40"] = d40

}

Hope that does it! Good luck :)

A: There are a lot of ways to do what you are asking. Also, without a reproducible example it is difficult to validate that code will run. I couldn't tell what type of data was in each of your variable so I just guessed that they were mostly characters with one numeric. You'll need to change the code if that's not true.
The following method is using base R (no other packages). It builds off of what you have done. There are other ways to do this using map, do.call, or apply. But it's important to be able to run through a loop.
As someone commented, your code is just re-writing itself every loop. Luckily you have the variable i that you can use to specify where things go.
filenames <- list.files(path=getwd())
numfiles <- length(filenames)

# Declare an empty dataframe for efficiency purposes
df <- data.frame(
  ts = rep(NA_character_,numfiles),
  tss = rep(NA_character_,numfiles),
  tssc = rep(NA_character_,numfiles),
  d40 = rep(NA_real_,numfiles),
  stringsAsFactors = FALSE
)

# Loop through the files and fill in the data
for (i in 1:numfiles){
  file <- read.table(filenames[i],header = TRUE)
  df$ts[i] <- subset(file, file$name == "plantNutrientUptake")
  df$tss[i] <- subset (ts, ts$path == "//plants/nitrate")
  df$tssc[i] <- tss[,2:3]
  df$d40[i] <- tssc[41,2]
  print(d40)
  print(filenames[i])
}

You'll notice a few things about this code that are extra.
First, I'm declaring the variable type for each column explicitly. You can use rep(NA,numfiles) but that leave R to guess what the column should be. This may not be a problem for you if all of your variables are obviously of the same type. But imagine you have a variable a = c("1","A","B") of all characters. R will go through the first iteration of the loop and guess that the column is numeric. Then on the second run of the loop will crash when it runs into a character.
Next, I'm declaring the entire dataframe before entering the loop. When people tell you that loops in [modern] R are slow it is often because you are re-allocating memory every loop. By declaring the entire dataframe up front you speed up the loop significantly. This also allows you to reference any cell in the dataframe...which is exactly what you want to do in the loop.
Finally, I'm using the $ syntax to make things clear. Writing df[i,"d40"] <- d40 is the same as writing df$d40[i] <- d40. I just think it is clear to use the second method. This is a matter of personal preference.


text:
Q: Magnific Popu get data attribute and put it in a variable Need help in getting data attribute and put it in a variable to be used in markup.  The attribute is "data-mydesc"
Any help is greatly appreciated.
html

javascript
                $('.thumbnails').magnificPopup({
                    type:'image',
                    delegate: '.image-additional a:visible',
                    image: {
                markup: '
'+
                        '

'+
                        '

'+
                        '

'+
                        '

'+
                    '
'+
                        '

'+
                        '
'+
                            '
',
                 cursor: 'mfp-zoom-out-cur',
                  tError: 'The image could not be loaded.'
                  },
                  preloader: true,
                    gallery: {
                        enabled:true
                    }

                });


text:
Q: Can Lipschitz maps increase the Lebesgue dimension ? Given a map $f:X\rightarrow Y$ of compact metric spaces, such that there is a $C\in \mathbb{R}$ with $d(f(x),f(x'))\le C\cdot d(x,x')$.
Does this already imply, that the Lebesgue dimension of $f(X)$ is at most the Lebesgue dimension of $Y$?
My motivation were space filling curves. All constructed examples were not rectifiable, so I was wondering, whether the additional assumption of being Lipschitz rules out the existence of space filling curves.

A: Let me add to the examples by Benoit and Victor another Cantor example, this time a straightforward naive one rather than ingenious.
Consider at and just after stage $0$ a closed interval $I$ with the standard (Euclidean) metrics but of length $\frac{11}{10}$. At stage $k>0$ remove the center open interval of length  $\frac 1{2^{k-1}\times 11^k}$ of each interval left after the previous stage $k-1$. After all stages $0\ 1\ \ldots$, in the remaining set $C$ in addition to the Euclidean metrics consider also the following pseudo-metrics:
$$d(x\ y) = |x-y| - s_{x\ y}$$
where $s_{x\ y}$ is the sum of the lengths of all removed intervals which are between points $x\ y$. The identity map from Euclidean $C$ to $C$ with the pseudo-metric $d$ is Lipschitz with constant 1. Let $C'$ be the metric space induced by $C$. Then $C'$ is homeomorphic to a nondegenerated closed interval, and the map induced by the identity on $C$ is Lipschitz with constant 1.
Actually, C' is isometric with the unit Euclidean interval $[0;1]$.

A: The answer to your first question is No. It is natural, as Lebesgue dimension is a topological invariant.
There is a very simple example, which took me however a little time to figure out. Consider the Cantor set obtained by recursively replacing a square by four squares of $1/4$-th side length, one at each corner, endowed with the metric inherited from the Euclidean one. There is an orthogonal projection that maps this Cantor set onto a segment, see
(source)
Such a map is $1$-Lipschitz, but a segment has Lebesgue dimension $1$ while a Cantor set has Lebesgue dimension $0$.
What you need to rule out Lipschitz space-filling curves is for example Hausdorff dimension.

A: There are no Lipschitz space filling curves.  For a gentle introduction to where this question leads, see http://eprints.nuim.ie/1626/1/SBuckleycurvesfunctions41.pdf. Theorem 3 is the classical result you want.

A: A similar but even simpler example: take a Cantor set on $[0,1]$ having positive measure, and transport it optimally to a segment with the same measure.


text:
Q: I need help mocking a method in my c# project I'm fairly new to this TDD and I'm lost with this at the moment.
I'm trying to use .Setup to get the product by ID of 99 and check it's actually returned in .Returns(saveProduct), which causes me the error below:
enter image description here
What am I doing wrong?
public class ProductControllerTests
{
    private Mock<ICart> cartMock;
    private Mock<IProductRepository> productRepositoryMock;
    private Mock<IOrderRepository> orderRepositoryMock;
    private Mock<IProductService> productServiceMock;
    private Mock<ILanguageService> languageServiceMock;
    private Mock<IStringLocalizer<ProductService>> stringLocalizerMock;
    private ProductViewModel product;

    private ProductController productController;

    public ProductControllerTests()
    {
        //setup
        product = new ProductViewModel();
        cartMock = new Mock<ICart>();
        productRepositoryMock = new Mock<IProductRepository>();
        orderRepositoryMock = new Mock<IOrderRepository>();
        stringLocalizerMock = new Mock<IStringLocalizer<ProductService>>();
        productServiceMock = new Mock<IProductService>();
        languageServiceMock = new Mock<ILanguageService>();
        productController = new ProductController(productServiceMock.Object, languageServiceMock.Object);

    }

    [Fact]
    public void CreateValidModelState() // MOCKED
    {
        // Act
        ProductService productService = new ProductService(cartMock.Object, productRepositoryMock.Object, orderRepositoryMock.Object, stringLocalizerMock.Object);

        productController = new ProductController(productService, languageServiceMock.Object);

        productServiceMock.Setup(x => x.SaveProduct(product)); //It works without this?!? what's it FOR!?

        //Arranje

        product.Id = 99;
        product.Name = "Test box";
        product.Description = "The best box ever.";
        product.Details = "Toss it and see if it gets back.";
        product.Stock = "9000";
        product.Price = "9000";

        var saveProduct = productController.Create(product);

        //productServiceMock.Setup(x => x.GetProductById(It.IsAny<int>())).Returns(saveProduct);
        //productServiceMock.SetupGet(x => x.GetProductById(99)).Returns("Test box");

        //var expectedProduct = productServiceMock.GetProduct(1);

        Assert.IsType<RedirectToActionResult>(saveProduct);

    }

}

}

A: There is a lot of room for improvement in your code snippet.
First, you create private members but then you over write the variable name with local variables.
The idea behind mocking is that when you mock an interface you can Setup its' methods to return whatever you wish them to return. So in your case
productServiceMock.Setup(x => x.GetProductById(99)).Returns(saveProduct);

the line above means that wherever in your controller you have the GetProductById(int) method is called with 99 as a parameter, the method will return the saveProduct object.
You could also write the Setup like
productServiceMock.Setup(x => x.GetProductById(It.IsAny<int>())).Returns(saveProduct);

In this case wherever in your controller the GetProductById() method is called, no matter what is the parameter passed, you will get the saveProductObject.
In this test you have written I can not see any value. What I mean is that create a controller, you create the saveProduct and then you assert it is not null. Of course it is not null, because you populated above.
It would make sense to actually use one of your controllers methods that you know that the GetByUserId() method is used. Then make an assertion upon the return object based on the methods logic.
---Update---
Imagine you have a handler
public class HandlerExample {

    private IInjectedService _injectedService;

    public HandlerExample(IInjectedService injectedService){
        _injectedService = injectedService;
    }

    public int Handle(testNumber)
    {
        var serviceResponse = _injectedService.TestMethod(testNumber);

        if(serviceResponse)
            return 1;

        return 2;
    }
}

And your interface looks like
public interface IInjectedService
{
    bool TestMethod(int testNumber);
}

I won't give any example on the implementation here because it is not relevant. Your test method would then make sense to be like
[Fact]
public void Test()
{
    mockedInjectedService = new Mock<IInjectedService>();
    mockedInjectedService.Setup(x => x.TestMethod(99)).Returns(true);

    var handler = new Handler(mockedInjectedService.Object);

    var sut = handler.Handle(99);

    Assert.Equal(sut, 1);
}

sut is a convention for "system under test"


text:
Q: Airflow and Google Sheets I'm new to Airflow and Python. I'm trying to connect Airflow with Google Sheets and although I have no problem connecting with Python, I do not know how I could do it from Airflow.
I have searched for information everywhere but I only find Python information with gspread or with BigQuery, but not with Google Sheets.
I would appreciate any advice or link.

A: As far as I know there is no gsheet hook or operator in airflow at the moment. If security is not a concern you could publish it to the web and pull it in airflow using the SimpleHttpOperator.
If security is a concern I recommend going the PythonOperator route and use df2gspread library. Airflow version >= 1.9 can help obtaining credentials for df2gspread


text:
Q: Employee no longer with the company When an employee is fired or let go, it is critical to disable their accounts and access to resources immediately.  How do you handle this at your organization?

A: HR should coordinate with IT before the employee is actually terminated.  This way, IT can remove access before the action takes place.  This is important because it prevents the employee from deleting or removing data that they either a) didn't want the company to see or b) wanted to delete to harm the company (via time loss, research loss, record loss, etc) in some way.
It is also important to have IT not remove any data, for similar reasons as with b).  Companies often need to go back and retrieve the data of prior employees for legal reasons in addition to business continuity reasons.  IT should only grant access to this data to people approved by HR.

A: First: Make it your process to tell I/T before you tell the employee that they have been terminated. Have them taken out before they know they're fired.
Second: Keep careful, detailed records of all systems that the user has access to, and remove them in order of priority. Make sure the people in I/T understand whose responsibility it is to remove each piece of access.
Third: In the event of an "off the cuff" firing, detail someone to keep an eye on the employee until I/T finishes removing their privileges.

A: Assuming you aren't firing them for fraud or anything.
Before you start a policy of putting black bags over their head, and dragging them kicking and screaming from the building - consider what future interaction you are going to have with them.
If you need to call a ex-sysadmin a week later to ask how some system you have forgotten about actually works it helps to have dealt with them as a professional not as a potential terrorist.

A: You simply implement the pre-arranged procedure.
i.e. the most important thing is that you've already got a plan and not just scrabbling around doing what comes to mind at the time. If you have months to think about and develop a plan it'll be so much better than if you think about it off the cuff.
Oh and for what it's worth I'd say worry more about physical things (keys, building access, user storage, copies of media) than locking out electronically - most malicious data loss comes in these ways than via purely electronic ways.

A: *

*coordinate with HR

*turn off computer while employee is being fired/let go

*HR escorts employee from the building

*at the very least change passwords on accounts

*determine if accounts need to be saved/gone through, etc.

*take appropriate action from here (delete accounts, archive accounts, forward email for a bit, etc.)

As a side note, it's a much more lengthy and immediate issue if it's an I.T. person that you have to let go, given the amount of admin access they may have to everything.

A: This is more of a procedural question than a technical one. Basically, you need to have a provisioning process and a de-provisioning process. People tend to forget about de-provisioning.
That process might be as simple as "call so and so and create accounts" or may involve opening help desk tickets or may be done by an enterprise application. That isn't really relevant -- what is relevant is that you need to handle this stuff consistently and have a pre-arranged plan.
We have a few user identity stores and a delegated admin model. Essentially, a designated rep  in each business unit can access the provisioning system and setup user accounts. A ticket is opened with IT support to assign/deassign PCs, and a ticket with another organization takes care of ID/building/parking access cards.
What happens to data depends on the organization. Places that get sued often tend to purge first, ask questions later. Other places vary widely. I've worked in some places that purged everything, other places that kept critical data in the home directory of an engineer who left 5 years earlier.
I think the best practice is to "impound" the PC and home directory data for a few weeks, then delete everything unless there is a good reason not to.

A: Every system needs a system owner who's responsible for this. They could delegate tasks like this to that system's administrator but it's the owners task to initiate change hence the owner should know if to prioritize access removal and so on. Depending on the size, the CSO or whatever the english title for the information security officer is should coordinate and/or request specific routines to follow when this happens.
Have a manual routine/policy to begin with if the ownerships aren't clear enough and then start automating the parts that seem costly or generally problematic.
Going the whole way there are identity life-cycle systems to look for as well to help in managing this.


text:
Q: How to run two functions in parallel in python when one collects data from the other? I'm new to multiprocessing and want to collect data in one function and write data in another function simultaneously. Here's a psuedocode of what I have.
def Read_Data():
 for num in range(0,5):

     ## Read 5  random values

     print('Reading ' + str(values[num]))
 return(values)

def Write_data(values):

 ## Arrange the random values in ascending order

 for num in range(0,5):
     print('Writing' + str(arranged_values[num]))

if __name__=='__main__'
  values = Read_Data()
  Write_data(values)

I want the output to look like this.
reading 1, writing none
reading 3, writing none
reading 5, writing none
reading 4, writing none
reading 2, writing none
reading 7, writing 1
reading 8, writing 2
reading 10, writing 3
reading 9, writing 4
reading 6, writing 5

Now the reason I want it to run parallel is to make sure I'm collecting data all the time and not losing data while I'm modifying and printing.
How can I do it using multiprocessing?

A: This should illustrate a few concepts. The queue is used to pass objects between the processes.
The reader simply gets its value somewhere and places it on the queue.
The writer listens on the queue forever.
Adding a "TERMINATED" signal is a very simple way of telling the writer to stop listening forever (there are other more effective ways using signals and events but this just illustrates the concept).
At the end we "join" on the two processes to make sure they exit before we exit the main process (otherwise they are left hanging in space and time)
from multiprocessing import Process, Queue
from time import sleep

def reader(q):
    for i in range(10):
        print("Reading", i)
        q.put(i)
        sleep(1)
    print("Reading TERMINATED")
    q.put("TERMINATE")

def writer(q):
    while True:
        i = q.get()
        if i == "TERMINATE":
            print("Writer TERMINATED")
            break
        print("Writing", i)

q = Queue()

pr = Process(target=reader, args=(q,))

pw = Process(target=writer, args=(q,))

pw.start()

pr.start()

pw.join()
pr.join()


text:
Q: javascript/jquery not working after migrating website to another server I have been trying really hard to get my website up and working, but for some unknown reason I am not able to get it work like the it was working before the migration.
The problem that I am facing is that Javascript/jQuery are not working on the website after migration. I have installed jquery update as well, but it still does not work. I have even tried adding same js file using preprocess_html hook, but it does not work as well.
I am using Drupal Commerce Kickstart distribtion and Kickstart theme based on Omega. Before the "products page" listing was showing buttons like this:

And now buttons are being shown like this:

Also jQuery code that was working before on the website is not working now. I have even tried changing jQuery versions in jQuery update module, but they did not help.
Any suggestions and workarounds are warmly welcome. It has been three long days and I am still unable to figure out what is causing this problem
Thank you so much.


text:
Q: How to pass matrix as paramter in pthread_create() function? I have just started with O.S programming and was exploring threads. I want to multiply 2 matrices and get their product using the pthread_create(), pthread_join() and pthread_exit() functions. However, pthread_create() takes input as void* whereas, I want to pass an int** parameter.
I already tried:

*

*Passing m3 [my resultant matrix] in the pthread_create() function by typecasting it as (void*) and then typecasting it back to (int**) in my threadMultiply function but that didnt work

*Putting m1,m2,m3 as global variables but that too gave me errors.

I am very confused and don't know how to approach this anymore. Any help would be much appreciated, thanks
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

int** alloc(int, int);
void display(int**, int, int);
void* threadMultiply(void* para);

int main()
{
    int r1,c1,r2,c2,r3,c3;  // rows and columns of each matrix
    int **m1, **m2, **m3;   // all 3 matrices

    // took inputs for r1,c1,r2,c2
    m1=alloc(r1,c1);
    printf("Enter the %d elements of the first matrix\n", r1*c1);
    for(int i=0;i<r1;i++)
        for(int j=0;j<c1;j++)
            scanf("%d", &m1[i][j]);
    m2=alloc(r2,c2);
    printf("Enter the %d elements of the second matrix\n", r2*c2);
    for(int i=0;i<r2;i++)
        for(int j=0;j<c2;j++)
                scanf("%d", &m2[i][j]);
    display(m1, r1, c1);
    display(m2, r2, c2);

    if(c1 != r2)
    {
        printf("\nMatrices cannot be multiplied, check dimensions");
        return 0;
    }

    r3 = r1;
    c3 = c2;
    m3=alloc(r3,c3);
    int MAX_THREADS = r3*c3;
    pthread_t threads[MAX_THREADS];

    // Creating threads.
    for (int i = 0; i < MAX_THREADS; i++)
    {
        int *p;
        pthread_create(&threads[i], NULL, threadMultiply, (void*)(p));  //variable 'i' is of type int however function takes parameter of type void* so we have to do type-casting
    }

    // joining and waiting for all threads to complete
    for (int i = 0; i < MAX_THREADS; i++)
        pthread_join(threads[i], NULL);

        printf("\nThe resultant matrix is:");
        display(m3, r3, c3);

return 0;
}

int** alloc(int row, int col)
{
    //dynamic memory allocation for first 2 matrices
    int **m=0;
    m=(int**)malloc(row*sizeof(int*));

    for(int i=0;i<row;i++)
    {
        *(m+i)=(int*)malloc(col*sizeof(int));
    }

return m;
}

void *threadMultiply(void *para)
{
    int i,j,k;
    for(i=0;i<r1;i++)
    {
        for(j=0;j<c2;j++)
        {
            m3[i][j] == 0
                for(k=0;k<c1;k++)
                    m3[i][j]+=m1[i][k] * m2[k][j];
        }
    }
    printf("thread finished ...");
    pthread_exit(NULL);
}

EDIT:
So after reading the comments, I tried this again. The code compiles but gives me a segmentation fault and doesn't display the second matrix
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

typedef struct matrix {  // using struct to reference 2 matrices in the threadMultiply function
    int r1, c1, r2, c2;
    int **m1;
    int **m2;
}mat;

int** alloc(int, int);
void display(int**, int, int);
void accept(int**, int, int);
void* threadMultiply(void* para);

int main()
{
    int r1,c1,r2,c2,r3,c3;  // rows and columns of each matrix
    int **a, **b, **c;  // all 3 matrices
    long int *ret_value;    //using long int, since int cannot be type casted to void
    mat *m;
    printf("Enter the number of rows and columns(m x n) of the first matrix\n");
        printf("Rows=");
        scanf("%d", &r1);
        printf("Columns=");
        scanf("%d", &c1);
        a=alloc(r1,c1);
        printf("Enter the %d elements of the first matrix\n", r1*c1);
    accept(a,r1,c1);
        printf("Enter the number of rows and columns(m x n) of the second matrix\n");
        printf("Rows=");
        scanf("%d", &r2);
        printf("Columns=");
        scanf("%d", &c2);
        b=alloc(r2,c2);
        printf("Enter the %d elements of the second matrix\n", r2*c2);
    accept(b,r2,c2);
    printf("\nThe first matrix is:");
    display(a, r1, c1);
        printf("\nThe second matrix is:");
        display(b, r2, c2);

        if(c1 != r2)
        {
            printf("\nMatrices cannot be multiplied, check dimensions");
            return 0;
        }

        r3 = r1;
        c3 = c2;
        c=alloc(r3,c3);
        m->m1 = a;
    m->m2 = b;
    m->r1 = r1;
    m->c1 = c1;
    m->r2 = r2;
    m->c2 = c2;

    // Creating one thread for each operation
    int MAX_THREADS = r3*c3;
    pthread_t threads[MAX_THREADS];
    for (int i = 0; i < MAX_THREADS; i++)
    {
        pthread_create(&threads[i], NULL, threadMultiply, (void*)(&m));
    }

    // joining and waiting for all threads to complete
    for(int i=0;i<MAX_THREADS;i++)
    {
        for(int j=0;j<r3;j++)
        {
            for(int k=0;k<c3;k++)
            {
                //joining all the threads and retreiving value in ret_value
                if(pthread_join(threads[i],(void **) &ret_value) != 0)
                    perror("\nThread join failed.\n");
                c[j][k] += (long int)ret_value;   // int doesn't work here for some reason
            }
        }
    }

        printf("\nThe resultant matrix is:");
        display(c, r3, c3);

return 0;
}

int** alloc(int row, int col)
{
    //dynamic memory allocation for first 2 matrices
    int **m=0;
    m=(int**)malloc(row*sizeof(int));

    for(int i=0;i<row;i++)
        *(m+i)=(int*)malloc(col*sizeof(int)); //m+i so that we can access all the rows by incrementing value of i. (m+i) = m[i]

return m;
}

void display(int **m, int r, int c)
{
    int i,j;
    for(i=0;i<r;i++)
    {
        printf("\n[");
        for(j=0;j<c;j++)
        {
            if(j<c-1)
            {
                printf("%d\t", m[i][j]);
            }
            else
            {
                printf("%d]", m[i][j]);
            }

        }
    }
}

void accept(int **a, int row, int col)
{
    int i, j;
    printf("Enter the elements\n");

    for(i = 0; i < row; i++)
        for(j = 0; j < col; j++)
            scanf("%d", (*(a + i) + j));  //same as a[i][j]
}
void *threadMultiply(void *para)
{
    mat *m = (mat*)para;
    int i = m->r1;
    int j = m->r2;
    int k = m->c2;
    long int return_val = m->m1[i][k] * m->m2[k][j];
    printf("\nThread finished ...");
    pthread_exit((void *) return_val);
}

A: Recommendation: Pointer declaration (cppreference.com)
There in the sections,
Explanation

Pointers are used for indirection, which is a ubiquitous programming technique; they can be used to implement pass-by-reference semantics, to access objects with dynamic storage duration, to implement "optional" types (using the null pointer value), aggregation relationship between structs, callbacks (using pointers to functions), generic interfaces (using pointers to void), and much more.

Pointers to void

Pointer to object of any type can be implicitly converted to pointer to void (optionally const or volatile-qualified), and vice versa:
...
Pointers to void are used to pass objects of unknown type, which is common in generic interfaces: malloc returns void*, qsort expects a user-provided callback that accepts two const void* arguments. pthread_create expects a user-provided callback that accepts and returns void*. In all cases, it is the caller's responsibility to convert the pointer to the correct type before use.

How does this apply to your code
In your main function:
// Creating threads.
for (int i = 0; i < MAX_THREADS; i++) {
    int *p; // <- WARNING: pointer to int is uninitialized
    pthread_create(
        &threads[i],
        NULL,
        threadMultiply,
        (void*)(p) // <- here you don't have to cast to void*
    );
}

The pointer p is uninitialized. Assign to p the address of any object you want to pass as argument (parameter) to the thread starting function.
Since you can pass only one argument, there is a problem if your multiply function requires three matrices (and their row and col counts). Therefore, you can pack the information into a struct.
Example:
//global
struct arg {
    int r1, c1, r2, c2, r3, c3;
    int **m1;
    int **m2;
    int **m3;
};

int main()
{
    //...

    struct arg p = {
        r1, c1,
        r2, c2,
        r3, c3,
        m1, m2, m3
    }; //for demonstration purposes only,
       //normally you would have to allocate a struct for each thread

    pthread_create(&threads[i], NULL, threadMultiply, &p); //need address of operator

    //...

}

In order to avoid the introduction of a new struct, you can of course declare all the variables global, but with the struct you can pass different parameters to different threads (simultaneously).
Then the multiply function:
void *threadMultiply(void *para)
{
    struct arg *p = para; //implicit cast
    int r1 = p->r1;
    int c1 = p->c1;
    //...
    int **m1 = p->m1;
    //...
    //do your multiplication
}


text:
Q: Question about completeness of the space of bounded linear operators.
Let $(X,\|\cdot\|_X)$ be a Banach space and $(Y,\|\cdot\|_Y)$ be a normed linear space. Can we say that $(B(X,Y),\|\cdot\|_{\text {op}})$ is Banach?

I know that if $Y$ is Banach then regardless of what the space $X$ is, the space $B(X,Y)$ is necessarily Banach. One of my friends claimed that if $Y$ is not Banach then $B(X,Y)$ cannot be Banach. What he claimed is even much stronger than that. He claimed that $Y$ and $B(X,Y)$ are isometrically isomorphic regardless of the space $X.$ I don't think so because then what is the necessity of $X.$ Can anybody please shed some light on it?
Thanks for your time.

A: $\textbf{Proposition}$. If $B(X,Y) $ is a Banach space (with the operator norm), then $Y$ is also complete.
Proof.  Let $ (y_n)_n \subset Y $ be a Cauchy sequence and let  $ f \in X^* \setminus \{ 0 \}$. For all  $ n \in \mathbb N $, define  $  T_n \colon X \to Y$, by  $ T_n(x) = f(x) y_n $. Then,  $ T_n $ is linear and bounded, for all $  n \in \mathbb N $. To see that it is bounded, notice that
$ || T_n(x)||  = | {f(x)}| \ ||{y_n}|| \leq  ||{f}|| \ ||{y_n}|| \ ||{x}||$, for all $ x \in X $. Moreover, $ || {T_n-T_m} ||= \sup_{x \in B_X} |{f(x)}| \ ||{y_n - y_m}|| \xrightarrow{n.m \to \infty} 0$. Hence,   $ (T_n)_n \subset  B(X,Y) $ is a  Cauchy sequence. By completeness, we can find  $ T \in B(X,Y) $ such that
$ T_n \to  T$ in the operator norm. Pick any  $ x \in X \setminus \ker f $, then  $ T_n(x) \to T(x) $ and thus  $ y_n \to T(x) / |{f(x)}| \in Y $.
$\textbf{EDIT}$: It is true that $B(X,Y)$ is isometric to $Y$. Let $f \in X^*$ with $||f||=1$. Consider the map
$$ Y \ni y \mapsto T_y \ \colon X \to Y ~~~\text{ where } ~~~T_y(x)=f(x) y. $$
This map is linear and for all $y \in Y$, $||T_y|| = \sup_{x \in B_X}|f(x)| \ ||y||= ||y|| \ ||f||=||y||$. In other words, it's a linear isometry.


text:
Q: CSS nth-child for a range of elements I'm a bit new to using nth-child() so any help would be greatly appreciated.  I'm trying to use it in my css file and not directly into the html.  Below is my code - I want to highlight the first four items that populate into this list.

                        @icd.ICDCode

                @Html.TextAreaFor(m => icd.UserText, new { @class = "span11", id = "icd_" + Model.Encounter.DictationID.ToString() + "_" + icd.ICDCode.Replace('.', '-'), icd = icd.ICDCode })

I'm trying to use a class like this: .primary-billing .div:nth-child(-n+4), but it doesn't seem to work properly.
Please help.

A: You just need to change .div to div (it's an element, not a class).
See here: http://jsfiddle.net/sQCCA/


text:
Q: Workaround for running php on a static page? I have a 'contact me' hosted on a git page that runs a very simple php script (name, email, anti-spam check, and message).
Now I understand that gitpages are static, and do not run any server side code, but I was wondering if there is a work around for this - say, running the php on an external php web service provider? Or using a built in webserver? Or embedding google forms?
I'd appreciate any help, or if you can point me in the right direction with my options.

A: If you're talking about GitHub pages: it would be a serious security issue if GitHub were to let its users run PHP scripts uploaded by them. The GitHub page is meant for showcasing and explanation, rather than running scripts. It's therefore rather fishy that you need to run a script every time someone visits your page.
As for embedding, you should see if GitHub allows this, I have not set up a GitHub page myself but I would be surprised if they'd let you embed external pages.

A: IF GitHub allows it, use a off-site page to handle the script OR just use C-forms: https://form.c-sol.no
GitHub page:
<form action="http://your-site.tld/formsubmit.php" method="post">
FORM CONTENT
</form>

formsubmit.php:
<?php
session_start();
$Name = html_specialchars($_POST['Name']);

//Your sendmail script
?>

Of course make sure that it is allowed by GitHub :)
Good luck.


text:
Q: What is the difference between -H and -L options of chown? From the chown manpage:
The following options modify how a hierarchy is traversed when the -R option is also specified.  If more than one is specified, only the final one takes effect.

-H     if a command line argument is a symbolic link to a directory, traverse it

-L     traverse every symbolic link to a directory encountered

-P     do not traverse any symbolic links (default)

What is the exact difference between the -H and -L options? As I understood it, -H allows for directory symlink  traversal only when that directory is specified as argument, where -L traverses all directory symlinks  in any case.
(These options apply only when chowning recursively using the -R option. In non-recursive mode, a directory symlink specified as argument is always traversed.)  Is this correct?

A: Your understanding is correct; these options match the same options in find.
Thus
chown -R .

or
chown -R -P .

changes the owner recursively without de-referencing any symlinks;
chown -R -H *

changes the owner recursively, de-referencing any symlinks in the current directory (since they end up being part of the arguments) but
chown -R -H .

still doesn't de-reference any symlink, and finally
chown -R -L .
chown -R -L *

both de-reference syminks.
(As an aside for the examples above, note that . and * don't necessarily result in the same outcome, depending on your shell's globbing options — * typically doesn't match dotfiles.)


text:
Q: How to configure lighttpd to only allow current subnet to access? I'm new to lighttpd. Here is the goal I want to achieve. I want only the client in my current can access my lighttpd server. For example, current ip address of lighttpd server is '192.168.10.100', only the client with ip address '192.168.10.0/24' can aceess the lighttpd server. The server ip address may change. How to configure lighttpd to only allow current subnet to access?
Here is what I tried. I don't know how to fill the remoteip value. Can anyone help me out? Thanks in advance.
$HTTP["remoteip"] == "192.168.10.0/24" {

}

A: See https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModAccess
server.modules += ( "mod_access" )

$HTTP["remoteip"] != "192.168.10.0/24" {
  url.access-deny = ("")
}


text:
Q: Apply Maven mirror to archetypes In my settings.xml, I redirected everything to my own repository by setting
<mirrors>
    <mirror>
        <id>nexus</id>
        <mirrorOf>*</mirrorOf>
        <url>http://dox4453:8084/nexus/content/groups/public</url>
    </mirror>
</mirrors>

But when I use the archetype:generate, I get a warning:
[WARNING] Error reading archetype catalog http://repo.maven.apache.org/maven2

Does this mirroring not apply to archetypes? Or is there something that can overwrite the mirror settings?


text:
Q: Kotlin: Why are unary plus/minus not able to infer generic type from assignment? Why are unary plus/minus not able to infer generic type from assignment?
Using invoke, for example: inline operator fun <reified T> invoke(): T
You can call the method and are able to use it... for example val foo: Long = this()
But, using unaryPlus or unaryMinus in the same fashion doesn't work.
The method signature: inline operator fun <reified T> unaryPlus(): T
The non-working call: val foo: Long = +this

A: Operator must be declared as extension function or member of some class:
inline operator fun <reified T> T.unaryPlus(): T = this

Then you can use it on any T:
fun main(args: Array<String>) {
    data class Type(val value: Int)
    val foo = +Type(42)
}


text:
Q: Move text along cursor on hovered div I have a div I want to hover, as soon as it's hovered I want to show a text that moves with the cursor but solely on the y-axis. You can find the effect I'm talking about on this website hovering an image.
My code so far:

{{cart.title}}

TypeScript:
cartHovered(i) {
  this.backgroundColor = this.carts[i].backgroundColor;
  this.hoveredCart = i;
}

cartLeft()
  this.hoveredCart = -1;
}

How can I achieve this effect using Angular when hovering .cart-item?

A:
 {
     fromEvent(window, 'mousemove').pipe(
       filter(() => this.hoveredCard != -1),
     ).subscribe(({clientY}) => this.floatingElements.toArray()[this.hoveredCard].nativeElement
       .style.top = clientY) // <-- offset should be adjusted depending on this cursor Y

  })
}

angular thing here is ngZone.runOutsideAngular and it is used to stop angular from spamming change detection on every event


text:
Q: Schematic Map in GIS Tools? The Question:
Is there way to leverage GIS tools to author/edit a schematic map where elements' geometries has canvas-based coordinates rather than real-world coordinates on Earth?
Perhaps to achieve this, a special Coordinate Reference System (CRS) could be used; one that does "No Projection", one that maps an (X,Y) point directly as-is on a Canvas (instead of on Earth).
Motivation:
I'm maintaining a Geo-database feeding a real-world map. I'd like to also maintain, in parallel, a "schematic map" where I arbitrarily locate the same elements on a planner canvas. So while each element has a Geometry column with real-world coordinates, it also has another geometry column (point, line...etc) with simple X/Y canvas-based coordinates (not real-world) (similar to vectors in an SVG).
Then it would be of great value if I could view/edit this schematic map in GIS tools (like QGIS).

Example:

*

*A Real-World Map, in one QGIS project, has layers of features using their typical geometry column in a typical CRS (say WGS 84) - this map is typical, no problems here!

*A Schematic Map, in another QGIS project, has layers of the same features but using another geometry column that is canvas-based (rather than the real-world) coordinates.

Although the essence of GIS is to manage elements located on Earth (real-world coordinates), my special use-case would benefit highly from managing a schematic map in the same environment and with the same tools as a real one.
Any thoughts?
NOTE: I'm not trying to generate a schematic map automatically (like ArcGIS' Schematics extension does).


text:
Q: How do you hide/show forms in Android? I come from Windows .Net forms development.
This is a pretty basic/fundamental question.
I'm attempting to build an Android app that will have multiple screens/forms (like most do)
My question is how do you achieve this in Android?
For example, a listview loads with menu items.  When the user clicks a menu item, how is the new layout/form loaded?
Do you simply set visibility of your UI controls based on user actions? Or is there a built in mechanism to control the loading of "forms"?
I hope this makes sense. I have some java background and have actually done a small amount of Android development. (But have yet to do an UI type things)
Edit: A better way to phrase this might be: What is the Android equivalent of forms?
Thanks
Kevin

A: Just an addition to what Hesham Saeed has said, use
setContentView(R.layout.layoutId);

inside MyOtherActivity.java. This will load layoutId.xml layout file.

A: These forms are called Activities, and each activity binded with a layout/view.
You have to use intents,
Intent newActivity = new Intent(getApplicationContext(),MyOtherActivity.class);
startActivity(newActivity);


text:
Q: mysql_fetch_assoc lost one value i have this code:
function get_team_a($id_team){
    $result = mysql_query("SELECT * FROM `table1` WHERE `id` = '{$id_team}'");
    return mysql_fetch_assoc($result);
}

In table i have 3 columns:
ppl op  id
10  23  1006
6   21  1005
11  15  1004

But when i do that:
$team_zgl= get_team_a($team_id);

'.$team_zgl['id'].'

i have nothing but this works:

'.$team_zgl['op'].'

'.$team_zgl['ppl'].'

What the?!

A: mysql_fetch_assoc() only fetches one row at a time.
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
    $rows[] = $row;
}
return $rows;

This will return a multi-dimensional array of the rows which you can then iterate over.
If not even one row is being returned you probably have a syntax error in your query.

Your code is vulnerable to injection. You should use properly parameterized queries with PDO/mysqli


text:
Q: Why is oncreate executed always when moving between activities? I have a doubt about activity lifecycle.
I have two activities in wich I trace all lifecycle callback methods.
If I go from activity1 to activity2, return to activity1 and so on, with startActivity(intent) at buttons onclick, I see that oncreate is always executed for both activities, but no ondestroy have been executed.
I change fromone activity to another whith this:
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(), Activity2.class);
        startActivity(intent);
    }
});

This is what I obtaing at log
When the app is launched:
09-23 23:01:03.863    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onCreate
09-23 23:01:03.951    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onStart
09-23 23:01:03.953    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onPostCreate
09-23 23:01:03.953    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onResume
09-23 23:01:03.960    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onPostResume

When clicking the button to go to activity2:
09-23 23:01:46.722    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onPause
09-23 23:01:46.758    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity2 onCreate
09-23 23:01:46.848    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity2 onStart
09-23 23:01:46.854    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity2 onPostCreate
09-23 23:01:46.855    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity2 onResume
09-23 23:01:46.855    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity2 onPostResume
09-23 23:01:47.114    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onSaveInstanceState
09-23 23:01:47.155    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onStop

When clicking the button to go to activity1:
09-23 23:02:08.156    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity2 onPause
09-23 23:02:08.372    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onCreate
09-23 23:02:08.683    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onStart
09-23 23:02:08.683    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onPostCreate
09-23 23:02:08.683    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onResume
09-23 23:02:08.684    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity1 onPostResume
09-23 23:02:09.078    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity2 onSaveInstanceState
09-23 23:02:09.088    2485-2485/com.qqapps.androidactivitylifecycle I/Test? Activity2 onStop

You can see that Activity1 onCreate is executed when I return to it.
The same thing happens when I define activity1 as parent of activity2 with this at AndroidManifest.xml
<activity
    android:name=".Activity1"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity
    android:name=".Activity2"
    android:label="@string/title_activity_activity2"
    android:parentActivityName=".Activity1" >
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.qqapps.androidactivityparent.Activity1" />
</activity>

When I return to activity button using the option at the action bar, oncreate is excecuted for activity1.
This is what I obtaing at log
When the app is launched:
09-25 15:36:17.269    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onCreate
09-25 15:36:17.469    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onStart
09-25 15:36:17.469    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onPostCreate
09-25 15:36:17.470    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onResume
09-25 15:36:17.470    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onPostResume

When clicking the button to go to activity2:
09-25 15:36:49.210    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onPause
09-25 15:36:49.224    5208-5208/com.qqapps.androidactivityparent I/Test? Activity2 onCreate
09-25 15:36:49.253    5208-5208/com.qqapps.androidactivityparent I/Test? Activity2 onStart
09-25 15:36:49.253    5208-5208/com.qqapps.androidactivityparent I/Test? Activity2 onPostCreate
09-25 15:36:49.254    5208-5208/com.qqapps.androidactivityparent I/Test? Activity2 onResume
09-25 15:36:49.255    5208-5208/com.qqapps.androidactivityparent I/Test? Activity2 onPostResume
09-25 15:36:49.528    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onSaveInstanceState
09-25 15:36:49.566    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onStop

When returning to activity1 from the action bar:
09-25 15:37:17.741    5208-5208/com.qqapps.androidactivityparent I/Test? Activity2 onPause
09-25 15:37:17.754    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onDestroy
09-25 15:37:17.765    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onCreate
09-25 15:37:17.790    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onStart
09-25 15:37:17.790    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onPostCreate
09-25 15:37:17.791    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onResume
09-25 15:37:17.792    5208-5208/com.qqapps.androidactivityparent I/Test? Activity1 onPostResume
09-25 15:37:17.957    5208-5208/com.qqapps.androidactivityparent I/Test? Activity2 onStop
09-25 15:37:17.958    5208-5208/com.qqapps.androidactivityparent I/Test? Activity2 onDestroy

In this case I see that onDestroy is called for both activities when clicking the action bar option. I think this is extrange.
As I see here
http://developer.android.com/training/basics/activity-lifecycle/index.html
I think oncreate only is only called when the app is launched or when de system has destoyed the app, but I don't see ondestroy calls.
Thanks

A: If you use buttons to go from activity1 to activity2 and from activity2 to activity1, you will continue to create new activities and just create a big pile of them in the activity stack in your app. You will then see onCreate() being called every time you switch and you will never see onDestroy() being called, because none of your activities are being destroyed. They are all there in the activity stack in your task. You can even see them all if you use the command line tool adb shell dumpsys activity activities.
Also, as I've indicated in my comment, When you return from activity2 to activity1 by using the button in the action bar, you are using "up navigation". There are special rules for how this is handled: See http://developer.android.com/training/implementing-navigation/ancestral.html#NavigateUp


text:
Q: NOE Model and Hammerstein-Wiener Model Similarities in System Identification A nonlinear OE Model is defined as such:

\begin{align}
\hat{y} &= g(\phi(t))  \\
\phi(t) &= (u(t), u(t-1), ..., u(t-n_u), \hat{y}(t-1), ..., \hat{y}(t-n_y))^T
\end{align}

where $g$ can be any nonlinear function.
Is this model equivalent to a Hammerstein-Wiender model where there is no input nonlinearity (Wiener model)?

where the $B$ polynomial corresponds to the input $u$ and $F$ polynomial corresponds to the model output $\hat{y}$.


text:
Q: ID not integer... EasyAPNS I have a method that get's all devices that share a specific ID. Foreach of those device UID's, I am trying to send a APN (Apple Push Notification) using the easyAPN's class.
The method that is having the problem is $apns->newMessage($id);
It seems to think I am not passing a valid integer for $id.
The $id is an array like so Array ( [0] => 1 )
I have also tried passing just the value of the array like so $apns->newMessage($id[0]).
No matter what I do.. I keep getting this error...
"Notice: TO id was not an integer. 1) Messages_model::send_apns -> File: sendMessage.php (line 28) 2) APNS::queueMessage -> File: messages_model.php (line 195) 3) APNS::_triggerError -> File: class_APNS.php (line 599)"
Here is my method... please let me know where I've gone wrong with the $id.
function send_apns($data)
{
    include 'apn_classes/class_DbConnect.php';
    include 'apn_classes/class_APNS.php';

    $message = new Messages_model();
    $db = new DbConnect();
    $db->show_errors();
    $apns = new APNS($db);

    //get uid's for aid
    $sql = "SELECT `devices`.`uid` FROM `devices` WHERE `devices`.`aid` = '".$data['target']."'";
    //echo $sql;
    $query = mysql_query($sql);
    if(mysql_num_rows($query))
    {
    while($uid_data = mysql_fetch_array($query))
        $uids[] = array(
            "uid" => $uid_data['uid']
        );
    }

    //make sure there is a uid
    if(!empty($uids))
    {
        //check the device apn pid
        foreach($uids as $uid)
        {
            $sql = "SELECT `apns_devices`.`pid` FROM `apns_devices` WHERE `apns_devices`.`deviceuid` = '".$uid['uid']."'";
            //echo "$sql";
            $query = mysql_query($sql);
            if(mysql_num_rows($query) > 0)
            {
                while($pid_data = mysql_fetch_array($query))
                {
                    $pids[] = array(
                        "pid" => $pid_data['pid'],
                    );

                    if(!empty($pids))
                    {
                        foreach ($pids as $pid)
                        {
                            $id = array($pid['pid']);
                            print_r($id);
                            //Send APN
                            $apns->newMessage($id[0]);
                            $apns->addMessageBadge(128);
                            $apns->addMessageAlert($data['message']);
                            $apns->addMessageSound('chime');
                            //$apns->addMessageCustom('acme2');
                            $apns->queueMessage();
                            $apns->processQueue();
                        }
                    }
                }
            }
        }

    }
    else
    {
        echo "Device Does not Exist";
    }

}

A: Try to convert $id to integer:
...
foreach ($pids as $pid) {
  $id = intval($pid['pid']);
  print_r($id);
  //Send APN
  $apns->newMessage($id);
  ...


text:
Q: Eclipse misunderstands exception-throwing aspect In Eclipse + AJDT, I implemented a method annotation to check for authorisation as follows.
Annotation:
@Retention(RetentionPolicy.RUNTIME)
public @interface Secured {}

Aspect:
public aspect SecurityCheck {
  pointcut checkSecurity(Secured annotation) : execution(@Secured * *.*(..)) && @annotation(annotation);

  Object around(Secured annotation) throws PermissionException:
    checkSecurity(annotation) {
    ...
    if (...) throw new PermissionException();
    ...
    return proceed(annotation);
  }
}

Usage:
@Secured
public void someMethod() {}

The annotation marks all the methods where the aspect should be applied. Aspect checks authorisation and throws PermissionException on failure.
However, as it is a checked exception, someMethod() needs to declare it:
@Secured
public void someMethod() throws PermissionException {}

Eclipse does not like this: there is nothing inside someMethod() to throw PermissionException, so it complains. I have to do a workaround:
@Secured
public void someMethod() throws PermissionException {
  warn();
}

@SuppressWarnings("unused")
public static void warn() throws PermissionException {}

This makes Eclipse happy and it works just fine. However, it is quite ugly to call warn() every time just to make Eclipse shut up.
What could be done better? Is this a straightforward Eclipse bug?

A: I believe you've stumbled upon a bug (https://bugs.eclipse.org/bugs/show_bug.cgi?id=240608) here which didn't get fixed I believe.
Do you need it to be a checked exception?


text:
Q: Install software from all subdirectories I'm somewhat new to Ubuntu and I installed it to do a small project. I extracted about 30 tar archives with packages in them and now I have a lot of directories, each containing the source code and a configure file.
How can I quickly loop through all the subdirectories and run the configure shell script in each one?
So far, I have tried creating a shell script (called i.sh) that loops through the folders and runs the configure script, but to no avail. Is there any way it can be corrected? And how would I execute it?
find . -type d | while read d; do
    ./configure
    make
    sudo make install
done

I executed it by going into the terminal and running sudo bash ./i.sh.
Thank you!

A: To iterate over all directories in the current directory, use a simpler loop:
for dir in ./*/; do
   # more here
done

The pattern ./*/ would match subdirectories in the current directory.
Using find would most likely do the wrong thing here as it would find subdirectories in the unpacked tar archives.
For each directory, $dir, you want to cd into that directory and do the build:
for dir in ./*/; do
    ( cd "$dir" && ./configure && make && sudo make install )
done

The parenthesis makes the commands run in a subshell. The change of the directory inside the subshell will not be reflected outside of the subshell, so there's never a need to "cd back".
I've strung together the commands with && ("and").  This means that if one command fails, the later commands would not be run at all.
You would not execute this with sudo, as the only step that might possibly need root privileges is the make install step, which is already prefixed by sudo.
Note that this would install all the projects under /usr/local by default.  To install in another installation prefix, use e.g. --prefix=$HOME/local with configure (which means you would not need sudo at all, since you in already have write permissions in your home directory).


text:
Q: Suspending VMWare Fusion instance that uses Boot Camp partition? I run my Windows 7 that's installed on Boot Camp via VMWare Fusion. I like keeping it open so that I don't need to wait 3 minutes until it starts up and so that I don't need to login every time I close the application. The only problem is that it uses up lot's of resources (e.g. 1GB ram) even when I'm not actively using it.
What I would really want is to have it running in the background, but not consuming any resources. Sort of like hibernating the virtual machine, such that when I start it up, ideally the same exact state is restored very quickly and doesn't require a login.
I thought that I might be able to do this with VMWare Fusion's Suspend command, but it's disabled on my version. Is suspend really the feature I'm looking for? If so, how can I enable this feature?
Update: According to the help, it seems that this is the feature I'm looking for, however it's not supported with boot camp partitions. Is there any similar feature, hack, or do you have any other suggestions which can produce similar results as VMWare's suspend feature for Boot Camp partitions?

A: I know that Parallels 6 can 'pause' the boot camp partition. It suspends the virtual machine and frees up system resources without actually suspending the machine i.e. hibernation, however I don't know of any hack/workaround for VMWare Fusion.
Also Parallels can suspend the machine very quickly (around 5 seconds) so you can quit the app freeing up resources. I use it quite a lot as my computing class requires Windows.

Pausing a Virtual Machine
  Pausing a virtual machine releases the resources, such as RAM and CPU, currently used by this virtual machine. The released resources can then be used by the host computer and its applications or by other virtual machines running on the host computer.

Hope this helps.