Statistical Quality Control Data Gathering

Question: Data has been gathered for a specific analytical test method to start SQC. The issue is that when the data is tested for normality, using Anderson Darling, the null hypothesis can not be rejected.
-I have attached a photo to provide more information about the data.
My question is, does this "non-Gaussian-nes" mean that the test method contains some sort of bias?
PS- Sorry if there are any issues with the form of my question; please let me know if you need additional information.
Answer: As far as using your data for standard quality control methods which require that you have Gaussian data, the results of your tests confirm that you are currently unable to reject the null hypothesis and that the data would be acceptable (regarding that requirement).
Most quality-control tests also require that the data is in statistical control, as evidenced by a Shewhart Chart or control-chart.  Things may also change as you currently only have 20 points of data.
While any test is bound to have some type of bias, the Anderson-Darling test is fairly reliable.  You can test with Shapiro-Wilk, or the K-S test (sorry, I don't recall how to spell their names, but it is a common test) can also be used.  There is also an option for a normal probability plot within minitab that will draw the confidence interval along with the plot.
Comment: Thank you for your response. So what would happen if the collected data, that is going to be used to create the SQC, does not follow a gaussian distribution?
Comment: At that point, you would need to looking at options to either transform your data or use some of the other tools designed for non-Gaussian data.  There are plenty of tools out there, and Minitab has a good selection of tools to start with.
Comment: But wouldn't a non-gaussian data set indicate some form of bias during the data collection? For example, these points are being collected by 4 people at different times over many weeks. Could it be possible that someone is performing the analysis of the quality control material differently?
Comment: Currently, your data is normal, or rather there is not enough evidence to reject that null hypothesis. If you suspect your data collection method, you can conduct a measurement system analysis  ([tag:msa]) to know for sure.


How to set preset in onvif supported ip camera

Question: <code>    public void setPreset(string name,int PanSpeed,int TiltSpeed,int ZoomSpeed)
    {

        if (ptzClient == null)
            setPTZClient();
        PTZVector pv = new PTZVector();
        pv.panTilt = new Vector2D();
        pv.zoom = new Vector1D();

        pv.panTilt.x = (float)10;
        pv.panTilt.y = (float)10;
        pv.zoom.x = (float)10;

        PTZPreset ps = new PTZPreset();
        ps.token = "20";
        ps.name = name;
        ps.ptzPosition = pv;

        PTZSpeed pzs = new PTZSpeed();
        pzs.panTilt = new Vector2D();
        pzs.zoom = new Vector1D();
        pzs.panTilt.x = (float)TiltSpeed;
        pzs.panTilt.y = (float)PanSpeed;
        pzs.zoom.x = (float)ZoomSpeed;

        var setpresetres = new SetPresetResponse();
        setpresetres = ptzClient.SetPreset(new SetPresetRequest("Profile_1", name,null));

        var presetres = new GetPresetsResponse();
        presetres = ptzClient.GetPresets(new GetPresetsRequest("Profile_1"));

    }
</code>
I write this method for set preset ....but i dont know where i set the object of PTZSpeed ,PTZVector
Please help me....
Answer: I think you mixing thing here. Use SoapUi or equivalent to take a look at the soap message to be sent.
<code><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.onvif.org/ver20/ptz/wsdl">
<soap:Header/>
<soap:Body>
    <wsdl:SetPreset>
        <wsdl:ProfileToken>?</wsdl:ProfileToken>
        <wsdl:PresetName>?</wsdl:PresetName>
        <wsdl:PresetToken>?</wsdl:PresetToken>
    </wsdl:SetPreset>
</soap:Body>
</soap:Envelope>
</code>
Note that you only need to submit a Profile token, your name of the preset, and a token for the preset. If I remember correctly, the preset token will be returned in the response. The profile token are one of the items returned from the Mediaservice.GetProfiles method.
The speed settings for pan, tilt, zoom are only used when you use the Move, GoToHome or GoToPreset command.


Traversing a nested Dictionary in Julia with a JSON like structure

Question: I was wondering if there was an efficient ("canonical") way to traverse a dictionary with a JSON like structure. For example, I have a dictionary with an array of dictionaries that sometimes don't have the same keys. I then need to iterate over these dictionaries and check if an specific key has a certain value. For example:
for cell in cells
  if cell["key1"]["key2"]["key3"] == true
     # do stuff
  end
end

The issue is that sometimes the cell won't have either "key1", or "key2" or "key3", so a simple get(cell, key1, false) won't work. Of course, I could always write a bunch of if statements, but I was wondering if there was a smarter and more direct way of doing this.
Answer: Define your own operator!
▷(d::Dict{K,V}, k::K2) where {K, V, K2<:K} = get(d, k, nothing)
▷(d::Dict{K,V}, k::Symbol) where {K, V} = get(d, k, d ▷ string(k))
▷(::Nothing, k::K2) where K2 = nothing

In my code the Symbol version is for convenience.
Now let us do the setup:
cellA = Dict("key1"=>Dict("key2"=>Dict("key3"=>true)))
cellBad = Dict("key1"=>Dict("keyBad"=>Dict("key3"=>true)))

Let's use this new API:
julia> cellA ▷ :key1 ▷ :key2 ▷ :key3
true

julia> cellA ▷ :key1 ▷ :key2 ▷ :key3  == true
true

julia> cellBad ▷ :key1 ▷ :key2 ▷ :key3

julia> cellBad ▷ :key1 ▷ :key2 ▷ :key3 == true
false

See the list of available operators and their precedence at User-defined infix operator


How to write this glissando/arpeggio for orchestral harp?

Question: I want to end my piece with the following orchestral harp glissando/arpeggio (not sure which term best applies), starting with Ab2 on the fourth beat, using only the first and fifth note of each octave it travels through (Ab2-Eb3-Ab3-Eb4-Ab4-Eb5-etc.) until the final Ab6. I want this final note to flow seamlessly int the thrum of the two bass staff notes (Ab2+Eb3).
My question is twofold: First, which is the correct way of notating this: a) using an arpeggio line/arrow, b) by writing the notes out in a 9:8 tuplet, or c) with a glissando line with some special marking to indicate which notes to use? (Method c) not pictured below.)

Second: Is this kind of glissando/arpeggio even possible to play on an orchestral harp at a tempo of 75 bpm? I'm still learning what can and cannot be done on this instrument.
Finally, if this is either impossible to play on a harp, or if it is possible but neither method pictured above is correct, how would I write this specific sort of glissando/arpeggio, keeping the same starting and ending notes and sticking only to firsts and fifths?
Answer: I'm assuming that everywhere you said A and E you actually mean Ab and Eb, right? The answer definitely isn't c), glissando should only be used for sweeps across all strings, but there's no pedal position that can produce exclusively 2 pitches. In fact, out of all 2,187 possible pedal combinations, the fewest distinct pitch classes possible is 4, and only 42 position are capable of that small of a pitch collection.
The difference between a) and b) is more of a musical decision than a correct notation decision. Both would create an arpeggio, but a) would be more up to the performer's interpretation. That being said, a) would almost certainly be much quicker. In either case, I would notate the lower pitches in the bass clef staff using cross-staff stems or beaming.
This shouldn't be problematic for an experienced harpist, large arepeggios are common for harp. Each hand can easily cover a spread of a 10th, so in this case they could easily play the first 3 notes in one hand and the next 3 in the other. While the second group of 3 are being played they would simply move their first hand up to play the top 3 pitches.
Comment: Thanks for all the info, it's much appreciated. I wasn't sure whether to mention the accidentals in the note names – I'd seen similar examples where they weren't included – but I'll go and edit the OP. I went ahead and switched the arpeggio (b)) to use cross-staff beaming.
Answer: According to Piston (Orchestration) & Blatter (Instrumentation and Orchestration), the default manner of playing a chord for orchestral harp arpeggiated and any annotation to the chord changes the speed of the arpeggiation: the arpeggio line denoting a longer, exaggerated arpeggiation, while a square bracket denotes no arpeggiation.
So without any annotations to the chord, it would be arpeggiated. Your options a) & b) would probably end up being interpreted in the same manner by the harpist, although your 9-let does explicitly set out taking up the whole beat, whereas the arpeggio line is left for the player to interpret. Note that all of the chords in the left hand would be arpeggiated by default, unless you bracket the notes or specify that the line is to be played non-arpeggiated (e.g. non arpeggiando).
Pat's point about the reach of a harpists hand is well made & yes, harpists would probably break up the chord you have written in the manner described in Pat's answer.


I don't fully understand a proof

Question: My problem is in understanding the last part, when $(x_i -y_j)(a_{ij}-b_{ij})=0$. It is suppose to imply $(a_{ij}-b_{ij})=0$ but I don't know why it can't be $(x_i -y_j)=0$. Please help.
Lemma Let $x_1, x_2, \dots x_n$ and $y_1, y_2, \dots y_n$ be real numbers. Let $A = (a_{ij})$ be an $n \times n$ matrix with entries $$a_{ij} = \left\{ \begin{array}{l l}
  1, & \textrm{if $x_i + y_j \ge 0$}\\
  0, & \textrm{else.}
\end{array} \right.$$
Let $B = (b_{ij})$ be an $n \times n$ matrix with entries $0$ or $1$ such that the sum of elements of each row and each column of $B$ equals to the corresponding sum for the matrix $A$. Show that $A = B$.
Proof
Let
\begin{align}
S &= \sum_{i=1}^n\sum_{j=1}^n(x_i+y_j)(a_{ij} - b_{ij})\\
&= \sum_{i=1}^n\sum_{j=1}^nx_i(a_{ij} - b_{ij})  + \sum_{i=1}^n\sum_{j=1}^n y_j(a_{ij} - b_{ij})\\
&= \sum_{i=1}^n x_i \sum_{j=1}^n(a_{ij} - b_{ij})  + \sum_{j=1}^n y_j\sum_{i=1}^n (a_{ij} - b_{ij})
= 0\\
\end{align}
because the row and column sums of $A$ and $B$ are the same.
On the other hand, using the definition of $a_{ij}$, we have

When $x_i + y_j \ge 0$ the $a_{ij} - b_{ij} = 1 - b_{ij} \ge 0$
When $x_i + y_j < 0$ the $a_{ij} - b_{ij} = - b_{ij} \le 0$

So, $(x_i + y_j)(a_{ij} - b_{ij}) \ge 0$ for all $i, j$. Since $S = 0$, then $(x_i + y_j)(a_{ij} - b_{ij}) = 0$ for all $i, j$, and $a_{ij} = b_{ij}$ for all $i, j$, and we are done.
$\square$
Comment: Please do not use pictures for critical portions of your post. Pictures cannot be searched and are inaccessible to those using screen readers.
Comment: For future uses (please not here): taking a screenshot normally leads to better image quality than this.
Comment: Sorry but it's too large I'll write it when I have time. If someone cannot see it properly just wait.
Comment: I already did it, it's in the queue for approval. I changed one line because i thought it was a typo, you can change it back if it wasn't.
Comment: I was doing it now but thanks
Answer: You are right. The proof is too short. Let $i$ be fixed and let $J = \{j : x_i+y_j= 0\}$. Then $a_{ij} = b_{ij}$ for all $j\notin J$. Therefore,
$$
|J| = \sum_{j\in J}a_{ij} = \sum_ja_{ij} - \sum_{j\notin J}a_{ij} = \sum_jb_{ij} - \sum_{j\notin J}b_{ij} = \sum_{j\in J}b_{ij}.
$$
Hence, $b_{ij} = a_{ij} = 1$ also for all $j\in J$. Listo! ;o)
Comment: What you proved there is that all the non-matching entries in a row or in a column must sum up the same. But how does it implies they are all equal?
Comment: They are all either 0 or 1... Can there be a zero in the $b_{ij}$'s that sum up to $|J|$?
Comment: I don't know what you mean but consider this example: 1,0,0,0,1,1,0(A) and 0,1,0,0,0,1,1(B) the entries which have changed are the 1,2,5,7 and $|J|=4$ and it achieves the property you've written but they are not equal. Maybe I've misunderstood what you've written
Comment: I assume that your matrices are 1x7. Well, they have the same row sum, but the column sums differ from each other.
Comment: It's simple. In the equation in my answer you have a sum of $|J|$ zeros and/or ones that equals $|J|$. There is thus no other possibility that all summands equal one.

