text:
Q: Tricky series inequality proof by induction involving square roots Prove by induction that
$$1+\frac{1}{\sqrt{2}}+\frac{1}{\sqrt{3}}+...+\frac{1}{\sqrt{n}}<\sqrt{n},    (n\ge2)$$
Induction basis is correct: $$\frac{1}{\sqrt{2}}<\sqrt{2}$$
So we need to prove that
$$1+\frac{1}{\sqrt{2}}+\frac{1}{\sqrt{3}}+...+\frac{1}{\sqrt{n}}+\frac{1}{\sqrt{n+1}}<\sqrt{n+1}$$
One of my attempts was to replace $1+\frac{1}{\sqrt{2}}+\frac{1}{\sqrt{3}}+...+\frac{1}{\sqrt{n}}$ by a number that we know from the induction hypothesis to be greater than it, which is $\sqrt{n}$, and if we show that the inequality is still true then we prove the initial statement.
$$\sqrt{n}+\frac{1}{\sqrt{n+1}}\overset{?}{<}\sqrt{n+1}$$
And, unfortunately, the inequality doesn't hold. I checked it in Wolfram Alpha and the difference between one side of the inequality and the other is really really small. In my opinion, that is why this inequality is so tough to prove (for me, obviously).
Thanks for your help.

A: Your base case is wrong. The inequality has an opposite sign. It is easy to prove it by induction once you try to prove the right thing.

A: The inequality is not true:
$$
1+\frac1{\sqrt2}\simeq1.707>1.4142\simeq\sqrt2.
$$
The reverse inequality can be proved by induction, as you are trying: the inductive step would be
$$
\sqrt n+\frac1{\sqrt{n+1}}>\sqrt{n+1}.
$$
This can be seen as follows: from $n+1>n$, we get
$$
n(n+1)>n^2.
$$
Taking square root and adding $1$,
$$
\sqrt{n(n+1)}+1>n+1.
$$
Now divide by $\sqrt{n+1}$:
$$
\sqrt{n}+\frac1{\sqrt{n+1}}>\sqrt{n+1}.
$$

A: The induction step is incorrect.  Infact, the reverse inequality holds for this question, and the proof of that is simple:
Inductive case: For $n=1$, $1 \geq \sqrt{1}$ is true.
Now, note that if $\displaystyle\sum_{i=1}^k \frac 1 {\sqrt i} \geq \sqrt{k}$ is given, then we have:
$$
\frac{1}{\sqrt{1+k}} \geq \frac {1}{\sqrt{k} + \sqrt{k+1}} \geq \sqrt{k+1}-\sqrt{k}
$$
Simply add the above two inequalities, we get:
$$
\displaystyle\sum_{i=1}^{k+1} \frac 1 {\sqrt i}=\displaystyle\sum_{i=1}^k \frac 1 {\sqrt i}  + \frac{1}{\sqrt{k+1}}\geq \sqrt{k} + (\sqrt{k+1}-\sqrt{k}) \geq \sqrt{k+1}
$$
Hence, the reverse inequality $\displaystyle\sum_{i=1}^{k} \frac 1 {\sqrt i} \geq \sqrt{k}$, for $k \geq 1$, is what holds by induction.

A: Actually, from the standard comparisons (above and below) of sums and integrals in most calculus books, $$ 2 \sqrt {n+1} - 2 \; \; < \sum_{k=1}^n \frac{1}{\sqrt k} \leq \; \;  2 \sqrt n - 1. $$ The equality case on the right side holds only for $n=1.$


text:
Q: Full Screen Image with Transparent System Tray The Search Page in Windows Phone 7 (Bing search) is lovely; uses the entire area for a nice piccy.  The system bar is transparent but the icons are still there.
I can't seem to reproduce this effect.

*

*If I set an image on the LayoutRoot it only goes up to the bottom of the system tray.

*If I hide the system tray, it is always hidden.

*If I make the system tray background transparent, I can see the dark/light theme colour (black or white) through it, which looks terrible with the image background in LayoutRoot.

*If I try and set the Background of phone:PhoneApplicationPage nothing happens.  I tried styling this but couldn't make it work.

I'd be grateful if a Windows Phone 7 guru could help me out here.

