text:
Q: Windows 7 => Windows 10 Upgrade, can't reset This is a laptop that came with Windows 7 professional. Then when Windows 10 update became available, I upgraded it so for neither of the systems I have an installation media. I'm trying to reset it because it has become sluggish and generally would like to clean it up.
I go to Recovery => Reset This PC => Remove Everything It says it can't find the recovery environment and I need to insert the installation media.

A: This is because normally when you install the OS it will create a small partition of basic settings that it needs in this case called the recovery partition.
If it's missing, and my old laptop had the same problem, you will likely need to get a disk from the Laptop manufacturer for about 20 bucks...depending because it will come with the vendor licensed version of windows -with all of the bloat-ware unfortunately.
If you want to continue to fiddle around you can try with another computer to get an installable media such as a disk or USB stick with by following the directions at Microsoft https://www.microsoft.com/en-gb/software-download/windows10 under the subheading "need to create a USB, DVD, or ISO." insert the media and try a repair. or insert the media just before you try to factory reset. You could also try to install the OS completely by booting from the media, but I cannot guarantee you will be able to verify a license this way since it was likely bought in bulk by whomever made your Laptop. On the plus side Windows 10 is supposed to be linked by account to hardware so that might work...I just haven't dealt with a laptop since they changed this model and expect them to refer you to the Laptop manufacturer for a recovery disk.


text:
Q: How to draw this figure and extract information out of it? Consider a unit sphere. The cube of the maximum size that can be inscribed inside it has the vertices $ (\pm1, \pm1, \pm1)/\sqrt3 $. A tetrahedron can be created from this cube by choosing appropriate vertices. A tetrahedron has 4 faces and I need 4 great circles of the unit sphere that are parallel to these faces. Then I need to arrange 8 points such that their distance from the great circles is maximized. How do I do it?

A: We first define the points of the cube and tetrahedron. From the tetrahedron points, we choose all subsets of 3 points, defining the surfaces of the tetrahedron.
cube = Flatten[
   Table[{x1, x2, x3}, {x1, -1, 1, 2}, {x2, -1, 1, 2}, {x3, -1, 1,
     2}], 2];
tetr = cube[[{1, 4, 6, 7}]];
surf = Subsets[tetr, {3}];