I don't fully understand a proof


Function that reverses characters in (possibly nested) parentheses in the input string

Question: Write a function that reverses characters in (possibly nested) parentheses in the input string.
Input strings will always be well-formed with matching ()s.
For inputString = "(bar), the your text output should be solution(inputString) = "rab";
For inputString = "foo(bar)baz", the output should be solution(inputString) = "foorabbaz";
For inputString = "foo(bar)baz(blim)", the output should be solution(inputString) = "foorabbazmilb";
For inputString = "foo(bar(baz))blim", the output should be solution(inputString) = "foobazrabblim".
Because "foo(bar(baz))blim" becomes "foo(barzab)blim" and then "foobazrabblim".
I tried the code below, but every time it runs, the return value is always inputString. Not sure why because I am using String.Replace.
string solution(string inputString) {
    int first, last;
    string word;
    while (true) {
        if (inputString.Contains("()")) {
            first = inputString.LastIndexOf("(");
            last = inputString.IndexOf(")");
            word = inputString.Substring(first+1, last-first-1);
            inputString.Replace(inputString.Substring(first, last-first), backwardinator(word));
        } else {
            break;
        }
    }

    return inputString;
}

string backwardinator(string word) {
    string newWord = "";

    for (int i = word.Length - 1; i >= 0; i--) {
        newWord += word[i];
    }

    return newWord;
}

Comment: Suggested reading: [string replace does not actually replace the value in the string](https://stackoverflow.com/questions/1948978)
Comment: This line inputString.Contains("()") is wrong it will always result false when there are "(…)" between the parentheses
Comment: Re @ŇɏssaPøngjǣrdenlarp's comment. Please note that `StringBuilder` has a `.Replace` method. Also realize that since this is very likely homework, you are unlikely to get an answer, tips and coaching yes, an answer, no
Answer: C# Strings are immutable, which means they can't be mutated/modified.  The method returns a new string that represents the result of the operation on the source string. In your example, you would need to assign the result of inputSting.Replace(…) to inputString much like how you're assigning words with the result of substring the line prior.
Have you recently learned about recursion?


How can you add a multiple value field to an entity?

Question: Edit: My question is similar to How to create multi-value, multi-bundle entity reference fields in code?, except the field doesn't need to reference multiple bundles.
We have an existing view of custom entities.  The view needs to now be filtered based on some related fields that are not part of the entity (or any entity).  Kind of like adding a Taxonomy Reference field to a Content Type.  What is the best way to add those fields to the entity?
I see that many modules use attachLoad to attach fields to an entity, but when I try my implementation those fields don't show up in my list of Fields or Filters in Views.
This is a screenshot of the checkboxes field:

This is my controller:
class ContactsController extends EntityAPIController {

  public function attachLoad(&$queried_entities, $revision_id = FALSE)
  {
    foreach ($queried_entities as $key => $entity)
    {
      $queried_entities[$key]->foo = "bar";
    }
    parent::attachLoad($queried_entities, $revision_id);
  }

}

And this is my hook_entity_info:
function contacts_entity_info() {
  $return = array(
    'contacts' => array(
      'label' => t('Contact'),
      'entity class' => 'Contacts',
      'controller class' => 'ContactsController',
      'views controller class' => 'ContactsViewsController',
      'base table' => 'contacts',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'ckid',
        'bundle' => array(),
      ),
      'bundle keys' => array(),
      'bundles' => array(),
      'load hook' => 'contacts_load',
      'view modes' => array(
        'full' => array(
          'label' => t('Default'),
          'custom settings' => FALSE,
        ),
      ),
      'label callback' => 'entity_class_label',
      'uri callback' => 'entity_class_uri',
      'module' => 'contacts',
      'access callback' => 'contacts_access',
    ),
  );

  return $return;
}

This is a suggested implementation of EntityDefaultViewsController:
/**
* EntityTest Views Controller class.
*/
class ContactsViewsController extends EntityDefaultViewsController {

  /**
   * Add extra fields to views_data().
   */
  public function views_data() {
    $data = parent::views_data();

    // Add your custom data here
    $data['contacts_topics']['table'] = array(
      'group' => t('Contacts Topics'),
      'base' => array(
        'field' => 'ckid',
        'title' => t('Contacts Topics'),
      ),
      'join' => array(
        'contacts' => array(
          'left_field' => 'ckid',
          'field' => 'ckid',
        ),
      ),
    );

    $data['contacts_topics'] = array(
      'ckid' => array(
        'title' => 'Contact Entity ID',
        'field' => array(
          'handler' => 'views_handler_field_numeric',
          'click sortable' => TRUE,
        ),
        'sort' => array(
          'handler' => 'views_handler_sort',
        ),
        'filter' => array(
          'handler' => 'views_handler_filter_numeric',
        ),
        'relationship' => array(
          'base' => 'contacts',
          'base field' => 'ckid',
          'handler' => 'views_handler_relationship',
          'label' => t('Contact entity relationship'),
          'title' => t('Conact entity relationship'),
        ),
      ),
    );

    return $data;
  }
}

Unfortunately I don't see anything in the Views SQL that shows that any of these attempts to add the fields or join the topics table to the contacts table are working.
Comment: how are these un-related fields 'related' to your entity. How do these entities know to show X other fields in addition to their own??
Comment: There is no entity relationship between them, it's simply an extraneous table I've defined in schema.  It's a many-to-many relationship, so each contact can have many topics.  The examples I've seen is simply a many-to-one example, and the deadline is ticking :(
Comment: It's kind of like I want to add a taxonomy field to this entity, so users can select any different kind of topics they are interested in, but I don't want to define a separate field for each topic...
Comment: I just found the [Relation](http://drupal.org/project/relation) module... I'm thinking this might be what I'm looking for
Comment: Relation was very quick and easy to get going, but the problem is that the Views integration didn't go far enough to provide the related entity as a Filter... going back to the beginning again.
Answer: How to attach a field to an entity programically solved this problem for me.  It's not an exact duplicate, but the answer and the comments pointed me to the right direction.
So this code creates the field and the instance and it attaches it to the entity very nicely:
function contacts_enable()
{
  if (!field_info_field('related_topics'))
  {
    $field = array(
      'field_name' => 'related_topics',
      'type' => 'list_text',
      'cardinality' => -1,
      'settings' => array(
        'allowed_values_function' => '_contacts_get_related_topics',
      ),
    );

    field_create_field($field);

    $instance = array(
      'field_name' => 'related_topics',
      'entity_type' => 'contacts',
      'label' => 'Related Topics',
      'bundle' => 'contacts',
      'default_value' => NULL,
      'settings' => array(
        'user_register_form' => FALSE,
      ),
      'widget' => array(
        'active' => 1,
        'module' => 'options',
        'settings' => array(),
        'type' => 'options_buttons',
        'weight' => -1,
      ),
    );

    field_create_instance($instance);
  }
}

Comment: Nice one Jonathan, thanks. In case somebody is wondering, if you use a structure like the Model project to create entities, a good point to place the above code (properly adapted of course) would be function save of ModelTypeController (which is based on EntityAPIControllerExportable).


Homeomorphic Spaces in Topology

Question: Let $X$ and $Y$ be two topological spaces.
Let $f : X \to Y$ and $g: Y \to X$, such that

$f$ and $g$ are surjective;
$f$ and $g$ are continous.

Does this imply that $X$ and $Y$ are homeomorphic?
It seems similar to Bernstein's theorem in set theory, and many of the topological properties like compactness, connectedness, etc are getting preserved.
Any help would be appreciated.
Comment: You should ask a different question.
Editing an already answered question *changing the question altoghether* disrupts the question system and disregards the work which was already put in the answers below.
Comment: @JackozeeHakkiuz Apologies. I'll do that.
Comment: @JackozeeHakkiuz https://math.stackexchange.com/q/4138074/499096
Answer:
For a continuous surjection $S^1 \mapsto [-1,+1]$ take the first coordinate projection map $(x,y) \mapsto x$.
For a continuous surjection $[-1,+1] \mapsto S^1$ take the map $x \mapsto (\cos(2 \pi x),\sin(2\pi x))$.
Answer: No. There exists a continuous surjection $f$ between $\mathbb{R}$ and $\mathbb{R}^2$ (see here), and a continuous surjection $g$ between $\mathbb{R}^2$ and $\mathbb{R}$ (obvious), but they are not homeomorphic.
Comment: Thanks :). A follow up question, what would happen if f and g were taken to be bijective ?
Answer: No it does not.
Consider $[0,1]$ and $[0,1]^2$. The projection on any component certainly constitutes a continuous surjection $[0,1]^2 \rightarrow [0,1]$.
Conversely, there are space filling curves, giving continuous surjections $[0,1]\rightarrow [0,1]^2$.
But $[0,1]$ and $[0,1]^2$ are not homeomorphic. Deleting a point in the interior of $[0,1]$ results in a disconnected space, which is not true, when deleting a point in the interior of $[0,1]^2$.
Comment: Thanks for replying. A follow up question, what would happen if f and g were taken to be bijective ?
Comment: That's a good one.

Homeomorphic Spaces in Topology


How to find all jpeg files having name without underscore from a specific folder and its subfolders in batch file then rename it

Question: I have the following script which gets all the files of type .jpg or.png located in the subfolder IN and renamed it with the folder name one layer up from IN which is named after the agent number.
for example, there is this path \\servername\SECH\DATA\CLI\45\IN\image504.jpeg, it should rename it to 45_image504.jpeg.
I want to use for /R because I want it to look only in the subfolders of CLI unless there is another way to pass the location to search in the for  loop. I want to know how this script can be improved to look for jpg files that do not have an underscore in the name.
For /R  \\servername\CLI\ %%a in (*.jpg *.png) DO (    echo filename %%~nxa     For %%g in (%%a\..) do (
     SET LAST_FOLDER=%%~nxg
     If "!LAST_FOLDER!" == "IN" (
         FOR %%V IN (%%a\..\..) DO (
              SET FOLDER_NAME=%%~nxV
              SET CURRENT_FILE_NAME=%%~nxa
              SET PREFIX=!FOLDER_NAME!_

              echo FOLDER_NAME : !FOLDER_NAME!
              echo CURRENT_FILE_NAME  : !CURRENT_FILE_NAME!
              If "!CURRENT_FILE_NAME:~0,4!" == "!PREFIX!" (
                   echo filename exists
               ) Else (
                  Rename "%%~a" "!FOLDER_NAME!_%%~nxa"
              )

         )
      )
                    ) )

Comment: In fact it looks like all you need is the single command line `@for /F "delims=" %%G in ('dir "\\servername\CLI\*.jpg" "\\servername\CLI\*.jpeg" "\\servername\CLI\*.png" /A-D /B /S 2^>nul ^| %SystemRoot%\System32\findstr.exe /V /C:_') do @for %%H in ("%%~dpG..") do @ren "%%G" "%%~nxH_%%~nxG"` to rename the files not containing already an underscore with folder name and an underscore prepended as long as no folder contains an underscore in its name. There is nothing else needed in the batch file as just this command line for this file rename operation.
Comment: Thank you I was able to make it works @Mofi
Answer:
Since the target files are located in a certain directory hierarchy depth, you should perhaps not search for them recursively in order to avoid unexpected matches.
Hence I would do it the following way:
@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_ROOT=\\servername\SECH\DATA\CLI"      & rem // (full path to target dir.)
set "_SDIR=IN"                              & rem // (name of sub-sub-directory)
set "_VSTR=_"                               & rem // (separator char. or string)
set _MASKS="*.jpg" "*.jpeg" "*.jpe" "*.png" & rem // (list of quoted patterns)

rem // Change into target directory:
pushd "%_ROOT%" && (
    rem // Loop through immediate sub-directories:
    for /D %%E in ("*") do (
        rem // Change into sub-sub-directory:
        pushd "%%~E\%_SDIR%" 2> nul && (
            rem // Loop through matching files, excluding those with separator:
            for /F "delims= eol=|" %%F in ('
                dir /B /A:-D-H-S %_MASK% ^| findstr /V /I /C:"%_VSTR%"
            ') do (
                rem // Actually rename the current file:
                ren "%%F" "%%~nxE%_VSTR%%%F"
            )
            rem // Return from sub-sub-directory:
            popd
        )
    )
    rem // Return from target directory:
    popd
)

endlocal
exit /B


How to reposition mac desktop in cocoa

Question: Is there a function that allows you to manipulate the desktop like Dashboard->Manage Widgets?
The desktop appears to reposition itself and slide up. What I want to do is not just slide the desktop when my toolbar is temporarily active but have the entire desktop resize. I assume if you can grab a handle to manipulate the desktop like Dashboard, additional similar operations should be possible.
Desktop windows continue to redraw and operate normally so this is not a screen cap that is just repositioned.
Is Dashboard executing a desktop animation function? or executing a complex set of functions to emulate this effect? or private API? Anyone know?
Answer: My guess is emulation. It's probably a window at a very high window level that grabs a screen cap of your desktop to use as its background then animates the rest.
In any case, there's no Cocoa function to let you do this with your own UI.
Comment: That's like the trick used before to simulate transparent or semi-transparent backgrounds but we know modern OSes no long require that for compositing. My guess is there must be a function to access the core OGL plane to move the desktop. I'm not hinting-- this just what I think based on how it draws the windows effects and animations
Comment: Would love to know the function/library if it exists. :-)
Comment: This is easy to test: start playing a movie in QuickTime Player. Open Dashboard and click the Manage Widgets button. The movie keeps playing!