A: Try this:
Set the d:DesignHeight="800" and Background="Transparent" for the <phone:PhoneApplicationPage >
Then for the ApplicationBar,
Set Mode="Minimized" BackgroundColor="Transparent"
Almost similar to the one in Bing Search page, but still a little area at the bottom I couldn't cover.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Backup data from RAID 1 disk out of its server I'm facing with a pretty easy problem in my opinion.
I've extracted a working disk from a RAID1 and I'm looking to copy only data (FS and RAID configuration doesn't matter) into another location (another FS).
My problem is I'm not able to mount properly this disk into another linux.
I've first looked the partition table :
# fdisk -l /dev/sdc
Disk /dev/sdc: 640.1 GB, 640135028736 bytes
255 heads, 63 sectors/track, 77825 cylinders, total 1250263728 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

   Device Boot      Start         End      Blocks   Id  System
/dev/sdc1              63  1249535699   624767818+  fd  Linux raid autodetect
/dev/sdc2      1249535700  1250017649      240975   fd  Linux raid autodetect
/dev/sdc3      1250017650  1250258624      120487+  82  Linux swap / Solaris

I've understood I should use dmraid tools. Once installed :
# cat /proc/mdstat
Personalities :
md0 : inactive sdc1[1](S)
      624767744 blocks

unused devices: <none>

And some other informations :
# mdadm --examine /dev/sdc1
/dev/sdc1:
          Magic : a92b4efc
        Version : 0.90.00
           UUID : 8f292f54:7e5aef72:7e5ab5fd:b348fd05
  Creation Time : Mon Jun  2 03:39:41 2008
     Raid Level : raid1
  Used Dev Size : 624767744 (595.82 GiB 639.76 GB)
     Array Size : 624767744 (595.82 GiB 639.76 GB)
   Raid Devices : 2
  Total Devices : 2
Preferred Minor : 0

    Update Time : Tue Feb  7 22:34:59 2012
          State : clean
 Active Devices : 2
Working Devices : 2
 Failed Devices : 0
  Spare Devices : 0
       Checksum : a505b324 - correct
         Events : 15148

      Number   Major   Minor   RaidDevice State
this     1       8        1        1      active sync   /dev/sda1

   0     0       8       17        0      active sync   /dev/sdb1
   1     1       8        1        1      active sync   /dev/sda1

From here, I've tried to mount but I'm not comfortable with dmtools and how it's working.
# mount /dev/sdc1 /mnt/sdc1
mount: unknown filesystem type 'linux_raid_member'

# mount /dev/md0 /mnt/sdc1
mount: /dev/md0: can't read superblock

I've seen some options to alter RAID array with mdadm but I only want to copy data on its filesystem before wiping them... Anyone has a clue ?

A: You need to do
shell># mdadm --assemble --scan

once done, you should be able to see that md0 became active when you type
shell># cat /proc/mdstat

if it is not the case, try
shell># mdadm --assemble --scan --run

and repeat
shell># cat /proc/mdstat

to see if md0 became active.
Once md0 is active, you can mount it with
shell># mount /dev/md0 /mnt/sdc1

and recover your data by copying it wherever you want.


text:
Q: Boot: "Couldn't find data partition. Spawning adbd" Xubuntu 14.04 on a Samsung laptop. Problem similar to the question posed here with the difference that I've not installed ubuntu-touch. I had adb installed which I then uninstalled and ran update-grub but still not booting. Linux kernels up to 3.13.0.61 boot and work fine but newer versions give me this error OR just give me a blank screen.

initrd: Couldn't find data partition. Spawning adbd ...

So to summarize, I can't get any kernel newer than 3.13.0.61 to work.
Here is the output of apt-cache policy *adb android*:
    android-tools-adbd:
  Installed: (none)
  Candidate: 4.2.2+git20130218-3ubuntu23
  Version table:
     4.2.2+git20130218-3ubuntu23 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
        100 /var/lib/dpkg/status
android-emulator:
  Installed: (none)
  Candidate: 20140328-2310-0ubuntu2
  Version table:
     20140328-2310-0ubuntu2 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/multiverse amd64 Packages
qtubuntu-android:
  Installed: (none)
  Candidate: 0.54+14.04.20140402-0ubuntu2
  Version table:
     0.54+14.04.20140402-0ubuntu2 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
libandroid-properties-dev:
  Installed: (none)
  Candidate: 0.1.0+git20131207+e452e83-0ubuntu12
  Version table:
     0.1.0+git20131207+e452e83-0ubuntu12 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
libandroidsdk-common-java:
  Installed: (none)
  Candidate: 22.2+git20130830~92d25d6-1
  Version table:
     22.2+git20130830~92d25d6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
libandroid-properties1:
  Installed: 0.1.0+git20131207+e452e83-0ubuntu12
  Candidate: 0.1.0+git20131207+e452e83-0ubuntu12
  Version table:
 *** 0.1.0+git20131207+e452e83-0ubuntu12 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
        100 /var/lib/dpkg/status
android-src-vendor:
  Installed: (none)
  Candidate: 7-0ubuntu1
  Version table:
     7-0ubuntu1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/multiverse amd64 Packages
libmirclientplatform-android:
  Installed: (none)
  Candidate: 0.1.8+14.04.20140411-0ubuntu1
  Version table:
     0.1.8+14.04.20140411-0ubuntu1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
libandroidsdk-sdklib-java:
  Installed: (none)
  Candidate: 22.2+git20130830~92d25d6-1
  Version table:
     22.2+git20130830~92d25d6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
libandroidsdk-ddmuilib-java:
  Installed: (none)
  Candidate: 22.2+git20130830~92d25d6-1
  Version table:
     22.2+git20130830~92d25d6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
android-headers:
  Installed: (none)
  Candidate: 4.2.2-2-0ubuntu1
  Version table:
     4.2.2-2-0ubuntu1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
androidsdk-traceview:
  Installed: (none)
  Candidate: 22.2+git20130830~92d25d6-1
  Version table:
     22.2+git20130830~92d25d6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
libandroidsdk-sdkstats-java:
  Installed: (none)
  Candidate: 22.2+git20130830~92d25d6-1
  Version table:
     22.2+git20130830~92d25d6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
android-copyright:
  Installed: (none)
  Candidate: 20140328-2310-0ubuntu2
  Version table:
     20140328-2310-0ubuntu2 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/multiverse amd64 Packages
lxc-android-config:
  Installed: (none)
  Candidate: 0.162
  Version table:
     0.162 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
android:
  Installed: (none)
  Candidate: 20140328-2310-0ubuntu2
  Version table:
     20140328-2310-0ubuntu2 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/multiverse amd64 Packages
libandroid-json-org-java:
  Installed: (none)
  Candidate: 20121204-20090211-1
  Version table:
     20121204-20090211-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
libandroid-json-org-java-doc:
  Installed: (none)
  Candidate: 20121204-20090211-1
  Version table:
     20121204-20090211-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
android-tools-adb:
  Installed: (none)
  Candidate: 4.2.2+git20130218-3ubuntu23
  Version table:
     4.2.2+git20130218-3ubuntu23 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
        100 /var/lib/dpkg/status
android-platform-headers:
  Installed: (none)
  Candidate: (none)
  Version table:
libandroidsdk-hierarchyviewerlib-java:
  Installed: (none)
  Candidate: 22.2+git20130830~92d25d6-1
  Version table:
     22.2+git20130830~92d25d6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
libandroidsdk-swtmenubar-java:
  Installed: (none)
  Candidate: 22.2+git20130830~92d25d6-1
  Version table:
     22.2+git20130830~92d25d6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
gcc-arm-linux-androideabi:
  Installed: (none)
  Candidate: 0.20130705.1-0ubuntu7
  Version table:
     0.20130705.1-0ubuntu7 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
libandroidsdk-ddmlib-java:
  Installed: (none)
  Candidate: 22.2+git20130830~92d25d6-1
  Version table:
     22.2+git20130830~92d25d6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
androidsdk-ddms:
  Installed: (none)
  Candidate: 22.2+git20130830~92d25d6-1
  Version table:
     22.2+git20130830~92d25d6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
gcc-i686-linux-android:
  Installed: (none)
  Candidate: 3
  Version table:
     3 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
libmirplatformgraphics-android:
  Installed: (none)
  Candidate: 0.1.8+14.04.20140411-0ubuntu1
  Version table:
     0.1.8+14.04.20140411-0ubuntu1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
android-tools-fastboot:
  Installed: (none)
  Candidate: 4.2.2+git20130218-3ubuntu23
  Version table:
     4.2.2+git20130218-3ubuntu23 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
android-tools-fsutils:
  Installed: (none)
  Candidate: 4.2.2+git20130218-3ubuntu23
  Version table:
     4.2.2+git20130218-3ubuntu23 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
androidsdk-hierarchyviewer:
  Installed: (none)
  Candidate: 22.2+git20130830~92d25d6-1
  Version table:
     22.2+git20130830~92d25d6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
androidsdk-uiautomatorviewer:
  Installed: (none)
  Candidate: 22.2+git20130830~92d25d6-1
  Version table:
     22.2+git20130830~92d25d6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages

Here is the output of update-initramfs
sudo update-initramfs -u -k 3.13.0-101-generic
update-initramfs: Generating /boot/initrd.img-3.13.0-101-generic
/etc/initramfs/post-update.d//zz-flash-touch-initrd: 9: /etc/initramfs/post-update.d//zz-flash-touch-initrd: /usr/sbin/flash-touch-initrd: not found
run-parts: /etc/initramfs/post-update.d//zz-flash-touch-initrd exited with return code 127

dkms does not return anything. Here is the output of dpkg -l linux*  http://paste.ubuntu.com/23609521/

A: Workaround

*

*Run purge to remove configuration
 sudo apt-get purge initramfs-tools-ubuntu-touch

Otherwise remove that residue configuration manually
 sudo rm /etc/initramfs/post-update.d/zz-flash-touch-initrd

*Rebuild the RAM Disk for the non working kernels, example
 sudo update-initramfs -u -k 3.13.0-105-generic

Correct answer: Report this bug
You should report this a bug against initramfs-tools-ubuntu-touch, it should not leave such configuration that break system if the package was not removed completely.


text:
Q: React Native adjustsFontSizeToFit - behaving oddly when combined with panResponder (ios) To preface, I'm attempting to make a resizable Text component, which allows the user to resize the height/width by dragging. The resizing works as expected. My issue is with automatically adjusting the fontSize to fit the component dimensions.
I'm using the adjustsFontSizeToFit prop, which works, but not without some odd behavior. Essentially, as the user drags, and the text grows/shrinks, it will occasionally "hide" the last letter of the text. If you drag slightly further, the last letter will then appear again. In case that's not clear, here is a picture of the issue...
Starting position:
https://i.imgur.com/GuxJKBZ.png
Second Position:
https://i.imgur.com/nf6Ncif.png
Final Position:
https://i.imgur.com/kjeKBJO.png
I've been desperately looking for an answer and trying different solutions, but nothing seems to work. I don't understand what could be causing the issue, but as best I can surmise, it seems like the font just doesn't adjust quickly enough, so it causes the final letter to be clipped. My reasoning for this thought, is that the disappearing doesn't happen once the fontSize reaches its maximum value. This issue just doesn't make, though, since the font definitely has room to fit the final letter.
Anyway, it's been almost a week of banging my head against the wall, so I'm really hoping someone out there can shed some light on this issue. The only workaround I see is to code out my own fontSize adjustment, but that seems ridiculous, considering React Native has a prop for that.
Any help would be greatly appreciated.
edit... I forgot to mention that I have found one solution to remove the disappearing letter. That solution is to remove height from the style and replace it with lineHeight. This creates a different issue, however, which is that the fontSize no longer adjusts to the height of the component, meaning the font will sometimes be larger than the component, leading it to be cut off.

A: I had a similar problem (although I'm not using PanResponder), I just added a few blank spaces ( ) after the text. So that React Native ends up clipping the trailing blank spaces as opposed to text.
For example:
<Text>
  Foo

</Text>

Should result in each character of "Foo" always being displayed


text:
Q: How to change background image in winforms based off of text box? Below is my current code for my winforms app. Here the user will click the button and then the system will land on a specific index to an array and then print to the text box the contents of that index in the array. The "if" statement is where I am trying to match a specific background image to the specific index. Below in my test "if" statement I am trying to match a specific image in my resource file but I can't seem to figure out what to set the bool to match. I have tried "if(Map_Text="Woods")" which I get CS0029 error. Any tips or online guides I can review?(I apologize if I mis-said anything I am new to coding)
private void button1_Click(object sender, EventArgs e)
        {
            int start1 = random.Next(0, Map_Array.Length);
            Map_Text.Text = Map_Array[start1];

            if(Map_Text = "Woods")
            {
                this.BackgroundImage = Properties.Resources.Woods;
            }

}

A: In your if statement, you're attempting to assign the string "Woods" to Map_Name, which is the reason you're getting CS0029 (which means that the compiler can't implicitly convert the two types.)
Additionally, you'd need to check the Text property of Map_Name instead of checking Map_Name directly, as you're assigning the result of your random selection to that property above your if statement.
if (Map_Text.Text == "Woods") {
  this.BackgroundImage = Properties.Resources.Woods;
}


text:
Q: Probability in picking a computer from a laboratory In laboratory 1, there are 20 computers, of which 14 are Dell, 6 are HP. In laboratory 2, there are 20 Dell computers and 10 HP computers. A new laboratory is being formed, for which 9 computers from lab 1 are taken, and 6 computers from lab 2 into the new laboratory. From this new laboratory, we randomly select a computer. What is the probability that the chosen computer is a Dell computer?
How I would solve this:
Let $A$ denote the event that a Dell computer is chosen.
Let $M_i$ denote the event that the $i$-th laboratory is chosen.
$P(M_1) = 9/15$ because we pick $9$ computers from laboratory $1$.
$P(A\mid M_1) = 14/20$.
$P(M_2) = 6/15$ because we pick $6$ computers from laboratory $2$.
$P(A\mid M_2) = 20/30 = 2/3$.
$P(A) = P(M_1) \times P(A\mid M_1) + P(M_2) \times P(A\mid M_2) = 9/15 \times 14/20 + 6/15 \times 20/30 = 103/150$
Now, knowing how tricky probability tasks are, I am not quite confident this is correct. Can someone please go through my answer, and if wrong correct it? Thanks in advance.


text:
Q: Cannot Upgrade from Ubuntu 18.04 to 20.04 I am having problems upgrading from Ubuntu 18.04 to 20.04
This is what happens.
sudo apt update
Hit:1 http://us.archive.ubuntu.com/ubuntu bionic InRelease
Hit:2 http://us.archive.ubuntu.com/ubuntu bionic-updates InRelease
Get:3 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]
Get:4 http://us.archive.ubuntu.com/ubuntu bionic-backports InRelease [74.6 kB]
Hit:5 https://dl.winehq.org/wine-builds/ubuntu bionic InRelease
Hit:6 https://dl.winehq.org/wine-builds/ubuntu focal InRelease
Hit:7 http://ppa.launchpad.net/apandada1/brightness-controller/ubuntu bionic InRelease
Hit:8 http://dl.openfoam.org/ubuntu bionic InRelease
Hit:9 http://ppa.launchpad.net/cybermax-dexter/sdl2-backport/ubuntu bionic InRelease
Hit:10 http://ppa.launchpad.net/micahflee/ppa/ubuntu bionic InRelease
Hit:11 http://ppa.launchpad.net/mkusb/ppa/ubuntu bionic InRelease
Hit:12 http://ppa.launchpad.net/nilarimogard/webupd8/ubuntu bionic InRelease
Hit:13 http://ppa.launchpad.net/xorg-edgers/ppa/ubuntu bionic InRelease
Fetched 163 kB in 2s (71.4 kB/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done
1 package can be upgraded. Run 'apt list --upgradable' to see it.

apt list --upgradable
Listing... Done
wine-stable/focal 6.0.2~focal-1 all [upgradable from: 3.0-1ubuntu1]
N: There are 26 additional versions. Please use the '-a' switch to see them.

How do I upgrade wine so it is compatible with Ubuntu 20.04.
I have been trying this many, many times. And I am tired of trying. There are 26 versions, can somebody help me?
Thanks


text:
Q: Can I say " There do be something"? We can say 'Do be careful', 'do be straightforward about it'.
And we can say ' There do exist...', such as:
----- From a synchronic point of view, there do exist cases of regular abrupt metathesis, ...
----- However, there do exist many situations where onsite capacity is the most viable option...
So I wonder if I can accordingly say sentences like'There DID BE such a teacher then in my school'?
Is it right(and why)? Have you ever seen such expressions? Thank you very much.

A: Short answer: No, it's not right.
Long answer: There DID not be such a sentence, then, in modern English.
Note that all your "Do be..." sentences are the imperative "do". That is, they're commands.
However, the "do" in "there do exist..." is there to emphasize the contrast from previous sentences.
So, there DID exist such a sentence, then, in modern English, but there did not be such a sentence, then, in modern English.


text:
Q: Counting words in a string - c programming I need to write a function that will count words in a string. For the
purpose of this assignment, a "word" is defined to be a sequence
of non-null, non-whitespace characters, separated from other words by
whitespace.
This is what I have so far:
int words(const char sentence[ ]);

int i, length=0, count=0, last=0;
length= strlen(sentence);

for (i=0, i<length, i++)
 if (sentence[i] != ' ')
     if (last=0)
        count++;
     else
        last=1;
 else
     last=0;

return count;

I am not sure if it works or not because I can't test it until my whole program is finished and I am not sure it will work, is there a better way of writing this function?

A: You needed
int words(const char sentence[])
{
}

(note braces).
For loops go with ; instead of ,.

Without any disclaimer, here's what I'd have written:
See it live http://ideone.com/uNgPL
#include <string.h>
#include <stdio.h>

int words(const char sentence[ ])
{
    int counted = 0; // result

    // state:
    const char* it = sentence;
    int inword = 0;

    do switch(*it) {
        case '\0':
        case ' ': case '\t': case '\n': case '\r': // TODO others?
            if (inword) { inword = 0; counted++; }
            break;
        default: inword = 1;
    } while(*it++);

    return counted;
}

int main(int argc, const char *argv[])
{
    printf("%d\n", words(""));
    printf("%d\n", words("\t"));
    printf("%d\n", words("   a      castle     "));
    printf("%d\n", words("my world is a castle"));
}

A: See the following example, you can follow the approach  : count the whitespace between words .
int words(const char *sentence)
{
    int count=0,i,len;
    char lastC;
    len=strlen(sentence);
    if(len > 0)
    {
        lastC = sentence[0];
    }
    for(i=0; i<=len; i++)
    {
        if((sentence[i]==' ' || sentence[i]=='\0') && lastC != ' ')
        {
            count++;
        }
        lastC = sentence[i];
    }
    return count;
}

To test :
int main()
{
    char str[30] = "a posse ad esse";
    printf("Words = %i\n", words(str));
}

Output :
Words = 4

A: #include <ctype.h> // isspace()

int
nwords(const char *s) {
  if (!s) return -1;

  int n = 0;
  int inword = 0;
  for ( ; *s; ++s) {
    if (!isspace(*s)) {
      if (inword == 0) { // begin word
        inword = 1;
        ++n;
      }
    }
    else if (inword) { // end word
      inword = 0;
    }
  }
  return n;
}

A: bool isWhiteSpace( char c )
{
    if( c == ' ' || c == '\t' || c == '\n' )
        return true;
    return false;
}

int wordCount( char *string )
{
    char *s = string;
    bool inWord = false;
    int i = 0;

    while( *s )
    {
        if( isWhiteSpace(*s))
        {
            inWord = false;
            while( isWhiteSpace(*s) )
                s++;
        }
        else
        {
            if( !inWord )
            {
                inWord = true;
                i++;
            }
            s++;
        }
    }

    return i;
}

A: Here is one of the solutions. It counts words with multiple spaces or just space or space followed by the word.
#include <stdio.h>
int main()
{
    char str[80];
    int i, w = 0;
    printf("Enter a string: ");
    scanf("%[^\n]",str);

    for (i = 0; str[i] != '\0'; i++)
    {

        if((str[i]!=' ' && str[i+1]==' ')||(str[i+1]=='\0' && str[i]!=' '))
        {
            w++;
        }

    }

    printf("The number of words = %d", w );

    return 0;
}

A: I know this is an old thread, but perhaps someone needs a simple solution, just checks for blank space in ascii and compares current char to that while also makign sure first char is not a space, cheers!
int count_words(string text){
int counter = 1;
int len = strlen(text);
for(int i = 0; i < len; i++){
    if(text[i] == 32 && i != 0) {
        counter++;
    }
}
return counter;}

A: Here is another solution:
#include <string.h>

int words(const char *s)
{
    const char *sep = " \t\n\r\v\f";
    int word = 0;
    size_t len;

    s += strspn(s, sep);

    while ((len = strcspn(s, sep)) > 0) {
        ++word;
        s += len;
        s += strspn(s, sep);
    }
    return word;
}

A: #include<stdio.h>

int main()
{
char str[50];
int i, count=1;
printf("Enter a string:\n");
gets(str);
for (i=0; str[i]!='\0'; i++)
        {
        if(str[i]==' ')
                {
                count++;
                }
        }
printf("%i\n",count);
}

A: #include<stdio.h>
#include<string.h>

int getN(char *);

int main(){
    char str[999];
    printf("Enter Sentence: "); gets(str);
    printf("there are %d words", getN(str));
}

int getN(char *str){
    int i = 0, len, count= 0;
    len = strlen(str);
    if(str[i] >= 'A' && str[i] <= 'z')
       count ++;

    for (i = 1; i<len; i++)
        if((str[i]==' ' || str[i]=='\t' || str[i]=='\n')&& str[i+1] >= 'A' && str[i+1] <= 'z')
        count++;

return count;
}

A: #include <stdio.h>

int wordcount (char *string){

    int n = 0;

    char *p = string ;
    int flag = 0 ;

    while(isspace(*p)) p++;

    while(*p){
        if(!isspace(*p)){
            if(flag == 0){
                flag = 1 ;
                n++;
            }
        }
        else flag = 0;
        p++;
    }

    return n ;
}

int main(int argc, char **argv){

    printf("%d\n" , wordcount("    hello  world\nNo matter how many newline and spaces"));
    return 1 ;
}

A: I found the posted question after finishing my function for a C class I'm taking.  I saw some good ideas from code people have posted above. Here's what I had come up with for an answer. It certainly is not as concise as other's, but it does work.  Maybe this will help someone in the future.
My function receives an array of chars in.  I then set a pointer to the array to speed up the function if it was scaled up.  Next I found the length of the string to loop over.  I then use the length of the string as the max for the 'for' loop.
  I then check the pointer which is looking at array[0] to see if it is a valid character or punctuation. If pointer is valid then increment to next array index.  The word counter is incremented when the first two tests fail.  The function then will increment over any number of spaces until the next valid char is found.
  The function ends when null '\0' or a new line '\n' character is found. Function will increment count one last time right before it exit to account for the word preceding null or newline.  Function returns count to the calling function.
#include <ctype.h>

char wordCount(char array[]) {
    char *pointer;    //Declare pointer type char
    pointer = &array[0];  //Pointer to array

    int count; //Holder for word count
    count = 0; //Initialize to 0.

    long len;  //Holder for length of passed sentence
    len = strlen(array);  //Set len to length of string

    for (int i = 0; i < len; i++){

        //Is char punctuation?
        if (ispunct(*(pointer)) == 1) {
            pointer += 1;
            continue;
        }
        //Is the char a valid character?
        if (isalpha(*(pointer)) == 1) {
            pointer += 1;
            continue;
        }
        //Not a valid char.  Increment counter.
        count++;

        //Look out for those empty spaces. Don't count previous
        //word until hitting the end of the spaces.
        if (*(pointer) == ' ') {
            do {
                pointer += 1;
            } while (*(pointer) == ' ');
        }

        //Important, check for end of the string
        //or newline characters.
        if (*pointer == '\0' || *pointer == '\n') {
            count++;
            return(count);
        }
    }
    //Redundent return statement.
    count++;
    return(count);
}

A: I had this as an assignment...so i know this works.
The function gives you the number of words, average word length, number of lines and number of characters.
To count words, you have to use isspace() to  check for whitespaces. if isspace is 0 you know you're not reading whitespace. wordCounter is a just a way to keep track of consecutive letters. Once you get to a whitespace, you reset that counter and increment wordCount. My code below:
Use isspace(c) to
#include <stdio.h>
#include <ctype.h>

int main() {
  int lineCount = 0;
  double wordCount = 0;
  double avgWordLength = 0;
  int numLines = 0;
  int wordCounter = 0;
  double nonSpaceChars = 0;
  int numChars = 0;
  printf("Please enter text.  Use an empty line to stop.\n");
  while (1) {
      int ic = getchar();
      if (ic < 0)    //EOF encountered
          break;
      char c = (char) ic;
      if (isspace(c) == 0 ){
      wordCounter++;
      nonSpaceChars++;
    }
      if (isspace(c) && wordCounter > 0){
      wordCount++;
      wordCounter =0;
    }
      if (c == '\n' && lineCount == 0) //Empty line
      {
          break;
      }
      numChars ++;
      if (c == '\n') {
          numLines ++;
          lineCount = 0;
      }
      else{
          lineCount ++;
    }
  }
  avgWordLength = nonSpaceChars/wordCount;
  printf("%f\n", nonSpaceChars);
  printf("Your text has %d characters and %d lines.\nYour text has %f words, with an average length of %3.2f ", numChars, numLines, wordCount, avgWordLength);
}

A: Here is one solution. This one will count words correctly even if there are multiple spaces between words, no spaces around interpuncion symbols, etc. For example: I am,My   mother is.   Elephants ,fly away.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int countWords(char*);

int main() {
    char string[1000];
    int wordsNum;

    printf("Unesi nisku: ");
    gets(string);  /*dont use this function lightly*/

    wordsNum = countWords(string);

    printf("Broj reci: %d\n", wordsNum);

    return EXIT_SUCCESS;
}

int countWords(char string[]) {
    int inWord = 0,
        n,
        i,
        nOfWords = 0;

    n = strlen(string);

    for (i = 0; i <= n; i++) {
        if (isalnum(string[i]))
            inWord = 1;
        else
            if (inWord) {
                inWord = 0;
                nOfWords++;
            }
    }

    return nOfWords;
}

A: this is a simpler function to calculate the number of words
int counter_words(char* a){`

 // go through chars in a
 // if ' ' new word
 int words=1;
 int i;
 for(i=0;i<strlen(a);++i)
 {
      if(a[i]==' ' && a[i+1] !=0)
      {
           ++words;
      }
 }

return words;}


text:
Q: Resistor near point-of-contact for better ESD-protection? This question is about ESD-protection while installing/removing components (RAM, SSDs, etc.) inside a PC.
When grounding the GND of an USB-port to earth or to my wrist strap (as advised earlier) the moment-of-contact would be the moment i plug the USB-cable (which is attached to my wrist strap somehow) into the USB-port.
So, the USB-port is the point-of-contact where an ESD-event (due to a potential-difference) could happen at the moment-of-contact.
In theory, is the USB-port better protected when the resistor is nearby?
(Maybe far fetched question, but i'm wondering on which end of my self-made cable i should place a resistor.)

A: There is no difference in having the resistor by the USB plug or by the wrist strap - it's in series, so the location has no bearing on things.
The "moment of contact" is the moment when the path between your wrist and the USB socket is made. That could either be when you have the strap attached and plug it in, or put the wrist strap on when it's already plugged in. Either way it's via the resistor.
The only "improvement" in the location of the resistor would be to have it inside the laptop. That way, if you happen to be touching the metal shield of the USB connector with your finger as you plug it in, the resistor would still be in the path. That's the only time the resistor in your cable would possibly be ineffectual.


text:
Q: Do real vectors attain matrix norms? The $p$-norm of a matrix $A$ for $p \geq 1$ is defined as $$\|A\|_p = \max_{ x \in \mathbb{R}^n, \|x\|_p=1} \|Ax\|_p.$$ My question: does this equal $$
\max_{ x \in \mathbb{C}^n, \|x\|_p=1} \|Ax\|_p$$ The only difference is the replacement of $\mathbb R^n$ by $\mathbb C^n$. The answer is certainly yes for $p=1,2,\infty$ and the Wikipedia article on matrix norms appears to imply the answer is yes for any $p$.

A: Note that this is not true for the norms $\|A\|_{p,q}$.  For example, if $A = \pmatrix{1 & -1\cr 1 & 1\cr}$, $$\max_{x \in {\mathbb R}^2: \|x\|_\infty = 1} \|A x\|_1 = 2$$
but $x = \pmatrix{1\cr i\cr}$ has $\|x\|_\infty = 1$ and $\|Ax\|_1 = 2 \sqrt{2}$.

A: If the entries of $A$  are not all real, the answer may be no.  For example, consider the $2 \times 1$ matrix $A = (1 \ i)$ with $p=2$.
$$\max_{x \in {\mathbb C}^2, \|x\|_2 = 1} \|Ax\|_2 = \sqrt{2}$$ but
$$\max_{x \in {\mathbb R}^2, \|x\|_2 = 1} \|Ax\|_2 = 1$$

A: Have you considered looking at the wikipedia article on Matrix norm? I guess your answer is well written there. In any case, if not, then yes, it is true regardless of whether $x$ is over $\mathbb{R}^n$ or $\mathbb{C}^n$.


text:
Q: Why groups that admit Folner Sequences are amenable I've been looking at Folner's Condition recently, and I'm struggling to find a proof for why the existence of a Folner sequence on a locally compact group implies that it is amenable (and the converse to this).
[EDIT: So far I've looked at amenability in terms of invariant means, so my question should be:
"How does to existence of a Folner sequence imply the existence of a left invariant mean on a locally compact group?"]
If anyone could give a proof for this or point me in the direction of one on the internet that I can read that would be really helpful - have struggled to find anything myself.
Thanks in advance,
Jo


text:
Q: How Do I get a single instance of an interface in Typescript I am trying to figure out how to get a single instance of an interface in Typescript.  I have the following code that works:
export interface IOpenStatus {
    filePath: string;
    openSuccess: boolean;
    error: string;
    fileData: string;
}

openStatus: IOpenStatus[];

However, if I want just a single instance of the interface to be defined, this fails:
openStatus: IOpenStatus;

This fails as well:
let openStatus= new IOpenStatus();

It seems that the array "[]" is somehow substituting for an instance creation mechanism (albeit for multiple instances).  In my situation, I never want to instantiate more than a single instance of the interface.
How do I instantiate a single instance of the interface? I am needing to use an interface because I am going to return this data from the server with this same interface.
UPDATE
I can see part of the problem was I didn't specify the context. I am doing this in an Angular2 application.  In my situation, I was using
openStatus: IOpenStatus[];
as part of a class property definition (a component to be exact). It seems that the array notation does simply allow Javascript to anticipate the instantiation of an array of the type of the interface without any further definition (it can be used as an array of such, immediately thereafter).
What I have to do, in the end to utilize:
userOpenStatus = new OpenStatus();
is to implement the interface in a class such as :
export interface IOpenStatus {
    filePath: string;
    openSuccess: boolean;
    error: string;
    fileData: string;
}

export class OpenStatus implements IOpenStatus {
    filePath: string;
    openSuccess: boolean;
    error: string;
    fileData: string;
}

A: Given:
export interface IOpenStatus {
    filePath: string;
    openSuccess: boolean;
    error: string;
    fileData: string;
}

This, on its own, is a syntax error:
openStatus: IOpenStatus[];

(Though it would be valid as a class property declaration.) You might need something like:
let openStatus: IOpenStatus[];

This corresponds exactly to the plain JS version:
let openStatus;

The only difference is the type annotation. If you don't want it to be an array of your type, just say:
let openStatus: IOpenStatus;

In order to appear after the new keyword, an identifier must be the name of a constructor function, and the easiest way to declare one of those is with the class keyword. But you could just use a type literal:
openStatus = {
    filePath: "/blah",
    openSuccess: true,
    error: "",
    fileData: "Hello, world."
};

That has all the properties required for IOpenStatus, so it can be assigned to a variable of that type.


text:
Q: Restarting an EC2 instance on the instance that is supposed to be restarted I'm running through a loop with a PHP script that's on AWS instance. From my experiences with AWS, as soon as the instance is stopped, all of the code that's in the process of being executed is stopped. What I have is this:
<?php
require("vendor/autoload.php");
use Aws\Ec2\Ec2Client;

$instance_id = 'instance_id';
$creds = array('key' => 'key',
                'secret' => 'secret',
                'region' => 'us-west-2');
$client = Ec2Client::factory($creds);
$instance = array('InstanceIds' => array($instance_id), 'DryRun' => false);

for($i=0;$i<10;$i++) {
    // Execute irrelevant code
    // .....

    $result = $client->stopInstances($instance);
    sleep(300);
    $result = $client->startInstances($instance);
}
?>

So, my question is this: Once the instance is stopped, everything that is written after that will not be executed since the instance will be stopped, right? The loop will not continue on to the next iteration, right? If so, then how could I get around that?


text:
Q: How to load a BMP file using wxPython on Windows? It seems that wxPython is missing "some" examples.
I have the following piece of code that doesn't work on Windows:
import wx
wx.InitAllImageHandlers() # calling it doesn't make any difference
print wx.Image("sample.bmp") # also tried with type=wx.BITMAP_TYPE_ANY

The returned value is None and I can also see a warning: Warning: No handler found for image type.
I tried to add the second line but it seems that it doesn't change a thing.

A: You probably need wx.App created first.
import wx

app = wx.App(False)
print wx.Image("wallpaper.bmp")


text:
Q: Mysql set different UUID for different row in multi row insert I am trying to generate different uuid for each row, during multiple insert.
First I created a new table:
CREATE TABLE uuid_test(
    `id`       INTEGER      INTEGER AUTO_INCREMENT PRIMARY KEY,
    `col1`     VARCHAR(20)  DEFAULT '',
    `uuid_col` VARCHAR(200) DEFAULT '',
    `col2`     INTEGER      DEFAULT 0,
    `col3`     BIT(1) DEFAULT 1,
    UNIQUE (`col1`, `uuid_col`, `col2`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;

Then I tried of adding a trigger
DELIMITER $$
CREATE TRIGGER test_trigger
BEFORE INSERT ON uuid_test
FOR EACH  ROW
BEGIN
    SET NEW.uuid_col := UUID() ;
END
$$

Then I tried to insert two column using isert select
INSERT INTO kudos_voting(col1, col2) select col1, col2 from table2;

The result:
mysql> select * from uuid_test;
+----+------------+--------------------------------------+------------+-------+
| id | col1       | uuid_col                             | col2       | col3  |
+----+------------+--------------------------------------+------------+-------+
|  3 | gjsfgjks   | 3205a742-961f-11e5-be40-086266261210 |          4 |     1 |
|  4 | gjsfgjks   | 3206ccaf-961f-11e5-be40-086266261210 |          4 |     1 |
+----+------------+--------------------------------------+------------+-------+

Here I am facing two doubts.

*

*Why the same uuid is inserted everytime

*Though I have added  UNIQUE
(col1, uuid_col, col2), then why its not throwing any error
during insertion of the same value.

A: Please, be more careful: the uuids are different (3205a742 vs 3206ccaf - compare the first parts). So everything works like you suggested and there shouldn't be any errors.


text:
Q: Ubuntu, Samba, Shared folders and unknown files I am using ubuntu on my laptop with a EDGE connection. I have no computers on my LAN.
First time this happened as a coincidence when i left a folder shared after office on my laptop and found it infected. After that i have tried to reproduce the issue and everytime this happens:

*

*If i share a folder with samba and Guest Read+Write (777) permissions, after some time (varies, sometime a couple hours, sometime more than that) i start seeing strange files as shown below:
-r-xr--r--  1 nobody  nogroup      0 2010-08-19 23:19 ctf
-rw-r--r--  1 nobody  nogroup 337103 2004-08-04 00:10 dnpdwh.exe
-r-xr--r--  1 nobody  nogroup      0 2010-08-20 05:45 khx
-r-xr--r--  1 nobody  nogroup      0 2010-08-19 20:14 khy
-rw-r--r--  1 nobody  nogroup 596628 2008-04-14 22:01 mzbxsv.exe
-rw-r--r--  1 nobody  nogroup 510302 2004-08-04 19:50 uxnpfo.exe
I can always delete them but they keep popping back, i don't know from where they come or even why.
[EDIT]:
Issue was Samba listening on public IP and then with 777 i was inviting the un-initiated to my system who though it was windows and thus dropping by viruses. Fixed with modifying samba configuration to:
  interfaces = 127.0.0.0/8 eth0
  bind interfaces only = yes

in
/etc/samba/smb.conf

followed by
/etc/init.d/smbd restart

Problem was evident from log entries in /var/log/samba/log.IP_HERE
It was also evident as Samba was using nobody and nogroup to write files in Publicly writable shares.

A: MMM i few things i would recommend to you:

*

*look for signs of strange processes, with chkrootkit
( http://www.chkrootkit.org )

*Do a portscan with nmap from a
different machine to make sure nothing strage is open or that you have anything else secure.

*Check your firewall rules and do changes if you see it is too wide to outsiders

*Verify your samba conf and limit it by the known ips you have if you don't share the data with anyone else, this will keep any outsiders from using it.

*Not sure if this would be a problem to you but you can aswell set samba to use passwords to access/create the data, that is ofc assuming the files are being created by a 3rd party and not within your own system, but then checking if your system has been rootkited as pointed above would be the best.


text:
Q: Find issued ram through memory address my pc sometimes get memory issue with error like this or just hanging some seconds...
---------------------------
Unexpected error
---------------------------
An error has occurred. MPC-HC will close now.

Exception:
ACCESS VIOLATION

Crashing module:
C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispig.inf_amd64_c0e159863e7afdde\nvd3dumx.dll
Offset: 0xDD216748, Codebase: 0x7FF775610000
The thread 628 tried to write memory at address 0x16728

---------------------------
OK
---------------------------

I have 2 physical ram, this occurs often while memory are 70% full,

I want to know which memory have issue and so replace it,
There are a way to know?! or just replace 2 of them?!
Also maybe this is not physical ram issue and OS issue?!

A: Most likely, this is an error caused by MPC-HC writing to a protected area of RAM, not an issue with the physical RAM modules.

*

*First, get the latest version of MPC-HC from the development site (v. 1.9.22 on the day the question was asked), not from a third-party. Probably, you want the full 64-bit installation file.

*Second, check that you have sufficient disk space for virtual RAM, i.e., memory moved to the SSD or HDD when physical RAM is insufficient for the current operation(s). Also set virtual memory to an appropriate size. My own preference is to set the size manually, somewhere between 0.2 and 1.5 times the size of physical RAM, and to set Initial size and Maximum size the same, to avoid fragmenting the page file. (N.B. this seems to be an area with many differing opinions, so caveat user and feel free to experiment,)

*

*If this does not resolve the issue, try to repair the operating system files with DISM and SFC, because all applications depend on various Windows libraries, which might be damaged, assigning memory to a protected area.

*You can also try a RAM test application, such as Windows 10 built-in  Memory Diagnostic tool or a free third-party tool, such as MemTest86.


text:
Q: Checking for indepenedent sets in a bipartite graph with equal number of odd and even elements in SageMath By using the IndependentSets module in SageMath, we can list all the independent sets of a graph. Suppose I have a bipartite graph on the Symmetric Group with partite sets consisting of even and odd permutations.
How do I enumerate and list out all those independent sets which consists of equal number of elements from even and odd permutations. What all methods and functions do I need to use. Is there some built in function  for listing the type of a symmetric group element as even or odd.
My idea of pseudo-code idea would be:
G=SymmetricGroup(4)
CG = G.cayley_graph(generators=[G((1,2)),G((1,3)),G((1,4)),G((2,3)),G((2,4)),G((3,4))])
CGU = CG.to_undirected()
I=IndependentSets(CGU)
for list in I:
   for i in list:
       if enumerate(type(list[i])=='even')==enumerate(type(list[i]=='odd'):
add list in list1

print(list1)

However, I encountered the error that list indices must be integers or slices and not permutation group elements. How do rectify this? Any hints?

A: Try this:
from sage.graphs.independent_sets import IndependentSets
S = SymmetricGroup(3) # Or whatever you want.
P1 = [S((1, 2)), S((1, 3)), S((2, 3))] # Two parts of the partition,
P2 = [S((1,2,3)), S((1,3,2)), S(())]   # adjust these as you want.
G = BipartiteGraph([P1,P2])
I = IndependentSets(G)
L = []
for l in I:
    if (sum(x.sign()==1 for x in l) == sum(x.sign()==-1 for x in l)):
        L.append(l)
print(L)

or slightly more efficiently, replace the third last line with
    if (sum(x.sign() for x in l) == 0):


text:
Q: An error occurred while loading the PDF document I would like you to help me with this problem.
I have some time working with a project in Laravel 5.6. This week I installed the barryvdh / laravel-dompdf package via composer as indicated in the documentation.
I added the respective service provider in the config \ app.php file.
When trying to use the package for the first time I get the following error in Chrome:
"An error occurred while loading the PDF document"
When I download the document and visualize it with a text editor, I realize that the only thing that is wrong with the file is that it lacks the first line:% PDF-1.3. When adding said line manually the document is "fixed".
To continue testing, I installed a new laravel project, and then I installed the package and created a route with the same code from the previous project. To my surprise, this project does load the PDF document in Chrome.
Please give me some idea of what things I can review.
Thank you very much

A: I have already solved it.
The cause of the problem was that the config/app.php configuration file did not have the <?php line at startup, and this was what caused the problem.


text:
Q: Azure Table entity name change I just modified the name of the property of the table on Azure.  And it reflected as totally new property, which makes sense.  My question is, is there a way to change property name  on Azure Table without iterate each record?

A: No, each entity is it's own set of property names and values.  There is really no such thing as a 'table property' in the same sense that you think of a column in an RDBMS table.  Most storage explorer tools iterate through the entities and build a collection of all of the properties for each entity and then display those as 'columns' which is why it looks like the properties are related to the table itself.  If you want to change the property names of existing entities then you need to iterate through each entity and change it.


text:
Q: How to generate a random code for each session using php for Wordpress? I am using Contact form 7 in Wordpress , where I want to add a field of uneditable random code . I am using the following code and using the Dynamic hidden field to display it. But is there any way that I can show this code on any page (where I want) after submitting this form? e.g, Your submitted code was : 32372377
function rzh_cf7_GenNomor() {
  $panjang = 10; // Length number generated
  $karakter = "0123456789"; // random character
  for ($p = 0; $p < $panjang; $p++) {
    $string .= $karakter[mt_rand(0,strlen($karakter)-1)];

  }
  return $string;
}
add_shortcode('RZH_CF7_GEN_NOMOR', 'rzh_cf7_GenNomor');

A: You can add data to the global $_SESSION variable that will be accessible at any point within the application during a user session by accessing the $_SESSION variable. The variable is an array; below is an example of adding data to the session array.
$foo = add_shortcode('RZH_CF7_GEN_NOMOR', 'rzh_cf7_GenNomor');
$_SESSION['foo'] = $foo;

A: You can call the following function in your custom shortcode in function.php
function generateRandomString($length = 10) {
   return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}


text:
Q: How to search through in JSON array on SQL I'm using MySQL 5.6.43 and trying to search through in JSON array in a table. My JSON in MySQL database is like this:
[
    {
        "Name": "AAA",
        "CountryCode": "AFG",
        "District": "Kabol",
        "Population": 1780000
    },
    {
        "Name": "BBB",
        "CountryCode": "AFG",
        "District": "Qandahar",
        "Population": 237500
    },
    {
        "Name": "CCC",
        "CountryCode": "USD",
        "District": "Qandahar",
        "Population": 237500
    }
]

I want to take the just AFG CountryCode's. So my result should be like this:
[
    {
        "Name": "AAA",
        "CountryCode": "AFG",
        "District": "Kabol",
        "Population": 1780000
    },
    {
        "Name": "BBB",
        "CountryCode": "AFG",
        "District": "Qandahar",
        "Population": 237500
    }
]

How can I achieve that?

A: SELECT test.data, JSON_ARRAYAGG(JSON_OBJECT('Name',jsontable.Name,
                                            'CountryCode',jsontable.CountryCode,
                                            'District',jsontable.District,
                                            'Population',jsontable.Population)) filtered
FROM test,
     JSON_TABLE(test.data,
                '$[*]' COLUMNS (Name VARCHAR(255) PATH '$.Name',
                                CountryCode VARCHAR(255) PATH '$.CountryCode',
                                District VARCHAR(255) PATH '$.District',
                                Population VARCHAR(255) PATH '$.Population')) jsontable
WHERE jsontable.CountryCode = 'AFG'
GROUP BY test.data;

fiddle
In MySQL 5.6 you must use string functions - JSON is not implemented in this version yet:
SELECT CONCAT('[', GROUP_CONCAT('{', SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(test.data, '}', nums.num), '}', -1), '{', -1), '}'), ']') filtered
FROM test
CROSS JOIN (SELECT 1 num UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) nums
WHERE LOCATE('"CountryCode":"AFG"', SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(test.data, ' ', ''), '}', nums.num), '}', -1))
GROUP BY test.data

fiddle
If source array may contain more than 4 objects per value then expand nums subquery.
Restriction: Neither key nor value to be searched must contain a space.


text:
Q: How to trigger new deployment in openshift when we change openshift config maps i have implemented following things in openshift
created Config Map In openshift for environmental configurations
reading those config maps as environmental variables in openshift.
I have a requirement like whenever i change values in the config maps new POD
   needs to be created.
Please suggest me how i can achieve this?

A: Unfortunately there is no out of the box solution yet.
However i solved this issue by generating a hash of my config map "CONFIG_HASH".
This hash is then mounted in the container as an environment variable:
      env:
      - name: CONFIG_HASH
        value: ${CONFIG_HASH}

Consequently, each time the config changes, a deployment is triggered (because the environment has changed).
You will however likely have to use a pipeline (Jenkins, GitlabCI,...) to do this...


text:
Q: Qual é o melhor método de conexão entre o PHP e o Firebird? Utilizo as funções ibase_ para conectar e manipular os dados no Firebird com o PHP. Vi que muitas pessoas também utilizam pdo_firebird. A versão do Firebird que utilizo é a 2.5. Afinal, estou utilizando o melhor e mais viável método de manipular os dados ou seria melhor mudar para pdo?
Surgiu essa dúvida esses dias por ter pesquisado tanto sobre alguns probleminhas no Firebird e vi que a maioria dos posts que pesquisei menciona o pdo. Também pelo fato de ibase_ pudesse ser melhor para uso com o Interbase, já que o próprio nome já diz.

A: Segue a classe que tenho:
Connection.class.php
    <?php

    class Connection {

        public static $conn;

        //lê o arquivo .ini com as config

        public static function open($name) {
            if (file_exists("config/{$name}.ini")) {
                $db = parse_ini_file("config/{$name}.ini");
            } else {
                throw new exception("Arquivo '$name' nao encontrado");
            }

            $user = isset($db['user']) ? $db['user'] : NULL;
            $pass = isset($db['pass']) ? $db['pass'] : NULL;
            $name = isset($db['name']) ? $db['name'] : NULL;
            $host = isset($db['host']) ? $db['host'] : NULL;
            $type = isset($db['type']) ? $db['type'] : NULL;
            $port = isset($db['port']) ? $db['port'] : NULL;

            switch ($type) {
                case 'pgsql':
                    $port = $port ? $port : '5432';
                    $conn = new PDO("pgsql:dbname={$name}; user={$user}; password={$pass};host=$host;port={$port};");
                    break;
                case 'mysql':
                    $port = $port ? $port : '3306';
                    $conn = new PDO("mysql:host={$host};port={$port};dbname={$name}", $user, $pass);
                    break;
                case 'sqlite':
                    $conn = new PDO("sqlite:{$name}");
                    break;
                case 'ibase':
                    $conn = new PDO("firebird:dbname={$name}", $user, $pass);
                    break;
                case 'oci8':
                    $conn = new PDO("oci:dbname={$name}", $user, $pass);
                    break;
                case 'mssql':
                    $conn = new PDO("mssql:host={$host},1433;dbname={$name}", $user, $pass);
                    break;
            }

            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            self::$conn = $conn;
        }

        public static function select($sql) {
            return self::$conn->query($sql);
        }

        public static function exec($sql, $ret_id = false) {
            $retorno = self::$conn->exec($sql);
            if ($ret_id)
                $retorno = self::$conn->lastInsertId();
            return $retorno;
        }

        public static function close() {
            self::$conn = null;
        }

    }

ibase.ini
host =
name = localhost/dados/banco.fdb
user = SYSDBA
pass = 1234
type = ibase

A chamada da classe ficaria assim:
Connection::open('ibase');

$sql = Connection::select('SELECT * FROM banco');//Select

$sql = Connection::exec('INSERT INTO banco (campo) VALUES ('Teste')');//Insert

Connection::close('ibase');

Não esquece de adicionar o pacote abaixo:


text:
Q: Which to use...REST, ASMX, WSE or WCF? I have a Windows Service which performs a certain function, and then needs to send that information off to a webservice for processing. The webservice is hosted by a remote web application. I am trying to ascertain the best way to call the webservice(s) as each web application might be only 2.0, or 3.5 etc. In my windows service, I am defining each "client" in the app.config, e.g.
<Client WebServiceUrl="http://location.com/webservice.svc" Username="" Password="">

</Client>

The web application must implement two web services that are required for my windows service to run, however not sure the best way to implement the "rules" for the web application.
EDIT:
I'll try and rephrase..
The Windows Service runs every 30 seconds and obtains a list of information. The service supports multiple "clients" as shown above. When each client process is run, the data is collected and is then needed to be sent to the supporting web application.
The windows service does not know what to do with the data, it is just sending it. Each web application for a client would be in different locations, and could possibly be built in 2.0, 3.5, PHP, etc. All the windows service cares about, is that when it performs its processing for a client, it is able to send the data to the webservice location defined in the app.config of the windows service.
What I'm trying to determine is how to connect to the webservice (which I'm leaning towards WCF, however Basic or WS not sure), and what rules need to be defined for the web application in how to build the response.
If the Windows service is to support php applications etc, WSHttpBinding would not be an option, which would mean BasicHttpBinding would then work. The other thing to decide is whether or not to utilise a RESTful service or SOAP service.
Hope this makes more sense.

A: I'm not really clear on what you are doing.
It seems like you have 3 things: A Windows Service, and then a web service, hosted in a web app.
I think your question is, what to use, REST, ASMX, WSE or WCF, when interconnecting the Windows Service app with the remote web service.
ASMX, WSE and WCF are alternative programming models for the web service.  REST is not a programming model.  It is not like the other three.
ASMX and WSE will require that you use Web services and SOAP.
WCF can allow you to use Web services and SOAP, REST (XML or JSON) over HTTP, or a binary format over TCP, among other options.
Because it is flexible and current technology, I'd recommend WCF.  ASMX is now termed "legacy technology" by Microsoft.  Doesn't mean it won't work, but it will not get updates.  (Much like WinForms versus WPF).  WSE is no longer in mainstream support, as far as I know.  For these reasons, I wouldn't recommend starting a new project on WSE, nor on ASMX.

WCF is more general than ASMX and can seem more complicated, for that reason.  But once you make some choices and zero in on what you want (for example choose HTTP and REST, or choose binary and TCP), it's more powerful.  WCF can be used as the programming model on both the client or sender (in your case,  the Windows Service, I guess) and/or on the server (the web service hosted in the web app).
Using WCF on the client side does not imply you must use it on the server side, and vice versa.  On the other hand, if you control the source code on both ends, I would recommend using WCF on both sides.
As for "how to implement the rules for the web app" - I don't understand what you are asking there. Maybe if you are more specific on the question there, someone will be able to help out.

Update: Based on your additional explanation, I'm going to suggest you look at the REST stuff in WCF for .NET 3.5.  In PHP it's very easy to implement a REST-style service, and with WCF, the same is true for .NET.  Now in your case the Windows service is the client and it is sending out a request, an update request, to various servers that reside on your customers' networks.  According to REST principles, I'd make those outbound requests PUTs or POSTs, depending on the semantics of the call.
Then you could ship some example service code to your (uppercase) Clients, to get them started on building what they need to receive your outbound PUT/POST messages.
Security is a concern though. You didn't mention it at all, which is surprising.  Security is not one of those things best deferred, so that you "add it on later".  You should think about it early - it may affect the protocol choices you make.  For example, if you need to mutually authenticate the clients and servers (the latter at your "uppercase" Clients' networks), then you may want to go with SOAP, which gives you good options on the protocol side for security.  Secure Web services extensions (WS-Sec, etc) are well supported in WCF, but not sure about the status of this capability in PHP.


text:
Q: Load external script dynamic, and access it, so I can trigger its domready function I am trying to load the Zopim chat client. Normally it is included with a document write action. This causes it to be loaded before the domReady function is triggered, as it needs this to start itself.
I want to load it later, and this works by using prototype (framework determined by Magento) to create a new script element and attaching it to the head. The script is loaded perfectly, but the domReady doesn't fire, so the script is never started.
The script is a nameless class, by this I mean that all its functions are encapsulated in {}
UPDATE: Sorry, I got it wrong, it is as self invoking function, the same syntax as the first answer suggest.
(function C(){
})();
This function call when run sets up listening events for the domReady event under various browsers and then waits. When the domready event fires, it calls a function (that is within the self-invoked function) that starts everything. What I need, is a way to access this function somehow.
END UPDATE
Within that is a function named C.
How can I call this function directly?
Or put another way, how can I start an external javascript file that depends on domready going off, when that event doesn't happen?
Can I load an external javascript file into a variable, so I can name the class?
Can I access the nameless class {} somehow maybe via the script tag?
Is there a way to alter the external file/javascript so I can have it look for another event, one that I can trigger?
About the only solution I can think of at the moment is to create a iframe and load the script in that.

A: If you want to fire it after loading it asynchronously after the domready is already fired, you can do this:
Make your function C a self invoking function by:
(function C(){
})();

With this approach you would be changing the external script though.

A: You may trigger the event programmatically, for example:
window.dispatchEvent(new Event('DOMContentLoaded'));

See Creating and triggering events.
But note that this solution can be tricky to make it work correctly, cause when you trigger the event, some event handlers that have registered to the event will trigger a second time. And this causes problems like page not working as expected or an infinite loop (event registering, handler call, event registering, handler call indefinitely).
So you would need a solution to make sure that the different scripts that registered to the DOMContentLoaded event have their handlers only called 1 time exactly.


text:
Q: How to stop SSIS from "Phoning Home" Working on maintaining a substantial set of SQL Server Integration Services 2008 R2 packages, I've run into an oddball problem.
These packages make frequent use of Script Tasks, each containing C# code used to integrate with some internal Web Services.
Editing one of those scripts involves these steps:

*

*Select the Script Task in the designer

*Right click, select Edit to bring up the Script Task Editor dialog

*Press the Edit Script button

*Wait (just over) 15 seconds

*Edit the script

*Close the script editor

*Press the OK button on the Script Task Editor dialog

*Wait (just over) 30 seconds

*Dialog disappears

It's the waiting, highlighted in bold, that's getting me frustrated.
There's no CPU activity, no disk IO, no network traffic during those times - the editor appears to be just frozen.
BTW - those timings are reliable - I've used a stopwatch to measure them over the past couple of days and they vary by less than my accuracy in hitting the start/stop button on the stopwatch.
The only clue I've been able to find is that netstat shows an extra network connection during the pause:
C:\>netstat -o -b

Active Connections

  Proto  Local Address          Foreign Address        State           PID
  TCP    fsis-datam-dev2:3478   akamai-9.fx.net.nz:http  SYN_SENT        700
  [VSTA.exe]

My current hypothesis is that the delays are some kind of timeout as SSIS (or perhaps the Visual Studio Tools for Applications editor) "phones home" for some reason. The machine in question doesn't have internet connectivity, so the requests are in vain.

A: Yes, your guess is correct and this is a (fairly) well-known issue. The .NET runtime contacts crl.microsoft.com to check for revoked certificates; if your machine has no internet access then the runtime waits until the connection attempt times out, which can result in SSIS packages starting very slowly, Visual Studio apparently locking up etc.
Common fixes are to allow internet access to crl.microsoft.com only, or to use the local HOSTS file to redirect the name to 127.0.0.1.


text:
Q: The call is amibiguous - same signature, single method In a brand new MVC5 project, I have a single html helper:
public static IHtmlString Localized(this HtmlHelper html, string url)
{
    return /* code here */
}

In an empty page, I attempt to call this:
@{ ViewBag.Title = "Home Page"; }
@Html.Localized("~/content/images/mobile/hero.png");

And I get this error:
CS0121: The call is ambiguous between the following methods or properties: 'EUCA.HtmlHelpers.Localized(System.Web.Mvc.HtmlHelper, string)' and 'EUCA.HtmlHelpers.Localized(System.Web.Mvc.HtmlHelper, string)'
How is one method conflicting with itself?

A: This question has been answered here:
The call is ambiguous between the following methods or properties (bug??)
App_Code causes the code to be compiled twice, which doesn't seem to cause a problem in some basic cases. Extension methods an edge case that does not work with App_Code.


text:
Q: How should I do the Vuex with one page of Vue and .NET Core? I have a .NET Core 3.x project, where I also have added an Web API. On one of the pages I have a Vue-page.
Because I was not competent enough to set up a Vue-project inside the .net-project. I decided to have Vue on only one page (to show data).
So how can I use Vuex, when it is only one page that uses Vue?
The most important part of the site is this page because it will be i kind of lookup in the catalog. And to do that I want to browse through data stored in Vuex.
Is this possible. Or is it another way that is easier?

A: You can still use vuex with the vue cdn or within a script tag. When you initialize a new vue element, import the store variable and pass it into the vue element. You will then be able to access like normal.
Something like:
new Vue({
  el: '#app',
  store,
  components: { App },
  template: '<App/>'
})


text:
Q: Bound the determinant Let $A$ be an $n\times n$ matrix, does the following equation
$|det(A)|\leq \Pi_{i, j} (|a_{i,j}|+1)$
hold? In particular, when does the equality hold? Can we tighten the inequality?
(I believe this is correct, but want to see a direct proof from the definition of determinant.)

A: Partial answer:
$$|\det(A)| = \left|\sum_{\sigma \in S_n} sgn(\sigma) \prod_{i=1}^n a_{i,\sigma_i}\right|\leq \sum_{\sigma \in S_n}\prod_{i=1}^n |a_{i,\sigma_i}|$$
This last term is the sum of all products of $n$ different entries $|a_{ij}|$, and as the product
$$\prod_{i,j}(1+|a_{ij}|)$$
does in particular contain all such terms as summands (pick the $|a_{ij}|$ which appear in one of the above summands, and the in the remaining terms pick $1$ ), you are done.


text:
Q: Dynamic pthread spawning sync required(???) I'm trying to write some code using posix threads but I'm stuck from the first step and to be honest I can't realise why. I know that my problem has probably to do with some sort of synchronisation but I can't figure it out.
What I have in main is the following:
while(1){
  int x = getX();
  pthread_t t;
  printf("Main: %d\n",x);
  pthread_create(&t, NULL, process_x, &x);
}

When I try to print the x value from the main and also the process_x function what I get is something like this:

Main: 1
Main: 2
Main: 3
Main: 4
Main: 5
Process_x: 5

What do I miss here?
---- EDIT -----
OK, maybe I need to provide some more info. The getX function receives data from a socket and returns an identifier while for our needs now the process_x just prints the argument it receives.

A: You need to consider that you pass the address of x to a thread, and then without waiting for the thread to finish printing, you modify it's value. Obviously, this will mean that if a few iterations are over before the thread gets to print it's value, the value would have changed.
Two Ways around this:
1) Use a pthread_join and wait for the thread to finish. This is esseentially useless. Because then what is the point of spawning the new thread?
OR
2) Allocate a new address for each thread, and let the thread free it after it finishes printing.
i.e. malloc a new integer, assign x to that integer, pass the new mallocd integer to the thread, let the thread free it when done.

A: A thread will not be executed as soon as you create it using a call to pthread_create. The scheduler can decide to keep it in queue. During that time your while loop has run 5 times and value of x might also have changed to 5. Now when your thread(s) is(are) eventually scheduled, it(they) only sees the latest value of your x and hence print(s) only 5.
I strongly suspect that Process_x was printed only once?
There is no default way to get pthreads executed in any specific order. You need to use some synchrnization techniques like semaphores. Also if you want to see Process_x print all your values, convert x into an array and pass x[i] as argument to pthread_create

A: Apparently using malloc doesn't work because it sets x to 0 so the process always reads 0. But thanks to everyones ideas I finally made it work using a condition variable and now everything is ok. Here is the code.
int main{
  pthread_t t;
  int x;
  while(1){
    pthread_mutex_lock(&receive);
    x = getX();
    printf("Main: %d\n",x);
    pthread_create(&t, NULL, process_x, &x);
    pthread_cond_wait(&goOn, &receive);
    pthread_mutex_unlock(&receive);
  }
}

void *process_x(void* arg){
  pthread_mutex_lock(&receive);
  int x = *(int *) arg;
  pthread_cond_signal(&goOn);
  pthread_mutex_unlock(&receive);
}


text:
Q: Computing $\sum_{n=1}^∞\frac{1}{(n+1)(n+2)(n+3)....(n+p)}$ I have a series question which I can not solve for two days.
$$\sum_{n=1}^∞\frac{1}{(n+1)(n+2)(n+3)....(n+p)} = \frac{1}{p.p!}$$
How can I prove and solve this equation?

A: Note the following $$\sum_{n=1}^∞\frac{1}{(n+1)(n+2)(n+3)....(n+p)}$$
Using partial fraction decomposition the summation becomes $$\frac{1}{p-1}\sum_{n=1}^∞ \left(\frac{1}{(n+1)(n+2)....(n+p-1)}-\frac{1}{(n+2)(n+3)....(n+p)}\right)$$
We can use the telescoping series. The consecutive terms cancel. So your answer is incorrect. The correct answer would be $$\frac{1}{p-1} \times \frac{1}{(1+1)(1+2)....(1+p-1)}=\frac{1}{(p-1)p!}$$
We are done! As mentioned by @ThomasAndrews, the formula would be correct if the denominator was $n(n+1)(n+2)(n+3)....(n+p)$ which can be confirmed through the same method.

A: $$\frac{1}{(n+1)(n+2)(n+3)....(n+p)} = \frac{n!}{(n+p)!}=\frac{1}{\Gamma(p)}\frac{\Gamma(n+1)\Gamma(p)}{\Gamma(n+p+1)}=\frac{1}{\Gamma(p)}\beta(n+1,p)$$
then
\begin{eqnarray}
\sum_{n=1}^\infty\frac{1}{(n+1)(n+2)(n+3)....(n+p)}
&=&
\sum_{n=1}^\infty\frac{1}{\Gamma(p)}\beta(n+1,p)\\
&=&
\frac{1}{\Gamma(p)}\sum_{n=1}^\infty\int_0^1t^{n}(1-t)^{p-1}dt\\
&=&
\frac{1}{\Gamma(p)}\int_0^1\sum_{n=1}^\infty t^{n}(1-t)^{p-1}dt\\
&=&
\frac{1}{\Gamma(p)}\int_0^1\frac{t}{1-t}(1-t)^{p-1}dt\\
&=&
\frac{1}{\Gamma(p)}\int_0^1t(1-t)^{p-2}dt\\
&=&
\frac{1}{\Gamma(p)}\int_0^1t^{p-2}(1-t)dt\\
&=&
\frac{1}{\Gamma(p)}\int_0^1t^{p-2}-t^{p-1}dt\\
&=&
\frac{1}{\Gamma(p)}\frac{1}{p(p-1)}\\
&=&
\frac{1}{p!(p-1)}
\end{eqnarray}
For $p=2$ we know
$$\sum_{n=1}^\infty\frac{1}{(n+1)(n+2)}=\sum_{n=1}^\infty\frac{1}{n+1}-\frac{1}{n+2}=\frac12$$
that shows our answer is true.


text:
Q: How to uninstall previous version as part of msi install? I have a product that's packaged as an MSI. When my customers install a new version of my product over the top of an existing version it's not working nicely because of a custom VBS action, as explained below. My question is: how I can change my MSI so that installing over the top will always do a full uninstall of any existing version beforehand?
The detail is:
I have a product with a variety of versions deployed at various different companies. About once a year each of my customers would receive a new version of my product and deploy to their company's workstations. The people responsible for deployment would prefer they can install the new version over the top of the old version, instead of having to include an uninstall step in their install package.
The msi install creates and writes some files to [CommonApplicationData]\MyApp folder. During execution the application creates more files in [CommonApplicationData]\MyApp folder. During uninstall I need to delete all these files. Since they're not installed by the msi they aren't automatically uninstalled, so I created a vbs script that deletes that folder and anything else in it. I put a command to execute that vbs in ExecuteDeferred:
...
RemoveFiles
RemoveFolders
CreateFolders
MoveFiles
InstallFiles
PatchFiles
If REMOVE="ALL" Then
    REM line below is my custom script
    call VBScript From Installation (MyApp_UninstallCleanup)
End
DuplicateFiles
BindImage
CreateShortcuts
...

So far so good and it works fine when installing & uninstalling. However, if I install a new version of my product over the top of an existing version it appears things happen in this order:
a) install new version, creating various files in [CommonApplicationData]\MyApp folder, and in [Program Files]\MyApp..., overwriting files of old version
b) run my vbs, deleting the [CommonApplicationData]\MyApp folder
I do have the GUIDs for the old versions listed in the Upgrade table in my new MSI, and apart from this custom script the upgrade process seems to work ok.
The product itself is pretty small so it would be fine if the installer always removed previous versions entirely before installing the new version. There are no user settings on the workstation that need to be retained and the file sizes aren't large. Hence for simplicity I want the previous versions to be uninstalled rather than updated with only the bits that have changed.
Is there a way I can change my new MSI so that it will uninstall previous versions first?
Notably, I have many companies who have the existing version of the MSI installed that contains the custom vbs. So the solution really needs to be one that can cope with the existing installed msi.
I've used Wise Installation Express 7.0 to create the MSI.
thanks!!
(cross-posted here)

A: Schedule RemoveExistingProducts action before InstallInitialize action:

In this case, the installer removes the old applications entirely before installing the new applications. This is an inefficient placement for the action because all reused files have to be recopied.

A: Answer from EdT on Symantec forums
If you have used the standard Wise template for your installs, then the RemoveExistingProducts action is sequenced at the end of the InstallExecute sequence. Although technically this is the most "efficient" placement, unless you have very carefully run UpgradeSync when creating your new package to upgrade the old, the end result is usually one of missing files or other aberrations.
The fix is to re-requence the RemoveExistingProducts action so that it runs between InstallValidate and InstallInitialize. That ensures that the old app is removed entirely before the new version is installed.
Look up "RemoveExistingProducts" in the help file MSI.CHM for a more detailed explanation of the options for positioning this action.


text:
Q: Python 3.6, Pandas Import .csv file, filter and analyze columns, save results to new .csv file I have a .csv file 'Data.csv', and want to import it to Python3.6 using pandas. I want to analyze this data by filtering multiple columns, and save my results to new .csv files with my analyzed data. My 'Data.csv' is separated by ',', and works with loc to filter my columns. If my imported file is comma delimited, can I change this to separate by tab '\t' for the new "filtered" .csv files?
(Running Python 3.6)
import pandas as pd
import numpy as np
df = pd.read_csv('Data.csv', sep = ',')
df1 = df.loc[:, ['STATION',"NAME","DATE","AWND","SNOW"]]
df1["DATE"] = pd.to_datetime(df1.DATE)
df1.to_csv('filteredData.csv', sep=',', header=True)

From here, I have my new .csv file with my desired columns and all rows of my data. I want to calculate the averages of each month, and produce two more .csv files by year (2016, and 2017).
df2 = df1.groupby(pd.Grouper(key='DATE', freq="M")).mean()

If I understand this correctly, this has grouped my data by the average of each month. How do I further separate each year (2016, and 2017) into its own .csv file and show the results as: NAME, Month, and Average?
Thanks for your help!


text:
Q: asking user for input valid command in java I am developing my own shell(command prompt).   [When
a user enters a built-in command, the shell is required to search   and execute the respective code accordingly.]
I have created my code using command split, and command parameters in order to store my commands. but one thing I'm confused about is that making a command that is not in the list.
I think of using if statement to print invalid comment (for example)
if (command!="exit")||(command!="about")||(command!="date")||(command!="time")||(command!="hist")||(command!="notepad")
                    ||(command!="")||(command!="hist -h")||(command!="hist -l")||(command!="c"){

System.out.println("invalid command");
}

but this statement is way too much if there are tons of command line.. so is there an easy way of implementing it !?

A: If this java and all commands are Strings and input command is also a String you can simplify what you are trying to do by creating a list of valid commands and do a contains check.
List<String> validCommands = Arrays.asList("exit", "about", "date");
if (!validCommands.contains(command)) {
    System.out.println("invalid command");
}

That being said there are better ways to maintain a list of valid command outside java program such as properties file and load list of valid commands from that file. This will make your program more maintainable.

A: Use a Map<String, Command>, to keep track of the available commands.  If the command is not in the map then it's invalid. For example:
public class Shell {
    private final Map<String, Command> supportedCommands;

    public Shell(Map<String, Command> supportedCommands) {
        this.supportedCommands = supportedCommands;
    }

    public void execute(String command, String[] args) {
        Command c = supportedCommands.get(command);
        if (c == null) {
            System.out.println("invalid command");
        } else {
            c.execute(args);
        }
    }

    public interface Command {
        public void execute(String[] args);
    }

}


text:
Q: Placeholder text on search bar misaligned in Firefox I have a universal search bar at the top of our site, and it works beautifully in both Chrome and Safari. The problem with Firefox is that the placeholder text is aligned to the bottom of the bar, instead of the middle. I know that placeholder is usually web-kit only, but this does show up in FF. See screenshot below:
Chrome:
http://www.cl.ly/2N3k340744071s1x291f
FF:
http://www.cl.ly/1e16472P2p1w0G2E062I
and here is the code that goes along with it. HTML;
<form action="#" id="nav_search_form">

<input type="text" placeholder="Search Careers And People" class="search" id="nav_search_q" />

                <input type="submit" style="visibility:hidden;">

              </form>

and CSS:
input.search  {
    border:1px solid #bdbdbd;
    padding:7px 10px 0 30px;
    font:13px/15px "Helvetica Neue", Helvetica, Arial, sans-serif;
    background:url(images/search.png) no-repeat 0 center;
    color:#525252;
    width:190px;
    -moz-border-radius:12px;
    -webkit-border-radius:12px;
    -o-border-radius:12px;
    -ms-border-radius:12px;
    -khtml-border-radius:12px;
    border-radius:12px;
    margin-top:17px;
    margin-left: 0px;
}

input.search.placeholder  {
    color:#b3b3b3;
}

input.search:hover {
    border-color:#8c8c8c
}

input.search:focus {
    border-color:#39b2e5
}

A: It's the padding:7px 10px 0 30px; that make the text appears at the bottom in firefox.
You have a padding-top of 7px and padding-bottom of 0px.
They have to be equal for the placeholder (or text) to be in the middle:
for example:
padding:3px 10px 3px 30px;

(I don't know if this will affect the good behavior in Chrome or Safari)


text:
Q: If não está funcionando corretamente Olá, pessoal. Tudo bem? Então, eu gostaria de tirar uma duvida.
Eu criei o seguinte codigo:
    import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        Scanner entrada = new Scanner(System.in);

        String Resposta = "";
        System.out.println("Digite a Combinação correta");
         System.out.println("L, M, N, B");
         System.out.println("Q, S, R, P");
         System.out.println("D, G, H, V");
         Resposta = entrada.nextLine();
         System.out.println(Resposta);
                 if(Resposta == "Floripa"){
            System.out.println("Show! Sou de Floripa");
        }

    }
}

o problema é o seguinte, quando eu digito Floripa, a variavel muda o valor pra floripa, porem mesmo assim o if não funciona

A: Para comparar Strings em Java, é necessário usar a função equals, e não o operador ==. Para funcionar, faça:
import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner entrada = new Scanner(System.in);

    String Resposta = "";
    System.out.println("Digite a Combinação correta");
     System.out.println("L, M, N, B");
     System.out.println("Q, S, R, P");
     System.out.println("D, G, H, V");
     Resposta = entrada.nextLine();
     System.out.println(Resposta);
             if(Resposta.equals("Floripa")){
        System.out.println("Show! Sou de Floripa");
    }

}
}


text:
Q: Is there a way to develop custom haptic feedback patterns? According to Apple's Human Interface Guidelines about haptic feedback, some apps/games call for custom haptic patterns.
How would someone go about doing a custom pattern for an app. Both react-native-haptic-feedback, and expo-haptics offer an API for pre-defined Apple's and Android's feedback patterns (Different impacts styles, and some notification patterns like success, error, etc). However, they don't offer creation of new patterns.
I am aware of the Vibration from react-native. However, it doesn't allow for fine tuning patterns using short impact styles from the two previously mentioned packages.
Is there an "out of the box" solution for creating something like this (e.g. two Light impacts, and one Heavy with 50ms pause between them)? I can't find it anywhere.
Apple describes something like this for native developers here


text:
Q: Spring Integration: NotWritablePropertyException - Invalid property 'Content-Type' In my Spring Boot application with Spring Integration http outbound gateway, I got http error code 415. So I added a headerMapper bean to the configuration, but this throws NotWritablePropertyException. Message is property 'Content-Type' is not writable or has an invalid setter method. Does the parameter type
of the setter match the return type of the getter?
Configuration:
<int:gateway id="requestGateway"
    service-interface="org.myorg.springintegration.gateway.http.RequestGateway"
    default-request-channel="post_send_channel" />

<int:channel id="post_send_channel" />

<int:header-enricher input-channel="post_send_channel">
    <int:header name="Content-Type" value="application/json; charset=utf8"/>
</int:header-enricher>

<int-http:outbound-gateway
    request-channel="post_send_channel"
    url="http://localhost:8080/incomes" http-method="POST"
    expected-response-type="java.lang.String" />

Request Gateway
public interface RequestGateway {
    String echo(Map<String, String> request);
}

Main class
@SpringBootApplication
public class HttpApplication {

    public static void main(String[] args) {
        SpringApplication.run(HttpApplication.class, args);

        ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("http-outbound-gateway.xml");

        Map<String, String> postMap = new HashMap<String, String>();
        postMap.put("amount", "2000");
        postMap.put("description", "Second Income");

        RequestGateway rg = context.getBean("requestGateway", RequestGateway.class);
        System.out.println(rg.echo(postMap));

        context.close();
    }
}

UPDATE on 17-May-2018
After configuring a header-enricher as suggested by Artem Bilan, I now get the following error:
2018-05-17 12:30:48.354  INFO 4452 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started _org.springframework.integration.errorLogger
[WARNING]
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:496)
    at java.lang.Thread.run (Thread.java:748)
Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.util.HashMap<?, ?>] to type [java.lang.String]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound (GenericConversionService.java:321)
    at org.springframework.core.convert.support.GenericConversionService.convert (GenericConversionService.java:194)
    at org.springframework.core.convert.support.GenericConversionService.convert (GenericConversionService.java:174)
    at org.springframework.integration.gateway.GatewayProxyFactoryBean.convert (GatewayProxyFactoryBean.java:755)
    at org.springframework.integration.gateway.GatewayProxyFactoryBean.invokeGatewayMethod (GatewayProxyFactoryBean.java:527)
    at org.springframework.integration.gateway.GatewayProxyFactoryBean.doInvoke (GatewayProxyFactoryBean.java:469)
    at org.springframework.integration.gateway.GatewayProxyFactoryBean.invoke (GatewayProxyFactoryBean.java:460)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke (JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy79.echo (Unknown Source)
    at org.javacodegeeks.springintegration.gateway.http.HttpApplication.main (HttpApplication.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:496)
    at java.lang.Thread.run (Thread.java:748)

A: I guess you mean header-enricher before http:Outbound-Gateway. You need to populate such a header, meanwhile a mapper is about to add an existing header to the request or not.
See Reference Manual for more info: https://docs.spring.io/spring-integration/docs/5.0.4.RELEASE/reference/html/messaging-transformation-chapter.html#content-enricher


text:
Q: Storing data so that it is deleted when the program is I originally thought that the best way to save data (user settings, high scores, etc) for my application would be by writing to an embedded file in the .exe. After some research I've found that this isn't possible and that I'm better off writing to the App Data folder which is designed for this purpose.
However, I don't like this as it means that the data will persist after the .exe is deleted. It certainly isn't ideal for me as I often make many versions of apps which I ask others to test out — this would mean that their App Data folder would be cluttered with useless data from testing.
Is there a better place or way to store data which will ensure that everything belonging to the application is deleted when the .exe is?
Note that I'd like to be able to store large files, so a string in My.Settings might not be able to handle it. I'd also prefer not to write to the same directory that the program is in.


text:
Q: How can I write a contraint in gurobi that involves min of a set? I am having trouble with this constraint:
E_i1,...,i <= min{x1,...,xi} where i comes from a set of 9 numbers called I. x and E are variables and binary.
I tried:
for i in I:

    f = model.addConstr(E[i] <= min((x[i])) , name = "f")

    print(x[i])

    print(E[I])

but it was giving the value of zero to all the E since it would just evaluate all the x.
The objective function should be:
(ΣPijk * xi) - Σ(pi1jk * ... * pi) * Ei
which means that it should evaluate the first P with the second P and the value of E will be based on the value of x of those two. Ex:
P1jk*1 + P2jk*1 + P3jk*0 - ((P1jkP2jk)(1)) - ((P2jkP3jk)(0))
So for the first (P1jk*P2jk)(1), E=1 because the min between {x1,x2} is 1.
For the second (P2jk*P3jk)(0), E=0 because the min between {x2,x3} is 0


text:
Q: how to get $\theta$ and $\phi$ in these two equations I would like to solve the below equations but I'm not really sure how to get $\theta$ and $\phi$ .
\begin{align*}
&a \sin \theta = h \\
&b \cos\phi \cos\theta = r
\end{align*}

A: With
$$a \sin \theta =h,$$
you get:
$$\cos \theta = \sqrt{1-\dfrac{h^2}{a^2}},$$
and:
$$\cos \phi= \dfrac{r}{b \cos\theta}=\dfrac{ba}{r\sqrt{a^2-h^2}}.$$

A: $$a\sin(\theta) = h \\ \implies \sin(\theta) = \frac{h}{a} \\ \implies \theta = \arcsin\left( \frac{h}{a} \right)$$ You can use a similar strategy to solve for $\phi$, with the difference that you can plug in  $\theta = \arcsin\left( \frac{h}{a} \right)$


text:
Q: No search indexes bound via Haystack using Haystackbrowser Has someone ever used this tool for all-text searching? I just installed this to my project and the installation seems working fine. But when I clicked the haystackbrowser button in my admin page, it returned to a webpage which said no search indexes bound via Haystack. I checked my project and I am sure that I created the search_index file.
Could someone please help me? Thanks!


text:
Q: Can CSS be considered a DSL? According to Wikipedia, CSS is a style sheet language. However, it's pretty much the only such type of language in use (at least from a web developer's perspective).
When trying to categorize CSS as a language or technology (e.g. for a résumé), would it be acceptable to simply call it a domain-specific language? If you don't think it can, why not?

A: It's a language. It's specific to a domain. If you're going to have a "DSL" list on your resume, I don't see why CSS wouldn't count as one.

A: Is it a DSL? Yes.
Should you put it in your resume as such? No!
You're debating it (since you're asking the question here). If you're debating it, or more importantly, if you think a potential employer will debate it, why bother? What's the upside?
Do you believe that an employer will say "I don't like that he puts DSL and CSS in the same context and I'm going to bring him over so he can convince me?" No. You're just making it more likely to have your resume ignored by the employer.
The only upside is that buzzword scanners will find both CSS and DSL in your resume. Meh.
Extra points for résumé though. Instead of resumé or even my lazy resume.

A: No

In software development and domain
  engineering, a domain-specific
  language (DSL) is a programming
  language or specification language
  dedicated to a particular problem
  domain, a particular problem
  representation technique, and/or a
  particular solution technique.  [wiki]

CSS is neither programming language nor specification language. CSS does not allow you to express any computations, doesn't have variables, and in fact in current version there are no expressions at all (might change in the future).

A: To answer the question of whether CSS is a domain specific language, according to Martin Fowler, it is.  In fact he lists it among examples of DSLs.
You do have to understand that talk about DSLs has been going on for a while now, and Wikipedia's more narrow definition has come along much later in the discussion.  Understand that Wikipedia is edited by peers who may or may not have a full grasp of what has been discussed so far.  It's definition covers the most common uses for DSLs, and why you may want to create one of your own.  However, it does not have a complete article.  The fact that it omits markup languages completely is an omission.  Perhaps the smart doctorates came along later and redrew the lines--but from the beginning markup languages were included with DSLs in early conversations.
Classifying CSS on a Resume
While CSS is a DSL, you don't want to list it under a section of DSLs on your resume.  The most common way to reference CSS is to lump it with HTML.

A: I disagree that CSS can be called a domain specific language.
Normally with a DSL what you would call the "domain" is a business domain, not a technical domain. A DSL defines keywords and constructs that indicate entities specific to the business. The goal is to make it easy for people who are experts in the business domain to use the DSL.
CSS is a declarative language to define styles for marking up documents in HTML, it does not have anything to do with a specific business domain and can therefore not be called a DSL.

A: It's not a general purpose language, so it's easy to categorize it as a domain-specific language.
At the same time, your question is also about whether it makes sense to place it under a heading of domain-specific languages on your resume. Personally, I don't think it makes sense to do that, since even though CSS is a DSL, it's general technology for people that work on websites and web applications.
If you're applying for a job in web development, I would expect you to know CSS and would expect that in a list detailing your knowledge of important web technologies such as HTML5, Javascript, etc.
There are DSLs that would make sense on the resume of a web developer, such as WebDSL. If you know them, I would mention them as DSL on your resume, because they show that you have knowledge of domain-specific technology in addition to your general technical knowledge. (At the same time, most web development teams focus only on the general technology currently, so it probably wouldn't be of importance anyway, but I mention it here as an example of what would make sense in such a section.)

A: Domain Specific Languages are languages created to support a particular set of tasks, as they are performed in a specific domain.
The Cascading Style Sheet language defines the style to use to visualize a document. We can use it to define how an HTML document will appear on the screen or how it will appear when printed.So css is used to perform Specific task which is designing webpage.

A: CSS is (by accident) a Turing complete language.
That feature makes it a DSL.
You might also look into DSSSL, which is a dialect of Scheme to manipulate SGML documents, and is an interesting DSL.
I don't mention DSL in my resume, except when claiming to be a DSL designer and implementor.
You could mention several DSLs in your resume, as an indication that you have the skills to learn another one easily.


text:
Q: Silverlight OOB White Screen Of Death: Silverlight Installation required after each reboot we are getting White Screen Of Death on few user's machine for last few months and a number of users is getting added from last month for the same issue. Earlier we were using the CleanSilverlight from the following site
http://support.microsoft.com/kb/2608523.
Now we have the following issue that requires immediate fix:

*

*Whenever we apply CleanSilverlight then my OOB starts working fine but it start displaying same white screen after few days without any action (Installation/Uninstallation)

*Whenever the system reboots then we need to apply CleanSilverlight and install the Silverlight once again on user's machine to work with OOB. It seems rebooting interferes with OOB application.

Both of these issues are very frequent from last one month. I don't know if any update to windows/browser is the root cause for the issue.
One the system is having the following configuration to run OOB:

*

*OS name and version: Windows 7 32-bit

*Browser name & version: IE 8 & Google Chrome 38.0.2125.111 m

*Silverlight version: 5.1.30514.0
Any help would be greatly appreciated.
Regards,
Maddy