From the 3 points defining a surface, we take the cross product to get a vectors perpendicular to the surfaces:
perpend = Cross[#[[2]] - #[[1]], #[[3]] - #[[1]]] & /@ surf;

Now we would like to define a 3D circle that we can then rotate. Here we met a small problem, because in MMA we only have 2D circles. We may draw a 3D circle using ParametricPlot, but this can not easily be rotated because only graphics primitives can be easily rotated. We therefore dig out the 3D line from the output of ParametricPlot:
circle = ParametricPlot3D[{Cos[p], Sin[p], 0}, {p, 0, 2 Pi}][[1, 1, 1, 3, 1, 3]];

This circle can now be rotated using Rotate. And we now rotate the original circle to the directions given in perpend:
Graphics3D[{Rotate[circle, {{0, 0, 1}, #}] & /@ perpend, Opacity[0.5],
   Sphere[]}, Axes -> True, AxesLabel -> {"x", "y", "z"}]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Counters in for loops An expression is displayed on screen, and every time an incorrect answer is submitted it displays hints.
This is my code for a onClick method:
TextView setHints = (TextView) findViewById(R.id.hints);
    // Get the Answer from your EditText
    String answer =  display.getText().toString();
    setAnswer.setText(answer);

for(int i = 0; i < multiArray.length ; i++)
    {
        // if the answer is in position 1 of Array [i]
        if(answer.equals(multiArray[i][1]))
        {
            // We have found the answer, Congratulate the User
            displayAnswer.setTextColor(getResources().getColor(R.color.green));
            displayAnswer.setText("CORRECT");
            break;

         }else{
             // Tell them how bad they are since they can't solve simple equations!
             displayAnswer.setTextColor(getResources().getColor(R.color.red));
             displayAnswer.setText("INCORRECT");

             for (int count = 0; count<5; count++){
                 if(Prefs.getHints(this)){
                     if (Integer.parseInt(answer) < Integer.parseInt(multiArray[random][1])){
                         setHints.setText("Greater");
                         break;
                     }
                     else{
                         setHints.setText("Less");
                     }
                     if (Integer.parseInt(answer) == Integer.parseInt(multiArray[random][1])){
                         setHints.setText("Hints");
                         break;
                     }
                 }

                 if (count > 5){
                     displayAnswer.setText("No Hints Left!");
                     break;
                 }

             }
         }

    }

The part that doesn't seem to be working correctly is:
if (count > 5){
                     displayAnswer.setText("No Hints Left!");
                     break;
                 }

I want displayAnswer.setText("No Hints Left!"); to be displayed after 4 attempts of clicking the submit button. When i run my app, i still can submit an answer after 5 attempts. What am  i missing here ?

A: count will never be greater than 5.  It is declared at the top of your for loop, which terminates at 4 (< 5).  You need to keep an activity-level (class level) variable that will track how many times the button has been clicked, instead of using the for loop.

A: Your loop stops if count = 5

for (int count = 0; count<5...

but your "No Hints Left!" is only displayed if count > 5.
How about changing both :

for (int count = 0; count<4...
if (count >=4)


text:
Q: Regex that extracts text between tags, but not the tags I want to write a regex which extract the content that is between two tags <title> in a string but not the tags.
IE I have the following
<title>My work</title>

This is my work.

Learning regex.

The regex
(<title>)(.*?)(<\/title>)

extracts <title>My work</title> but I want to extract only My work. How can I do that?
This is a link to the example http://regex101.com/r/mD8fB0

A: the best way is to use Assertions, for your case, the regex would be:
(?<=\<title\>).*?(?=\<\/title\>)

for more details have a look here

A: In your case, you could just use the second backreference from the regex, which would hold the text you are interested in.
Since you mention preg_match in your tags, I am assuming you want this for PHP.
$matches = array();
$pattern = '#<title>(.*?)</title>#'; // note I changed the pattern a bit
preg_match($pattern, $string, $matches);
$title = $matches[1];

Note that this is actually the first back reference in my patterns, since I've omitted the parentheses around the tags themselves, which were not needed.
Typically, you should not use Regex to parse HTML documents, but I think this might be one of those exception cases, where it is not so bad, since the title tag should only exist once on the page.

A: I used this as a replace function of Regex: (<.+?>)

A: You can use this following Regex:
>([^<]*)<

or,   >[^<]*<
Then eliminate unwanted characters like '<' & '>'


text:
Q: Regular Expressions for identifying harvard citations This is the regular expression I used to identify Harvard-style citations in a windows forms application using C#.
\([a-zA-Z]*\,\s[0-9_]*\

Citation example :
(Barnes, 1997)

but citing two or more authors, the regular expression doesn't locate them.
Citation example :
(Smith, 2001; Brown & Black, 2007)

Please tell me a way to overcome the problem.

A:   \(([\w\&\.\s]+,\s\d{4}(;\s+[\w\&\.\s]+,\s\d{4})*)\)

Should be more like that. Add other symbols that can be present in the author name
You can also add more capture groups if you need too.


text:
Q: Black screen during startup causes automatic reboot On a notebook with Ubuntu 18.04.2 (x86, 32 bit) the boot process has been causing problems since a few days.
Boot problem in detail:

*

*On startup no grub menu appears.

*The dark purple background typical for Ubuntu without any Ubuntu logo or text appears for several seconds.

*The screen briefly turns black and the notebook restarts automatically.

*The grub menu appears.

*I choose "Ubuntu".

*Ubuntu searches for file system errors.

*Ubuntu boots up.

*The usual Unity 7 desktop appears after a while.

After shutting down and turning on again, the process starts again from the beginning. See syslog.
What is the reason for this problem and how can it be solved?

A: Adding following line
GRUB_GFXPAYLOAD_LINUX=text
to /etc/default/grub and update grub with
sudo update-grub
solved the problem.
See: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1724639


text:
Q: Setting up GlusterFS cluster using Ansible I'm trying to setup a 3 node GlusterFS cluster using Ansible and have run into some issues trying to setup the backend storage.
My current setup consists of 3 nodes, each of which has a 10G disk attached (/dev/vdb) in addition to the primary storage (/dev/vda).
I'm trying to use the official gluster-ansible-role (https://github.com/gluster/gluster-ansible-infra) to prepare the backend disks (/dev/vdb). My aim is to:

*

*Create a volume group 'storage_vg' which contains /dev/vdb as the physical volume.

*Create a logical volume 'storage_lv' from 'storage_vg'.

*Create a XFS file system on 'storage_lv' and mount it under /mnt/brick

My playbook is as follows:

- hosts: all
  become: True
  roles:
    - gluster.infra
  vars:
    gluster_infra_fw_state: disabled
    gluster_infra_volume_groups:
      vgname: 'storage_vg'
      pvname: '/dev/vdb'
    gluster_infra_thick_lvs:
      vgname: 'storage_vg'
      lvname: 'storage_lv'
    gluster_infra_mount_devices:
      path: '/mnt/brick'
      vgname: 'storage_vg'
      lv: 'storage_lv'

The playbook fails with the following error:
TASK [gluster.infra/roles/backend_setup : Group devices by volume group name, including existing devices] ******************************************************************
fatal: [gluster-node1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'str object' has no attribute 'vgname'\n\nThe error appears to be in '/root/.ansible/roles/gluster.infra/roles/backend_setup/tasks/get_vg_groupings.yml': line 3, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Group devices by volume group name, including existing devices\n  ^ here\n"}

I've uploaded the full log file here https://paste.ubuntu.com/p/dGPD7KRPMF/

A: Details of how this was resolved can be seen here: https://github.com/gluster/gluster-ansible-infra/issues/70
A few changes had to be done to get this to work.

*

*There was a suggestion by the developers to use the 1.0.4 branch instead of the default branch.

*The size variable needs to be set under gluster_infra_thick_lvs

*On Debian (Buster), xfsprogs needs to be installed.
Here's my working playbook.
---
- hosts: all
  become: True
  roles:
    - gluster.infra
  vars:
    gluster_infra_fw_state: disabled
    gluster_infra_volume_groups:
      - vgname: 'storage_vg'
        pvname: '/dev/vdb'
    gluster_infra_thick_lvs:
      - vgname: 'storage_vg'
        lvname: 'storage_lv'
        pvs: '/dev/vdb'
        size: '100%FREE'
    gluster_infra_mount_devices:
      - path: '/mnt/brick'
        vgname: 'storage_vg'
        lvname: 'storage_lv'


text:
Q: Dependent Dropdown issues in Drupal 7 I am using two select boxes in my form: one for country and one for state. I want the states box to be displayed based on the selection of the country box.
I also have two database tables: countries and states.  The  country's table structure is { Country Code and Country Name } and the states table structure is { Country Code and State Name }.
Thanks in advance.

A: Take a look at Hierarchical Select module.
Demos and showcase


text:
Q: Parsing Custom Created MIDI Files in Android I have re-created a MIDI file without altering any of its Meta events. I have merely added SysEx (System Exclusive) messages under each note_on and note_off event. I use this library to parse MIDI files and extract tracks in order to get the MIDI messages.
Following is some sample code that I have tried (I have the MIDI file inside the raw folder).
try {

    InputStream is = getResources().openRawResource(R.raw.mysamplemidifile);
    File tempFile = File.createTempFile("temp", ".mid");
    tempFile.deleteOnExit();
    FileOutputStream out = new FileOutputStream(tempFile);
    IOUtils.copy(is, out);
    MidiFile midi = new MidiFile(tempFile);
    ArrayList<MidiTrack> tracks = midi.getTracks();
    MidiTrack sysExTrack = tracks.get(tracks.size() - 1);

} catch (Exception e) {
    e.printStackTrace();
}

Originally the total number of MIDI messages is ~2500. But the library is able to fetch only about 2300 MIDI messages.
The sysExTrack variable contains the incompletely parsed SysEx data.
I am at a loss to understand what is going wrong here. Any help with the same is appreciated.
Edit:
The MIDI file gets parsed correctly in iOS.


text:
Q: On the rank of a matrix $S$ with coefficients in $\mathbb F_{2^m}$ Let $\mathbb F$ be a finite field with characteristic 2 and let $S \in M(2k, 2k, \mathbb F)$ be the matrix defined as follows
 $$ S=\left[\begin{array}{ccccccc}
                          0 & \cdots &  &  & 0 & 1 & s_1 \\
                          0 & \cdots &  &  & 0 & s_1 & s_2 \\
                          0 & \cdots &  & 1 & s_1 & s_2 & s_3 \\
                          0  & \cdots & 0 & s_1 & s_2 & s_3 & s_4 \\
                          \vdots &  &  & & & &\vdots \\
                          1 & s_1 & & \cdots & & & s_{2k-1}  \\
                          s_1 & s_2 & & \cdots & &  &s_{2k}
\end{array}\right],$$
with $s_{2i}=s_i^2$  $\;\;\forall \;i=1, \ldots, k$.
Show that the rank of $S$ is exactly $k$.
Obviously the rank is at least $k$, since the odd rows (or the columns) are linearly independent.
This problem comes up studying binary BCH codes.

A: The result is true indeed. Here is a rather technical solution. I work by induction over $k$, thus denoting by $S_k$ the above $(2k)\times(2k)$ matrix. Let us transform the matrix through the following series of row and column operations:
$C_{2k} \leftarrow C_{2k}+s_1 C_{2k-1}$ and
then, for odd $j$ from $3$ to $2k-3$,
$L_k \leftarrow L_k+s_{k-j}L_j$ for $k$ from $j+1$ to $2k$.
After those operations, the matrix obtained from $S_k$ has the following form:
$$S'_k=\begin{bmatrix}
0 & D \\
T & ? \end{bmatrix}
$$
where $D=\begin{bmatrix}
1 & 0 \\
s_1 & 0
\end{bmatrix}$, the odd-labelled columns of
$T$ are $\begin{bmatrix}
0 \\
0 \\
\vdots \\
0 \\
0 \\
1 \\
0
\end{bmatrix}$,  $\begin{bmatrix}
0 \\
0 \\
\vdots \\
1 \\
0 \\
0 \\
0
\end{bmatrix}$, ..., $\begin{bmatrix}
1 \\
0 \\
\vdots \\
0 \\
0 \\
0 \\
0
\end{bmatrix}$, and $T$ is equivalent to $S_{k-1}$.
By the induction hypothesis $T$ has rank $k-1$ and hence its column space is spanned by the above vectors. To conclude that $S_k$ has rank $k$ we then need to prove that the even-labelled entries in the last column of $S'_k$ are all zero.
Let $p \in \{2,...,k\}$. By careful examination, one finds that the $(2p,2k)$-entry of $S'_k$ equals
$$s_{2p}+\sum_{(i_1,\dots,i_\ell) \in A_p} s_{i_1} s_{i_2}\cdots s_{i_l}$$
where $A_p$ is the set of all lists $(i_1,\dots,i_\ell)$ of positive integers whose sum is
$2p$ and in which $i_1$ and $i_\ell$ are odd and the other entries are even.
Now, we show by induction that this sum equals $s_{2p}$. First of all, $\theta : (i_1,\dots,i_\ell) \mapsto (i_\ell,\dots,i_1)$ is an involution on $A_p$, and as $\mathbb{F}$ has characteristic $2$ we deduce that
$$\sum_{(i_1,\dots,i_\ell) \in A_p} s_{i_1} s_{i_2}\cdots s_{i_l}=
\sum_{(i_1,\dots,i_\ell) \in A_p,(i_1,\dots,i_\ell)=(i_\ell,\dots,i_1)} s_{i_1} s_{i_2}\cdots s_{i_l}.$$
Next, if we have a symmetric list $(i_1,\dots,i_{2j})=(i_{2j},\dots,i_1)$ in $A_p$ with an even number of entries and $j \geq 2$, we use equality $s_{i_j}s_{i_{j+1}}=s_{i_j}^2=s_{2i_j}$ to see that it defines the same product has the symmetric list $(i_1,\dots,i_{j-1},2i_j,i_{j+2},\dots,i_{2j})$ with $2j-1$ entries.
Pairing lists in this manner and - if $p$ is odd - noting that $s_p^2=s_{2p}$, we find that
$$\sum_{(i_1,\dots,i_\ell) \in A_p} s_{i_1} s_{i_2}\cdots s_{i_l}=
\begin{cases}
s_{2p}+\sum_{(i_1,\dots,i_\ell) \in B_p} s_{i_1} s_{i_2}\cdots s_{i_l} & \text{if $p$ is odd} \\
\sum_{(i_1,\dots,i_\ell) \in B_p} s_{i_1} s_{i_2}\cdots s_{i_l} & \text{if $p$ is even,}
\end{cases}
$$
where $B_p$ denotes the subset of $A_p$ consisting of the symmetric lists
$(i_1,\dots,i_{2j+1})$ in which $i_{j+1}=2t$ for some odd integer $t$.
If $p$ is odd then $B_p$ is empty and we are done.
Assume now that $p=2q$ for some integer $q$. Then,
$(i_1,...,i_{2j+1}) \mapsto (i_1,...,i_{j-1},i_j,(i_{j+1})/2)$
maps $B_p$ bijectively onto $A_q$,
 and using $s_{i_{j+1}}=s_{(i_{j+1}/2)}^2$ we deduce that
$$\sum_{(i_1,\dots,i_\ell) \in B_p} s_{i_1} s_{i_2}\cdots s_{i_l}
=\Bigl(\sum_{(i_1,\dots,i_\ell) \in A_q} s_{i_1} s_{i_2}\cdots s_{i_l}\Bigr)^2.$$
By induction, we deduce that
$$\sum_{(i_1,\dots,i_\ell) \in B_p} s_{i_1} s_{i_2}\cdots s_{i_l}
=(s_{2q})^2=s_{2p},$$
QED.

A: A more succinct proof can be given using generating functions. I won't give the details, but it boils down to the identity
  $$ \frac{\sum_{n\geq 1} s_{2n-1}x^n}{\sum_{n\geq 0} s_{2n}x^n} =
     \frac{\sum_{n\geq 1} s_{2n}x^{n+1}}{\sum_{n\geq 1} s_{2n-1}x^n}, $$
where $s_0=1$ and the computations are mod 2, of course.
Incidentally, if you expand either side of the above identity as a power series in $x$, then the coefficient of $x^n$ is a polynomial $p_n(s_1,s_3,s_5,\dots)$. It appears that the number of terms of $p_n$ is the number of ways to write $n$ as a sum of powers of 2, without regard to order of the summands. I have not tried to prove this, so perhaps someone can supply a proof. A bijective proof would be especially interesting.

A: Here is a simplified answer expanding Richard Stanley's remark.
As I have already pointed out in my first answer, the only difficulty is to prove that the last column of the matrix is a linear combination of the odd-labelled columns.
To obtain this result, it suffices to prove that, with $s_0:=1$ and the formal power series
$A:=\sum_{n \geq 0} s_n x^n$, there is a sequence $(t_n)_{n \geq 0}$ of elements of $\mathbb{F}$ such that
$$\frac{1}{x}(A+1)=\sum_{n \geq 0} t_n x^{2n} A.$$
Noting that $A$ is invertible, this amounts to proving that the odd coefficients of the formal power series $\frac{A+1}{xA}$ are all zero.
This is obtained by noting that $\sum_{n \geq 0} s_{2n+1}x^{2n+1}=A+A^2$, whence
$$\frac{A+1}{xA}=\frac{\sum_{n \geq 0} s_{2n+1}x^{2n}}{A^2}
=\frac{\sum_{n \geq 0} s_{2n+1}x^{2n}}{\sum_{n \geq 0} s_{2n}x^{2n}}\cdot$$


text:
Q: position a div off screen in Opera Mobile (overflow:hidden not working) I'm working on a responsive web layout, with a menu that is positioned off screen - basically I'm using the following code:
CSS:
body {
    overflow:hidden;
}
.offscreen {
    background:#F00;
    height:100px;
    position:absolute;
    right:-90px;
    top:100px;
    width:100px;
}

HTML:
<body>
    <div class="offscreen">
    </div>
</body>

Demo can be found here.
The problem:
Opera Mobile (12.10 on Android 4.1.2) positions the div off screen, but allows scrolling - apparently it ignores the overflow:hidden rule.

My question:

*

*Any ideas how I can make Opera Mobile hide the div & disable the horizontal scroll?

A: Try this:
overflow:hidden;
overflow-y:hidden;
overflow-x:hidden;

Not tested.


text:
Q: Monotone class theorem - proof explanation I am studying the proof of the monotone class theorem in the book "Real analysis for graduate students" by Richard Bass, but I got stuck at a particular point.

The idea behind the proof is clear to me, we want to define subsets ($\mathcal{N}_i)$ of $\mathcal{M}$ that have properties of $\sigma$-Algebras and then show that these subsets ($\mathcal{N}_i)$ are actually the same as $\mathcal{M}$. This would show that the smallest monotone class that contains $A_0$ is in fact a $\sigma$-Algebra.
Now here is where I get stuck. I do not understand the claim I underlined in red.

$A_0$ is clearly a subset of $\mathcal{M}$. For each element $B_i$ in $A_0$, we know that $B_i^c$ is also in $A_0$, as $A_0$ is an algebra. But this is only for the elements IN $A_0$. How do we show that $A_0^c$ is an element in $\mathcal{M}$? (as this would imply that $A_0$ is in $\mathcal{N_1}$ by definition.)


text:
Q: how to toggle collapse content right to left beside icon bootstrap 4 i am unable to toggle content right to left beside icon  can any one can assist me

                    Right Link 1

                    Right Link 2

            <button class="navbar-toggler ml-auto " type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation">

            </button>

A: html:

  demo
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

  </button>

            Home

            Link

            About

css:
.navbar-collapse {
    position: absolute;
    top: 54px;
    left: 100%;
    padding-left: 15px;
    padding-right: 15px;
    padding-bottom: 15px;
    width: 100%;
    transition: all 0.4s ease;
    display: block;
}
.navbar-collapse.collapsing {
    height: auto !important;
    margin-left: 50%;
    left: 50%;
    transition: all 0.2s ease;
}
.navbar-collapse.show {
    left: 0;
}

test it: https://www.codeply.com/go/yggim0FPTG


text:
Q: Proving the statement: "If R is complete and transitive, then I is an equivalence relation". I have difficulties to prove this: "If R is complete and transitive, then I is an equivalence relation".
I do not know where to start ...
Thank you in advance.

A: It's true under the following interpretation:
Let $R$ be a complete and transitive relation on a set $X$.
Then define $$\forall x,y \in X: xIy \leftrightarrow xRy \land yRx$$
then $I$ is an equivalence relation.
Proof:

*

*by completeness of $R$ we have that $xRx$ must hold (either that or its reverse :) ) so $xIx$ also holds by definition.

*If $xIy$ holds we know that $xRy$ and $yRx$ both hold, and this is independent on their order ($\land$ is symmetric) so we have $yRx \land xRy$ and hence $yIx$, so $I$ is symmetric.

*Suppose $xIy, yIz$ hold. Then the first gives us $xRy$, $yRx$, the second $yRz$, $zRy$. From $xRy$, $yRz$ we conclude $xRz$ from $R$'s transitivity, and the same we do for $zRy$, $yRx$ giving us $zRx$. So we have both $xRz$ and $zRx$ hence $xIz$ and so $I$ is transitive.


text:
Q: WebDeployment is not I am trying to deploy an web application that was created on VB with the .NET Framework 2.0 using the TFS 2017 continuous deploy. It doesn't have a solution file inside like vbproj or csproj, so I needed to avoid all the suggestions to include extra information on the vbproj.In order to run the MSBuild even locally I need to change in my .sln this tag, so all my compiled code is also there
Debug.AspNetCompiler.TargetPath = "....\PrecompiledWeb\ARB\Debug\"
Unfortunately, I can't deploy the application using the TFS. So far I tried to deploy it through my Visual Studio project, and is working fine with every option:  I tried MSDeploy, Web Deploy Package, and FileSystem, and is working fine from the Visual Studio Publish Option

With that, even my transformation take place.
Now lets say I go to my TFS and I put this parameters on the MSBuild

/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsASingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="\\MyServer\Content"

My files are compiled but never stored in my Content folder. No one of them!!! I can't figure out what is going on here.

A: From your screenshot, you are using a Web Site project, not a Web Application project. The output structure of a Web Site project in TFS is different from build in VS (you can see a PrecompiledWeb folder in your build source directory on build agent server). Instead of using MSBuild argument, you can consider add tasks below to copy the files you want to publish:

We strongly suggest you switch from Web Site projects to Web Application projects to avoid these issues.


text:
Q: PHP - Multiple delimiter implode I want to implode a string with multiple delimiters. I've already eplode it with this PHP function:
function multiexplode ($delimiters,$string) {
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded = multiexplode(array(",",".","|",":"),$text);

The output of this is:
Array (
   [0] => here is a sample
   [1] =>  this text
   [2] =>  and this will be exploded
   [3] =>  this also
   [4] =>  this one too
   [5] => )
)

Can I implode this array with the following multiple delimiters: , . | : ?
Edit:
For define the rules I think this is the best option:
$test = array(':', ',', '.', '|', ':');
$i = 0;
foreach ($exploded as $value) {
    $exploded[$i] .= $test[$i];
    $i++;
}
$test2 = implode($exploded);

The output of $test2 is:
here is a sample: this text, and this will be exploded. this also | this one too :)

I only now need to know how to define the $test array (maybe with preg_match()?) so that it matched these values , . | : and set the variables in a order where it occurs in the string into an array. Is this possible?

A: function multiexplode ($delimiters,$string) {
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

$string = "here is a sample: this text, and this will be exploded. this also | this one too :)";
echo "Input:".PHP_EOL.$string;

$needle = array(",",".","|",":");
$split = multiexplode($needle, $string);

$chars = implode($needle);
$found = array();

while (false !== $search = strpbrk($string, $chars)) {
    $found[] = $search[0];
    $string = substr($search, 1);
}

echo PHP_EOL.PHP_EOL."Found needle:".PHP_EOL.PHP_EOL;
print_r($found);

$i = 0;
foreach ($split as $value) {
    $split[$i] .= $found[$i];
    $i++;
}

$output = implode($split);
echo PHP_EOL."Output:".PHP_EOL.$output;

The output of this is:
Input:
here is a sample: this text, and this will be exploded. this also | this one too :)

Found needle:

Array
(
    [0] => :
    [1] => ,
    [2] => .
    [3] => |
    [4] => :
)

Output:
here is a sample: this text, and this will be exploded. this also | this one too :)

You can see it working here.
For more information what's the function of strpbrk in this script, see here.
It's my first contribution to Stack Overflow, hope it helps.


text:
Q: get an IO object from a link in Rails I want to write a method (in Ruby/Rails) that takes a URL (String) to a text file  and uses JSON to parse it.
# LOAD entity file
  def load (url)
`    result = JSON.parse(x)
  end
What should x be? (I know it needs to be either a String or an IO object, but how do I get a string/IO object whose content is the content of the file that url points to?

A: require 'open-uri'

def load(url)
  open(url) do |file|
    JSON.parse(file.read)
  end
end


text:
Q: Can't connect Client VPN Endpoint to RDS in a VPC I had set up a Client VPN Endpoint (Client CIDR 10.0.132.0/22), with associations to two private subnets (10.0.2.0/24 and 10.0.3.0/24), using one security group.
I also have a RDS Database using the same two subnets and the same security group.
The security group has an inbound rule that allows all traffic from the same security group.
I'm able to connect to the VPN, but when I try to connect to mysql it doesn't resolve the host.
I thought it could be DNS but from EC2 I looked up for the private IP of the database (10.0.2.X), then I tried to connect using the IP and it didn't work either.
Then I thought it could be something in the security group and I added an inbound rule accepting all traffic from anywhere but still not being able to connect.
I can access the RDS from an EC2 instance, that means RDS works fine and it doesn't sound like a security group problem.
I think the issue can come from the VPN. I can connect to the VPN correctly and I can see the connection in AWS console (Client IP 10.0.132.X).
Extra info:
VPN:

Associations:

Authorization:

Route Table:

Any help?
Thanks

A: I found out what was wrong.
I had two wrong things.
First I included split tunnel and removed the two route tables (0.0.0.0/0) so only VPN (10.0.0.0/16) traffic will go over the VPN.
Second I added a DNS suggested in many places that is the VPC CIDR +2 (example 10.0.0.2)


text:
Q: Stieltjes Constant limit what is the limit :
$\lim_{n->\infty} \frac{\gamma_{n-1}}{\gamma_{n}}$
$\gamma_{n}$ being the nth Stieltjes Constant

A: An asymptotic formula for $\gamma_n$ is given here:
http://www.ams.org/journals/mcom/2011-80-273/S0025-5718-2010-02390-7/S0025-5718-2010-02390-7.pdf
From that formula, it is perhaps possible to find at least some estimates for the limit you ask about.


text:
Q: What is the standard way to query many-to-many relations with Diesel? diesel version = "2.0.0"
Database Postgres
I have products and categories with many-to-many relation
Schema:
diesel::table! {
    categories (id) {
        id -> Int4,
        name -> Varchar,
    }
}

diesel::table! {
    products (id) {
        id -> Int4,
        name -> Varchar,
        description -> Varchar,
    }
}

diesel::table! {
    productscategories (id) {
        id -> Int4,
        product_id -> Int4,
        category_id -> Int4,
    }
}

diesel::joinable!(productscategories -> categories (category_id));
diesel::joinable!(productscategories -> products (product_id));

diesel::allow_tables_to_appear_in_same_query!(
    categories,
    products,
    productscategories,
);

Models:
#[derive(Identifiable, Deserialize, Serialize, Debug, Queryable, AsChangeset, Clone)]
#[diesel(table_name = products)]
pub struct Product {
    pub id: i32,
    pub name: String,
    pub description: String,
}

#[derive(Identifiable, Deserialize, Serialize, Debug, Queryable, AsChangeset, Clone)]
#[diesel(table_name = categories)]
pub struct Category {
    pub id: i32,
    pub name: String,
}

#[derive(Identifiable, Deserialize, Serialize, Debug, Queryable, AsChangeset, Associations)]
#[belongs_to(Product)]
#[belongs_to(Category)]
#[diesel(table_name = productscategories)]
pub struct ProductCategory {
    pub id: i32,
    pub product_id: i32,
    pub category_id: i32,
}

To get one product with it's relation is relatively easy as mentioned Here
But how to get all products with their relative categories to have result of Vec<ProductOutDto> :
#[derive(Deserialize, Serialize, Debug)]
pub struct ProductOutDto {
    pub id: i32,
    pub name: String,
    pub description: String,
    pub categories: Vec<Category>,
}

and possibly the other way around Vec<CategoryOutDto>
#[derive(Deserialize, Serialize, Debug)]
pub struct CategoryOutDto{
    pub id: i32,
    pub name: String,
    pub products: Vec<Product>,
}

Currently I am getting things like :
use crate::schema::categories::dsl::categories as DbCategories;
use crate::schema::products::dsl::products as DbProducts;
use crate::schema::productscategories::dsl::productscategories as DbProductsCategories;

let query_result: Vec<(Product, Category)> = DbProducts
            .inner_join(DbProductsCategories.inner_join(DbCategories))
            .select((DbProducts::all_columns(), DbCategories::all_columns()))
            .load::<(Product, Category)>(&mut connection)?;

then I am iterating over query_result to get transform Vec<(Product, Category)> into Vec<ProductOutDto> to group categories with their relative product.
the question that is there a better or standard way to achieve this without iterating my self and make such transformation ?


text:
Q: GBQ BQ-CLI Export CSV to Google Storage with query and specified delimiter I'm trying to export a table from Google Bigquery into CSV and save the file into a google storage using bq extract but the issue is I want to export that table into 2 CSV files with different filters, and also using ; as delimiter for my CSV file. But I cannot find any documentation online where I can use queries with bq extract.
For example, I have table mytable.cities and I would like to export that table into 2 CSV files: the first CSV file I want export the table with a condition where city = 'Los Angeles' and for my second CSV with where city = 'New York'.
My syntax currently is this:
bq extract --destination_format=CSV --field_delimiter=';' mytable.cities gs://myBucket/myFile.csv

I did not use the command bq query because it doesn't give me the option to change my delimiter to ;
How can I achieve this?

A: An easy way to do this is to write a code that uses BQ API to run your queries and then use GCS API to save the results as CSV. See code below to do this:
from google.cloud import bigquery
from google.cloud import storage

bq_client = bigquery.Client()
gcs_client = storage.Client()

bucket = gcs_client.get_bucket("your-bucket-name")

query_1 = """
    SELECT mascot_name,mascot FROM `bigquery-public-data.ncaa_basketball.mascots`
    where non_tax_type = 'Devils'
"""

query_2 = """
    SELECT mascot_name,mascot FROM `bigquery-public-data.ncaa_basketball.mascots`
    where non_tax_type = 'Dragons'
"""

df_1 = bq_client.query(query_1).to_dataframe()
bucket.blob("devils.csv").upload_from_string(df_1.to_csv(index=False,sep=";"),"text/csv")

df_2 = bq_client.query(query_2).to_dataframe()
bucket.blob("dragons.csv").upload_from_string(df_2.to_csv(index=False,sep=";"),"text/csv")

NOTE: The example above used a public dataset to test the query and import to csv.
See bucket after code is ran:

Sample file content (devils.csv):


text:
Q: DocBlocks and Coda I was just wondering if anybody was aware of any plug-ins that would make Coda use my php docBlocks..?
I have searched the programs itself and there doesn't seem to be the options for it.
I have also done a fairly thorough google search and came up trumps.


text:
Q: Play how to implement an implicit Writes or Format for a case class including an Enumeration Following this answer shows how to bind an Enumeration to a form using a case class.
However in Play 2.7.3 this code fails with:
No Json serializer found for type jura.SearchRequest. Try to implement an implicit Writes or Format for this type.

When I implement the formatter:
object SearchRequest {
  implicit val searchRequestFormat: OFormat[SearchRequest] = Json.format[SearchRequest]
}

I get

No instance of play.api.libs.json.Format is available for
  scala.Enumeration.Value in the implicit scope

Should I be trying to write a formatter for the system scala.Enumeration type?
Or is there another way to implement a formatter when Enumerations are involved?
Test case here.

A: I use for any Enumeration this Library: enumeratum
With Dotty there will be great Enumerations, but until then I think moving to enumeratum  is the best way handling Enumerations in Scala. See also Dotty - Enumerations.
As a bonus there is a play-json Extension, see Play JSON Extension.
With this your code would look like this:
import enumeratum.{ PlayJsonEnum, Enum, EnumEntry }

sealed trait SearchRequest extends EnumEntry

object SearchRequest extends Enum[SearchRequest] with PlayJsonEnum[SearchRequest] {

  val values = findValues

  case object SuperRequest  extends SearchRequest
  case object SimpleRequest extends SearchRequest
  ..
}

In essence PlayJsonEnum[SearchRequest] does all the work.

A: To write the enum as a string as cchantep says you can use Writes.enumNameWrites, we specifically use to read and write the ID. Therefore we have an EnumFormat in the package global for enums:
package object enums {

  implicit def reads[E <: Enumeration](enum: E): Reads[E#Value] = new Reads[E#Value] {
    def reads(json: JsValue): JsResult[E#Value] = json match {
      case JsNumber(s) =>
        try {
          JsSuccess(enum.apply(s.toInt))
        } catch {
          case _: NoSuchElementException => JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not appear to contain the value: '$s'")
        }
      case _ => JsError("Number value expected")
    }
  }

  implicit def writes[E <: Enumeration]: Writes[E#Value] = new Writes[E#Value] {
    def writes(v: E#Value): JsValue = JsNumber(v.id)
  }

  implicit def formatID[E <: Enumeration](enum: E): Format[E#Value] =
    Format(reads(enum), writes)

  def readsString[E <: Enumeration](enum: E): Reads[E#Value] = new Reads[E#Value] {
    def reads(json: JsValue): JsResult[E#Value] = json match {
      case JsString(s) => {
        try {
          JsSuccess(enum.withName(s))
        } catch {
          case _: NoSuchElementException => JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not appear to contain the value: '$s'")
        }
      }
      case _ => JsError("String value expected")
    }
  }

  implicit def writesString[E <: Enumeration]: Writes[E#Value] = new Writes[E#Value] {
    def writes(v: E#Value): JsValue = JsString(v.toString)
  }

  implicit def formatString[E <: Enumeration](enum: E): Format[E#Value] =
    Format(readsString(enum), writesString)
}

And used:
object SearchRequest extends Enumeration(1) {
  type SearchRequest = Value

  val ONE /*1*/ , TWO /*2*/ , ETC /*n*/ = Value

  implicit val searchRequestFormat: Format[SearchRequest] = formatID(SearchRequest)
}

A: Add the following to your Enumeration Object
implicit object MatchFilterTypeFormatter extends Formatter[MatchFilterType.Value] {
    override val format = Some(("format.enum", Nil))
    override def bind(key: String, data: Map[String, String]) = {
      try {
        Right(MatchFilterType.withName(data.get(key).head))
      } catch {
        case e:NoSuchElementException =>  Left(Seq(play.api.data.FormError(key, "Invalid MatchFilterType Enumeration")))
      }
    }
    override def unbind(key: String, value: MatchFilterType.Value) = {
      Map(key -> value.toString)
    }
  }
  implicit val matchFilterTypeFormat = new Format[MatchFilterType.MatchFilterType] {
    def reads(json: JsValue) = JsSuccess(MatchFilterType.withName(json.as[String]))
    def writes(myEnum: MatchFilterType.MatchFilterType) = JsString(myEnum.toString)
  }

And then the Formatter/Controller given in the question will work.
A working test case is here.


text:
Q: Possible to add ASP .Net Identity classes to existing project? I have an existing ASP .Net web project (not MVC). In order to add ASP .Net Identity database tables i followed the instructions to create a user using this link http://www.asp.net/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project
The tables have been created but is there a way to import all the required classes into my project so i could take advantage of the ready built classes/methods across my application rather than writing my own? If yes how?
I've read a ton of articles but not sure if this possible. When creating a new project with authentication selected it does contain these classes but I dont know if i should just copy and paste those classes into my project?
Appreciate any help/advice.

A: Since most of what you are asking for has a combination of UI and identity framework parts, probably the easiest solution is to create a new mvc 5 site with visual studio 2013. This will create an AccountController and associated views to manage most of what you are talking about. To work this into an existing project, you can selectively include some of these files into your existing project. This at least did work for me where I was doing something similar for a VS 2012 solution.


text:
Q: Javascript open menu on website I feel like my explanation is not precise enough:
I am interessted in a short command line which, pasted into the console of firefox, opens the "help" menu of "www.stackoverflow.com". The button "Tags" on the stackoverflow.com website can be clicked on by
document.getElementsById('nav-tags').click()

The "help" menu on the top right does not have an Id... is it still possible to open it via javascript and additionally click on the first entry after opening "help"?
Former Question:
my problem is rather difficult to explain since I am not familiar with javascript. I am trying to press a button from VBA in order to create folders in a MS Sharepoint environment and to change their settings (for example reading/writing rights). While I figured out the first, the latter is quite difficult because I have to navigate through the Sharepoint website. This could be done with VBA "Sendkey" commands but after some testing it seems to be very error-prone. Additionally, a lot of stackoverflow questions are answered with "execscript" as the solution.
So I am trying to break down the task bit by bit (javascript from VBA)...
First step, send the click command from the firefox console:
executing
document.getElementByID('logo').click();

in the firefox console on this website https://www.google.de/?gws_rd=ssl#q=asd navigates to the main google website.
In the Sharepoint environment the "relevant" code looks like this:

                    Bibliothek

So I tried:
document.getElementById('Ribbon.library-title').click();

and recieved
undefined

Browsing throught lots of stackoverflow-questions led me to the conclusion that it must have something to do with the unsorted list elements. My guess would be that the classname "ms-cui-tt-a" needs to be in the comandline since it is connected to the "onkeydown" command. But since I am not sure whether I am right and even if I would be, I still dont know how to combine it properly. Thus, any hints are very well appreciated.
Regards, poe

A: Since there is no ID which can be used, one needs to create a list of all the elements in question and has to select the correct one either by title or something else, in this case by order.
the list is being created by the following command
$ document.getElementsByClassName('icon-help js-help-button');
since there is only one Element
$ document.getElementsByClassName('icon-help js-help-button')[0].click();
will open the menu.
With regard to my former Questions and the Sharepoint 2013 environment
$ document.getElementsByClassName('ms-cui-tt-span')
There are 3 entries in the list (starting from 0 to 2)
$ document.getElementsByClassName('ms-cui-tt-span')[1].click()
the second Element will be clicked.


text: Q: Testing our app in test flight introduces new bugs when using a non developer iPad We have recently set up our multiplayer app on test flight to do beta testing. When we have someone download the app that is using an iPad that is not registered with the team as a developer iPad, we get new bugs come up and problems we have never seen before. However when we test the game using 2 iPads that are registered on the team as developer iPads, we don't run into these issues or bugs. Any suggestions or recommendations as to why this may be happening?


text:
Q: how to get images from XML file I am new to iPhone. I need to get images from a local XML file and local folder that contain images. I am able to get a string from the XML file. But I don't how to get images through XML file. Please post some code or a link. Thank you in advance

A: You can store the path of your images (in local folder) in the xml as string. You can retrieve the path from xml and show the image from the file using:
UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePathRetrievedFromXML];

where 'filePathRetrievedFromXML' is your image's path.

A: If you want the images to be uploaded to serer then you have to convert the image to data and then pass it on as string in your xml file and on server side again convert the data to image and you will get the images stored locally to the webserver..
Another thing is if you want the local images in xml file and are going to use it locally then store the name of the images in the xml and fetch the name accordingly...


text:
Q: Swing TableHeader with JCheckBox does not work in Nimbus so I am using the following renderer to render a JCheckBox in a table header on a specific column.
However, this does not work when using the Nimbus theme in the application while it works in other themes.
Any idea how I could make this renderer work, across themes?
Dracula theme: dracula themed table header
Nimbus theme: nimbus themed table header
Usage:
JTableHeader tblHeader = myTable.getTableHeader();
tblHeader.setDefaultRenderer(new CheckHeaderRenderer(tblHeader, tblHeader.getDefaultRenderer()));

And the renderer:
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

public class CheckHeaderRenderer
implements TableCellRenderer
{
    private final JCheckBox check = new JCheckBox();
    private final TableCellRenderer wrappedRenderer;
    private final java.util.List<ActionListener> listeners = new ArrayList<>();

    public CheckHeaderRenderer(final JTableHeader header, final TableCellRenderer r)
    {
        this.wrappedRenderer = r;

        check.setOpaque(false);
        check.setFont(header.getFont());
        header.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent e)
            {
                JTable table = ((JTableHeader) e.getSource()).getTable();
                TableColumnModel columnModel = table.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int modelColumn = table.convertColumnIndexToModel(viewColumn);

                if (modelColumn != 0) { return; }

                check.setSelected(! check.isSelected());
                TableModel model = table.getModel();

                for (int i = 0; i < model.getRowCount(); i++)
                {
                    model.setValueAt(check.isSelected(), i, 0);
                }

                ((JTableHeader) e.getSource()).repaint();

                // run registered servers
                for (final ActionListener al : listeners) {
                    al.actionPerformed(null);
                }
            }
        });
    }

    public void addActionListener(ActionListener l)
    {
        listeners.add(l);
    }

    @Override
    public Component getTableCellRendererComponent(
            JTable tbl, Object val, boolean isS, boolean hasF, int row, int col
    ) {
        JLabel lbl = (JLabel) this.wrappedRenderer.getTableCellRendererComponent(tbl, val, isS, hasF, row, col);
        lbl.setHorizontalAlignment(SwingConstants.LEFT);

        if (0 != col) {
            lbl.setBorder(new EmptyBorder(0, 10, 0 ,10));
        }

        if (0 == col)
        {
            lbl.setIcon(new CheckBoxIcon(check));
            lbl.setHorizontalAlignment(SwingConstants.CENTER);
        }

        return lbl;
    }

    private static class CheckBoxIcon
    implements Icon
    {
        private final JCheckBox check;

        public CheckBoxIcon(JCheckBox check) {
            this.check = check;
        }

        @Override
        public int getIconWidth() {
            return check.getPreferredSize().width;
        }

        @Override
        public int getIconHeight() {
            return check.getPreferredSize().height;
        }

        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            SwingUtilities.paintComponent(g, check, (Container) c, x, y, getIconWidth(), getIconHeight());
        }
    }
}


text:
Q: Swift - Proper Way to Implement Expandable Cell List I have an XCode/Swift usecase for which I am unclear on the correct way to implement.

I want to do as is done above, but I want 1) Each cell to be static 2) I want to click on a cell and have it expand to include another view. Eg, if I click on the date I want it to expand to show a calendar, and shift the cells below it down. I want to also be able to close tge cell.
I have considered and tried using the UITableView and implementing my own expand/collapse there, however I am confused as to how I would imbed another view in that, and more specifically, how that would work with static cells that I coded on Storyboard, since I would have to implement cellForRowAt with a static cell. I could also do this without using a TableViewController, but I am not sure how I would approach that.
Any thoughts on how to approach this problem would be great.


text:
Q: FlexUnit and callLater I'm trying to use callLater with FlexUnit v0.9:
public function testCallLater():void {
   Application.application.callLater( addAsync(function():void {
      assertTrue(true);
   }, 1000));
}

but when it runs I get this error:
ArgumentError: Error #1063: Argument count mismatch on flexunit.framework::AsyncTestHelper/handleEvent(). Expected 1, got 0.
at Function/http://adobe.com/AS3/2006/builtin::apply()
at mx.core::UIComponent/callLaterDispatcher2()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:8628]
at mx.core::UIComponent/callLaterDispatcher()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:8568]

I'm not sure what the problem is.  Is callLater incompatible with FlexUnit?

A: First, you should really consider migrating to FlexUnit 4.0: http://blogs.digitalprimates.net/codeSlinger/index.cfm/2009/5/3/FlexUnit-4-in-360-seconds
Second, callLater is meant to be used to delay processing until the next frame in visual classes.  Your test case class is not a visual class extending UIComponent, therefore you should not try to use callLater.
Third, addAsync is use to test the results of an asynchronous operation.  This is typically used in testing the results of a network request, of a file read, of a timer event, etc.  That is why normally you see an "event" as a parameter in the addAsync test function (because asynchronous requests use events to process results).  In your case, you're not responding to an asynchronous operation with your addAsync call, and therefore you shouldn't be looking for an event in your test function.  Remove the event:Event parameter and the error will go away.
However, perhaps you can re-phrase this question to state what you're trying to accomplish?  The code sample that you've indicated is not really doing anything useful.  If you can be a little more specific we can help you write a better test case.
For help with using addAsync with older versions of FlexUnit, see this tutorial: http://life.neophi.com/danielr/2007/03/asynchronous_testing_with_flex.html

A: It looks like you are expecting an event, but not getting one. I imagine the following code would work.
public function testCallLater():void {
   Application.application.callLater( addAsync(function(/*removed event declaration*/):void {
      assertTrue(true);
   }, 1000));
}

A: Just in case someone needs it, this works :
private function testCallLater():void {
    Application.application.callLater(doCallLater, [ addAsync(funcUnderTest, 1000) ]);
}

private function doCallLater(testFunc:Function):void {
    testFunc(null);  // Dummy arg necessary because of addAsync expecting one arg
}

private function funcUnderTest(e:Object = null):void {
    assertTrue(true);
}


text:
Q: Convert the String Monday 5 October to date using Google Apps Script I need to convert the date string of type WEEKDAY DATE MONTHNAME, Example: from "Monday 5 October" to date object.
I have tried with
Utilities.formatDate(new Date("Monday 5 October"), "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'")

How do I convert it, I am ok using V8 apps script engine

A: The Date constructor accepts timestamp strings formatted according to IETF-compliant RFC 2822 timestamps and ISO8601.
There are many ways to convert your string to date, but probably one of the simplest is appending the current year to your string, using getFullYear():
const source = "Monday 5 October";
const date = new Date(`${source} ${new Date().getFullYear()}`);

Reference:

*

*Date() constructor

*IETF-compliant RFC 2822 timestamps


text:
Q: Como alterar a cor de um Icon através retorno booleano em Flutter? Tenho um método que consulta livros que estejam favoritados no banco de dados do Firestore, a página do livro possui um ícone de estrela em cor preta, uso método isFavorite para consultar se o livro aberto está favoritado pelo usuário ou não, caso esteja ele deverá retornar true e mudar a cor do ícone para amarelo porém a alteração não acontece.
O método updateFavorite funciona perfeitamente adicionado e removendo o livro favorito do banco ao tocar no ícone, somente a cor dele que não consigo configurar.
       InkWell(
          child: Icon(
            Icons.star,
            size: 30,
            color: isFavorite == true ? Colors.yellow
            : Colors.black,
          ),
          onTap: (){

            model.updateFavorite(model.getUserId(), document.documentID);
          },
        ),

==============

Future<bool> isFavorite() async{

            firebaseUser = await _auth.currentUser();

            DocumentSnapshot favoritesRef = await Firestore.instance.collection("users")
                .document(firebaseUser.uid).get();

            if(favoritesRef.data["favorites"].contains(document.documentID)){
              print("SIM");
              return true;
            }
            else {
              print("NÃO");
              return false;
            }

          }

==============

      Future<bool> updateFavorite(Future<DocumentReference> uid, String bookId) async{

        firebaseUser = await _auth.currentUser();

        DocumentReference favoritesRef = Firestore.instance.collection("users")
            .document(firebaseUser.uid);

        return Firestore.instance.runTransaction((Transaction tx) async{

          DocumentSnapshot postSnapshot = await tx.get(favoritesRef);
          if(postSnapshot.exists){

            if(!postSnapshot.data["favorites"].contains(bookId)){
              await tx.update(favoritesRef, <String, dynamic>{
                "favorites": FieldValue.arrayUnion([bookId])

              });
              // Delete de bookId from Favorites
            } else {
              await tx.update(favoritesRef, <String, dynamic>{
                "favorites": FieldValue.arrayRemove([bookId])
              });

            }

          }

        }).then((result){
          print(firebaseUser.uid);
          print(bookId);
          return true;

        }).catchError((error){
          print("Error: $error");
          print("DEU RUIM");
          return false;
        });

      }

A: Bom, conforme já comentaram, aparentemente você não está controlando o estado da sua aplicação de forma correta, sendo assim após a execução do seu método updateFavorite() você não está avisando o Flutter que ele deve renderizar novamente seu Icon.
Eu percebi que você utiliza 2 Futures, 1 para atualizar o favorito, e outro no ícone para de fato verificar se é ou não um favorito para renderizar a cor. Nesse caso você pode utilizar também um FutureBuilder, Widget bem bacaninha que sempre atualiza quando o Future tem o seu resultado. Criei um exemplo para você ter ideia do funcionamento e adaptar para o seu uso.
main.dart
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  YourBusiness yourBusiness = new YourBusiness();

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
          body: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  FutureBuilder(
                    future: yourBusiness.isFavorite(''),
                    builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
                      bool isFavorite = false;
                      if(snapshot.hasData) { // Verificar se o Future possui dado
                        isFavorite = snapshot.data;
                      }

                      return Icon(Icons.ac_unit,
                        size: 160.0,
                        color: isFavorite ? Colors.greenAccent: Colors.black,
                      );
                    }
                  ),
                  RaisedButton(
                    child: Text('CHANGE COLOR'),
                    onPressed: () {
                      yourBusiness.updateFavorite('').then((bool) {
                        setState(() {});
                      });
                    },
                  ),
                  RaisedButton(
                    child: Text('SET STATE'),
                    onPressed: () {
                      setState(() {});
                    },
                  )
                ],
              )
            ],
          ),
        )
    );
  }
}

your_business.dart
class YourBusiness {

  bool _isFavorite = false;

  Future<bool> isFavorite(String yourParams) async {
    await Future.delayed(Duration(seconds: 1));

    // DO YOUR STUFF HERE

    return _isFavorite;
  }

  Future<bool> updateFavorite(String yourParams) async {
    await Future.delayed(Duration(seconds: 1));

    // DO YOUR STUFF HERE

    _isFavorite = true;
    return _isFavorite;
  }

}

Resultado

Leve em consideração que cada vez que você der update no estado deste Widget, o Future do Icon será executado novamente, o que não é uma boa ideia, mas você pode definir outras estratégias, então vai da lógica que você quer montar no seu App.
Aconselho a utilização de algum padrão para controle de estado da aplicação, como o Bloc.


text:
Q: Armazenando em um vetor sem apertar ENTER a cada inserção É necessário armazenar em um vetor uma sequencia de números, mas apertando o ENTER só no final da linha.
Por exemplo:

ENTRADA: 10 20 30 15 50 <ENTER>

Vetor[] = {10, 20, 30, 15, 50}

A: Se está a utilizar c++ pode utilizar um vector que é simples para poder ir adicionando números à medida que os lê.
Quanto à leitura em si pode fazer de várias formas. Uma das mais diretas é com stringstream. Neste cenário a leitura pode ser toda feita do cin de uma vez só com getline e colocada numa stringstream. De seguida vai lendo numero a numero da stream até terminar e adicionando ao vector com o método push_back.
Implementação:
#include <iostream>
#include <sstream>
#include <vector>

int main() {
    std::vector<int> nums; //criar o vector de numeros
    std::string linha; //string para ler a linha toda da consola
    std::getline(std::cin, linha); //ler a linha

    std::stringstream ss; //criar a stream
    ss << linha; //colocar a linha na stream

    int num;
    while (ss >> num){ //le numero da stream testando se chegou ao fim
        nums.push_back(num); //adiciona o numero ao vector
    }

Agora para mostrar pode utilizar o ranged for loop de c++11 por exemplo:
    for (auto n : nums){
        std::cout << n << std::endl;
    }

Caso não esteja a utilizar c++11 ou posteriores pode sempre utilizar o vector de uma forma bem clássica:
    for (size_t i = 0; i < nums.size(); ++i){
        std::cout << nums[i] << std::endl;
    }

Saída:
10
20
30
15
50

Veja o código a funcionar no Ideone


text:
Q: How to get the sum of a list of numbers with recursion? (getting the list as an input) I don't know how to write this problem in python. Specially this problem wants to get a list from input and then calculate its sum.
def sum(num):
    Sum = 0
    for i in num:
        Sum = Sum + i
    return Sum

A: Try:

def sum_recursive(listt):
    if len(listt) == 0:
        return 0
    else:
        return listt[0] + sum_recursive(listt[1:])

print(sum_recursive([10,20,30]))
>> 60

print(sum_recursive([]))
>> 0


text:
Q: Trying to toggle a light by mouse clicks public void processLightClick(int row, int col) {
    states[row][col] = !states[row][col];

    if(states[row][col] = true){
        lights[row][col].setFill(ON_PAINT);
    }
    else if(states[row][col] = false){
        lights[row][col].setFill(OFF_PAINT);
    }
    turns++;

    System.out.println(row+":"+col);
    status.setText("Turn Number " + turns);
}

This is the code I have. I'm trying to get it to toggle states and colors each time a specific square is pressed but the paint stays the same and doesn't toggle the state back and forth when I press the same square twice

A: You are using an assignment operator "=" instead of a comparison operator "==" in your if-statement. Try this.
public void processLightClick(int row, int col) {
    states[row][col] = !states[row][col];

    if(states[row][col] == true){
        lights[row][col].setFill(ON_PAINT);
    }
    else if(states[row][col] == false){
        lights[row][col].setFill(OFF_PAINT);
    }
    turns++;

    System.out.println(row+":"+col);
    status.setText("Turn Number " + turns);
}

A: As user2615117 pointed out, you are not using the comparison operator, but the assignment operator.  Here, however, I also would use the ternary operator to make the code more concise:
lights[row][col].setFill((states[row][col] == true) ? ON_PAINT : OFF_PAINT);

Another possible improvement would be to have a single array of Light objects which contain both the state and the paint of the light.


text:
Q: 2D Rotated rectangle contains point calculation My issue is that I've been trying to check if a rectangle that is rotated by a certain amount of degrees contain a point, but I wasn't able to calculate that after many attempts with the help of some code samples and examples that I've found online.
What I got is the rectangle (X, Y, Width, Height, Rotation) and the point (X, Y) and I've been trying to create a simple function that lets me instantly calculate that, which would be something something like this:
public bool Contains(Rect Rectangle, float RectangleRotation, Point PointToCheck);

But as I mentioned, I wasn't able to do so, those mathematical calculations that include some formulas I found online are way too much for me to understand.
Could someone help me with calculating this? If you could provide the calculation in C# code form (not formulas) then that would be great! Thanks.
PS: Using the 2D Physics Engine that is available in Unity3D is not a option, my rectangle is not associated with a gameobject that I could attach a 2D collision component to, I need to do this mathematically without the involvement of gameobjects or components.
Edit: I forgot to mention, the rectangle is being rotated by the middle of the rectangle (center/origin).

A: Rather than checking if the point is in a rotated rectangle, just apply the opposite of the rotation to the point and check if the point is in a normal rectangle. In other words, change your perspective by rotating everything by -RectangleRotation, so that the rectangle does not appear rotated at all.
public bool Contains(Rect rect, float rectAngle, Point point)
{
    // rotate around rectangle center by -rectAngle
    var s = Math.Sin(-rectAngle);
    var c = Math.Cos(-rectAngle);

    // set origin to rect center
    var newPoint = point - rect.center;
    // rotate
    newPoint = new Point(newPoint.x * c - newPoint.y * s, newPoint.x * s + newPoint.y * c);
    // put origin back
    newPoint = newPoint + rect.center;

    // check if our transformed point is in the rectangle, which is no longer
    // rotated relative to the point

    return newPoint.x >= rect.xMin && newPoint.x <= rect.xMax && newPoint.y >= rect.yMin && newPoint.y <= rect.yMax;
}


text:
Q: Shiny interactive plots: ternary plots third axis variable? Based on the information in
http://shiny.rstudio.com/articles/selecting-rows-of-data.html
I'm making my first experiences with interactive plots.
With a normal plot (on a cartesian coordinate system), all is great.
When it comes to a ternary plot, it's more tricky. A ternary plot has three variables and function nearPoints() has only two parameters to identify location on a plot: xvar and yvar.
The following code demonstrates the problem:
    library(ggtern)
library(shiny)
## data ####
dd <- data.frame(x=c(3,1,5), y=c(45,29,10), z=c(10,45,94),
                 ss = c(58,75,109))
################
runApp(## UI ####
   list(
     ui = (basicPage(
       headerPanel("interactive tests"),
       mainPanel(
         plotOutput("f1", click = "plot_click1"),
         verbatimTextOutput("info1"),
         plotOutput("f2", click = "plot_click2"),
         verbatimTextOutput("info2")
       )
     )),

     ## server ####
     server = function(input, output) {
       output$f1 <- renderPlot({
         plot(dd$x,dd$y)
       })

       output$f2 <- renderPlot({
         figura <- ggtern(data = dd,
                          aes(x = x,y = y,z = z)) +
           geom_point()
         print(figura)
       })

       output$info1 <- renderPrint({
         nearPoints(dd, input$plot_click1, xvar = "x", yvar = "y")
       })

       output$info2 <- renderPrint({
         nearPoints(dd, input$plot_click2, xvar = "x", yvar = "y")
       })
     }
   )
)

The first plot is a simple scatterplot, in which clicking an observation returns the appropriate line in the dataframe.
The second plot is a ternary plot, and in this case it does not work.
If someone has a solution or can point me in the right direction, it'd be great.
Thanks,
António


text:
Q: QProcess does not work with "wget" I am trying to execute command like this:
wget --user=abc --ask-password https://xxxxx.com/file.zip

then  I have to deliver password.
This code should handle it:
connect(&checkFW, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput()));
//QString command = "wget --user=abc--ask-password https://xxxxxxx.com";
//checkFW.start("sh",QStringList() << "-c" <<"cd ;"+command);
checkFW.start("wget", QStringList() << "--user=abc" << "--ask-password"<< "https://xxxxxx.com/file.zip");
if (!checkFW.waitForStarted()){
    qDebug()<<"Could not start ";
    return false;
}

QString cmd = "password\n";
checkFW.write(cmd.toLatin1());
checkFW.waitForFinished(5000);
QByteArray result = checkFW.readAll();
QString mystr(result);
qDebug()<<"output:"<< mystr;

I used QProcess several times but this time I can't manage to work it. Some suggestions? I tried different methotds and any response. Of course the file I reqested was not downloaded.

I checked again and file was download to /home directory, not app's directory. So it works , but there is no output.

A: You are passing arguments to the QProcess in a wrong way.
checkFW.start("wget", QStringList() << "--user=abc" << "--ask-password"<< "https://xxxxxx.com/file.zip");

Here is example with ping (Windows).
#include <QCoreApplication>
#include <QProcess>
#include <QDebug>

int main(int argc, char *argv[])
{
    QProcess proc;
    QStringList args;
    args << "google.com";
    args << "-n";
    args << "3";

    proc.start("ping", args);
    proc.waitForFinished();
    qDebug() << proc.readAllStandardOutput();
}

A: If you just put:
checkFW.setProcessChannelMode(QProcess::MergedChannels);

before:
 checkFW.start();

You will get all the output in stdout even the errors


text:
Q: Using Terminal Command while Running Anaconda on Macbook While my Jupyter Notebook is running, the terminal shows that it is saving files periodically. How to run "pip install" using command lines in the terminal while the Jupyter Notebook is running? I believe I need to find a way to get back to the "~ username $:," from which I can type commands. I tried 'cd/' but it didn't seem to work.
So far I've been closing out of Anaconda, finishing "pip install", and getting back into Anaconda.

A: It sounds like you are using a unix-type system. In that case you can

*

*In the jupyter notebook do !pip install <whatever package it is>

*In the terminal window, type ^Z and then bg, then type your pip install command.

*Open another terminal window, and do your pip install.


text:
Q: Attempting to use either PHP(preferrably) or JavaScript for Videos I am experiencing a project roadblock I am unable to resolve and I am seeking advice/guidance.
I am controlling HTML content with PHP.
My goal is to create some sort of list that the user may select an option, that has dynamically pulled the file names of the items in the folder, and display that video in an embeded iframe.
I have attempted to save the selection into the $_SESSION or $_POST variable to compare with the items in the folder, until discovering a match, to set an iframe with the selected video.  I have also attempted this with/without the html element of form.
Here is my code:

Chose a video

<form method="post">
    <select name="videoSelection" class="video selectpicker" data-style="btn-primary" data-width="fit" value="<?php echo $_POST['videoSelection'] ?>" >
        <?php
            if ($handle = opendir('../media/video/'))
            {
                while (false !== ($file = readdir($handle)))
                {
                    if ($file != "." && $file != "..")
                    {
                        echo "<option value='$file'>$file</option>";
                    }
                }
                closedir($handle);
            }
        ?>
    </select>
</form>

            <?php
                if(isset($_POST['videoSelection']))
                {
                    $videoSelection = $_POST['videoSelection'];
                }
                else
                {
                    echo "
Variable Not set!
";
                }

                if ($handle = opendir('../media/video/'))
                {
                    while (false !== ($newFile = readdir($handle)))
                    {

                        if ($newFile == $videoSelection)
                        {
                            echo '';
                        }
                        else
                        {
                            echo var_dump($videoSelection);
                        }
                    }
                    closedir($handle);
                }
            ?>


text:
Q: Is it possible to determine, whether current code output is being buffered in PHP? Is there a method to determine, whether the echo/print in a random place in a file is being buffered with ob_start? Thanks

A: ob_get_level() will return the current output buffering level (the number of output buffers active, since you can call ob_start() multiple times in a row), so a return value of 0 means no output buffering is active

A: You can use the ob_get_level() function:
<?php
if(ob_get_level() > 0) {
    // output buffering active
}

A: Yes there is...
See ob_get_level():
if (ob_get_level() > 0) {
    //Output Buffering Is Active!
}

But be sure to read the comments on that page for insight as to what's going on, as certain php.ini settings can set a output buffer from before the start of the script...

A: You could use ob_get_clean() to see what's hiding inside that buffer.


text:
Q: Запуск и взаимодействие с внешним приложением Задача: автоматический вход на аккаунт Steam
Как взаимодействовать с процессом, если по имени его не находит а ClassName при каждом запуске меняется?
+еще и хендл дается только окну, все внутренние элементы его не получают (как вебсайты)
Запускаю через Process.Start();
Я не прошу готовый код, хотя бы направление дайте куда копать.

A: Если вы запускаете именно через Process.Start() - нестатическую версию метода без параметров - то объект process и будет представлять ваш процесс.
var process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "C:\\HelloWorld.exe";
// ...
process.Start();
// и дальше используете process.MainWindowHandle и process.Id как вам угодно


text:
Q: Bash-- trap CTRL+C reset terminal properties and end infinite while loop So I  have this infinite loop that changes terminal properties such as foreground/background color.
Specifications: When CTRL+C is pressed, before exiting the loop/script it should reset the terminal to original properties.
Now I think I need to trap CTRL+C and somehow use setterm reset to reset the terminal, but just can't seem to integrate to the script.
When I trap the CTRL+C, outside the while loop it doesn't reset the terminal.
It doesn't work inside the infinite loop also.
Upon exit the terminal properties stay changed,
example:
    #!/bin/bash
    while true;
    do
    tput civis
    tput bold
    tput setb 2
    tput setf 4
    tput bold
    tput 10 40; echo "hello"
    tput 11 40; echo "there"
    done

How do I trap CTRL+C, reset terminal, and exit?

A: Never mind.. using trap 'reset; exit' SIGINT inside the loop solves this problem.


text:
Q: import bootstrap in typescript file not working I am trying to import bootstrap into my typescript file so that I can use the bootstrap tooltip on SVG shapes that I am adding to a canvas based on a search result. Anyway, I an adding these SVGs in a typescript file and I need add the bootstrap tooltip which I am doing by calling $('.tooltip').tooltip({title: "it works!"}). However, in order to do this, I need to import both jQuery and bootstrap. I am able to import jQuery using -- import * as $ from "JQuery"; -- however when i try to import bootstrap, using -- import "bootstrap" -- I get the following error message in the browser.
I am using node.js and have the latest bootstrap
Browser Error Results


text:
Q: I can't get PHP Facebook API to work So I want to implement Facebook login on my site. I have dowloaded the SDK, created an app and pasted the app id and secret in.
The problem I am getting is that, while the login flow appears to work and I am getting values returned ok from
facebook->getUser()
and
facebook->getAccessToken()
Calls to
$user_profile = $facebook->api('/me','GET')
throw an exception saying I have no access token.
Since this is unmodified example code straight from the SDK I'm kind of at a loss - if the coding example given doesn't work how am I supposed to figure anything out? :)
Same issue with the code on this page:
https://developers.facebook.com/docs/php/howto/profilewithgraphapi/
Basically that does the same thing but handles the exception so I go round and round in a "login to facebook" loop.
I can see the app added to the list in my facebook profile OK when I log in so that side appears to be working. It seems that either the SDK is broken or the access token I'm getting back is for some reason not valid.
Any help or pointer as to what I've missed would be much appreciated!
Thanks
Justin

A: Try this
$config['cookie'] = true;

and relogin.
This is from the PHP code I use to login.

A: Here is the complete flow of the code hope this helps.
Say the page for the FB connect is login.php and I will have the following PHP code on the top of the page
require_once 'src/facebook.php'; //include the facebook php sdk
 $facebook = new Facebook(array(
    'appId'  => FACEBOOK_APP_ID,
    'secret' => FACEBOOK_APP_SECRET,
    'cookie' => true,
    'domain'=> FACEBOOK_CONNECT_DOMAIN
  ));

 $user = $facebook->getUser();
 if($user){
   // lets set the access token before making a api call.
   $new_access_token = $facebook->getAccessToken();
   $facebook->setAccessToken($new_access_token);
   $user_profile = $facebook->api('/me','GET')
   ......
   ......
 }else{
  // display the fb login
 }


text:
Q: strlen() output is not correct I am using strlen() function to print the size of the  string as shown below.
int main()

{

char c[]={1,2,3,4,5};  //same output if c[5]={1,2,3,4,5}

printf( "Length of string C is %d", strlen(c));

return 0;
}

Output

Length of string C is 19

Why is it printing 19 ?

A: In C, a string is a character array terminated with a special character '\0' (ASCII: 0).
char c[]={1,2,3,4,5}; is a character array.
To make it a string, give last value as 0, i.e. char c[]={1,2,3,4,5,0}; or better char c[]={1,2,3,4,5, '\0'};
Now your strlen didn't work because, it finds the end of a string by searching for the '\0' terminator, which you didn't gave in your array.
It keeps on searching for '\0' (and causes access of array element out of bounds, which is an undefined behavior, and sometimes very bad). It finds it (by luck) at the 19th character hence returns that result.


text:
Q: How can I use an iTunes smart playlist to find and delete audio files? I just imported 300 AIFF files into iTunes in order to easily convert them to AAC. That part is done, and now I want to delete the AIFF files. I know how to do this from Terminal, but I'd like to find the best way to do this from iTunes.
I created a smart playlist with these rules:

*

*date added is 2/24/2012

*kind begins with "AIFF"

This smart playlist contains all 300 AIFF files that I want to delete, as expected. But when I select the files in this playlist, the Edit > Delete menu item is disabled, and the context menu does not display any menu items related to deleting or trashing the files. If I go to the smart playlist, select all the files, then change the source list selection to the entire Music library, the selection is lost.
Since my iTunes library only contains these 600 files, I could do the manual step of showing the Kind field in the list, sorting by kind, and selecting the 300 AIFF files. But I was hoping to be able to do this from the smart playlist. Does anyone know how to do this? Maybe I'm missing something obvious.
(Mac OS X 10.7.3, iTunes 10.5.3)

A: Select all songs hold  ⌥ and press ⌫. Confirm and they are gone.


text:
Q: C#, WMPLib - How to check if the player is playing or not to trigger another process I'm new to C#. I want to use only 1 timer to do 2 events with different interval (0.2s and 1s). 0.2s interval is for checking error in system and it cannot stop. 1s interval is for playing sound if an error occurred. So, now I'm using a calculation to skip calling function checkError() because if I don't like this the sound won't play properly because of the duration of mp3 file but I would like to use check state of player if it's still playing or not instead of this calculation. For example, it will call checkError() again after finished play sound.  What should I do ?
Ps. Sorry for my English :(
    WMPLib.WindowsMediaPlayer wmp = new WMPLib.WindowsMediaPlayer();
    int count = 0;
    int errorFlag = 0;
    int called = 0;

    public Form1()
    {
        InitializeComponent();
        timer1.Start();

    }

    private void button5_Click(object sender, EventArgs e)
    {
        if (errorFlag == 0)
            errorFlag = 1;
    }

    private void button6_Click(object sender, EventArgs e)
    {
        if (errorFlag == 1)
            errorFlag = 0;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (errorFlag == 1)
        {
            checkError();
            if (called == 0)
                checkError();
        }

    }

    private void checkError()
    {
        if (called == 0)
        {
            Console.WriteLine(WMPLib.WMPPlayState.wmppsPlaying);
            called = 1;
            wmp.URL = "C:/Users/ndrs-tnp/Desktop/エラー音.mp3";
            wmp.controls.play();
        }
        count += 1;
        if (count == 5)
        {
            called = 0;
            count = 0;
        }
    }

A: read this
https://learn.microsoft.com/en-us/windows/win32/wmp/axwmplib-axwindowsmediaplayer-playstate--vb-and-c
if (player.playState == WMPLib.WMPPlayState.wmppsPlaying)
{
    playStateLabel.Text = "Windows Media Player is playing!";
}
else
{
    playStateLabel.Text = "Windows Media Player is NOT playing!";
}


text:
Q: Can you set, or where is, the local document root? When opening a file from your hard drive into your browser, where is the document root?  To illustrate, given the following HTML code, if the page is opened from the local machine (file:///) then where should the css file be for the browser to find it?
<link href="/temp/test.css" rel="stylesheet" type="text/css" />

A: It depends on what browser you use, but Internet Explorer, for example, would take you to the root directory of your harddrive (eg. C:/), while browsers such as Firefox does nothing.

A: You can, but probably don't want to, set the document root on a per-file basis in the  head of your file:

<base href="my-root">

A: On a Mac, the document root is what you see in the window that appears after you double click on the main hard drive icon on your desktop. The temp folder needs to be in there for a browser to find the CSS file as you have it written in your code.
Actually, you could also write the code like this:
<link href="file:///temp/test.css" rel="stylesheet" type="text/css" />

A: Eric, the document root is the folder in which your file is, wherever it may be.

A: As far as local, static html goes, unless you specify it, most browsers will take the location of the html file you are viewing as the root. So any css put in there can just be referenced by it's name only.
The lazy way to get the correct reference for your css file is to open it in your browser. Then just grab the url that you see there - something like: file:///blah/test.css and copy that into your stylesheet link on your html: <link href="file:///blah/test.css" rel="stylesheet" type="text/css">
Either that or you can just take the url for the html file and amend it to refer to the stylesheet.
Then your local page should load fine with the local stylesheet.

A: If you're interested in setting the document root, you might look at getting a web server installed on your machine, or, if you already have one (like Apache or IIS), storing your project-in-development in the web root of that server (htdocs in Apache, not entirely sure in IIS). If you'd rather leave your files where they are, you can set up virtual hosts and even map them to addresses that you can type into your browser (for example, I have a local.mrwarshaw.com address that resolves to the web root of my personal site's development folder).
If you're on Windows and don't want to mess around with setting up a server on your own, you could get a package like XAMPP or WAMPP, though bear in mind that those carry the extra weight of PHP and MySQL with them. Still, if you've got the space, they're a pretty easy drop-in development environment for your machine.


text:
Q: Build comma-separated list of rows from SQL results I am new to python and have setup pymssql to execute a stored procedure as per commonly found examples:
cur.execute("EXEC [dbo].[GetIPList]")

row = cur.fetchone()
while row:
    print "%s" % (row[0])
    row = cur.fetchone()

I want to build a variable which is a comma separated list of all rows.
If I use "cur.fetchall"  instead of "cur.fetchone" I get a tuple which I am not sure how to use in the subprocess.
What's the best approach to be taking here ?

A: Something like this:
s = ','.join([ r[0] for r in cur.fetchall() ])


text:
Q: MySQL query on max date I have for example these 2 tables:
Organiser        Events
----------       -------
id         1     id
           |__ * organiser_id
                 date
                 status

How do I select the ids of all organisers who's latest event it's status equals for example 'active'.
I think I have to use max(date) in maybe a subquery or do I need to use a join? Still haven't found the solution, so any help is appreciated!
Thanks
EDIT:
I just found this solution (dunno if this is the best one?):
SELECT o.id, e.date
FROM Organiser o
INNER JOIN events e on e.organiser_id = o.id
WHERE e.date = (SELECT max(date)
                FROM events e2
                WHERE e2.organiser_id = o.id)

A: try
SELECT o.name, ep.date
FROM ( SELECT date,max(id) AS maxDateID FROM events es GROUP BY date ) md
INNER JOIN events ep ON ep.id=md.id
INNER JOIN organiser o ON o.id=ep.organiser_id
WHERE e.status='active'

REFERENCE

A: SELECT
      id
FROM
      Organiser AS o
WHERE
      ( SELECT status
        FROM Events AS e
        WHERE e.organiser_id = o.id
        ORDER BY `date` DESC
        LIMT 1
      ) = 'active'


text:
Q: \_tfq_simulate_ops.so not found while import tensorflow_quantum Trying import of initial libraries related to tensorflow_quantum:
import tensorflow as tf
import tensorflow_quantum as tfq

import cirq
import sympy
import numpy as np

Getting error in 2nd line:

  File "Path_to_anaconda_site_packages\tensorflow_core\python\framework\load_library.py", line 61, in load_op_library
    lib_handle = py_tf.TF_LoadLibrary(library_filename)

NotFoundError: Path_To_Tensorflow_Quantum\core\ops\_tfq_simulate_ops.so not found

A: This is the solution provided by the Tensorflow team, it worked for me.
!pip install tensorflow-gpu==2.1.0
!pip install cirq==0.7.0 pathos==0.2.5 tensorflow-quantum==0.2.0

A: Do following steps:
!pip uninstall tensorflow
!pip install tensorflow

then restart runtime to import the packages.It works.

A: This might be something that would be worth raising as an issue on the TensorFlow Quantum Github here (https://github.com/tensorflow/quantum/issues). Without much information on the platform your are using or even what python version you have it might be hard to diagnose the problem here, but a quick fix you could try might be that you have an older version of TensorFlow installed. TensorFlow Quantum requires tf == 2.1.0.
pip install --upgrade pip
pip install --upgrade tensorflow

If that doesn't do it, then it might be worth opening an issue on github and giving a few more details on there :)


text:
Q: Book Title; Expeditions to Moon encounter hostile Venusians there Can anyone identify a book about multiple Lunar expeditions which encountered Venusian invaders?
It may have been a Badger Book, and was apparently written just after WW2, as it refers to Marshal Petain being sentenced to death (which he was) and shot (which he wasn't).
A scientist named Leinster has invented a new weapon, which for some reason is best employed from a Lunar base. Being an idealistic type, he sends details of it to all nations at once, rather than let any one have a monopoly.
This triggers a frantic "Race to the Moon", with expeditions from the US, Russia, China, GB, France, Germany and India. The first  few chapters include potted histories of the countries concerned.
On arrival, they find that an expedition from Venus has already arrived. Venus is a  dictatorship, and plans to impose the "Venusian System" on Earth. Iirc the Venusian astronauts are named Rustag, Klusak and Korio, or similar, and Korio is the "good Venusian" who averts war.
One memorable quote. The Chinese Captain reflects on how their Great Leader was always right, and that. "If the Great Leader said something today which contradicted something he had said yesterday, the important thing was that yesterday was dead. If one forgot that yesterday was dead, one was liable to join yesterday".

A: Satellite, by R L Fanthorpe.  Since it's by Lionel Fanthorpe it's almost certainly from Badger Books.
It features a scientist called Leinster, who invents a new rocket projectile, spurring a rush to establish a base on the moon.  There they encounter a hostile alien force.
I found this by searching for part of the quote: "If one forgot that yesterday was dead, one was liable to join yesterday" which lead me to this google books link.  Searching within the text, the names Rustag, Klusak and Korio all appear.


text:
Q: Basic Recursion Exercise Find a recursive formula to divide N people in to couples and singles.
The answer:
$$A_n = A_{n-1} + A_{n - 2}(n - 1)$$
Some one can explain the answer , why do we need to multiply by n-1?

A: If the people were indistinguishable, the number would simply be $\left\lfloor \dfrac{n}{2}\right\rfloor + 1$, since you can form between $0$ and $\left\lfloor \dfrac{n}{2}\right\rfloor$ pairs (both bounds inclusive).
But with distinguishable people, you can either put the new person with number $n$ into a singleton group - that gives the summand $A_{n-1}$, since there are $A_{n-1}$ ways to divide the remaining $n-1$ people - or pair the new person up with one of the $n-1$ others. Each of the $n-1$ possible pairs with person $n$ leaves $A_{n-2}$ ways to divide the remaining $n-2$ people, that gives the summand $(n-1)A_{n-2}$.


text:
Q: Unity crashes when I destroy an object I've made this code myself so I'm not sure what I've done wrong, I have a colider for my sword but whenever I get in range and swing my whole unity crashes
using System;
using UnityEngine;

public class Attack : MonoBehaviour
{
    private CircleCollider2D cc2;
    private float x = 3;
    private Boolean timer = true;
    private Boolean hasAttacked = false;

    private void Start()
    {
        cc2.isTrigger = true;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(hasAttacked == false)
        {
            hasAttacked = true;
            if (Input.GetKey(KeyCode.Mouse0))
            {
                while (timer == true)
                {
                    x -= Time.deltaTime;
                }

                while (x >= 1)
                    if (collision.gameObject.name == "Enemy")
                    {
                        Destroy(GameObject.Find("Enemy"));
                    }

                if (x == 0)
                {
                    hasAttacked = false;
                    x = 3;
                }
            }

        }
    }
}

The Player is the parent of the sword if it makes a difference
It could be that they both try to destroy each other because the enemy is made to destroy the player

A: The problem is with the while (timer == true). If it's true, then it will stuck in there. Also when you decreasing x by Time.deltaTime, there is a little chance it will equals with 0, you should check with x <= 0.
Also you should check for input in Update.
I would save the reference of the enemy in OnCollisionEnter2D, and clear that in OnCollisionExit, and handle the attack in the Update. Something like that:
private GameObject _enemy;
private float _actCooldown = 3.0f;

private void Update()
{
    if (Input.GetKeyDown(KeyKode.Mouse0) && _actCooldown <= 0.0f)
    {
        if (_enemy != null)
        {
            Destroy(_enemy);
            _enemy = null;
        }

        _actCooldown = 3.0f;
    }

    _actCooldown -= Time.deltaTime;
}

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.name.Equals("Enemy")) _enemy = collision.gameObject;
}

private void OnCollisionExit2D(Collision2D collision)
{
    if (collision.gameObject == _enemy) _enemy = null;
}

Of course if there are more enemies, you'll have to add more logic to it.


text:
Q: Android get sharedPreferences to store user choices I want to display the the fruit of choice as a drawable
i have it so that it saves but I don't know how to get it from the activity preference
and use it
I was thinking there might be somthing like fruit = getpreference (something like this)
int resourceID = getResource.getIdentifier(fruit,"drawable",getPackageName());

favortieFruit.setImageResource(resourceID);

Options.java
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;

public class Options extends PreferenceActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.options);
        //Get the custom preference
        Preference customPref = (Preference) findPreference("listPref");
        customPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

            public boolean onPreferenceClick(Preference preference) {

                SharedPreferences customSharedPreference = getSharedPreferences("Fruits", Activity.MODE_PRIVATE);
                SharedPreferences.Editor editor = customSharedPreference.edit();

                editor.commit();
                return true;
            }
        });
    }
}

Options.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
        <PreferenceCategory
                android:title="Fruit Selection" android:key="listPref">
                <ListPreference android:title="Fruit #1" android:key="listPref1" android:defaultValue="digiGreen" android:entries="@array/Fruits" android:entryValues="@array/listValues" android:summary="Select Fruit #1 "/><ListPreference
                        android:title="Fruit #2"
                        android:summary="Select Fruit #2 "
                        android:key="listPref2"
                        android:defaultValue="digiGreen"
                        android:entries="@array/Fruits"
                        android:entryValues="@array/listValues" /><ListPreference
                        android:title="Fruit #3"
                        android:key="listPref3"
                        android:defaultValue="digiGreen"
                        android:entries="@array/Fruits"
                        android:entryValues="@array/listValues" android:summary="Select Fruit #3 "/><ListPreference
                        android:title="Fruit #4"
                        android:key="listPref4"
                        android:defaultValue="digiGreen"
                        android:entries="@array/Fruits"
                        android:entryValues="@array/listValues" android:summary="Select Fruit #4 "/><ListPreference
                        android:title="Fruit #5"
                        android:key="listPref5"
                        android:defaultValue="digiGreen"
                        android:entries="@array/Fruits"
                        android:entryValues="@array/listValues" android:summary="Select Fruit #5 "/><ListPreference
                        android:title="Fruit #6"
                        android:key="listPref6"
                        android:defaultValue="digiGreen"
                        android:entries="@array/Fruits"
                        android:entryValues="@array/listValues" android:summary="Select Fruit #6 "/>
        </PreferenceCategory>
</PreferenceScreen>

strings.xml
<string-array name="Fruits">
   <item>Apple</item>
   <item>Pear</item>
   <item>Grape</item>
      <item >Berry</item>
        <item >Tomato</item>
</string-array>

<string-array name="listValues">
   <item>apple</item>
   <item>pear</item>
   <item>grape</item>
   <item>berry</item>
   <item>tomato</item>
</string-array>

==============================
Found the solution
Options.java
import android.os.Bundle;
import android.preference.PreferenceActivity;

public class Options extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

    }
}

Getting the settings
SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(this);
        for (int num = 1; num < 7; num++) {

            String icon = sp.getString("listPref" + num, null);

            try {
                Class<drawable> res = R.drawable.class;
                Field field = res.getField(icon);
                PoliticiansArray[num] = field.getInt(null);
                Class<string> stringRes = R.string.class;
                Field stringField = stringRes.getField(icon);
                SayingsArray[num] = stringField.getInt(null);

            } catch (Exception e) {
                Log.e("MyTag", "Failed", e);
            }

A: You should add a PreferenceChangeListener to your ListPreference
This is an example of how to get the newly selected value from a ListPreference:
final ListPreference myPreference = (ListPreference) findPreference("listPref");
    myPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        // @Override
        public boolean onPreferenceChange(Preference preference,
                Object newValue) {
            SharedPreferences customSharedPreference = getSharedPreferences("Fruits", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = customSharedPreference.edit();
            editor.putString("favfruit", (String) newValue);
            editor.commit();
            return true;
        }
    });

When you want to get back the value you saved on SharedPreferences, do it like this:
SharedPreferences settings = getSharedPreferences("Fruits", Activity.MODE_PRIVATE);
String fruit= settings.getString("favfruit",null);

Then, get your drawable:
int resourceID = getResource.getIdentifier(fruit,"drawable",getPackageName());
favortieFruit.setImageResource(resourceID);