How to reposition mac desktop in cocoa


Linear Model with Categorical Predictor Variable: What's the Math behind it?

Question: I do understand how linear regression models work with numerical data (finding the line that has the least squares). Having read Grolemund's and Wickham's R for Data Science, I was wondering about one of their examples which goes like this (edit: This is only a fraction of the data they use but I wanted to create a small and reproducable example without tidyverse, as Roland pointed out below):
(daily <- data.frame(n = c(842,943,914,915,720,832,933,899,902,932,930,690,828,928,894,901,927,924,674,786), wday = c("Tue","Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")))

mod <- lm(n ~ wday, data = daily)

Obviously, the cut could be regarded as an ordinal variable so that it can easily converted to the number but as the plot shows, this will not result in a linear line. I did consult R's lm() manual but did not find any information why the use of lm() here is ok.
Comment: Good point, Roland. I will provide a different example.
Comment: The code is not showing the model (or obfuscating it so much that people who don't follow the tidyverse hype can't see it).
Answer: First of all, days are not ordinal, but nominal. (The elegant way to include them in a regression is to convert them into a factor, you haven't done that, but in this particular case it doesn't matter, because right now they have character type, which will be automatically converted to factor.)
So the question is, what goes on under the hood with nominal variables? (R will call them "unordered factor".) This: $$Y_i = \beta_0 + \beta_{Tue} D_{i,Tue} + \beta_{Wed} D_{i,Wed} + \ldots + \beta_{Sun} D_{i,Sun}+\varepsilon.$$ Here $D_{i,Tue}$ is a variable which takes the value of 1, if the $i$th day is Tuesday, zero otherwise. Likewise for the remaining days. These are usually called dummy, or indicator variables. In R, they're generated totally automatically, you don't have to do anything, except for making sure that R handles the variable as factor. Note, that there is no indicator for Monday.
So, the important point is: you can now see that it is indeed a usual linear model!
How it works? Just think over the interpretation of the coefficients. If the day is Monday, then every dummy takes the value of zero, every product will be zero, so we have $Y_i = \beta_0 +\varepsilon$, i.e., $\beta_0$ will be the estimated value for Monday. (Simply the average in this case.) If we are on Tuesday, we have $Y_i = \beta_0 + \beta_{Tue} +\varepsilon$, so $\beta_{Tue}$ is the difference between the estimated values of Tuesday and Monday. (As $Y_i-\beta_0 = \beta_{Tue} +\varepsilon$, but we already know that $\beta_0$ is the estimated value for Monday.) And so on!
So you can see why we included one dummy less: the omitted level will be the so-called reference, what you see in the intercept, and every other one will have an interpretation of "compared to" the reference. One important remark: what will be the reference level is something that you can set yourself, by explicitly calling factor or using relevel on a variable that is already a factor, or it will be decided by R automatically, but if the original variable is a character, then it'll be the first in alphabetical order (which is not necessarily meaningful!).
If we were to include all dummys, we would run into perfect collinearity as the sum of the dummys would be a constant 1 - just as the intercept. Of course we could write $Y_i = \beta_{Mon} D_{i,Mon} + \beta_{Tue} D_{i,Tue} + \beta_{Wed} D_{i,Wed} + \ldots + \beta_{Sun} D_{i,Sun}+\varepsilon$, in this case every coefficient will take the value of the estimated response on that day - use the logic introduced above to track this! - but we don't really like this approach (just think over what would happen if we had to include two factors!).
Note, that these are just the most basic ways to encode categorical variables. ?contr.treatment or this page gives you more information on the other possible options.
Comment: I'm struggling to understand how day of the week can be validly considered "ordinal:" exactly which one is first and which one last?  This is a *circular* variable.
Comment: Might be worth mentioning that there are other standard ways of defining contrasts and different statistics software will use different contrasts by default, see also `help("contr.treatment")`.
Comment: @whuber 's comment that days are *circular* is still apt. Treating days as unordered categories means that you dispense with the circular ordering of days (e.g., Friday does not follow Thursday by one day, and does not precede Thursday by six days in your model).
Comment: Sorry--I grievously misread it! (+1)
Comment: @IsabellaGhement Thanks, and you're right (I included an extension to mention this).
Comment: Yes, that is true, I definitely agree. Nevertheless, it's hard to say more without context (as outline by @Peter Flom in his recent answer).
Comment: @whuber Wait, I just said that they're _not_ ordinal...! (If you refer to my first sentence.)
Comment: No worries... :)
Comment: Very nice answer, Tamas! (+1)
Comment: The coefficients in the model *without* a dummy variable for Mon are interpreted differently than those in the model *with* such a dummy variable.  For example, the coefficient $\beta_{Tue}$ in the model *without* a dummy variable for Mon represents the difference in the mean values of Y between Tue and Mon.  The coefficient $\beta_{Tue}$ in the model *with* a dummy variable for Mon represents the mean value of Y for Tue.
Comment: @Roland True, thanks for the idea, I included a sentence to mention this!
Answer: summary(mod)

gives you a nice overview over what's going on under the hood. Basicallly what happens is that the categorical variable is automatically turned into a number of binary variables, i.e. is it a monday (0 or 1), is it a tuesday, and so on.
One thing to note is that there are seven days, but only six binary variables, so that linear dependency is avoided.
Answer: How to treat "day of week" is an interesting question and I am not sure we can just automatically say that treating it as nominal is best in all cases. It will depend on context (and none was offered here). One commonly useful approach would be weekday and weekend - and, indeed, these data show huge differences between weekdays and weekends. But I could easily see cases where some other categorization would be useful, e.g.
"How much time do you spend in church?"  Sunday vs. other seems sensible but
"How much time do you spend in worship?" might need special treatment depending on the religion of the person.
Or, getting to my old area of research - "How much alcohol do you drink on a typical day?" is often a bad question as it varies hugely by day.
Do you eat dinner out? is likely to be different on Fridays and Saturdays from other days (at least in the parts of the world where Sat and Sunday are typically weekend).
In addition, R (by default) chose Friday as the reference (because it is first, alphabetically). This may or may not be ideal. Yes, if you look carefully, the results mean essentially the same thing regardless of choice of reference, but people who get hung up on statistical sig. may find that changing the reference changes what is significant.


I got duplicated modules after updating an installation. How to remove them?

Question: I have a site built using the Commerce Kickstart profile. Then there are enabled modules provided by the distribution at:

profiles/commerce_kickstart/modules/contrit

and also there are modules which I added at:

sites/all/modules

The distribution added some modules: colorbox, entity, etc. in its last version.
The problem is that I already had these modules at sites/all/modules.
The I got those modules duplicated at:

profiles/commerce_kickstart/modules/contrit/colorbox

and

site/all/modules/colorbox

I guess this is wrong. My question is which folder do I have to delete?
Comment: As per my understanding with distribution, module needed for it need to be inside it as it's mentioned in there, so you will need to delete from your sites/all/modules. But I will recommend you to ask this question at http://drupalcommerce.org/ before you go to take any action regarding this..
Comment: You should delete from your sites/all/modules. I don't understand the need of your to put it at first place. Did it come at update itself ?
Comment: I'm almost sure that these modules weren't in previous version of the distribution. Then I added them in site/all/modules. And I added them just because I needed.
Comment: What @RajeevK said - you need to get rid of the ones in sites/all/modules. Download a fresh copy of Kickstart, and any modules under profiles/kickstart/modules/contrib that are _also_ under sites/all/modules in the offending site...delete from sites/all/modules. Make sure you take a backup first, of course
Answer: Here are the steps I would perform to address this question, in the specified order:

Download and unpack a fresh copy of the new Commerce Kickstart release.
Create a list of all your modules in your sites/all/modules folder, and identify all modules in there with the same name (module namespace) as in the new Kickstart release. The result should be a list of the duplicate modules that need to be resolved.
Use the Hacked! module to identify any hacks, patches, customizations, etc that might have been applied to any of these duplicate modules in the sites/all/modules folder.
Disable and uninstall the duplicate modules.
Backup and then delete the entire folder of each of the duplicate modules in the sites/all/modules (or move them to a folder outside your Drupal root directory).
Enable the fresh copy of the new Kickstart release. That inherently will also re-enable the vanilla version of the duplicate modules, as contained in the new Kickstart release.
Reply any hacks, patches, customizations, etc that are appropriate to be  re-applied (e.g. because upgrading to the new Kickstart release does not make them obsolete).
Should you run into weird problems because of some of the duplicate modules being moved to another directory, then download and enable the Registry Rebuild module (and/or related Drush RR command). That will probably resolve those problems.


argparse and TypeError: execv() arg 2 must contain only strings

Question: I know this one has been asked quite a bit, however trawling through the answers given either:

Have not resolved my issue
Don't really relate to what I am seeing

I am relatively new to coding in general and this is the first time I have tried to use argparse.
Essentially I am getting the following error from my script:
TypeError: execv() arg 2 must contain only strings

I am attempting to write a pretty simple wrapper for Spike Fuzzer, when I have the arguments -p, -v and -s statically set to an integer (not using argparse), the script runs without issue. When I attempt to use the arguments for them, I see the above error.
Please see code below:
import argparse, subprocess, os, sys

parser = argparse.ArgumentParser(prog='fuzz.py',
                                usage='%(prog)s -i 127.0.0.1 -p 21 -d /root/example -v 0 -s 0',
                                )

parser.add_argument('--version', action='version', version='[+] Version: BETA')

parser.add_argument('-i', metavar='127.0.0.1',
                    help="IP Address"
                    )

parser.add_argument('-p',
                    type=int,
                    default=21,
                    metavar='21',
                    nargs=1,
                    help="Port (Default 21)",
                    )

parser.add_argument('-d', metavar='/root/example',
                    help="Spike script directory"
                    )

parser.add_argument('-f', metavar='example.spk',
                    nargs=1,
                    help="Spike File"
                    )

parser.add_argument('-v',
                    type=int,
                    default=0,
                    metavar='0',
                    nargs=1,
                    help="SKIPVAR (Default 0)",
                    )

parser.add_argument('-s',
                    type=int,
                    default=0,
                    metavar='0',
                    nargs=1,
                    help="SKIPSTR (Default 0)",
                    )

args = parser.parse_args()

def Directory():
    for file in os.listdir(args.d):
        if file.endswith(".spk"):
            print file
            fuzzer = subprocess.call(['generic_send_tcp', args.i, args.p, file, args.v, args.s])

Directory()

If you would like any more information please give me a yell and I will provide what I can.
Cheers,
AJ
Comment: The error seems pretty clear.  "...must contain only strings"  Look at the list you are passing to `subprocess.call`; does it consist entirely of strings?
Comment: Side note: You have the meaning of `metavar` wrong. That is supposed to be a "variable" name, not the default value repeated. For instance 'FILENAME' or 'PATH' for the '-f' option. I would also recommending longer, descriptive names for the options than just those one character names.  The `nargs` arguments don't have any effect because 1 is the default value.  The arguments to `ArgumentParser` are redundant. That information is usually determined by the object itself from `sys.argv` and from the arguments added.
Answer: With regard to the argparse use, the only glaring issue is the use of nargs=1.  With that the values will a one element list, not a string.  Leave that off (or use the default nargs=None), and values will be strings.
Print args after parsing to have a clear idea of what has been parsed.  And if need print selected values, eg. args.v.
Print this line:
['generic_send_tcp', args.i, args.p, file, args.v, args.s]

I'm guessing from the error that args.p is ['21'] when it should be simply '21'.
The choice of metavar, names etc are just a matter of style, and don't affect the running.
In [360]: p=argparse.ArgumentParser()

In [361]: p.add_argument('-f',nargs=1)
Out[361]: _StoreAction(option_strings=['-f'], dest='f', nargs=1, const=None, default=None, type=None, choices=None, help=None, metavar=None)

In [362]: p.parse_args(['-f','12'])
Out[362]: Namespace(f=['12'])

Comment: Unfortunately I can't mark this up due to low reputation (new account). Thanks very much hpaulj, worked a treat.


error in calculating dates in php functions

Question: I am working on a php project where I need to get the all dates for next 20 weeks  from a particular date and I am trying following logic
$epochdate = strtotime("17 August 2015");

for ($i=$epochdate + 604800, $i < $epochdate + ( 604800 * 20 ); $i = $i+604800, $j++) {
   echo date('Y-m-d H:i:s', $i);
   echo '
';
}

Everything is working fine but it gave wrong date after 2015-10-19 ..here is the output
2015-08-24 00:00:00
2015-08-31 00:00:00
2015-09-07 00:00:00
2015-09-14 00:00:00
2015-09-21 00:00:00
2015-09-28 00:00:00
2015-10-05 00:00:00
2015-10-12 00:00:00
2015-10-19 00:00:00
2015-10-25 23:00:00//it should be 2015-10-26
2015-11-01 23:00:00
2015-11-08 23:00:00
2015-11-15 23:00:00
2015-11-22 23:00:00
2015-11-29 23:00:00
2015-12-06 23:00:00
2015-12-13 23:00:00
2015-12-20 23:00:00
2015-12-27 23:00:00

What is wrong here?
Comment: on this date the switch to daylight saving time is made in 2015
Answer: This most likely happens because of the transition from standard time to daylight time in some time zones.
Try using the DateTime class instead:
$epochdate = new DateTime("2015-08-17");
for ($i = 0; $i < 20; $i++) {
  $epochdate->modify('+1 week');
  echo $epochdate->format('Y-m-d H:i-s') . '
';
}

Output:
2015-08-24 00:00-00
2015-08-31 00:00-00
2015-09-07 00:00-00
2015-09-14 00:00-00
2015-09-21 00:00-00
2015-09-28 00:00-00
2015-10-05 00:00-00
2015-10-12 00:00-00
2015-10-19 00:00-00
2015-10-26 00:00-00
2015-11-02 00:00-00
2015-11-09 00:00-00
2015-11-16 00:00-00
2015-11-23 00:00-00
2015-11-30 00:00-00
2015-12-07 00:00-00
2015-12-14 00:00-00
2015-12-21 00:00-00
2015-12-28 00:00-00
2016-01-04 00:00-00

If the date comes in the day month year format as in your example you may need to use DateTime::createFromFormat() first.
Answer: Why did you make it so complicated?
For your logic with strtotime() you can just do that
 <?php
    $epochdate = "17 August 2015";
    for ($i=0; $i<=20; $i++) {
       echo date('Y-m-d H:i', strtotime($epochdate.' +'.$i.' weeks');
       echo "
";

    }


Exporting Excel Data from Webpage

Question: I am currently trying to write a python script that will open my companies inventory system which is a link in google chrome, sign in, and then click the save as excel button that is posted on top of a specific page. This will hopefully automate the process of opening the link, navigating over to the tab, clicking export, then exporting this data daily.
Any idea of where to start? I was thinking maybe can get this done using web scraping but not sure with the log in details needed. Also, how can I export this file once in? Just need some ideas to start me on this journey. Any and all help is appreciated!
Comment: At the moment the question is too broad and lacks details that will help us to provide specific help, e.g. it may be that the inventory system has an API or you may just need to replicate the requests being made or you may need a more specific tools like Selenium.
Answer: Simply start with selenium python automation

Divide you whole process in smaller tasks and write python code
for that each task:)

Exporting Excel Data from Webpage


How can I pass user real name as a contextual filter in views

Question: I am trying to simply provide a view of author content by passing a contextual link for the author ID to provide a URL with the author's name as selected with the Real Name module.
For instance: "/sitename/content-type/realname".
When I set up the filters, the only way I can get it to work is by providing the user name, not the real name as set by the real name module. I would like to keep the login name private, and use the real name as assigned.
Has anyone had any success doing this?
Answer: If the real name is stored in one field in your user, you can set up a relationship with the user and then point to that in the contextual filter, eg, here I just created a "real name" text field in the user and then did this:

and then for nice looking urls, did this in the filter:

so I can go to
www.example.com/by-real-name/this-real-name
or
www.example.com/by-real-name/that-real-name
It's really up to you re: case transformation, but two real caveats:  you have to make sure real names are unique AND it gets really squirrelly if and when special characters are in the real name field.
Comment: Thank you for the great suggestions.  I don't currently have the real name field anywhere other than Profile 2, but was able to add author profile as a relationship after adding author as a relationship. This exposed the name field I had set up to be used for real name with contextual filters.  I was never able to get the URL to convert spaces to dashes unfortunately. When I enter the /content/real name, it still displays /content/real%20name. Perhaps I am misunderstanding what this is supposed to accomplish?
Comment: I am not sure how or where you are creating the links, but the space/dash stuff just allows you to use dashes in the url that Views will then convert internally to spaces to then match to the field.  So for example if you were to create a link in a block or other content displayed on the User's profile, you could create a friendly link using the contents of that real name field by converting those spaces to dashes.  But, realize, if a person has a dash in his/her name, it will be converted to a space and then the match won't work.


Criptografia AES128/256 C#.net E SQL 2008/2012

Question: Saudações,
Alguém tem o conhecimento de alguma implementação da criptografia AES compatível entre o c# e SQL? Desejo criptografar em C# e descriptografar em SQL.
Answer: Você pode implementar a biblioteca de criptografia em .NET e instalá-la diretamente no seu serviço MS SQL Server.
Uma vez que o assembly tenha sido devidamente instalado no servidor, suas classes podem ser configuradas e acessadas como no exemplo abaixo:
<code>CREATE PROCEDURE teste
AS
EXTERNAL NAME Biblioteca.Classe.MetodoTeste
</code>
Fonte: 'Deploying CLR Database Objects', MSDN.
Comment: @Pedro eu passei por uma situação similar no passado, e meu maior problema foi a falta de consistência entre as implementacões de algoritmos entre as duas plataformas. A instalação de um CLR foi a maneira encontrada para guarantir que os métodos de encriptação e descriptação seguissem os mesmos parâmetros. De qualquer maneira, boa sorte na sua busca!
Comment: Boa solução, mas não se adapta ao meu caso.... realmente precisava de um algoritmo interno que realize a criptografia. Obrigado de qualquer forma.
Comment: Não há como fazer isso usando as duas plataformas diferentemente. Voce precisa codificar e decodificar os dados "manualmente" pelo C#.


Can't Figure Out How to Pause YouTube Video on Click

Question: My users are using the old embed method of utilizing the  tag YouTube gives you instead of the iframe. I'm trying to figure out how to detect the player state (when it's paused, playing etc) when a user interacts with it so I can pause the video when the user clicks to the next slide.
Currently using Wordpress I have a metabox that allows them to paste in the YouTube embed code and then I output that block of code onto the slider. I'm working on my localhost (example: http://mysite.dev). Something to know is that potentially the user could have multiple videos on the slider.
For the life of me I can't get the YouTube API to execute.
1) This is the youtube embed object they are pasting into the box
<object width="475" height="271">
    <param name="movie" value="http://www.youtube.com/v/soefG7iisoE?wmode=opaque&version=3&enablejsapi=1&modestbranding=1&autohide=1&rel=0&hl=en_US"></param>
    <param name="allowFullScreen" value="true"></param>
    <param name="allowscriptaccess" value="always"></param>
    <embed src="http://www.youtube.com/v/soefG7iisoE?wmode=opaque&version=3&enablejsapi=1&modestbranding=1&autohide=1&rel=0&hl=en_US" type="application/x-shockwave-flash" width="475" height="271" allowscriptaccess="always" allowfullscreen="true"></embed>
</object>

2) This video is in a slider I made with a div of:

   [there youtube embed code outputs here - see point 1]

I'm using JQuery and I've tried calling the API like so:
function onYouTubePlayerReady(playerId) {
    // using the class and the tag as selector because there could be
    // multiple videos *and* the user might not put an ID in the object tag
    ytplayer = $('.videoContainer object');
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
    alert("Player's new state: " + newState);
}

I have a function called stopCycle contained within a jQuery(document).ready(function($) {}); code block and it's this function that I need to call when the user clicks to the next slide.
So here are my questions:

Do I need to call any external JavaScript file?
Within my JQuery document ready block how can I call the the YouTube api to check to see if the video is playing?
Is there anything else that I am missing in my code or something that you need to see?

I'm wondering if it would be better to have them only enter the YouTube URL and then I'll output the video using JQuery SWFObject. What I don't know how to do is loop out the video for each slide (total of 5). So if they had a video for each slider how would I do that?
I know... totally loaded full of questions here.
Answer: From what I see you have an error:
ytplayer = $('.videoContainer object');
//should be
ytplayer = document.getElementById("myytplayer");
Then you can use any of the api calls here, and everything should work fine and dandy
The reason why you cannot use a jQuery selector for this is because the is expecting an <embed> element. What jQuery returns is an array of all elements matching the selector.
To answer your questions:

1) Not unless you have your js in an external file
2) To get the current video ytplayer .getVideoUrl()
3) as said previously
4/5) You can setup a playlist using this: ytplayer .cuePlaylist
Answer: If you're using the Youtube API, you should be able to pause the video like this:
var ytplayer = document.getElementById("myytplayer");
pauseVideo = function(){
    if (ytplayer){
        ytplayer.pauseVideo();
    }
}

Pause

See here for details:
http://code.google.com/apis/youtube/js_api_reference.html#Playback_controls
EDIT
If the embedded player does not have an ID, you can try something like this:
function onYouTubePlayerReady(playerId) {
    $("#" + playerId)[0].addEventListener('onStateChange', "(function(state) { return playerState(state, '" + playerId + "'); })");
}

function playerState(state, playerId) {
    console.log(state);
    console.log(playerId);
}

Comment: What if the user doesn't add an id onto the embeded object? Is there a way of saying when "this" gets clicked pause the video?
Comment: I tried your code right now and it's not working. I'm wondering if I'm missing something with get the API to work with YouTube and the embed code. I took the code out, placed it in an empty HTML file and tried your code and nothings working so I'm thinking that I'm not calling the API to be initialized properly. Thoughts?
Comment: Have you tried using the first solution with a static video source (not dynamically added by a user in the forum)?
Comment: Okay so the api is calling the function. I just tried this: `function onYouTubePlayerReady(playerId) {
    console.log('onYouTubePlayerReady function called');
 console.log('playerId: ' + playerId);
}`

If I try something like this:
`ytplayer = $('#'+playerId)`

then the script breaks and nothing moves forward. Confusing as heck to get this working.
Answer: $('iframe').each(function(i,e){
    let iframeSrc = $(e).attr('src');
    $(e).attr('src',iframeSrc);
});

This will reset src for all videos, you can modify it to target only one
let iframeSrc = $('.youtube_video').attr('src');
$('.youtube_video').attr('src',iframeSrc);

Replace the class '.youtube_video' with your actual iframe class
Note: Don't forget to trigger this on click event


Products of alphabets: the behaviour of the empty word

Question: I'm having some problem with this question involving formal languages: let $L = \{ \epsilon, 01, abc \}$ and $T = \{x, y, z\}$. I'm supposed to find $L^3$, $LT$ and $TL$.
Now I know that the first one is just the set of all words length $3$ over the alphabet $L$, however, $I$ am confused by the presence of the empty word.
Would $L^3 = \{\epsilon \epsilon \epsilon, \epsilon \epsilon 01, \epsilon \epsilon abc, \epsilon 01abc, 01 \epsilon \epsilon, 0101 \epsilon, 010101, 01abc \epsilon, 01 \epsilon abc, \dots\}$
or
would $L^3 = \{010101, 0101abc, 01abc01, abc0101, \dots\}$?
Comment: Is $e$ the empty word? If so, what happens when you compose the empty worth with any other word?
Comment: Edited this in order to change the title which was so generic, that it may have collided with future titles.
Answer: Your first answer is correct, except that you should simplify the words containing $\epsilon$: $\epsilon\epsilon\epsilon=\epsilon$, $01\epsilon abc=01abc$, and so on. In fact, you can eliminate every instance of $\epsilon$ except the empty word itself, because for any word $w$ you know that $w\epsilon=\epsilon w=w$.


UWP Desktop Bridge app crashes on double click

Question: I'm working on a UWP Desktop Bridge App. I have created the packaging project and created an app package for sideloading.When I click on the App
Icon once, the app launches successfully.But on double click of the Icon, the app crashes.
I have created the packaging project following the link :
https://learn.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-packaging-dot-net
The App runs normally on single click of the app icon. Is it because on double click, the .exe is being invoked twice and that's the reason for the crash?
Here is the Main method of the Background process
   private static void Main(string[] args)
    {
        try
        {
            connection.AppServiceName = "CommunicationService";
            connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;

            // hook up the connection event handlers
            connection.ServiceClosed += Connection_ServiceClosed;
            connection.RequestReceived += Connection_RequestReceived;

            AppServiceConnectionStatus result = AppServiceConnectionStatus.Unknown;

            // static void Main cannot be async until C# 7.1, so put this on the thread pool
            Task.Run(async () =>
            {
                // open a connection to the UWP AppService
                result = await connection.OpenAsync();

            }).GetAwaiter().GetResult();

            if (result == AppServiceConnectionStatus.Success)
            {
                while (true)
                {

                }
            }
        }
        catch (Exception)
        {
        }
    }

The code to call:
    private async Task StartBackgroundProcess()
    {
        try
        {
            // Make sure the BackgroundProcess is in your AppX folder, if not rebuild the solution
            await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
        }
        catch (Exception)
        {
            MessageDialog dialog = new MessageDialog("Rebuild the solution and make sure the BackgroundProcess is in your AppX folder");
            await dialog.ShowAsync();
        }
    }

Also,inside package manifest:
<desktop:Extension Category="windows.fullTrustProcess" Executable="BackgroundProcess.exe" />
    <uap:Extension Category="windows.appService">
      <uap:AppService Name="CommunicationService" />
    </uap:Extension>

and
<rescap:Capability Name="runFullTrust" />

Is it possible to avoid the crash issue?
Comment: can you find error message for the crash? there should be some trace in the system Event Log
Answer: if it's a connection, if you try to connect it twice, it may be crashed.  you can make u app only start up once, if it started, then switch to started process.
public partial class App : Application
   {
       ///
       /// Application Entry Point.
       ///
       static Mutex muetx = new Mutex(true, "{666666666}");

       [System.STAThreadAttribute()]
       [System.Diagnostics.DebuggerNonUserCodeAttribute()]
       [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "220.127.116.11")]
       public static void Main()
       {
           if (muetx.WaitOne(TimeSpan.Zero, true))
           {
               TestBeginInvoke.App app = new TestBeginInvoke.App();
               app.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
               app.Run();
           }
           else
           {
               var pro = System.Diagnostics.Process.GetProcessesByName(nameof(TestBeginInvoke));
               var handle = pro.FirstOrDefault().MainWindowHandle;
               ShowWindow(handle, 1);
               ShowWindow(handle, 9);
               SetForegroundWindow(handle);
           }
       }

       [DllImport("USER32.DLL")]
       public static extern bool SetForegroundWindow(IntPtr hWnd);

       [DllImport("user32.dll")]
       private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);

   }

Comment: How do I know whether the background process has started or not?
Comment: try mutex and process
Comment: Mutex should be implemented in UWP ?
Answer: Please check the AppService Bridge Sample. It creates and starts a separate thread each time to create a new AppServiceConnection instance and call its OpenAsync method.
static void Main(string[] args)
{
    Thread appServiceThread = new Thread(new ThreadStart(ThreadProc));
    appServiceThread.Start();
}

static async void ThreadProc()
{
    connection = new AppServiceConnection();
    connection.AppServiceName = "CommunicationService";
    connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;
    connection.RequestReceived += Connection_RequestReceived;
    AppServiceConnectionStatus status = await connection.OpenAsync();
}

Comment: @GeethuSuresh I tried 'AppService Bridge Sample', it has no problem. Please provide a [mcve].


Distribution of the Levenshtein distance between two random strings

Question: The Levenshtein or edit distance between two strings is the minimum number of edits (adding a letter, removing a letter or changing a letter) required to transform one into the other.
Assume that we have two strings, each of size $n$ and that consist of letters drawn uniformly IID from an alphabet of $k$ letters. What is the (possibly approximate) distribution of their Levenshtein distance?
This can be seen as an extreme value problem since the Levenshtein distance is the minimum number of mismatches over all the possible ways to align the two sequences. For an alignment chosen randomly among those with $m$ insertions and $m$ deletions, the number of mismatches has a Binomial distribution with parameters $n-m$ and $1-1/k$, so it is tempting to compute the distribution of the minimum of all those Binomial variables (as in this question), but in this case, the Binomial variables are not IID.
A solution to this problem would be useful in biology (where $k=4$ in the case of DNA sequences) because it would give the statistical properties of the alignment between unrelated sequences.
Answer: I guess it is not a direct answer, but you can try to simulate the scenario and check the empirical distribution to have a rough idea (R code below).

So it seems that for strings longer than ~ 100 the distribution is symmetric and quite narrow around .53 times the length of the string.
<code># dependencies

library(ggplot2); theme_set(theme_classic())
library(parallel)
library(RecordLinkage)

# settings

alphabet <- c("A", "C", "G", "T")
Nsim <- 1e3
read_lengths <- seq(60, 500, 20)

# function to create a random string of length "n" using letters of the alphabet "alph"

random_read <- function(n, alph=alphabet) paste(sample(alph, size=n, replace=T), collapse="")

# simulate

res <- mclapply(read_lengths,
                function(N) replicate(Nsim, levenshteinDist(random_read(N), random_read(N))),
                mc.cores=6)

# arrange results as data.frame

res_df <- data.frame(dist=unlist(res),
                     length=rep(read_lengths, sapply(res, length)))

# plot densities

ggplot(res_df,
       aes(x=dist / length, col=length, group=length)) +
  geom_density() +
  ggtitle("Distribution of Levenshtein distance / length")

ggplot(res_df,
       aes(x=length, y=dist / length, col=length)) +
  geom_violin(aes(group=length)) +
  geom_smooth(col="black", lwd=1) +
  ggtitle("Distribution of Levenshtein distance / length")
</code>
Comment: Thanks for this analysis! I had done a similar one up to length 10,000 (the average keeps decreasing it seems). +1 for the good work, but I cannot check "accept" because I am looking for an analytical solution.
Comment: In case you want so simulate from an organism that do not have the letters evenly distributed, you can include sampling probabilities via the "prob" argument in calling of "sample" of the "random_read" function definition.
Answer: This looks a bit like the Tracy-Widom distribution perhaps? For longest common subsequences there is a "famous" result relating the distribution of LCS between random strings (under a bunch of limiting assumptions) to the Tracy-Widom distribution: https://arxiv.org/abs/q-bio/0410012. https://www.quantamagazine.org/beyond-the-bell-curve-a-new-universal-law-20141015/
Comment: It is a very interesting connection! I was not aware of this "famous" result, but it is spectacular!


Count word/pos from file

Question: I've almost solved an exercise from my python lectures. I've been asked to write a program that counts how often each word occurs in a file, and how often it has been tagged with which POS.
The counts should be written to a new file, which is also given on the command line.
For instance,
python3 wordcount-pos.py wsj00-pos.txt counts-wsj00-pos.txt

should produce a output like this:
   Mortimer 1   NNP 1

   foul 1   JJ  1

   ...

   reported 16  VBN 7   VBD 9

   ...

   before   26  RB  6   IN  20

   ...

   allow    4   VB  2   VBP 2

My code produces an output such as:
   Mortimer 1   {NNP:   1}

   foul 1   {JJ: 1}

   ...

   reported 2   {VBN:   7   VBD:    9}

   ...

   before   2   {RB:    6   IN: 20}

   ...

   allow    2   {VB:    2   VBP:    2}

It doesn't print the occurrences of "word" in my dictionary
Here it is my code:
import sys
from collections import defaultdict

def main():
    if len(sys.argv) != 3:
        print('Usage: python poscount.py <input file>', file=sys.stderr)
        sys.exit(1)

    input_filename = sys.argv[1]
    output_filename = sys.argv[2]
    # your code
    freq = defaultdict(list)
    with open(input_filename) as f:
        for line in f:
            # skip empty lines
            if line.strip() != '':
                #  split a word/pos pair into two separate strings
                word, pos = line.strip().rsplit("/", 1)
                # add word and list of pos as k, v into "freq" dictionary
                freq[word].append(pos)

    for k, v in freq.items():
        D = defaultdict(list)
        for i, item in enumerate(v):
            D[item].append(i)
        D = {k: len(v) for k, v in D.items()}
        # Output file
        with open(output_filename, "a") as f:
            print(k + "\t" + str(len(D.items())) + "\t" + str(D), file=f)

if __name__ == '__main__':
    main()

file from where extract the data: https://paste.elnota.space/nezemivaku.sql
Partial content of the file:
Pierre/NNP
Vinken/NNP
,/,
61/CD
years/NNS
old/JJ
,/,
will/MD
join/VB
the/DT
board/NN
as/IN
a/DT
nonexecutive/JJ
director/NN
Nov./NNP
29/CD
./.
Mr./NNP
 Vinken/NNP
is/VBZ
chairman/NN
Comment: What do you mean by `how often it has been tagged with which POS.`
Comment: So the error is that it should print e.g. `reported 16`, and instead it's printing `reported  2`?
Comment: That's correct @JohnGordon
Comment: If you could provide a sample input and output that would help us understand what you are trying to solve.
Comment: I attached a hastebin link to the question with the input
Comment: The hastebin link does not work with automated tools such as `wget`.
Comment: here it is: https://send.firefox.com/download/93891817cea23cf4/#Ta0Yl0GpWTE3MvAJgSnyiw
Comment: That link also does not appear to work with `wget`.  Can you include the first ten lines of the file in your post?
Answer: I think this will solve your problem
print(k + "\t" + str(sum(D.values())) + "\t" + str(D), file=f)

Comment: thanks for the reply, although it gives "KeyError: `Pierre`"
Comment: using D[k], gave you a keyError, could you print the content of D?
Comment: If I print D, I get a dictionary of "pos" values with their occurrences (see original post)
Comment: I think this will work
print(k + "\t" + str(sum(D.values())) + "\t" + str(D), file=f)

Count word/pos from file


How do I build a secure webservice with .Net?

Question: I need to build a simple webservice to get data in and out of a HR System over the Internet (it's a hosted solution). I am using IIS and ASP.Net with .Net 2.0.
Having looked into it, there are several ways of making the webservice secure - I am after some advice on which method to choose, with some views on pros and cons.
These are the methods I am aware of:
SoapHeaders over SSL
Post the UID/PWD in a Soap header and implement a SOAP extension (link).
Pretty straightforward to implement and should be quite secure over SSL. This is by far my preferred option due to the relative simplicity. Also, for historical reasons, I will need to consume the webservice from VBScript of all things, so the ability to just deal with simple SOAP is a bonus.
However, are there any caveats? Am I going to have clients complaining this is a security risk?
Using WCF with TransportWithMessageCredential
I found a lot of old articles referring to WS and if I am not misstaken, this is what is now provided in WCF? This Microsoft link has a primer.
If I understand it correctly, this uses certificate-based security between client and server for authentication. Is this correct or have I got it completely wrong?
I suspect this will be a much bigger job, at least implementation wise. Also, I won't be able to access the Webservice directly from VBScript, so will have to write a dll it call call and then deploy that locally - correct?
Is this even available in .Net 2.0?
Other methods

I could disallow anonymous access to
the asmx file and use rely on IIS to
do authentication through
challenge/response. This is actually
practical in my scenario but feels
very inelegant (and no idea how to
make that work from VBScript either).
Passing in a UID to the method call
is a poor cousin of the SoapHeader so
I won't use that.

I would be very grateful for any advice on the best approach to this problem. If anyone has a good argument why Soap Headers are secure then I would love to hear it, as that seems like the simplest to use, as long as it is "secure enough".
Answer: You should strongly consider using IIS and Windows to provide the authentication. IIS can map incoming requests to an AD user (NTLM, Certificates, Kerberos, etc.). From there, you'll have a WindowsPrincipal you can use to demand that the user is in a group. If you don't mind compiling the group name into the code, you can even use the PrincipalPermissionAttribute on your service methods so it'd be completely declarative.
By using Windows, you get the platform to deal with all the security issues. Passwords won't be transmitted in plain text, nor will you need to create and specify your own challenge/response type system (yuck). Different clients could authenticate in different ways (require certificates for some, allow NTLM for others).
Finally, you'll end up with less code since you can use Windows to manage the users and the .NET Framework to enforce security checks.
Edit:
Maybe you think securing the ASMX is hacky because that's the only step you're looking at? I'd agree! A webservice that only depends that you've denied anonymous sounds very weak indeed. The webservice code itself should demand group membership after the authentication is done. That way if you misconfigure the server, you've made it inaccessible, not insecure.
Answer: Use WCF. It requires .NET 3.0 or above (just as well use 3.5 SP1), but that's just .NET 2.0 with a couple of service packs and some new assemblies, so it's safe.
I recommend against ever again using ASMX web services for new development, unless there's no choice.
You may have read about "WSE" or "Web Service Extensions". These are obsolete, and were a series of extensions to ASMX web services to implement the WS-* set of protocols. From this, Microsoft learned that the ASMX platform wasn't extensible enough, and therefore created WCF (Windows Communication Foundation). Avoid WSE like the plague.
Answer: I´ve had this issue last week and I choosed SOAP with SSL. I also combinded that with as MD5 encrypted key of the data. This aplies of course only if you are "owner" of both server and client.
Comment: MD5 hashing (and hashing in general) should not be referred to as encryption. Hashing functions are typically one way while encryption is two ways (the data can later be decrypted). I'm sure you meant that you were MD5 hashing the data, but I just wanted to post that clarification for anyone stumbling upon this later.
Answer: WCF is the way to go. It offers many possible security solutions, some standards-based and interoperable, some .NET or Windows specific.
A quick search on 'WCF security' will give you lots of resources but I suggest you start with this article: 'Fundamentals of WCF Security' by Michele Leroux Bustamante.
Answer: You can also try 2 way SSL with IIS, this will let you make sure that the client is who they say they are, encrypt the data over the line, and also run the web service as different users based on the cert that is provided.


Delete sensitive string from all Git commits

Question: I have internal github in our organization. There is a particular git repo where I need to replace a sensitive string from all commits. There are around 2000 commits and the sensitive string is there from first commits. There are 7 valid branches as well. How can I delete/replace the sensitive string from all commits. I dont have internet access for the machine nor I have privileges to download bfg repo cleaner tool. I am trying my luck with git filter-branch command below. But this has not helped yet.
<code>git filter-branch -f --msg-filter 'sed "s/sensitivedata/noman/g"' -- --all
</code>
If nothing works my last resort is to delete the repo and create new one. But before doing that I wanted to see if I have an option preserving existing commits.
Any help and light towards this is highly appreciated.
Answer: I was facing the similar problem.
Try using below script, it worked for me.
<code># Replace "sensitivedata" with "noman" in all commits across specified branches
branches=("branch1" "branch2" "branch3")  # Add all valid branch names
for branch in "${branches[@]}"; do
    git checkout "$branch"
    git filter-branch -f --tree-filter 'find . -type f -exec sed -i "s/sensitivedata/noman/g" {} +' -- --all
done

</code>
Comment: I was able to delete the commits from git, but somehow github and the URL for gitrepo from browser still shows the deleted commits and its messages. How can this be removed?
Comment: When you perform a history rewrite with `git filter-branch`, the rewritten history is present in your local repository, but it may not automatically sync with GitHub or other remote repositories. To update the remote repository with the rewritten history, you'll need to force push the updated branches.


Is it possible to ask Dexie to exclude one or more table properties to be saved in IndexedDB?

Question: Is it possible to exclude one or more properties of a table when created in the store or an entry is saved in the indexeddb?
E.g. the following table description (Typescript) has four properties where only the first three shall be used for creation and adding new entries:
interface IContact {
  id?: number,
  first: string,
  last: string,
  notInDb: string
}

The property notInDb shall neither be considered when the table is created nor when an instance is added. notInDb is only used inside the actual class implementing the interface.
Answer: Indexeddb will only store own enumerable properties. So by it is possible using Object.defineProperty() and mark it {enumerable: false}.
Answer: You cannot select only certain properties from an object to be stored. I am guessing the reason you want to exclude a property is because it is too large or is not structured-cloneable.
indexedDB uses a structured-cloning algorithm that only accepts certain objects. This is basically serialization, but not to a string. So, you need to design your own serialization methods. Copy the properties you want into a basic object. This sounds like overhead, but it really is not that bad. Instead of trying to store the class itself, create a serialize method that creates a basic object and store that instead. Create a corresponding deserialize method that accepts a basic object and from it creates an instance of the class.
I suggest trying this approach first. If you later find that performance is an issue, and want to continue using indexedDB, then you probably will need to rethink your design, and design around indexedDB's requirements.


"All" value for a Combobox Data Filter in WPF

Question: During the construction of user control I populate the combobox with some data. Works fine. I have Status.ID as valuePath and Status.Name as displayPath.
cmb.ItemsSource = dbEntities.Status

The comobox will be used as a filter control and I need to insert some value for "All", which will be used as the empty filter.
First I tried a funny solution:
ObjectSet objectSet= dbEntities.Status;
Status stAll = new Status();
stAll.ID = -1;
stAll.Name = "All";
objectSet.AddObject(stAll);
cmb.ItemsSource = objectSet;

For some reason the object is not added to the objectSet. It didnt throw any exception either.
Then I tried to insert it manually to the first index but I got the error:
"Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."
My code looked like:
cmb.ItemsSource = entities.Status;
cmb.Items.Insert(0,"All");

Both didnt work. What would be the easiest way to add that line to the combobox? The error message got me confused. I am not sure how to use the ItemsSource for such a purpose.
edit: I did not have enough rep to answer my own question so here is the working code. Thanks Craig again.
CompositeCollection comp = new CompositeCollection();
comp.Add(new CollectionContainer {Collection = dbEntities.Status});
Status stAll = new Status();
stAll.ID = -1;
stAll.Name = "All";
comp.add(stAll);
cmb.ItemsSource = comp;
//do whatever filter you want when the selected value is -1

Answer: There are a couple different problems with what you are trying to do.  You can't manipulate the Items when you are using the ItemsSource, instead you have to go through the object that is set to the ItemsSource.  That is what the error message is about in the second part.  Its because when you set the ItemsSource the Items value is unused it is not populated with the values of the ItemsSource.
I'm not familiar enough with the ObjectSet class to know why the first case is not working.  However, it seems awkward to add an item to your values you are pulling from somewhere else, just to have the all case.  The better solution is to use a null value to represent nothing.  Unfortunately, there is no built in way to do this in WPF.  However, there is a fairly easy solution of using an Adaptor do do this.  I have used this solution a NullItemSelectorAdaptor, that enables null as a selection even if null is not in the list. All you have to do is wrap your combobox in the NullItemSelectorAdapter and null will be added as a value. The blog post explains everything pretty clearly, so I won't repeat it. You than can setup your filter so that null equates to no filtering.
Comment: Your link helped me to come up with this solution:

'CompositeCollection comp = new CompositeCollection();'
'comp.Add(new CollectionContainer {Collection = dbEntities.Status});'
'Status stAll = new Status();'
'stAll.ID = -1;'
'stAll.Name = "All";'
'comp.add(stAll);'
'cmb.ItemsSource = comp;'
Via Composite collection class I am able to add the item that indicates "All" manually. The selectedItem property does not return null but the selectedValue returns -1 which was necessary and enough for my solution. (I have no idea why it didnt work with ObjectSet though)


Access MailChimp forms

Question: I currently have a form that it is fully loaded from my Mailchimp Account. I configured it for display as a page using mailchimp configuration page (admin/config/services/mailchimp/signup). Then when I was trying to access it with no admin permissions I got Not authorized to access this page message.
Giving Access all Mailchimp Signup Pages permission to anonymous users fix this problem but it specify that have security implications and I think it is a wrong solution.
I searched all the drupal interface and was not able to find it on either side (Content, contact forms, etc...). This element it's only present on signup forms list (admin/config/services/mailchimp/signup) and there isn't any permissions configuration.
Answer: Recently found a FAQ from Drupal Mailchimp módule here
It says:

Q: How do I create anonymous signup forms on the site as either a page
  or a block?
A: Head to this path admin/config/services/mailchimp/signup/add, fill out the form and
  click on "Block", "Page", or both Display Modes.
Block - ...
Page - enter a path for which you'd
  like the signup form to appear, and click "Save". In order to make
  SignUp pages available to anonymous users, head over to where
  permissions are assigned (admin/people/permissions), and check the
  appropriate boxes next to the permission marked "Access all Mailchimp
  Signup Pages."

So this means that I should ignore that warning.

Access MailChimp forms


How to get data in JSON format from a controller returning IHttpActionResult in C#?

Question: I have a controller that uses Newtonsoft.Json to convert IEnumerable into JSON format.
[Route("")]
public IHttpActionResult Get()
{
    IEnumerable<Product> productList = ProductService.GetAllProducts();
    if (!productList.Any())
        return Ok();

    return Json(productList, new JsonSerializerSettings
    {
        ContractResolver = new WebContractResolver(),
        Converters = new List<JsonConverter> { new TrimStringDataConverter() }
    });
}

When I hit the API end point through POSTMAN, it gives me the expected JSON data.
[
    {
        "code": "prod101",
        "title": "LAPTOP"
    },
    {
        "code": "prod102",
        "title": "MOBILE"
    }
]

Now, I am writing unit test(NUnit) for the controller and I want to get this JSON formatted data in my unit test method.
I am able to get the IEnumerable -
IHttpActionResult actionResult = mockProductControllerClient.Get();
JsonResult<IEnumerable<Product>> contentResult = actionResult as JsonResult<IEnumerable<Product>>;
IEnumerable<Product> data = contentResult.Content;

I need the exact same data in Unit Test methods as being received in POSTMAN i.e. JSON data
Comment: `I need the exact same data in Unit Test methods as being received in POSTMAN` Why do you need that? _That is ASP.NET's job, to JSON encode the data. Your unit test doesn't need to test it._
Comment: Why are you testing the controller,  or your controllers ability to return JSON.  Surely you only want to test that your product list is valid.
Comment: You can do an In-memory integration test which can look like it came from postman
Comment: For Asp.Net Web API 2.* you can do something like this from a previous answer I wrote https://stackoverflow.com/a/37510032/5233410
Comment: @mjwills: I want to test out cases like json keys are in camel-cased ?
Comment: @Nkosi: Right. I can do that but I am wondering if I can get JSON in unit test.
Comment: @developer: I need to test the json keys. Actually, the ContractResolver being used does some stuff like include JsonProperty annotated properties only, do a camel-case of json keys etc.
I want to check if I am sending the right data and in the expected json format or not.
Comment: In WebAPI2 - you dont need to wrap response for JSON - the action will return what the requests content-type(mime-type) specified - which is most likely where you issue lies.  You must specify the type:

i.e.
"application/json"

And in your controller action you can just:  return this.Ok();
and it will be Json.

if your request has "application/xml" it will return XML.
Comment: @developer: I agree. I am getting the desired results once the response is disposed off the pipeline. I am getting JSON in my client/postman as mentioned in my question.
What I want is to get this json in a method that calls up the controller's method Get().
Answer: I found the answer -
IHttpActionResult keeps the SerializerSettings stored which might be applied down the pipeline when the response is disposed off.
In the unit test, since we are taking data from controller i.e. in middle of the pipeline, we will have to apply SerializerSettings ourselves.
So, first step is the extract the IEnumerable from action result -
IHttpActionResult actionResult = MockController.Get();
JsonResult<IEnumerable<Product>> contentResult = actionResult as JsonResult<IEnumerable<Product>>;

And then, apply the serializer settings and get your json -
string responseString = JsonConvert.SerializeObject(contentResult.Content, contentResult.SerializerSettings);
JArray responseJson = JArray.Parse(responseString);

Hope, this would help others.


How to bend VS2008 Setup project to my will

Question: I have a setup project (VS2008) for an existing application to which I have to add another project output, such that they reside in the same folder (two exes, and most of the dlls are shared).
The existing app has a CustomActionData argument of /Target="[TARGETDIR]\", but it installs its stuff in [TARGRETDIR]\EXE, which is fine although I can't see where this subfolder is defined, but I want the new project output to be in the same place. I've tried setting its CustomActionData argument to /Target="[TARGETDIR]\", and even  /Target="[TARGETDIR]\EXE", but it always goes into [TARGETDIR].
So my question is: how do I ensure that both project outputs end up in the same folder (ie [TARGETDIR]\EXE)?
Comment: Use Wix instead of Visual Studio Setup projects. The latter is deprecated, was never intended for real setup work and just isn't flexible. Wix is it's successor and does support these kinds of scenarios.
Comment: That's easy for you to say! This is legacy code that I have to work with. Are you saying that Setup projects WON'T do what I need?
Comment: It's probably possible, but a mess. There is a reason the technology was retired. Wix works with Visual Studio 2008 and depending on how complicated the existing installer is, should be relatively easy to convert (once you get to know the XML syntax)... (http://wixtoolset.org/documentation/manual/v3/votive/)
Comment: Thanks but that doesn't help me - I have a deadline to meet and recreating what is already a complex installer using wix instead won't fit the timescale by a long margin. So I really need some guidance on how to approach this, even if it does end up a conceptiual mess as long as it works. We can always address the conversion to wix at a later date.
Answer: Stop using the Project Output option. Just use your setup project File System view to drag the files from any project (or in fact anywhere on the system) into the destination folder.


Combinatorics: Group voting amongst themselves

Question: 5 members of a group vote for each other, how many ways can they do so such that they cannot caste a vote for themselves?
I believe it is $4^{5}$ since each member has 4 different possibilities. Am I correct in saying so?
Comment: Welcome to Math.SE. You are correct
Answer: Yes this is correct. Person 1 has 4 ways of voting. Person 2 has 4 ways and so on. So you get $4*4*4*4*4$ = $4^{5}$


VM freezing during WinPE boot up

Question: Got SCVMM 2012 R2 up and running, created a single VM w/ dynamic memory (512MB-4096MB) and a 40GB dynamic disk. The host is configured for NIC Teaming using switch independent configuration.
I setup a legacy network adapter and boot up to WinPE. The version of the boot.wim is WinPE4, configured to launch sccm. I do not know if it has virtual nic and storage drivers, but I didn't have a problem when creating standard hyper-v VMs in the past (2012, non R2). It downloads the boot.wim, but freezes at the very end when (I'm assuming) it goes to unpack it.

That's a 100% progress bar, and it just sits there. I'm in the process of creating a fixed disk VM, but I doubt that will resolve the problem. Posting here in the mean time in case anyone else has come across this as well.
Answer: It appears at the moment this was caused by the lack of HyperV drivers in the WinPE boot wim. The x64 version of the boot wim booted up fine. After looking at both in sccm, I noticed the 64 bit boot wim has an Intel emulated nic driver, while the 32 bit one does not.

Not sure where I'll be going from here.but this happened after upgrading our Windows Deployment Services (WDS) server to 2008r2.

VM freezing during WinPE boot up


Extending app inventor 2 "No Text While Driving" with location sensory

Question: I'm coding around with the app inventor2 project "No Text While Driving". I need to add some more functionality, as the app to determine if the smartphone is on the move, e.g. in a rolling car and thus lock the screen or prevent from being able to answer incoming sms.
In theory, I know I should have a block to check current location to previous location of the smartphone in the amount of time. Or is it possible to check movement only by accelerometer?
I have tried the following blocks without much success:

Can someone kind enough direct me to the wright use of blocks through an example? Thank you all in advance for your answers.
[Update1]
I have tried to follow Taifun's advice by adding the LocationSensor1 reading to a global variable and compare it with the CurrentAddress. The following code blocks should do the trick, but it didn't. Is it possible to check movement with accelerometer reading instead, and how?
Here is the updated blocks:
Comment: What about passengers in the car? "No texting while riding"?
Comment: in an App Inventor app, you neither can lock the screen nor prevent the user from answering incoming sms...
Comment: to set the current address to a variable and immediately after that compare it again with the current address always will give you the result, that both are identical... Therefore after having received a valid address the first time, then set the global variable and then start testing, if you are moving... To get the first valid address might take a few seconds...
Answer: You will need to store the result, wait a few seconds, check the sensor data again and compare to stored value. Then replace the stored value with the new one. Repeat.
Comment: Hi @Chet. Is it possible to post a block of code as an example. I'm not very familiar yet with TinyDB component usage.
Comment: I have never used it, just trying to help you formulate the solution.
Comment: you do not need `TinyDB`, just store the result in a global variable... it probably would help to do some tutorials first to learn some basics...
Comment: Hi @Taifun. Did some basic tuts, already. So if I store the LocationSensor1 data in a global variable, then I should have another LocationSensor2 or another variable to compare with? Can you elaborate a little on this, or direct me to a similar function tutorial or to an example of usage?
Comment: You store the LocationSensor1.CurrentAddress in a global variable and next time you compare the current value of LocationSensor.CurrentAddress with the global variable. If it's different, then you moved... It does not look like you understand the concept of a global variable, do you? Doing some more tutorials probably would help...
Comment: Hi @Taifun. Have tried to follow your advice with the global variable. Don't know what I did wrong, maybe is the GPS weak, but I get not the notifier to fire upon movement. Can the movement check be done using accelerometer instead and how? Have read the tuts, but find nothing but "the free fall" checking. Please advice.
Comment: Do you even get an initial location?
Comment: Hi @Chet. Nop I didn't. Guess GPS is not very reliable (slow) on the device. Thus I'm asking If it is possible to get the movement checked by using Accelerometer sensor. How can this be done? Do I have to check X,Y,Z, value changes simultaneously?
Comment: Accelerometer will not be useful to see if user is driving. Especially because once car gets to cruise speed it will no longer be accelerating.
Comment: So @Chet, the only way to determine if the mobile is in a cruising car, is through GPS and location sensory? To bad you haven't used it before, so you can post some sample blocks coding.
Comment: Yes, that is the case. Sorry I can't post some blocks. Since this.question is old you would have more luck opening a new question simply asking how to get GPS working in App Inventor 2.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/97789/discussion-between-user3244633-and-chet).


Eigenvectors of Normal matrix (orthogonality)

Question: Let's suppose A is normal matrix. I know that the eigenvectors of normal matrix and its conjugate are the same, and that for the fixed eigenvector the eigenvalues are conjugate. Let's fix some $e_1$ normal eigenvector $(||e_1||=1)$, so $Ae_1= λ_1 e_1$ and $A^*e_1=\bar{λ_1}e_1 $.
$$
S_1 = span\{e_1\}
$$
$$
T_1 = \{x : (x,e_1)=0\}
$$
How can I show that there is an eigenvector $e_2$ which belongs to $T_1$?
P.S. I know that if $x∈T_1$ then $Ax∈T_1,A^*x∈T_1$, because
$$
(Ax,e_1)=(x,A^*e_1)=(x,\bar{λ_1}e_1)={λ_1}(x,e_1)=0
$$
Answer: So $L_1$ subspace is $A$-invariant, due to the last thing that you prove. And it is a famous theorem about linear operators, that every linear operator has at least one eigenvalue, so there exists some $e_2$ eigenvector which belongs to $T_1$. Here you can find it page 5.


GRE subject:volume created by revolving area about line

Question: find volume created by revolving the region between $x=y^2$ and $y=x^2$ about the line $x=-1$.
My attempt is since to solve for $x$ first correct? so we have $x=y^2, x = \sqrt{y}$ so we. integrate from $0$ to $1$? I know its top function minus bottom but I forget do we do this
$$\pi \int_0^1 (y+1)^2 - \sqrt{y+1} dy$$
or is it this one? forget where to subtract the line really.
$$\pi \int_0^1 y^2 +1 - \sqrt{y} +1dy$$
thanks in advance I am studying for GRE subject, learned calc II in 2008 forgot most of it sadly. Hopefully the top integral is the correct set up but not sure.
Comment: well, it is just that it is a policy that we should not solve completely problems that may be homework problems. I believe you that it is a GRE question. I am just following the guidelines. I can check more carefully if you want. Give me a moment.
Comment: thanks! was looking for that keyword cylindrical shells! still a bit stuck however
Comment: yeah I know that man lol I meant which of the two integrals
Comment: also I know how to foil man, im not asking how to foil I am asking you if my integral is set up correctly but you don't seem to want to answer that lol
Comment: thanks :) yes just wanna know if setup of first integral is correct I am fully aware of the rules I didn't ask for an answer lol I myself have a discord server where I provide free math help as well I am against spoon feeding lol, thanks again so much for your help
Answer: It would help to draw the region first. I am not sure how to do it here. But anyway, the formula the OP is looking for is the washer method formula (which I had incorrectly called the cylindrical shell method, thank you @MathLover for pointing it out), which gives in this case
$$ \pi \int_0^1 \left( (\sqrt{y} + 1)^2 - (y^2 + 1)^2 \right) dy. $$
Comment: No worries. And sorry for the previous misunderstanding of your question.
Comment: Yes I know. I took it many years ago. Good luck!
Comment: What you are using is washer method and not cylindrical shell.
Comment: Aaah, thank you @MathLover. I will edit.
Comment: ahhhh I forgot to square them!!!!!!! thank you a million! that's all I was missing
Comment: its totally ok :) again thanks so much! this GRE subject is pulling from ALL areas of math lol many of which I merely forgot its been so long
Comment: lol thank you :)


Confidence intervals problem - nonnormal population?

Question: this is the problem:

we wish to estimate the mean execution time of a program. the program was run 35 times on randomly selected inputs, and the sample mean and the sample standard deviation of the execution times were evaluated as (x bar)=230ms, and S(sample sd)=14ms, respectively. find 95% CI for the true mean execution time u

what and how can you tell this is a non-normal population. i knew it because it is an example under "Large sample CI for non-normal population"
Comment: Almost nothing is normal. The distribution of long enough sums (and therefore averages) of independent identically distributed "nice" random variables are well approximated by a normal.
Answer: There is not enough information here to tell that it's not normal.  The point is that because the sample size is somewhat large, it doesn't matter that it's not normal, because of the central limit theorem.  However, the sample is not so large that I wouldn't use Student's t-distribution.  You'd have $34$ degrees of freedom.


Como utilizar o free em uma variável estrutura (lista encadeada)?

Question: Não consigo utilizar o free() em "struct Lista *proximo". Segue meu código:
#include "stdafx.h"
#include <stdlib.h>
#include <conio.h>
#include <locale.h>

struct Lista {
    int num;
    struct Lista *proximo;
}celula;

int main()
{
setlocale(LC_ALL, "Portuguese");
//Criar uma função para a inserção de dados na lista

struct Lista *inicio;
struct Lista *proximo_item;
short int resp = 1;
short int cont = 1;

inicio = (struct Lista *)malloc(sizeof(struct Lista));
if (inicio == NULL) {
    exit(1);
}

proximo_item = inicio;
do {
    printf("Inf. um numero para a lista: ");
    scanf_s("%d", &proximo_item->num);
    printf("Deseja continuar? 1 = Sim | != Nao\n");
    scanf_s("%hi", &resp);
    system("cls");
    if (resp == 1) {
        proximo_item->proximo = (struct Lista *)malloc(sizeof(struct Lista));
        proximo_item = proximo_item->proximo;
    }
} while (resp == 1);

proximo_item->proximo = NULL;
proximo_item = inicio;
while (proximo_item != NULL){
    printf("%dº item da lista: %d\n", cont, proximo_item->num);
    proximo_item = proximo_item->proximo;
    cont++;
}
free(proximo);
free(inicio);
free(proximo_item);
_getch();
return 0;
}

Comment: Neste caso o `fre()` não é tão necessário assim porque o programa está encerrando, mas entendo que queira fazer o certo para usar em outro lugares, ainda que este algoritmo seja muito ingênuo para uso em produção. Se você usou o `malloc()` em um laço, o `free()` precisa ser em um laço também. Como não vai usar mais, talvez poderia usar dentro do laço de impressão, vai imprimindo e liberando. Se puder fazer alguma outra coisa depois, então precisa de laço separada. É essencialmente navegar pela lista como já foi feito no código e liberar em vez de alocar, como já foi feito.
Answer: Troque isso:
free(proximo);
free(inicio);
free(proximo_item);

Por isso:
while (inicio != NULL) {
    struct Lista *deletando = inicio;
    inicio = inicio->proximo;
    free(deletando);
}

Comment: Funcionou, obrigado!


Rails 5.1 capistrano is stuck at webpacker compiling assets

Question: I'm trying to deploy a rails 5.1 app with capistrano and it seems to be stuck at compiling assets:
<code>02:38 deploy:assets:precompile
  01 $HOME/.rbenv/bin/rbenv exec bundle exec rake assets:precompile
  01 yarn install v0.27.5
  01 [1/4] Resolving packages...
  01 [2/4] Fetching packages...
  01 warning firstname.lastname@example.com: The platform "linux" is incompatible with this module.
  01 info "email@example.com" is an optional dependency and failed compatibility check. Excluding it from installation.
  01 [3/4] Linking dependencies...
  01 [4/4] Building fresh packages...
  01 Done in 48.92s.
  01 Webpacker is installed
  01 Using /project_name/releases/20170807195158/config/webpack/paths.yml file for setting up webpack paths
  01 Compiling webpacker assets
</code>
There are no errors, it just stays there for hours. If i inspect the node process doing this on the remote server it says that it uses 100% of the cpu for about 5 minutes and then the process seems to get killed but it still says "Compiling assets".
Answer: It seems that executing bundle exec rake assets:precompile on remote when there are more than a few assets fails.
The solution was to compile the assets locally and then rsync them to the remote server.