Finding side length for segments extending radii so as to form a tangent line

Question: I have a circle with radius $r$ and two line segments extending radii of the circle with length $r+h_1$ and $r+h_2$ respectively (you can think of them being at height $h_i$ over the circle). Forming a triangle from these line segments, the new side is tangent to the circle. I would like to find the length of this new segment (or equivalently, the angle the triangle makes at the center of the circle).

I generated the diagram with GeoGebra (plus GIMP), I hope that makes it easier to understand.
Answer: Drawing a line from the center point to the tangent line of your segment, which we will call $x$. Note that the line from the center to $x$ is perpendicular to the tangential segment, so we can solve for the lengths of the segment on either side of $x$.

On the bottom side, we have $\sqrt{(r+h_2)^2 -r^2} =\sqrt{2rh_2 +h_2^2}$, and on the top side we similarly have the side length $\sqrt{2rh_1 + h_1^2}$. Therefore the length of that segment is exactly $\sqrt{2rh_1 +h_1^2}+\sqrt{2rh_2 + h_2^2}$.


How to assign programatically a field to a paragraph bundle

Question: I'm developing a module to extend paragraphs module.
The idea is that the users can assign a description field to paragraphs bundles.
I have create a module, and also I have create the file field.storage.paragraph.parrados_description.yml If I go to admin/reports/fields  or if I try to assign the field to a paragraph bundle with UI I can see it in the list of fields.
But what I want to make it's create a form with paragraphs bundles checkboxes, so the administrator / site builder can check the bundles to assign the field to it when the user submit the form.
But I don't find any method to assign a field to a bundle.
Thanks
Oskar
Comment: Don't reinvent the wheel, use the field UI.
Comment: Because it's not the same assign the field to 3 bundles or to 30 bundles, and if it's a UI it means that there is a method that make it by code, so I don't want to reinvent the wheel, I want to use the wheel.
Answer:
But I don't find any method to assign a field to a bundle.

This is not one single method, it's a bit more complicated than that. Example for the body field in a node bundle. First create the bundle specific field config referencing the existing field storage:
  $field_storage = FieldStorageConfig::loadByName('node', 'body');
  $field = FieldConfig::loadByName('node', $type->id(), 'body');
  if (empty($field)) {
    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      'bundle' => $type->id(),
      'label' => $label,
      'settings' => ['display_summary' => TRUE],
    ]);
    $field->save();

Then add the field to the display modes:
    // Assign widget settings for the 'default' form mode.
    entity_get_form_display('node', $type->id(), 'default')
      ->setComponent('body', [
        'type' => 'text_textarea_with_summary',
      ])
      ->save();

    // Assign display settings for the 'default' and 'teaser' view modes.
    entity_get_display('node', $type->id(), 'default')
      ->setComponent('body', [
        'label' => 'hidden',
        'type' => 'text_default',
      ])
      ->save();

    // The teaser view mode is created by the Standard profile and therefore
    // might not exist.
    $view_modes = \Drupal::entityManager()->getViewModes('node');
    if (isset($view_modes['teaser'])) {
      entity_get_display('node', $type->id(), 'teaser')
        ->setComponent('body', [
          'label' => 'hidden',
          'type' => 'text_summary_or_trimmed',
        ])
        ->save();
    }
  }

Code example from https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/function/node_add_body_field/8.5.x


4th order Runge-Kutta with system of coupled 2nd order ODE in MATLAB

Question: I tried using Runge-Kutta methods to approximate motion equations in matlab but it turn out wrong.
$$
M\left(\frac{d^2x}{dt^2}\right)=F_n(\cosΦ - u\sinΦ) \\
M\left(\frac{d^2z}{dt^2}\right)=F_n(\sinΦ + u\cosΦ ) - Mg\\
M\left(\frac{d^2Φ}{dt^2}\right)=F_n(Bxx + uBz )
$$
Fn,M,θ,u is constant fn/M = 0.866
it seems that i did my coupled runge kutta wrongly.
my phi and omega does not change with time.
please help
    clc;                                               % Clears the screen
clear all;

thete=30;
g= 9.81;                                             %Constant

h=0.01;                                              % step size
tfinal = 3;
N=ceil(tfinal/h);                                      %ceil is round up

t(1) = 0;% initial condition
Vx(1)=0;%initial accleration
X(1)=0;
Vz(1)=0;
Z(1)=20;%initial velocity
fn = 0.866;
Bz = 0.35;
Phi(1)= 30;
W(1)= 0;

%Bxx = ((Z-Z(1))+5.8*cos(thete)+Bz*(sin(Phi)-sin(thete)));
Bxx = 0.5;
%sliding phase
F_X  = @(t,X,Vx,Phi) Vx;
F_Z  = @(t,Z,Vz,Phi) Vz;
F_Phi= @(t,Phi,W) W;
F_Vx = @(t,X,Vx,Phi)(fn*(cos(Phi)-0.05*(sin(Phi))));
F_Vz = @(t,Z,Vz,Phi)(fn*(sin(Phi)+0.05*(cos(Phi)))-g);
F_W  = @(t,Phi,W)((fn*(Bxx+Bz*0.05))/20000);

for i=1:N;                                         % calculation loop

    %update time
    t(i+1)=t(i)+h;
    %update motions main equation
    %rotation phase
    k_1 = F_X (t(i)      ,X(i)          ,Vx(i)          ,Phi(i));
    L_1 = F_Vx(t(i)      ,X(i)          ,Vx(i)          ,Phi(i));
    k_2 = F_X (t(i)+0.5*h,X(i)+0.5*h*k_1,Vx(i)+0.5*h*L_1,Phi(i)+0.5*h*L_1);
    L_2 = F_Vx(t(i)+0.5*h,X(i)+0.5*h*k_1,Vx(i)+0.5*h*L_1,Phi(i)+0.5*h*L_1);
    k_3 = F_X (t(i)+0.5*h,X(i)+0.5*h*k_2,Vx(i)+0.5*h*L_2,Phi(i)+0.5*h*L_2);
    L_3 = F_Vx(t(i)+0.5*h,X(i)+0.5*h*k_2,Vx(i)+0.5*h*L_2,Phi(i)+0.5*h*L_2);
    k_4 = F_X (t(i)+h    ,X(i)+h    *k_3,Vx(i)+    h*L_3,Phi(i)+h*L_3);
    L_4 = F_Vx(t(i)+h    ,X(i)+h    *k_3,Vx(i)+    h*L_3,Phi(i)+h*L_3);

    k_11 = F_Z (t(i)      ,Z(i)          ,Vz(i)            ,Phi(i));
    L_11 = F_Vz(t(i)      ,Z(i)          ,Vz(i)            ,Phi(i));
    k_22 = F_Z (t(i)+0.5*h,Z(i)+0.5*h*k_11,Vz(i)+0.5*h*L_11,Phi(i)+0.5*h*L_11);
    L_22 = F_Vz(t(i)+0.5*h,Z(i)+0.5*h*k_11,Vz(i)+0.5*h*L_11,Phi(i)+0.5*h*L_11);
    k_33 = F_Z (t(i)+0.5*h,Z(i)+0.5*h*k_22,Vz(i)+0.5*h*L_22,Phi(i)+0.5*h*L_22);
    L_33 = F_Vz(t(i)+0.5*h,Z(i)+0.5*h*k_22,Vz(i)+0.5*h*L_22,Phi(i)+0.5*h*L_22);
    k_44 = F_Z (t(i)+    h,Z(i)+    h*k_33,Vz(i)+    h*L_33,Phi(i)+h*L_33);
    L_44 = F_Vz(t(i)+    h,Z(i)+    h*k_33,Vz(i)+    h*L_33,Phi(i)+h*L_33);

    k_5 = F_Phi (t(i)      ,Phi(i)           ,W(i));
    L_5 = F_W   (t(i)      ,Phi(i)           ,W(i));
    k_6 = F_Phi (t(i)+0.5*h,Phi(i)+0.5*h*k_5,W(i)+0.5*h*L_5);
    L_6 = F_W   (t(i)+0.5*h,Phi(i)+0.5*h*k_5,W(i)+0.5*h*L_5);
    k_7 = F_Phi (t(i)+0.5*h,Phi(i)+0.5*h*k_6,W(i)+0.5*h*L_6);
    L_7 = F_W   (t(i)+0.5*h,Phi(i)+0.5*h*k_6,W(i)+0.5*h*L_6);
    k_8 = F_Phi (t(i)+    h,Phi(i)+    h*k_7,W(i)+    h*L_7);
    L_8 = F_W   (t(i)+    h,Phi(i)+    h*k_7,W(i)+    h*L_7);

    X(i+1)  = X(i) + (h/6)*(k_1+2*k_2+2*k_3+k_4);
    Vx(i+1) = Vx(i) + (h/6)*(L_1+2*L_2+2*L_3+L_4);
    Z(i+1)  = Z(i) + (h/6)*(k_11+2*k_22+2*k_33+k_44);
    Vz(i+1) = Vz(i) + (h/6)*(L_11+2*L_22+2*L_33+L_44);
    Phi(i+1)= Phi(i) + (h/6)*(k_5+2*k_6+2*k_7+k_8);
    W(i+1)  = W(i) + (h/6)*(L_5+2*L_6+2*L_7+L_8);

end

figure
plot(X,Z,'--', 'Linewidth', 1.5, 'color', 'red')
xlabel('time')
ylabel('height')
legend('position')
figure
plot(Phi,W,'--', 'Linewidth', 1.5, 'color', 'blue')
xlabel('time')
ylabel('height')
legend('rotation')
figure
plot(t,Vx,'--', 'Linewidth', 1.5, 'color', 'black')
hold on
plot(t,Vz,'--', 'Linewidth', 1.5, 'color', 'yellow')
hold on
plot(t,W,'--','Linewidth',1.5,'color','green')
xlabel('time')
ylabel('height')
legend('Vx','Vz','W')

fprintf('time %.3f\n x %.3f\n z %.3f\n ',t,X,Z);
fprintf('W %.3f\n',W);
fprintf('Phi %.3f\n',Phi);

Comment: Is this an exercise? In other words, is there a reason why you cannot use already implemented routines to solve the ode, such as ode45?
Comment: You are using matlab -- MATrix LABoratory. It would be the most natural to formulate everything in terms of vectors, which would then also reduce RK4 to the cookbook recipe.
Answer: One basic principle in programming is to make algorithms available for as large a class of data structures as possible. Matlab makes this easy since vectors and matrices are elementary data structures. Thus make an implementation of RK4 for general vectors and translate your state into a state vector for integration.
The following demonstrates this on the example of the 3-dimensional Lorenz system (this is for scilab, which is close, but not identical to matlab, here the only change should be in the endfunction statement which should be end in matlab. Also with @ expressions one could shorten some parts)
function [t, y] = RK4(odefunc, y0, t0, tf, N)
    T = tf-t0;
    h=T/N;
    time=t0;
    state=y0;
    t = zeros(N+1);
    y = zeros(N+1,length(y0));
    t(1) = t0;
    y(1,:) = y0;

    for i=2:N+1
        k1 = odefunc(time        , state           );
        k2 = odefunc(time + 0.5*h, state + 0.5*h*k1);
        k3 = odefunc(time + 0.5*h, state + 0.5*h*k2);
        k4 = odefunc(time +     h, state +     h*k3);
        state = state + (h/6)*(k1+2*k2+2*k3+k4);
        time = time + h;
        t(i) = time;
        y(i,:) = state;
    end
endfunction

function doty = lorenz(t, y, params)
    a=params(1); b=params(2); c=params(3);
    doty = [ a * ( y(2) - y(1) )
            -b * y(1) + y(1) * y(3)
            -c * y(1) - b * y(3) ]'
endfunction

function doty=odefunc(t,y)
    doty = lorenz(t,y,[0.5, 0.66, 1.4])
endfunction

[T,Y] = RK4(odefunc, [-1.2 0.2 0.8], 0, 10, 400)


Remote installation script great in XP, doesn't work in Windows 7

Question: I have a script to install an .msi file out to a list of remote workstations.  Works fine going out to XP machines.  I now get error code 1603 when trying to run out to Windows 7 machines.
psexec -u "domain\username" -p "password" @\\domain\path\ComputerList.txt  msiexec /i "\\domain\path\InstallFile.msi" /passive /qn

Is it a permissions error?  The user (me) is an Administrator on the Windows 7 workstations.
Comment: Any chance it would be an UAC setting blocking you? Can you try turning off UAC on windows client ? It will require a reboot : Here 2 method : http://www.blogsdna.com/1815/how-to-disable-uac-turn-off-uac-in-windows-7-beta-1-build-7000.htm
Answer: Try using the -h switch for psexec.  From the psexec help:
If the target system is Vista or higher, has the process run with the account's elevated token, if available.

This may resolve any issues that are occuring with UAC.


R if-else not working

Question: What is wrong with this if-else in my R program?
if(is.na(result)[1])
    print("NA")
else
    coef(result)[[1]]

I'm getting an error:
> if(is.na(result)[1])
+   print("NA")
> else
Error: unexpected 'else' in "else"
>   coef(result)[[1]]

So then I added curly braces around the if and the else and now I get this error:
> if(is.na(result)[1]) {
+     print("NA")
Error: unexpected input in:
"if(is.na(result)[1]) {
¬"
> } else {
Error: unexpected '}' in "}"
>     coef(result)[[1]]
Error: unexpected input in "¬"
> }
Error: unexpected '}' in "}"

Comment: @downvoter, please provide a comment if you downvote.
Answer: It is that you are lacking curly braces.  Try
if(is.na(result)[1]) {
    print("NA")
} else {
    coef(result)[[1]]
}

This matters less when your source an entire file at once but for line-by-line parsing (eg when you enter at the prompt) you have to tell R that more code is coming.
Comment: Or put the other way, the `if` part of the `if`-`else` statement is a syntactically valid, complete statement, which R evaluates. When it then encounters the `else`, as far as R is concerned this is a fresh statement and you can't call/use `else` like that.
Comment: Please see updated question. I am getting more errors now.
Comment: You may need to start from a clean slate.  How do you execute that function?  Source a file?
Comment: +1: it seem to work as in the code in my answer below
Comment: It's also worth noting that the else must come after the curly bracket on the same line, you cannot start the else on a new line.
Comment: Looks like R is picky about how you write the if { } else { }: '} else {' must be on the same line.  In C I got used to write '}\nelse {' R give you an syntax error.
Comment: That is  FAQ and it has to do with parser and line by line versus whole file mode.  In short use K&R style with the opening one on the same line.
Answer: I think your problem is signaled with this error message:
"if(is.na(result)[1]) {
¬"

Notice that strange little symbol? You have gotten a non-printing character that looks like one of those old IBM end-of-line markers. It could be problem with your LOCALE strings or with your keyboard mapping or with code you got off the Internet. Hard to tell, but you should definitely try to get rid of them by backspacing over them/
Answer: Without curly brackets, the if ... else ... construct should be on one line only:
if(is.na(result)[1]) print("NA") else coef(result)[[1]]

Answer: If you only have one condition and two results it's syntactically easier to use ifelse()
ifelse(is.na(result)[1],
   print("NA"),
   coef(result)[[1]]
)

Comment: You have to be careful with `ifelse()`; it will return an object with the same *length* and attributes as the test clause. We can see how this might be a problem via `ifelse(FALSE, NA, 1:10)`, which returns `1`, not `1:10`. If `coef(result)[[1]]` is more complex that the test, then your suggestion will fail. It might be syntactically simpler, but it isn't necessarily the right tool here.
Answer: This runs for me without errors
x      <- 1:5
result <- lm(c(1:3,7,6) ~ x)

if(is.na(result)[1]) {
  print("NA")
 } else {
  coef(result)[[1]]
 }

and produces
[1] -0.7

Comment: Although it might be better to do print(coef(.....)) - since that seems to be the intention here (rather than return a value) and the next question from this poster will likely be 'why doesnt this print out in my script file?'.
Comment: @Spacedman: all I was trying to do was show that there are circumstances where Dirk Eddelbuettel's code could run without an error message.
Comment: Ah, I guess my comment applies to Dirk's answer too...

R if-else not working


Extracting content from a broken site database

Question: I am working on a broken Drupal site which doesn't load.
Is it possible to extract the node data from the database and import them into a fresh Drupal installation?
Comment: Welcome to Drupal Answers! Are you sure the data in the database isn't corrupted? That could be the reason the site doesn't load.
Comment: DB seen fine, the error seems to steam from from the Drupal site?
Comment: If Drupal doesn't find the data that should be in the database, it won't work as it should. Are you sure it's not your case? Does the database contain all the data for all the created nodes?
Answer: You can use the Migrate API to connect to the legacy DB and import the data into a different Drupal instance. See Migrate API overview.
Comment: The broken site is Drupal 8, my objective is to migrate the the nodes from the broken Site DB into a fresh instance of Drupal instance o Docker. The migration in Drupal core is only allowing me to do so for older Drupal site 6 or 7.
Comment: You may have to do your own migration strategy for the API, or find a contributed module that handles D8 -> D8 migration. Nevertheless, the Migrate API is the answer.


What word describes an instrument's native character?

Question: (Caveat: this may be more appropriate in the English Stack Exchange, but I'm a musician and it has to do with instruments, so I put it here.)
As a composer of Celtic-style tunes, I usually pick up my mandolin and noodle in a few keys that work well on a mando, like G, D, Am, Bm for example. I almost never play in Eb (=Cm), say, because without resorting to fully-fretted positions it's not "natural" for a mandolin. The word "affordance," as used in a user-interface way, has some bearing here: the way a mandolin is physically organized "affords" ease of use in some keys over others. (The affordance of a door handle is obvious: it says "pull me." A flat plate on a door says "push.")
Now on a piano the layout, and how I play the instrument, is different from a mandolin. Whereas the mando is organized across four courses of strings arranged in fifths, and the hands have different jobs (picking and fretting), the piano is laid out in a linear array and both hands play notes. The "affordance" is different. It's much easier to play in Cm (and for me, D on a piano is sort of hard). If I compose a piece on piano and try to play it on mando, I am struck by how I would never have thought of it on a mando.
Pick your instrument - a penny whistle is key-oriented and range-limited, so only certain types of tune easily fall under the fingers. Drums are a whole different kettle (no pun) of fish: you use sticks and much of your body to play.
So here is the question: what word you would use to describe the instrument's native character?  I have used "affordability" here but that only refers to a part of the approach to the instrument. For some reason the word "modality" comes to mind (not in the scales/modes sense) but I have not been able to support that guess.
The word would be used like this: " Composing Irish tunes on a fiddle is easier than on a harmonium because the [?word?] of the instrument is more appropriate. Almost-candidates include words like: "feel," "character," "voice," "style," or "capability."
This question is not just about finding the word. I think the whole concept of different instruments leading to different compositions is intriguing. Comments?
Comment: This is rather difficult, since a true artist on any of those instruments will  be able to play anything well. However, I think I understand what you're trying to get at: the native idiom of an instrument, similar to some truisms like "strings love sharps, winds love flats, drums don't care..." or "that tune just falls under the fingers on violin, not so much on flute".
Comment: FTR, I think harmonium can work excellent in Celtic music... Ceud Failt Air Gach Gleann or Duthaigh 'icAoidh by Kathleen MacInnes are great examples. (Not sure if it's actually an accordion on the record, but certainly _could_ be harmonium.) But of course it's just accompaniment there, the _tune_ wouldn't work well.
Comment: @leftaroundabout haha I should have thought of melodeon and extrapolated to harmonium, but I don't play either one
Comment: What about *personality*?
Comment: @ToddWilcox yes personality is part of it, but not the umbrella word I hope to find, rather an attribute
Answer: Composing Irish tunes on a fiddle is easier than on a harmonium because they are more idiomatic to that instrument.

(music) Parts or pieces which are written both within the natural physical limitations of the instrument and human body and, less so or less often, the styles of playing used on specific instruments.
Comment: Of all the replies here, I think the word "idiom" comes closest. Although it doesn't quite nail it, the sense of uniqueness is suggested. I'd like the notion of affordance to be included though.
Answer: How about the instrument's habitus?  "Habitus" works as a cohesive expression for a collection of idiomatic features.  It feels more specific to the particular instrument than its "sphere" would.
Comment: Good catch, very fitting.
Answer: An instrument's gamut would be a nice description.  Unfortunately "gamut" has a musical meaning overshadowing the figurative meaning.  "ambit" is similarly hobbled.  How about its "domain"?
Comment: Welcome to Music Stack Exchange.  The site welcomes answers and questions from new members, and especially those that are cogent, easy to understand, and appropriate to the site, as yours is.  Again, welcome.
Comment: @user38137 Im familiar with gamut in digital photography, but that word refers to the range of possibilities. I'm looking for what describes the instrument's natural inclination. A dog generally barks, although its gamut includes whining and groaning and growling.
Answer: "Tone Color" is one phrase ("Klangfarbe" in German). "Timbre" is another. Sometimes the word "Character" is used. I'm not familiar with a special word; sometimes one just says "sound" as in "the sound of the piano." I checked a couple of orchestration books and they tend to describe things like the range and timbre separately rather than using a single word.
Comment: It is much more than just the sound. It includes how the instrument is played, and especially its "native" favourite places.
Answer: The word that springs most quickly to my mind is the word "character."  However, since you used that word in your question, such an answer is considered a no-no!
I like the examples you give, and the suggestions you provide toward possible answers.  I do think you should also post the same question on a language site, as a linguist might have better insights into what words would be best in this situation.
Until I can think of a possibly better one, I'll go with leftaroundabout's 'idiomatic.'  I've heard it used in that context by professional music commentators, though I'll admit I've heard it used more often the other way around-- that is, a particular piece of music is idiomatic for the piano.  Etc.
Answer: Perhaps you have two questions here.  There are the physical aspects of the instrument, associated with how the sounds are produced, and then there are the characteristics of the instrument, its range and adaptability etc.
Regarding the physical aspects then there are existing classifications.  Look up "Hornbostel-Sachs" on Wikipedia.
In respect of the instruments characteristics it gets trickier.  I think @leftroundabout gave a good suggestion of idiomatic.  I think that "character" might also be a good one.
Interesting question.
Comment: I know about the H-S instrument classification system (idiophones, aerophones, etc) but I'm looking for a generic instrument's "personal" offerings, if you will. As a composer, what does a flute offer that I can't get on a fiddle? A didjeridoo over a gong? Each instrument offers an "easy" way to play it (not necessarily the most complex or satisfying...)
Answer: Timbre: "the character or quality of a musical sound or voice as distinct from its pitch and intensity."
Comment: Another contributor already mentioned timbre, but that's only part of what the original poster is looking for.
Comment: I'm more interested in how an instrument is played, not what it sounds like.
Comment: Also, if you're going to quote definitions you should say where you're quoting them from.

What word describes an instrument’s native character?


A basic problem on expectation

Question: Suppose for a non-negative random variable $\int_{0}^{\infty} P(X \geq t) dt= \infty$ I need to show that $\sum_{n=1}^{\infty} P(X \geq na) = \infty$ for each $a$. How to go from continuous case to discrete case here ?
Answer: For $a > 0$ (other cases are trivial)
It follows from $$\int_0^\infty \mathbb{P}\big( X \geq t \big) \, dt = \infty $$
that
$$\int_0^\infty \mathbb{P}\big( X \geq at \big) \, dt = \infty \,\, . $$
Then $$\sum_{n=0}^\infty\int_n^{n+1} \mathbb{P}\big( X \geq at \big) \, dt = \infty \,\, . $$
Clearly $\mathbb{P}\big(  X \geq n a \big)\geq \mathbb{P}\big(  X \geq (n+1) a \big)$, then we have $$ \mathbb{P}\big( X \geq an \big) \geq  \int_{n}^{n+1}\mathbb{P}\big( X \geq at \big) \, dt$$
hence
$$  \sum_{n=0}^\infty  \mathbb{P}\big( X \geq an \big) \geq         \sum_{n=0}^\infty\int_n^{n+1} \mathbb{P}\big( X \geq at \big) \, dt = \infty \,\, . $$

A basic problem on expectation


create child using mkdir with variable

Question: I have the path /home/folder/test set as variable $1
I want to make a directory using mkdir, I think, that will be in a new folder but has the same name as the last child folder.  So for example I want to make a folder called /home/folder2/test.
Is this something that I should be using xargs for?  I'm not too experience with shell commands, so I'm pretty confused how to get this done.
Answer: Assuming a UNIX-like operating system, if you have a string /home/folder/test and you want the last part of it, you can simply use basename to get that:
pax> str="/home/folder/test"
pax> base="$(basename $str)"
pax> echo "${base}"
test

Once you have that, you can use it to make another directory:
pax> mkdir -p "/home/folder2/${base}"
pax> ls -al "/home/folder2/test"
total 0
drwxr-xr-x 2 pax pax  6 Apr  2 04:19 .
drwxrwxrwx 1 pax pax 49 Apr  2 04:19 ..

create child using mkdir with variable


Sequence Cauchy w.r.t $L^2$-norm but has no convergent subsequence

Question: I have a problem with following exercise: Let $C([0,1])$ be the space of continuous real valued functions on the closed unit inverval $[0,1]$. And let the $L^2$-norm given by: \begin{equation}
\Vert f\Vert_{L^2}:=\left(\int_0^1\vert f(t) \vert^2\right)^{1/2}
\end{equation}
Then I want to find a sequence of continuous functions $f_n:[0,1]\to \mathbb{R}$ that is Cauchy w.r.t. the $L^2$-norm and has NO convergent subsequence.
I though about following sequence: $f_n(x)=\frac{1}{n}\sin(2nx)$ for $x\in [0,\frac{\pi}{2}]$ and $f_n(x)=0$ otherwise. But first: I'm not sure if this works?! and Second, how can I check that there is no convergent subsequence?
Lot of thanks for your help!
Comment: Your functions $f_n$ satisfy $|f_n(t)| \le \frac 1n$, so in fact $f_n \to 0$ uniformly.
Comment: thank @UmbertoP. but how can I show that my function has no convergent subsequence?
Comment: Your sequence is convergent, so *every* subsequence is convergent too.
Comment: aah :) Ok ! Thank you
Answer: Define
$$
            f_n(t) = n\int_{0}^{t}\chi_{[1/2-1/2n,1/2+1/2n]}(u)du,
$$
where $\chi$ is the characteristic function of the given interval. $\{ f_n \}_{n=1}^{\infty}$ is a sequence of continuous functions, and it is a Cauchy sequence because $|f_n-f_{n+k}| \le 1$ and the difference function $f_n-f_{n+k}$ is non-zero only in the interval $[1/2-1/2n,1/2+1/2n]$. This gives the crude estimate
$$
            \|f_n -f_{n+k} \|^2 \le \frac{1}{n}.
$$
And, using the same type of estimate, it is clear that
$$
            \lim_n\int_{0}^{1}|f_n(t)-\chi_{[1/2,1]}(t)|^2dt = 0.
$$
If a subsequence $\{f_{n_m}\}_{m=1}^{\infty}$ converges to some $g\in C[0,1]$ in the norm of $L^2[0,1]$, then
$$
        \int_{0}^{1}|g(t)-\chi_{[1/2,1]}(t)|^2dt \\
   \le \int_{0}^{1}\{|g(t)-f_{n_{m}}|+|f_{n_{m}}(t)-\chi_{[1/2,1]}(t)|\}^2dt \\
   \le 2\int_{0}^{1}|g(t)-f_{n_{m}}(t)|^2+|f_{n_{m}}(t)-\chi_{[1/2,1]}(t)|^2dt.
$$
The far right side converges to $0$ as $m\rightarrow\infty$ and, hence,
$$
         \int_{0}^{1}|g(t)-\chi_{[1/2,1]}(t)|^2dt =0.
$$
Therefore,
\begin{align}
    0 & \le \int_{0}^{x}|g(t)-\chi_{[1/2,1]}(t)|^2dt \\
   & \le \int_{0}^{x}|g-\chi_{[1/2,1]}|^2dt+\int_{x}^{1}|g-\chi_{[1/2,1]}|^2dt \\
   & = \int_{0}^{1}|g-\chi_{[1/2,1]}|^2dt = 0\;\;\; 0 \le x \le 1,
\end{align}
which forces
$$
       \int_{0}^{x}|g-\chi_{[1/2,1]}|^2dt =0,\;\;\; 0 \le x \le 1.
$$
The integrand is continuous except possibly at $t=1/2$. Therefore, by the Fundamental Theorem of Calculus, for $x \in [0,1/2)\cup(1/2,1]$,
$$
      |g(x)-\chi_{[1/2,1]}(x)|^2= \frac{d}{dx}\int_{0}^{x}|g-\chi_{[1/2,1]}|^2dt = 0.
$$
So $g(x)=\chi_{[1/2,1]}(x)$ except possibly at $t=1/2$. So there is no way for $g$ to be continuous on $[0,1]$, regardless of the value of $g(1/2)$ because the left- and right-hand limits of $g$ at $1/2$ are not equal. This contradiction proves $\{ f_n \}$ has no convergent subsequence in your space.


Run one virtual machine on a Linux server + standard Linux functions

Question: I am looking for a method to setup a Linux server (running Ubuntu Server) that uses Samba for file sharing, as well as hosting a Windows virtual machine (in this case, Windows Small Business Server 2003, which in turn hosts SQL Server Express - Exchange won't be used on this).
I would like to have the Linux server serving the files over Samba, and hosting the Virtual Machine. This obviously rules ESXi out as it couldn't do Samba at the same time. What would be the next best solution to give reasonable speed? Vmware Server 2.0, VirtualBox, Xen?
There will be 10-15 users accessing the Samba shares and the SQL Express virtual machine.
Matt
Comment: Does your hardware support KVM?
Comment: Also, are you wanting to share out the NTFS filesystem from the guest VM from the host's Samba server?
Answer: You could still run ESXi if you want and just have both the Linux and Windows machines virtual.
There wouldn't really be much difference of running Linux with a Windows VM inside of it or just running both a Linux VM and Windows VM on top of ESXi as long as you don't need the Linux machine to have access to physical devices not supported through ESXi.
Answer: Couple of things come to mind here: any reason why you're using Small Business Server 2003 and not Windows 2003/2008 Standard?  There's alot of extra "stuff" on SBS that you obviously don't need.
KVM would be well-suited for this, so long as your processor supports VT (if Intel) or AMD-V; this should go for any VM solution you choose, regardless.
Answer: If you want something simple that just works, go for CentOS with Xen. It comes pre-configured out-of-the-box. Or if you really want to run Ubuntu, wait for the next LTS (Long Time Support) release of Ubuntu, which is set to be released this month (10.04). I think it also comes bundled with Xen.
I've been running VMware Server on a few machines for quite some time, but I think Xen is catching up, and unless you want a turn-key solution for an entire datacenter, Xen will do the job for you (even though Xen is capable of that too, but requires a bit more work than VWare).
Comment: And don't go for VirtualBox, it's for desktop virtualization, not server virtualization.
Answer: vmware server runs on windows or linux so if you ever need to moved machines about in a mixed environment is a major advantage over xen.
Answer: First check if your motherboard supports visualization, then go for Xen, Qemu or KVM whichever suits your need.
Answer: I do almost this exact thing using VirtualBox on Slackware 13.  Vbox support hardware vz,  multiple CPUs and USB pass through.  Make sure you have too much RAM on the server and ave a blast
\\Greg


Desabilitar data escolhida no DatePickerDialog

Question: Olá, pessoal, tudo bem? Gostaria de saber se é possível, através do DatePickerDialog, desabilitar datas que usuários escolheram? Tipo, usuários escolhem uma data no datepicker que não pode mais aparecer para outros usuários, como em salões de cabeleleiros, que não pode ter a mesma vaga para duas pessoas. Cheguei até a parte de criar o DatePickerDialog, porém, não sei como desabilitar estas datas após escolhidas pelos usuários.
 diaAgendamento= (TextView) findViewById(R.id.textViewDataInicial);
    diaAgendamento.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar calendar = Calendar.getInstance();
            int dia = calendar.get(Calendar.DAY_OF_MONTH);
            int mes = calendar.get(Calendar.MONTH);
            int ano = calendar.get(Calendar.YEAR);

            DatePickerDialog dialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Dialog_MinWidth, datePicker, dia, mes, ano);
            dialog.show();
        }
    });
    datePicker = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            month = month + 1;
            String date = dayOfMonth + "/" + month + "/" + year;
            diaAgendamento.setText(date);
        }
    };

Answer: Tente usar esta biblioteca  Material Date Time Picker, nela você pode setar uma opção para mostrar datas específicas.
Exemplo
datePicker.setSelectableDays(Calendar[] days)

Passando um array de Calendar como um parâmetro que contem todas as datas que podem ser selecionadas.
Comment: Talvez seja mais fácil se usar `setDisabledDays(Calendar[] days)`
Comment: Obrigado pela resposta de vocês, me ajudou. Só estou com uma dúvida: estou colocando o compile 'com.wdullaer:materialdatetimepicker:3.4.1' no meu build.gradle e mesmo assim não estou conseguindo chamar o setDisableDays.


vue mount data to many divs or table

Question: New to vue
trying to create a simple table or muliple divs (5 rows by 5 columns)
I would like to mount data to each of those td\div
I can change the data format coming in if it makes it easier, but planning on something like such
[{ box:1,
  name: 'a'
},
{ box:2,
  name: 'b'
},
{ box:3,
  name: 'c'
},
...
{ box:25,
  name: 'z'
}]

Was even thinking to adding row:1, col: 1 for box1, row:1, col2 for box 2 ... row:5, col:5 for box 25
Not sure how to setup the html and vue.  Do i need to do a loop to create the table in html, or is this something that can be done in vue template?
Thanks
Answer: Use v-for to loop over each item in the array and generate the rows of the table.

      Box
      Name

      {{ row.box }}
      {{ row.name }}

data: {
  rows: [
    { box: 1, name: 'a' },
    { box: 2, name: 'b' },
    { box: 3, name: 'c' }
  ]
}

You say you want to generate a 5x5 table; is your data sparse (only some cells contain data, others may be empty)? Please provide more information about exactly what you want the resulting table to look like and how you are storing the data.
Typically your data model should reflect what you want the table to look like; the templates are just "pure functions" that generate a view from the data without too much manipulation. Your data should be a "5x5 table" that you can just loop over in the template to generate the HTML.
If you are storing the associated data in a sparse kind of way (like an array where each item has a cell position { row: 1, col: 2 }, then you can use a computed property to generate the full table model with the relevant cells filled in with the necessary data, then the template will be basically the same as what I have shown above. You shouldn't be doing data manipulations in the template, do it in code in computed properties.
Comment: Thanks for the feedback - will give it a try.  My dataset will contain all rows\cols (not sparsed).   I am still in planning stage so I can setup my data structure any way that benefits me as long as each td has box num, name and eventually @click.

vue mount data to many divs or table


Regex parse Buffy Script using look behinds

Question: I'm having a difficult time parsing this page: http://www.buffyworld.com/buffy/transcripts/114_tran.html
I'm attempting to get the character name with the associated dialogue.
The text looks like this:

BUFFY: Wait!

She stands there panting, watching the truck turn a corner.

BUFFY: (whining) Don't you want your garbage?

She sighs, pouts, turns and walks back toward the house.

Cut to the kitchen. Buffy enters through the back door, holding a pile of
mail. She begins looking through it. We see Dawn standing by the island.

DAWN: Hey Buffy. Oh, don't forget, today's trash day.
BUFFY: (sourly)
Thanks.

Dawn piles her books into her school bag. Buffy opens a letter.

Close shot of the letter.

Dawn smiles, and she and Willow exit. Buffy picks up the still-wrapped
sandwich and stares at it.

BUFFY: (to herself) Somebody should.

She sighs, puts the sandwich back in the bag.

Cut to the Bronze. Pan across various people drinking and dancing,
bartender serving. Reveal Xander and Anya sitting at the bar eating chips from
several bags. A notebook sits in front of them bearing the wedding seating
chart.

ANYA: See ... this seating chart makes no sense. We have to do it again.
(Xander nodding) We can't do it again. You do it.
XANDER: The seating
chart's fine. Let's get back to the table arrangements. I'm starting to have
dreams of gardenia bouquets. (winces) I am so glad my manly coworkers didn't
just hear me say that. (eating chips)

Ideally, I'd match from
 or
 to the next
 or
. I was trying to use look aheads and look behinds for this:
reg = "((?<=
)|(?<=
))(?P<character>.+):(?P<dialogue>.+)((?=
)|(?=
))"
script = re.findall(reg, html_text)

Unfortunately, this doesn't match anything. When I leave off the lookahead ((?=
)|(?=
)), I match lines as long as there isn't a newline in the matching dialogue. It seems to terminate at the newline instead of continuing to the

ex. On this line, the "Thanks" isn't matched.
DAWN: Hey Buffy. Oh, don't forget, today's trash day.
BUFFY: (sourly)
  Thanks.
Thank you for any insight you have!
Comment: Which python? For me the first version matches something
Answer: Work around the dot notation:
re.findall('((?<=
)|(?<=
))([A-Z]+):([^<]+)', text)

Also you can try a special flag to include linebreaks into the semantics of the dot. Personally, when I can I use splits or some html parser. RE escaping, all the parameters, limitations and flags can drive mad anyone. There is also re.split.
dialogs = {}
text = html_text.replace('
', '
')
paragraphs = text.split('
')

for p in paragraphs:
    if ":" in p:
        char, line = p.split(":", 1)
        if char in dialogs:
           dialogs[char].append(line)
        else:
           dialogs[char] = []

Comment: Thank you for your help!


Reference request for simulation studies

Question: I'm looking for good references explaining how to design and analyze simulation studies (and, just to be clear, by this I mean the typical study you'd find in many modern papers, where you repeatedly generate data, estimate something and assess performance). The goal is to include this in a graduate computational course, so ideally it should be an article covering the basics with some practical tips and recommendations.
Burton et al. (2006) is a good place to start, but do you know of any other papers (or, most probably, (hand)book chapters) in the same spirit as this?

Reference:
Burton, A., Altman, D. G., Royston, P. and Holder, R. L. (2006), The design of simulation studies in medical statistics. Statist. Med., 25: 4279–4292. doi:10.1002/sim.2673
Answer: For general simulation, I think Simulation Modeling and Analysis by Averill M. Law is a great reference. I've spoken to him at conferences and attended his workshops - he's both gifted and a nice guy. He discusses designing simulation studies, pilot studies, determining warm-ups, etc.
For more formal treatment of some simulation procedures, Simulation by Sheldon Ross isn't bad (though I'm not a fan of Ross' writing style or typesetting).


jQuery passing click selector into IF statement

Question: I am trying to create a jQuery function to check whether a Cancel or Remove button was pressed on a facebox dialog, however I am not quite sure how to go about it.
Right now, I have:
// Confirm and remove group members
$("[id^='removeGroupMember_']").click(function () {
        confirmDialog('Removal', 'Are you sure you want to remove this person from the group?');

        //  I need to check the results of the confirm dialog prior
        //  to calling the code below to remove the actual rows

        $(this).parent().slideUp("fast", function () {
            $(this).remove();
            updateGroupRows();
        });
    return false;
});

Where confirmDialog is:
function confirmDialog(action, message) {
    $.facebox('
Confirm ' + action + '

' + message + '
' + action + 'Cancel
');
};

Right now, I have two functions for when those buttons are pressed, but I'm not sure how to check their result and feed that back in so I can decide whether or not to delete the associated row:
$('#dialogConfirmAction').live('click', function() {
    console.log('Yep... they dun clicked it.');
    return true;
});

$('#dialogConfirmCancel').live('click', function() {
    $.facebox.close();
    return true;
});

Any guidance you can provide is greatly appreciated!
Answer: What you want to do is change your confirmDialog function to be like so:
function confirmDialog(action, message, actionfunc) {
    $.facebox('
Confirm ' + action + '

' + message + '
' + action + 'Cancel
');
    if(actionfunc) {
        $('#dialogConfirmAction').click(actionfunc);
    }
};

You can then pass what you want to happen "on action" by passing a function to the confirmDialog function. This would make your other code look like this:
$("[id^='removeGroupMember_']").click(function () {
    var $that = $(this);
    confirmDialog('Removal', 'Are you sure you want to remove this person from the group?',
                  function() {
                      //This function will be run when the "action" link is clicked
                      $that.parent().slideUp("fast", function () {
                          $(this).remove();
                          updateGroupRows();
                      });
                  });
    return false;
});

And you can extend that by adding another variable to say what to do on cancel.
Comment: I made a typo when I first posted this, the selector in confirmDialog function was for the cancel button. I've fixed it.
Comment: I owe you one very giant beer my friend.  Essentially, you created a callback function, right?  By the way, I ended up caching the selector since calling `$(this).parent()` would mean calling the modal box instead of the original list item.
Comment: @iWasRobbed: Yep, that's basically what I did. And, yeah sorry. Haha I just copied the workings from your original click function into the new one. I'll edit it for the sake of completeness. **Edit** Fixed!
Answer: Try this:
 // Confirm and remove group members
$("[id^='removeGroupMember_']").click(function () {

        if(confirmDialog('Removal', 'Are you sure you want to remove this person from the group?')) {
            //  I need to check the results of the confirm dialog prior
            //  to calling the code below to remove the actual rows

            $(this).parent().slideUp("fast", function () {
                $(this).remove();
                updateGroupRows();
            });
        }
    return false;
});

Comment: @user341652: Just so you know, this doesn't work because `confirmDialog` is a) not the same as the `confirm()` function and b) the function creates a pop up which is not modal so there's no way it could properly return true or false to the calling function.


I am unable to create Amazon connect instance on free tier

Question: When I try to create an Amazon Connect instance, I receive the message:

You're signed in with an AWS account that was provided by AISPL. These accounts cannot create Amazon Connect instances. Sign in using an account provided by AWS, and then try to create an instance. Please contact support if you need further assistance.

This error shows when I am creating a instance please help me through this.
Comment: Welcome to Stack Overflow! I'm voting to close this question as off-topic because [we are not customer support for your favourite company](//meta.stackoverflow.com/questions/255745).
Answer: From Create an Amazon Connect instance - Amazon Connect:

Amazon Connect is not available to customers in India using Amazon Web Services through Amazon Internet Services Pvt. Ltd (AISPL). You will receive an error message if you try to create an instance in Amazon Connect.

It appears that AWS accounts created in India are administered by Amazon Internet Services Private Limited and have a few differences to 'normal' AWS accounts.
See also: Understand the differences between AWS and AISPL accounts
You might be able to create a non-AISPL AWS account by specifying a different address.
Comment: If anybody residing in India have given a different address and if you are able to create amazon connect instance please confirm.
Comment: aah. spent time creating an instance.
Comment: Yes it's working from new AWS account created with other country address( I gave US address) still used my india mobile number but it's accepting, verification is working fine. And also able to create an Amazon Connect instance.
Comment: Really messed up. Out of curiosity I wish to know why this is the case.


Using airflow with BigQuery and cloud sdk gives error "User must be authenticated when user project is provided"

Question: I am trying to run airflow locally. My DAG has a BigQueryOperator and I want to use the cloud sdk for authentication. I run "gcloud auth application-default login" in order to get the json file with the credentials. I try to test my Dag running the command:
airflow test testdag make_tmp_table 2019-02-13 I get the error message "User must be authenticated when user project is provided"
If I instead of using the cloud sdk use a service account that has admin rights to BigQuery it works, but I need to use authentication through the cloud sdk.
Does anyone know what this error message means or how I can run airflow and using the cloud sdk for authentication?
I have used the following source to try to understand how I can run airflow with BigQueryOperators locally.
https://medium.com/@jbencina/local-testing-with-google-cloud-composer-apache-airflow-75d4213d2893
Answer: I solved it by deleting the credentials file produced when I did:
gcloud auth application-default login and then recreating the file.
Then it worked. So I had the right method, just that something was broken in the credentials file.
Comment: This solution was not enough for me. I solved it by deleting the line `"quota_project_id": "myproject"` line in the `application_default_credentials.json` file. I don't know why Airflow doesn't like the quota project ID key, but I tested it multiple times, and this was the problem.
Comment: @dlebech there are literally no other search results on this but your trick worked for me as well.
Answer: either you are not working on the right project or you don't have permissions to do this job.
what I suggest is:
check your current configuration by running:
gcloud auth list

make sure that you have the right project and the right account set if not run these commands to set them:
gcloud auth application-default login

you will be prompted for a link. follow it and enter your account. after that you will see a verification code, copy it and add it to your gcloud terminal.
next thing to do is to make sure that your account has permissions to do the job that you are trying. probably you need this role roles/composer.admin if it didn't work add the premitive role roles/editor from your IAM console. But use that premitive role only for testing purposes and it's not adviasable to use it for production level project.
Comment: Thank you very much. It should work as you suggested. See my answer to my own question
Answer: as @dlbech said:

Blockquote
This solution was not enough for me. I solved it by deleting the line "quota_project_id": "myproject" line in the application_default_credentials.json file. I don't know why Airflow doesn't like the quota project ID key, but I tested it multiple times, and this was the problem


Mudar cor do Input ao digitar x caracters

Question: Eu gostaria que quando uma pessoa digitasse mais de 10 caracteres no meu input, ele trocasse a cor pra verde, caso contrario fica vermelho.
Isso sem da refresh. A pessoa não precisaria clicar no botão para poder alterar as cores. Eu gostaria que alterasse as cores enquanto a pessoa tivesse digitando mesmo.
Answer: Basta utilizar o evento input no JavaScript. Com ele você poderá detectar todas as alterações do campo.
Exemplo com JavaScript "Puro":

/* Captura o campo */
const fieldMessage = document.querySelector("#message")

/* O evento INPUT irá detectar todas as alterações no valor digitado/colado */
fieldMessage.addEventListener("input", _ => {

  /**
   * Verifica se o valor digitado possui mais de 10 caracteres
   * Caso possua, adiciona a classe `valid`
   */
  if (fieldMessage.value.length > 10) {
    fieldMessage.classList.remove("invalid")
    fieldMessage.classList.add("valid")
  }
  /* Caso contrário remove-a */
  else {
    fieldMessage.classList.remove("valid")
    fieldMessage.classList.add("invalid")
  }
})
input.valid {
  /* Altera a cor da borda */
  border: 2px solid green;

  /* Altera a cor da sombra */
  box-shadow: 0 0 5px green;
}

input.invalid {
  /* Altera a cor da borda */
  border: 2px solid red;

  /* Altera a cor da sombra */
  box-shadow: 0 0 5px red;
}
<input type="text" id="message" />

Exemplo com jQuery:

/* Captura o campo */
const fieldMessage = document.querySelector("#message")

$("#message").on("keyup", function(){
  if ($("#message").val().length > 10) {
    $(this).addClass("valid").removeClass("invalid")
  } else {
    $(this).addClass("invalid").removeClass("valid")
  }
})
input.valid {
  /* Altera a cor da borda */
  border: 2px solid green;

  /* Altera a cor da sombra */
  box-shadow: 0 0 5px green;
}

input.invalid {
  /* Altera a cor da borda */
  border: 2px solid red;

  /* Altera a cor da sombra */
  box-shadow: 0 0 5px red;
}

<input type="text" id="message" />
Answer: <input type="text" id="ex" onBlur="ts()">


Finitely generated, non abelian, infinite group

Question: I was making a diagram of different types of groups; finite /infinite, cyclic / non-cyclic, finitely generated / inifinitely generated, but realized that I didn't have any examples og infinite groups, that are both finitely generated and non -abelian. Does anyone have any examples? :)
I was thinking about creating an example based on matrices and matrix multiplication, but I didn't get very far. I know that since I am looking for a finitely generated group, It must be countable.
Comment: The question body and title disagree.
Comment: @ZAF $\mathbb Z$ is abelian.
Comment: $\mathbb{Z}$ isn't it ?
Answer: The group $\langle a, b\rangle$ is

finitely generated: obviously, it is generated by $\{a, b\}$,
non-abelian: the elements $ab$ and $ba$ are two distinct elements,
infinite: The mapping $\mathbb N\to \langle a, b\rangle$ that maps $n$ to $a^n$ is injective.
Comment: @AfterMath free group of rank 2
Comment: Thanx alot! Guess I couldn't see the forest for the trees...      May I also ask if the group  of "ordered sequences of powers of the elements a and b" has any other name than just "the group generated by the non - commutative elements a and b"?
Comment: @AfterMath It's the free grop of $\{a,b\}$, or the free group of rank $2$ (since, up to isomorphism, all free groups over a set of the same cardinality are equal)
Answer: Try $G=\mathbb Z \times S_3$.
Comment: Thanks! Good example :)
Answer: For the curious, John Meier's Groups, Graphs and Trees as well as Office Hours With A Geometric Group Theorist edited by Matt Clay and Dan Margalit make great introductions to the world of infinite, finitely-generated groups!


NullPointerException in recursively dividing triangle

Question: I'm having problem with the boolean divide(int depth) method in the Triangle class I created, the code is as follows. Other parts have passed the test, but because of the boolean divide(int depth), this programming throws a java.lang.NullPointerException.
I've been working on it for a long time but I still don't know what's wrong with the recursion. Both boolean divide() and boolean divide(int depth) don't take any argument, this makes it so difficult for me to write the recursion. Any hint will be appreciated, thanks a lot.
boolean divide(int depth)overwrites boolean divide(), boolean divide()divides the triangle into three sub triangles, it creates three Vertex2D on each edge of a triangle and the sub-triangles are stored in the Triangle class in an array as an attribute.
public class Triangle {
    private static final int NUM_OF_SUB_TRIANGLES = 3;
    private final Vertex2D[] vertices = new Vertex2D[3];
    private final Triangle[] subTriangles = new
Triangle[NUM_OF_SUB_TRIANGLES];
    public  Triangle(Vertex2D v1, Vertex2D v2, Vertex2D v3){
        vertices[0] = v1;
        vertices[1] = v2;
        vertices[2] = v3;
    }

// Method returns a vertex of the triangle according to input index
public Vertex2D getVertex(int index) {
    for (int i = 0; i < 3; i++) {
        if (index == i) {
            return vertices[i];
        }
    }
    return null;
}

public boolean isEquilateral(){
    double side1 = vertices[0].distance(vertices[1]);
    double side2 = vertices[0].distance(vertices[2]);
    double side3 = vertices[1].distance(vertices[2]);

    if(Math.abs(side1-side2) < 0.001 && Math.abs(side1-side3) < 0.001 && Math.abs(side2-side3) < 0.001){
        return true;
    }else{
        return false;
    }

}

// Method outputs the coordinates of threes vertices of the triangle
// edit this one
public String toString(){
    String s = "Triangle: vertices=" + vertices[0]
            + " [" + vertices[1].getX() + ", " + vertices[1].getY() + "] " + "[" + vertices[2].getX() + ", " + vertices[2].getY()
            + "]";
    return s;
}

// Method checks if the three sub triangles are created
public boolean isDivided(){
    for(int i = 0 ; i < NUM_OF_SUB_TRIANGLES; i ++){
        if(subTriangles[i] == null){
            return false;
        }
    }
    return true;
}

// Method returns a sub triangle according to the input index
public Triangle getSubTriangle(int index){
    for (int i = 0; i < 3; i++) {
        if (index == i) {
            return subTriangles[i];
        }
    }
    return null;
}

// Method divides the triangle into three sub triangles

public boolean divide(){
    if (isDivided()){
        return false;
    }else{
        // Find vertices of the three sub triangles
        Triangle t1 = new Triangle(vertices[0], vertices[0].createMiddle(vertices[1]), vertices[0].createMiddle(vertices[2]));
        Triangle t2 = new Triangle(vertices[0].createMiddle(vertices[1]), vertices[1], vertices[1].createMiddle(vertices[2]));
        Triangle t3 = new Triangle(vertices[0].createMiddle(vertices[2]), vertices[1].createMiddle(vertices[2]), vertices[2]);

        subTriangles[0] = t1;
        subTriangles[1] = t2;
        subTriangles[2] = t3;

        return true;
    }
}

public boolean divide(int depth){
    if(depth <= 0){
        return false;
    }else{
        while(depth > 0) {
            if (!isDivided()) {
                divide();
            } else {
                depth -= 1;
                for (int i = 0; i < 3; i++) {
                    getSubTriangle(i).divide(depth);
                }
                depth -= 1;
            }
        }
        return true;
    }

}
}

Comment: See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556)
Answer: The problem seems to be with this code
public Triangle getSubTriangle(int index){
    for (int i = 0; i < 3; i++) {
        if (index == i) {
            return subTriangles[i];
        }
    }
    return null;    // HERE
}

But why do you even loop in this method
if (index < 3) return subTriangles[index];
return null;

and then check your calling code that the retunred value is not null
Comment: the input may be negative
Comment: `if (index >= 0 && index < 3)`
Answer: The problem is on getSubTriangle(i).divide(depth). Change your code with:
public boolean divide(int depth){
    if(depth <= 0){
        return false;
    }else{
        while(depth > 0) {
            if (!isDivided()) {
                divide();
            } else {
                depth -= 1;
                for (int i = 0; i < 3; i++) {
                    Triangle t=getSubTriangle(i);
                    if (t!=null) {
                      t.divide(depth);
                    }
                }
                depth -= 1;
            }
        }
        return true;
    }

}

Just to test it:
public class Triangle {

    public static class Vertex2D {

        private float x;
        public Vertex2D(float i, float j) {
            x=i;
            y=j;
        }

        public float getX() {
            return x;
        }

        public void setX(float x) {
            this.x = x;
        }

        public float getY() {
            return y;
        }

        public void setY(float y) {
            this.y = y;
        }

        private float y;

        public double distance(Vertex2D vertex2d) {
            float x1=vertex2d.x-x;
            float y1=vertex2d.y-y;

            return Math.sqrt(x1*x1+y1*y1);
        }

        public Vertex2D createMiddle(Vertex2D vertex2d) {
            float x1=vertex2d.x+x;
            float y1=vertex2d.y+y;

            Vertex2D v=new Vertex2D(x1, y1);
            v.setX(x1);
            v.setY(y1);

            return v;
        }

    }

    private static final int NUM_OF_SUB_TRIANGLES = 3;
    private final Vertex2D[] vertices = new Vertex2D[3];
    private final Triangle[] subTriangles = new
Triangle[NUM_OF_SUB_TRIANGLES];
    public  Triangle(Vertex2D v1, Vertex2D v2, Vertex2D v3){
        vertices[0] = v1;
        vertices[1] = v2;
        vertices[2] = v3;
    }

// Method returns a vertex of the triangle according to input index
public Vertex2D getVertex(int index) {
    for (int i = 0; i < 3; i++) {
        if (index == i) {
            return vertices[i];
        }
    }
    return null;
}

public boolean isEquilateral(){
    double side1 = vertices[0].distance(vertices[1]);
    double side2 = vertices[0].distance(vertices[2]);
    double side3 = vertices[1].distance(vertices[2]);

    if(Math.abs(side1-side2) < 0.001 && Math.abs(side1-side3) < 0.001 && Math.abs(side2-side3) < 0.001){
        return true;
    }else{
        return false;
    }

}

// Method outputs the coordinates of threes vertices of the triangle
// edit this one
public String toString(){
    String s = "Triangle: vertices=" + vertices[0]
            + " [" + vertices[1].getX() + ", " + vertices[1].getY() + "] " + "[" + vertices[2].getX() + ", " + vertices[2].getY()
            + "]";
    return s;
}

// Method checks if the three sub triangles are created
public boolean isDivided(){
    for(int i = 0 ; i < NUM_OF_SUB_TRIANGLES; i ++){
        if(subTriangles[i] == null){
            return false;
        }
    }
    return true;
}

// Method returns a sub triangle according to the input index
public Triangle getSubTriangle(int index){
    for (int i = 0; i < 3; i++) {
        if (index == i) {
            return subTriangles[i];
        }
    }
    return null;
}

public static void main(String args[]) {
    Vertex2D v1=new Vertex2D(10,20);
    Vertex2D v2=new Vertex2D(-10,-20);
    Vertex2D v3=new Vertex2D(10,-20);
    Triangle t=new Triangle(v1, v2, v3);

    boolean r = t.divide(3);
    System.out.println(r);

}

// Method divides the triangle into three sub triangles

public boolean divide(){
    if (isDivided()){
        return false;
    }else{
        // Find vertices of the three sub triangles
        Triangle t1 = new Triangle(vertices[0], vertices[0].createMiddle(vertices[1]), vertices[0].createMiddle(vertices[2]));
        Triangle t2 = new Triangle(vertices[0].createMiddle(vertices[1]), vertices[1], vertices[1].createMiddle(vertices[2]));
        Triangle t3 = new Triangle(vertices[0].createMiddle(vertices[2]), vertices[1].createMiddle(vertices[2]), vertices[2]);

        subTriangles[0] = t1;
        subTriangles[1] = t2;
        subTriangles[2] = t3;

        return true;
    }
}

public boolean divide(int depth){
    if(depth <= 0){
        return false;
    }else{
        while(depth > 0) {
            if (!isDivided()) {
                divide();
            } else {
                depth -= 1;
                for (int i = 0; i < 3; i++) {
                    Triangle t = getSubTriangle(i);
                    System.out.println(t.toString());
                            if (t!=null) {
                                t.divide(depth);
                            }
                }
                depth -= 1;
            }
        }
        return true;
    }

}
}

And the output is (I'm not check about the meaning of result of algorithm):
Triangle: vertices=Triangle$Vertex2D@15db9742 [0.0, 0.0] [20.0, 0.0]
Triangle: vertices=Triangle$Vertex2D@15db9742 [10.0, 20.0] [30.0, 20.0]
Triangle: vertices=Triangle$Vertex2D@15db9742 [20.0, 40.0] [40.0, 40.0]
Triangle: vertices=Triangle$Vertex2D@6d06d69c [10.0, 20.0] [40.0, 40.0]
Triangle: vertices=Triangle$Vertex2D@7852e922 [40.0, 40.0] [30.0, 20.0]
Triangle: vertices=Triangle$Vertex2D@4e25154f [0.0, 0.0] [20.0, 0.0]
Triangle: vertices=Triangle$Vertex2D@4e25154f [10.0, 20.0] [30.0, 20.0]
Triangle: vertices=Triangle$Vertex2D@70dea4e [0.0, 0.0] [20.0, 0.0]
Triangle: vertices=Triangle$Vertex2D@5c647e05 [20.0, 0.0] [20.0, 0.0]
Triangle: vertices=Triangle$Vertex2D@33909752 [20.0, 0.0] [20.0, 0.0]
Triangle: vertices=Triangle$Vertex2D@33909752 [50.0, 20.0] [50.0, 20.0]
Triangle: vertices=Triangle$Vertex2D@55f96302 [20.0, 0.0] [40.0, 0.0]
Triangle: vertices=Triangle$Vertex2D@3d4eac69 [40.0, 0.0] [20.0, 0.0]
Triangle: vertices=Triangle$Vertex2D@42a57993 [-10.0, -20.0] [0.0, -40.0]
Triangle: vertices=Triangle$Vertex2D@42a57993 [-10.0, -20.0] [0.0, -40.0]
Triangle: vertices=Triangle$Vertex2D@42a57993 [-10.0, -20.0] [0.0, -40.0]
Triangle: vertices=Triangle$Vertex2D@75b84c92 [-10.0, -20.0] [-10.0, -60.0]
Triangle: vertices=Triangle$Vertex2D@6bc7c054 [-10.0, -60.0] [0.0, -40.0]
Triangle: vertices=Triangle$Vertex2D@232204a1 [-10.0, -20.0] [-10.0, -60.0]
Triangle: vertices=Triangle$Vertex2D@232204a1 [-20.0, -40.0] [-20.0, -80.0]
Triangle: vertices=Triangle$Vertex2D@4aa298b7 [-10.0, -20.0] [-20.0, -80.0]
Triangle: vertices=Triangle$Vertex2D@7d4991ad [-20.0, -80.0] [-10.0, -60.0]
Triangle: vertices=Triangle$Vertex2D@28d93b30 [-10.0, -60.0] [0.0, -40.0]
Triangle: vertices=Triangle$Vertex2D@28d93b30 [-10.0, -100.0] [0.0, -80.0]
Triangle: vertices=Triangle$Vertex2D@1b6d3586 [-10.0, -60.0] [-10.0, -100.0]
Triangle: vertices=Triangle$Vertex2D@4554617c [-10.0, -100.0] [0.0, -40.0]
Triangle: vertices=Triangle$Vertex2D@74a14482 [0.0, -40.0] [10.0, -20.0]
Triangle: vertices=Triangle$Vertex2D@74a14482 [20.0, -40.0] [30.0, -20.0]
Triangle: vertices=Triangle$Vertex2D@74a14482 [40.0, -40.0] [50.0, -20.0]
Triangle: vertices=Triangle$Vertex2D@1540e19d [20.0, -40.0] [50.0, -60.0]
Triangle: vertices=Triangle$Vertex2D@677327b6 [50.0, -60.0] [30.0, -20.0]
Triangle: vertices=Triangle$Vertex2D@14ae5a5 [0.0, -40.0] [10.0, -60.0]
Triangle: vertices=Triangle$Vertex2D@14ae5a5 [20.0, -80.0] [30.0, -100.0]
Triangle: vertices=Triangle$Vertex2D@7f31245a [0.0, -40.0] [10.0, -100.0]
Triangle: vertices=Triangle$Vertex2D@6d6f6e28 [10.0, -100.0] [10.0, -60.0]
Triangle: vertices=Triangle$Vertex2D@135fbaa4 [10.0, -60.0] [10.0, -20.0]
Triangle: vertices=Triangle$Vertex2D@135fbaa4 [40.0, -80.0] [40.0, -40.0]
Triangle: vertices=Triangle$Vertex2D@45ee12a7 [10.0, -60.0] [20.0, -80.0]
Triangle: vertices=Triangle$Vertex2D@330bedb4 [20.0, -80.0] [10.0, -20.0]
Triangle: vertices=Triangle$Vertex2D@15db9742 [0.0, 0.0] [20.0, 0.0]
Triangle: vertices=Triangle$Vertex2D@42a57993 [-10.0, -20.0] [0.0, -40.0]
Triangle: vertices=Triangle$Vertex2D@74a14482 [0.0, -40.0] [10.0, -20.0]
true

Comment: Thanks, but I still got the same error.
Comment: I tried, as you can read and it works. The null check is correct for sure. Probably there is another problem on Triangle building.


A purge script - saving and deleting files according to it date

Question: I'm working on a purge script in Python. The following script is working fine. The script browse a list of directories and, according to each file date, remove or keep any files. So if any files exist after X days or minutes, these files are removed.
purge_files_path = ['x:/path/destination', 'x:/path/destination', ]

kwargs = {"weeks":0, "days": 0, "hours": 0, "minutes": 23}

def purge(purge_files_path, kwargs):

    import os
    from datetime import datetime, timedelta

    for folder in purge_files_path:
        for(dir, _, files) in os.walk(folder):
            for file in files:
                path = os.path.join(dir, file)

                if os.path.exists(path):
                    file_date = datetime.fromtimestamp(os.path.getmtime(path))
                    delta = datetime.now() - file_date

                    if delta >= timedelta(**kwargs):
                        os.remove(path)

Now, I just want to add a new functionality. I want, before to remove a file, to save it in another folder. It could be easy, but I want to keep the folder architecture of any files.
So if a file which has to be purged and located on:
c:/source/folder1/folder2/file.txt

It has to be back up on :
c:/backup/folder1/folder2/file.txt

I could use shutil.copytree, but I have an error of existing folders.
Comment: before you do shutil.copytree,  check whether that folder folder exist in the backup folder.
Answer: Yes, just use os.rename instead of os.remove. You might want to use relpath to preserve directory structure. Just replace your call to os.remove(path) with the following snippet.
relative_path = os.path.relpath(path, folder))
backup_path = os.path.join(backup_dir, relative_path)
os.makedirs(os.path.dirname(backup_path), exist_ok=True)
os.rename(path, backup_path)

Note: If the directories are on different volumes, you need to use shutil.move instead of os.rename.
To get python 2 support, you need to drop the exists_ok=True like so
if not os.path.isdir(os.path.dirname(backup_path)):
    os.makedirs(os.path.dirname(backup_path))

Comment: Is ""exist_ok=True"" compatible with Python 2 ?
Comment: It is not. You need to use and if statement to check if you need to create the directory
Comment: Thank you for your advices @vidstige


How can I get the "smart sharpen" effect on my images with python?

Question: I am wondering how to smart sharpen an image using python or any  related image library like ndimage ,skimage or even PIL.I could find methods that actually sharpen my image but with a lot of noise and pixelating when zooming in .So since I know Photoshop I tried to get that smart sharpen effect which sharpens the image with a less noising and with a nice sweet contrast through python but I failed.
Notes:-
(1) methods has been tested:-
>>> # The 1st Method:
>>> import Image
>>> import ImageFilter
>>> image.filter(ImageFilter.SHARPEN)
>>> Image.filter(ImageFilter.EDGE_ENHANCE_MORE)    #Look down:1st image created

>>> # The 2nd Method:
>>> blurred_l=scipy.ndimage.gaussian_filter(b,3)
>>> filter_blurred_l = scipy.ndimage.gaussian_filter(blurred_l, 1)
>>> alpha =30
>>> sharpened = blurred_l + alpha * (blurred_l - filter_blurred_l)

>>> # The 3rd Method:
>>> shar=imfilter(Image,'sharpen')               #Look down:2nd image created

(2) I found a piece of code but it's in Perl . I only know Python In here  or  directly
(3) Here are 2 of the sharpened image using above methods the third done with smartsharp:
Original
Original image http://imageshack.us/a/img600/6640/babyil.jpg
First ....................................................................second
1st http://imageshack.us/a/img803/3897/sharp1.png 2nd http://imageshack.us/a/img809/2235/sharp2.png
third MY GOAL>that's the effect I want
3rd http://imageshack.us/a/img832/4563/smartsharp.jpg
(4) Here are the tool I used to create the third image above:
smrsharpm http://imageshack.us/a/img210/2747/smartsharpentoolm.jpg smrsharp http://imageshack.us/a/img193/490/smartsharpentool.jpg
Answer: Unfortunately, it's hard to know what "Smart sharpen" does without having access to the Photoshop code.  In the meantime, you can try to mix an unsharpen mask, total variation filtering and some color adjustment (perhaps a bit of hue boost).
Also see: http://www.kenrockwell.com/tech/photoshop/sharpening.htm#
Update: here is an example of how to remove motion blur from an image:
https://github.com/stefanv/scikit-image-demos/blob/master/clock_deblur.py
(the clock image is in the same repository).  Unfortunately, scikit-image does not currently have mature deblurring / inverse filtering--but we're working on it!
Comment: But the good news is anyone knows `Perl` can modify the code I attached in my post into my lovely `Python`. By the way Thank you for scikit-image project.
Comment: Only a pleasure!  I can't access the Perl code above--would you mind checking the link?
Comment: I tried to use `Wiener-filter` from `scikit-image`but it raised an error  **Impulse response must be a callable** (i.e I don't know how to use the Impulse response parameter to do wiener -filter). I'm stuck with this spot .your previous article is wonderful but the code is in `MatLab`  and I tried to figure out what **fspecial()** function does but I failed.It seems you can help  .can you update your answer illustrating how to use the `skimage.filter.wiener()` to do smart-sharpen.Thanks for your patience.
Comment: Unfortunately, the Wiener code needs a revamp.  I've added an example above on how to motion deblur an image.  This method can also be used if you only know your blurring kernel--essentially, you apply the Fourier transform to both your image (f -> F) and your kernel (h -> H), and then return the inverse FFT of (F / H), after making sure that the amplitude is limited in places where H is close to zero. Padding avoids boundary effects, and windowing the image limits oscillations in the reconstruction.
Comment: Surely ,providing suck a method in scikit-image will push it forward as an image processing library.Through googling I noticed how people admires such an effect.Thanks,I'm going to read the code.
Comment: Agreed; we're working on it and should have it available within one or two releases.
Answer: Photoshop's "smart sharpening" function uses a mathematical operation called deconvolution internally. numpy does have a deconvolve() function that could probably be pressed into service for this task, but I couldn't find a ready-made function to do smart sharpening specifically with numpy, so you'd probably have to code it up yourself.
An alternative approach would be to do it using the GIMP. There's a GIMP plug-in (intuitively named "G'Mic") that will do deconvolution among other sharpening algorithms, and you can automate GIMP using Python.
Comment: We have the standard Wiener-filter implemented in scikit-image, so you could generate a Gaussian kernel and apply its inverse (this process is called deconvolution).  Also see: http://yuzhikov.com/articles/BlurredImagesRestoration1.htm

There's also blind deconvolution, which tries to estimate the optimal deblur kernel, but this process can be quite sensitive.
Comment: @StefanvanderWalt I reposted the links.Now I'm going to try the Wiener-filter hope it works for me as I prefer to do the task through scikit-image or may be ndimage.Thanks
Comment: @StefanvanderWalt .I read the wonderful article you provided inside the comment but the code is in `MatLab` I think.So you may want to update your answer illustrating how to use the **Wiener-filter** in the deconvolution process as it is seemed to be the correct answer.Thanks
Comment: Mr Kindal.Is there anyway to import `GIMP` as a package and may be I can use the `G'Mic` through this package as I want to make a stand alone program.If so,this would be the answer.Thanks anyway for your valuable information.
Answer: @StefanvanderWalt
Unfortunately, the Wiener code needs a revamp. I've added an example above on how to motion deblur an image. This method can also be used if you only know your blurring kernel--essentially, you apply the Fourier transform to both your image (f -> F) and your kernel (h -> H), and then return the inverse FFT of (F / H), after making sure that the amplitude is limited in places where H is close to zero. Padding avoids boundary effects, and windowing the image limits oscillations in the reconstruction.
What values and dimensions the hann window used?
Answer: Well this is a rather old question and this is probably not the right answer either, but I was looking to do this with Photoshop 2020 and a python script and I had a hard time finding scattered information on how to do this so I'll post this anyway if anyone ever needs something like and this could help them.
First of all I used this python library : https://photoshop-python-api.readthedocs.io/en/0.14.0/index.html
With this API i was able to recreate basically any filter in photoshop with a python script.
Then I needed to find the string IDs for the actions to create the scripts, for this I used the Scripting Listener plugin that i found here : https://helpx.adobe.com/photoshop/kb/downloadable-plugins-and-content.html#ScriptingListenerplugin

I tried following the guide for Windows, but it actually didn't work
at first, at step 4 you actually have to put the 3 folders that you
extract from the ZIP in the "Plug-Ins" folder "Program
Files\Adobe\Adobe Photoshop 2020\Plug-ins" just like mac-os.

Then is just a matter of executing whatever filter in photoshop and get the JS or VBS log from the listener and converting it in python.
This is an example of the JS log for the Smart Sharpen:
var idsmartSharpen = stringIDToTypeID( "smartSharpen" );
var desc186 = new ActionDescriptor();
var idpresetKind = stringIDToTypeID( "presetKind" );
var idpresetKindType = stringIDToTypeID( "presetKindType" );
var idpresetKindCustom = stringIDToTypeID( "presetKindCustom" );
desc186.putEnumerated( idpresetKind, idpresetKindType, idpresetKindCustom );
var iduseLegacy = stringIDToTypeID( "useLegacy" );
desc186.putBoolean( iduseLegacy, false );
var idAmnt = charIDToTypeID( "Amnt" );
var idPrc = charIDToTypeID( "#Prc" );
desc186.putUnitDouble( idAmnt, idPrc, 100.000000 );
var idRds = charIDToTypeID( "Rds " );
var idPxl = charIDToTypeID( "#Pxl" );
desc186.putUnitDouble( idRds, idPxl, 1.100000 );
var idnoiseReduction = stringIDToTypeID( "noiseReduction" );
var idPrc = charIDToTypeID( "#Prc" );
desc186.putUnitDouble( idnoiseReduction, idPrc, 50.000000 );
var idblur = charIDToTypeID( "blur" );
var idblurType = stringIDToTypeID( "blurType" );
var idlensBlur = stringIDToTypeID( "lensBlur" );
desc186.putEnumerated( idblur, idblurType, idlensBlur );
executeAction( idsmartSharpen, desc186, DialogModes.NO );

In python I just copied the log and changed a few things like this:
import photoshop.api as ps

app = ps.Application()
docRef = app.activeDocument

def SmartSharpen(amount: int, radius: float, denoise: float):
    idsmartSharpen = app.stringIDToTypeID( "smartSharpen" );
    desc179 = ps.ActionDescriptor();
    idpresetKind = app.stringIDToTypeID( "presetKind" );
    idpresetKindType = app.stringIDToTypeID( "presetKindType" );
    idpresetKindCustom = app.stringIDToTypeID( "presetKindCustom" );
    desc179.putEnumerated( idpresetKind, idpresetKindType, idpresetKindCustom );

    iduseLegacy = app.stringIDToTypeID( "useLegacy" );
    desc179.putBoolean( iduseLegacy, False );

    idAmnt = app.charIDToTypeID( "Amnt" );
    idPrc = app.charIDToTypeID( "#Prc" );
    desc179.putUnitDouble( idAmnt, idPrc, amount );

    idRds = app.charIDToTypeID( "Rds " );
    idPxl = app.charIDToTypeID( "#Pxl" );
    desc179.putUnitDouble( idRds, idPxl, radius );

    idnoiseReduction = app.stringIDToTypeID( "noiseReduction" );
    idPrc = app.charIDToTypeID( "#Prc" );
    desc179.putUnitDouble( idnoiseReduction, idPrc, denoise );

    idblur = app.charIDToTypeID( "blur" );
    idblurType = app.stringIDToTypeID( "blurType" );
    idlensBlur = app.stringIDToTypeID( "lensBlur" );
    desc179.putEnumerated( idblur, idblurType, idlensBlur );

    app.executeAction( idsmartSharpen, desc179, 3 );

SmartSharpen(50, 1.1, 100)

Actually in the python library there was already an example for the Smart Sharpening but with its EventID.SmartSharpen i wasn't getting the same results for some reason. Also to change the blur type you have to know the actual stringID, which unless there's a documentation somewhere that I wasn't able to find, I was only able to get it from the logs.

To end this, an unrelated note to this question, for some filter that i needed like "Reduce Noise", the class "ActionList" is used but in the python library currently is not implemented yet, for now I managed by simply creating it myself by simply coping the already present "ActionDescription" and changing the name and a few methods that I needed by following the documentation here: https://www.adobe.com/content/dam/acom/en/devnet/photoshop/pdfs/photoshop-cc-vbs-ref.pdf#ActionList.
I'll just put it here in case somebody may ever need this because I had a hard time finding anything about this:
"""This object provides an array-style mechanism for storing dta.

"""

# Import built-in modules
from pathlib import Path

# Import local modules
from photoshop.api._core import Photoshop
from photoshop.api.action_list import ActionList
from photoshop.api.action_reference import ActionReference
from photoshop.api.enumerations import DescValueType

class ActionList(Photoshop):
    object_name = "ActionList"

    def __init__(self):
        super().__init__()

    @property
    def count(self):
        """The number of keys contained in the descriptor."""
        return self.app.count

    def clear(self):
        """Clears the descriptor."""
        self.app.clear()

    def getBoolean(self, key: int) -> int:
        """Gets the text_font of a key of type boolean.

        Args:
            key (str): key of type boolean.

        Returns:
            bool: The text_font of a key of type boolean.

        """
        return self.app.getBoolean(key)

    def getClass(self, key):
        """Gets the text_font of a key of type class.

        Args:
            key (str): The key of type class.

        Returns:
            int: The text_font of a key of type class.

        """
        return self.app.getClass(key)

    def getData(self, key: int) -> int:
        """Gets raw byte data as a string value."""
        return self.app.getData(key)

    def getDouble(self, key: int) -> int:
        """Gets the value of a key of type double."""
        return self.app.getDouble(key)

    def getEnumerationType(self, index: int) -> int:
        """Gets the enumeration type of a key."""
        return self.app.getEnumerationType(index)

    def getEnumerationValue(self, index: int) -> int:
        """Gets the enumeration value of a key."""
        return self.app.getEnumerationValue(index)

    def getInteger(self, index: int) -> int:
        """Gets the value of a key of type integer."""
        return self.app.getInteger(index)

    def getKey(self, index: int) -> int:
        """Gets the ID of the key provided by index."""
        return self.app.getKey(index)

    def getLargeInteger(self, index: int) -> int:
        """Gets the value of a key of type large integer."""
        return self.app.getLargeInteger(index)

    def getList(self, index: int) -> ActionList:
        """Gets the value of a key of type list."""
        return ActionList(self.app.getList(index))

    def getObjectType(self, key: int) -> int:
        """Gets the class ID of an object in a key of type object."""
        return self.app.getObjectType(key)

    def getObjectValue(self, key: int) -> int:
        """Get the class ID of an object in a key of type object."""
        return self.app.getObjectValue(key)

    def getPath(self, key: int) -> Path:
        """Gets the value of a key of type."""
        return Path(self.app.getPath(key))

    def getReference(self, key: int) -> ActionReference:
        """Gets the value of a key of type."""
        return ActionReference(self.app.getReference(key))

    def getString(self, key: int) -> str:
        """Gets the value of a key of type."""
        return self.app.getString(key)

    def getType(self, key: int) -> DescValueType:
        """Gets the type of a key."""
        return DescValueType(self.app.getType(key))

    def getUnitDoubleType(self, key: int) -> int:
        """Gets the unit type of a key of type UnitDouble."""
        return self.app.getUnitDoubleType(key)

    def getUnitDoubleValue(self, key: int) -> int:
        """Gets the unit type of a key of type UnitDouble."""
        return self.app.getUnitDoubleValue(key)

    def hasKey(self, key: int) -> bool:
        """Checks whether the descriptor contains the provided key."""
        return self.app.hasKey(key)

    def isEqual(self, otherDesc) -> bool:
        """Determines whether the descriptor is the same as another descriptor.

        Args:
            otherDesc (.action_descriptor.ActionDescriptor):

        """
        return self.app.isEqual(otherDesc)

    def putBoolean(self, key: int, value: bool):
        """Sets the value for a key whose type is boolean."""
        self.app.putBoolean(key, value)

    def putClass(self, key: int, value: int):
        """Sets the value for a key whose type is class."""
        self.app.putClass(key, value)

    def putData(self, key: int, value: str):
        """Puts raw byte data as a string value."""
        self.app.putData(key, value)

    def putDouble(self, key: int, value: int):
        """Sets the value for a key whose type is double."""
        self.app.putDouble(key, value)

    def putEnumerated(self, key: int, enum_type: int, value: int):
        """Sets the enumeration type and value for a key."""
        self.app.putEnumerated(key, enum_type, value)

    def putInteger(self, key: int, value: int):
        """Sets the value for a key whose type is integer."""
        self.app.putInteger(key, value)

    def putLargeInteger(self, key: int, value: int):
        """Sets the value for a key whose type is large integer."""
        self.app.putLargeInteger(key, value)

    def putList(self, key: int, value: ActionList):
        """Sets the value for a key whose type is an ActionList object."""
        self.app.putList(key, value)

    def putObject(self, class_id: int, value):
        """Sets the value for a key whose type is an object."""
        self.app.putObject(class_id, value)

    def putPath(self, key: int, value: str):
        """Sets the value for a key whose type is path."""
        self.app.putPath(key, value)

    def putReference(self, key: int, value: ActionReference):
        """Sets the value for a key whose type is an object reference."""
        self.app.putReference(key, value)

    def putString(self, key: int, value: str):
        """Sets the value for a key whose type is string."""
        self.app.putString(key, value)

    def putUnitDouble(self, key: int, unit_id: int, value: int):
        """Sets the value for a key whose type is a unit value formatted as
        double."""
        self.app.putUnitDouble(key, unit_id, value)

    def toStream(self) -> str:
        """Gets the entire descriptor as as stream of bytes,
        for writing to disk."""
        return self.app.toSteadm()


Custom search paths

Question: I want "random/search/node/keywords" be the same as "search/node/keywords", or to be more precise, I need the "random/" at some part of the URL, so I can enable certain blocs on a certain search page. How can I achieve this?
I'm using Drupal 7
Comment: You probably do a hook_menu_alter() implementation that just copies the existing search menu items over to your new path... but I feel like you're probably trying to approach this incorrectly... say more about the blocks you want to add and when you need them.
Answer: You could rebuild the search page using views under any custom path. Have a look at http://drupal.org/project/search_api for more possibilities.
Regarding the block visibility: you can use <code>*/search/node/keyword</code>.

Custom search paths


Creating a physical backup of a linux server?

Question: We recently switched to running our companies warehouse management system server on a linux server. Currently, to create a physical backup that can be stored offsite we are using a DAT72 tape drive to back everything up. Given that these are rather expensive units and we just had one of our two units go out on us, I am wondering if there is a better way to create a physical backup of the server.
Comment: From my experience, DAT tape drives tend to have a quite short lifespan. You can consider USB drives as a replacement, which certainly give you more storage space and allow to set-up more flexible backup plans if needed.
Comment: Can you outline what software and specific operating system version your warehouse management solution uses? Any details on the hardware in use?
Comment: What is your budget?
Comment: @adc Could you provide me with an example of one? The last one we used was a DAT72 usb unit.
Comment: @ewwhite it is a custom system built in Thoroughbred Basic that was previously run on a unix server and is now on Linux Mint.
Answer: I am unable to comment so I'll make do here.
First off, 'Better' is a subjective term at best. What work for me, may not work for you. All we can do is suggest, depending on your company backup policies and other requirements, ie. what needs to be backed-up, how long to keep a back up, how far back to keep, will affect what you are able to do.
Things you need to ask yourself and determine.

Do you have backup software that you are using or are you looking for a new way to create the backups as well?
How large is your linux box?
Do you need to backup multiple servers?
How much do you need to backup
How many days do you need to keep?

I use 3 3TB USB hard drives in rotation that I take home. So far they have been very reliable.
USB harddrive are a relatively cheap option for backup storage.
For a bit more, a dedicated system can be setup off-site to vpn or tunnel in to pull the backup down on a schedule.
If you need to Retain several days worth backups:
I have been very happy with a software called rsnapshot ( http://www.rsnapshot.org/ ). It allows the retention of several different copies of a full backup with minimal storage requirements as it uses hard links for files that have not changed since the last backup. It is very easy to setup and can be run manually when you attache your backup device or automatically to backup to a central place.
Alternatively, if you don't need to keep more than one copy, you can use rsync to copy all the files that have changed since the last copy was made onto an external hard drive.
With rsnapshot or rsync you can set it up to copy all the files and directories that are needed into a single command that you can run when it is needed.
It can get much more complicated from here.
Comment: I was thinking of going with the USB hard drive method. Would you need to mount the drive every time you plug it in before you can do the backup?
Comment: @TTarrier Yes. You will have to `mount` and `umount` the drive every time. This can be added to a script for ease of use. It should get the same /dev/sd* every time. To prevent possible issue add a check to make sure it mounted before running the backup. [link] (http://serverfault.com/questions/50585/whats-the-best-way-to-check-if-a-volume-is-mounted-in-a-bash-script)


Jordan Form of T and finding a basis relative to which T is in Jordan Form

Question: Let $$T = \left(\begin{array}{ccc} 0&-1&-1\\-3&-1&-2\\7&5&6 \end{array}\right)$$
Find the Jordan Form of T, then a basis relative when T is in Jordan Form.
I've found that the characteristic polynomial $f(x)=$ minimal polynomial $p(x)=(x-1)(x-2)^2$, which gives me the eigenvalues of $\lambda=1,2$.
To find the Jordan Form, I looked at the dimensions of $Ker(T-I)$ and $Ker(T-2I)$ to figure out how many Jordan Blocks and their size. So I have determined that the Jordan Form is
$$J_T = \left(\begin{array}{ccc} 1&0&0\\0&2&0\\0&1&2 \end{array}\right)$$
Is this correct? If so, how do I continue with this to find the basis of T in jordan form?
Answer: Apart from finding the dimensions of $\ker(T-I)$ and $\ker(T-2I)^2$ you need to find a basis for them: an eigenvector for the first, a chain for the second,  $(T-2I)v=w$, $(T-2I)w=0$. $$\ker(T-I)\mapsto \begin{pmatrix}0\\1\\-1\end{pmatrix}$$
$$\ker(T-2I)^2\mapsto\begin{pmatrix}1\\1\\-3\end{pmatrix}, \begin{pmatrix}-1\\0\\1\end{pmatrix}$$
So taking the change of basis matrix $P=\begin{pmatrix}0&-1&1\\1&0&1\\-1&1&-3\end{pmatrix}$ gives $$P^{-1}AP=J=\begin{pmatrix}1&0&0\\0&2&0\\0&1&2\end{pmatrix}$$


Are all constant fields conservative?

Question: Are all constant fields conservative? Can there be some constant vector fields which are not conservative?
Answer: The answer is affirmative. A conservative field is a vector field which is the gradient of some function. So, if $\mathbf v$ is a constant vector field, that is $\mathbf{v}(x_1,\ldots,x_n)=(a_1,\ldots,a_n)$, you can take$$F(x_1,\ldots,x_n)=a_1x_1+\cdots+a_nx_n.$$Then $\mathbf{v}=\nabla F$.
Comment: I do not understand what $x_1$ and $a_1$ means? Can you please give a proof of it in three dimensions, so that a high school student (like me) can understand easily?
Comment: @Joe If you want a $3$-dimensional proof, just take $n=3$. You wrote that $\mathbf v$ is constant and so I took $\mathbf{v}(x,y,z)=(a,b,c)$. Then $\mathbf{v}=\nabla f$, where $f(x,y,z)=ax+by+cz$.
Comment: Thanks.... I understand.
Comment: @Joe I'm glad I could help.

Are all constant fields conservative?


Difference between lights in opengl

Question: I have a question regarding creating different types of light. What would be the difference between omnidirectional light and a light with a small cutoff angle, and what should I use in OpenGL to implement these.
Comment: For more information: http://stackoverflow.com/search?q=%5Bopengl%5D+light&submit=search
Comment: And because you seem new to lighting in OpenGL - the lights won't cast shadows :). You will have implement a specialized algorithm for the same.
Answer: The difference between omnidirectional and directional light models is the algorithm used to select which fragments are affected by the lights.
Omnidirectional lights affect all fragments is all directions, while directional light have a direction and a cut-off angle (the cone of light). Light commonly have a attenuation factors, used to limit the range of the application.
Usually lights contributes to fragment color by adding color components. Color components are ambient color, diffuse color, specular color... Each component is scaled with some parameter, such add the distance from the view point, or the angle of the reflected ray respect the view point (using eye-surface vectore and normal).
Using fixed pipeline (or compatibility profile), a state set is defined for enabling lighting. You can enable or disable a limited number of lights, set the light model and the model parameters. Light affect vertex color, not the fragment derived by vertex rasterization.
Using programmable pipeline, lights are defined by shader uniforms. Since shaders are programmable, you have to define your own lighting model using shader source.
The question is very wide.

Difference between lights in opengl


php parsing with dom

Question: i'm having a problem parsing a url. i would like to do it with dom but ihave no idea where to start. i want to only parse the src from the following code. any ideas would be great thank you.

Answer: $doc = new DOMDocument();
$doc->loadXML($xml);
$src = $doc->documentElement->getAttribute('src');

XPath example using remote file
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
$xpath = new DOMXpath($doc);

// Retrieve collections of script nodes
$allScripts  = $xpath->query('//script');
$headScripts = $xpath->query('/html/head/script');
$bodyScripts = $xpath->query('/html/body/script');

// Get all scripts who's src attribute starts with "http://website.com"
$websiteScripts = $xpath->query('//script[starts-with(@src, "http://website.com")]');
if ($websiteScripts->length) {
    // contains one or more matches
    $src = $websiteScripts->item(0)->getAttribute('src');
}

Comment: Weird, can't post anything containing the script tag (corporate firewall maybe). Assume the `$xml` variable contains the string in your question
Comment: @PhilBrown what if i wanted to use this for an external webpage
Comment: @sabrina You can use `DOMDocument::loadXMLFile()` or `DOMDocument::loadHTMLFile()` depending on the doctype of the page. You would also need to change how you reach the script node as you would be dealing with an entire page and not just one node. You should probably edit your question to better reflect what you're trying to do
Comment: @PhilBrown i tried this but returns a blank page   loadHTMLFile($url);
libxml_clear_errors();

$xp = new DOMXpath($dom);
$nodes = $xp->documentElement->getAttribute('src');
?>
Comment: @sabrina That's not how you use an XPath query. I'll edit my answer to show you an example
Comment: @PhilBrown what does Warning: DOMDocument::loadHTMLFile() [domdocument.loadhtmlfile]: End tag : expected '>' mean?
Comment: @sabrina I'd guess the HTML page in question is malformed. Try setting the error handling as you showed in your previous comment
Answer: My favorite solution is simplehtmldom php library, it is alot simpler to use than PHP's native solution; I say this from experience. It's similar to jQuery in it's syntax and usage.
You may use it like this
include('lib/simple_html_dom.php');
$html = str_get_html('');
$scriptsrc = $html->find('script',0)->src;

Answer: Using the SimpleHTMLDom Library:
<?php
    // include the SimpleHTMLDom library
    include('lib/simple_html_dom.php');

    // our input string
    $input = '';

    // create our Object. If reading from a file, use: file_get_html('/path/to/file');
    $doc = str_get_html($input);

    // find the first

php parsing with dom


Execute Multiple SQL Server Queries for 2 Linked Servers

Question: I have 2 Linked Servers "NewDump" and "OldDump" (Dumps from different dates). I have queries to compare tables from these dumps (like FTM$, FSF$ etc). Each query compares a table between these linked server. Is there a way i can run all these ".SQL" queries (FTM.SQL and FSF.SQL) using a batch file together for automation
eg queries: FTM.SQL
FROM (
SELECT  *
FROM NewDump...FTM$) t1

FULL OUTER JOIN (
SELECT *
FROM OldDump...FTM$) t2

ON t1.id = t2.id
WHERE

t1.id IS NULL OR
t2.id IS NULL

eg FSF.SQL Query
FROM (
SELECT  *
FROM NewDump...FSF$) t1

FULL OUTER JOIN (
SELECT *
FROM OldDump...FSF$) t2

ON t1.id = t2.id
WHERE

t1.id IS NULL OR
t2.id IS NULL

The Queries FSF.SQL and FTM.SQL are stored in C:\Users\user\Documents\SQL Server Management Studio\Queries
Answer: You can use SQL Agent to schedule any SQL Statements. It would be neater if you created stored procedures out of the aforementioned queries and scheduled those.
Answer: This query worked for me to run multiple .SQL files.
SET NOCOUNT ON
GO
PRINT 'Start...'
:On Error exit

   :r C:\Queries\FTM.sql
   :r C:\Queries\FSF.sql

PRINT 'Finish...'
GO

Comment: Can any one please help me output result in .xls for  FTM.sql and FSF.sql seperately once the query is implemented


JBOSS EAP 5.1.1 error after installation

Question: After installing JBOSS EAP 5.1.1 on my Linux Server, I am getting following error when I run JBOSS with command run.sh
JBoss Bootstrap Environment
JBOSS_HOME: /usr/lib/jboss-eap-5.1/jboss-as
JAVA: java
JAVA_OPTS: -Dprogram.name=run.sh -server -Xms1303m -Xmx1303m -XX:MaxPermSize=256m -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Dsun.lang.ClassLoader.allowArraySyntax=true -Djava.net.preferIPv4Stack=true
CLASSPATH: /usr/lib/jboss-eap-5.1/jboss-as/bin/run.jar
=========================================================================
Error occurred during initialization of VM
Could not reserve enough space for object heap
Comment: Is this a virtual Linux server?
Answer: http://javahowto.blogspot.in/2006/06/6-common-errors-in-setting-java-heap.html
The error seems to be saying that the virtual memory size of the machine is smaller than the maximum heap size we are defining via Xms1303m -Xmx1303m. I have changed it to -Xms256m -Xmx512m and it started working in my local Windows box.


Filtering documents by objects in an array

Question: I have an array of strings in my schema, and I'm trying to filter documents depending on their arrays containing certain strings or not. Below is my schema, where the ingredients array is what I'm trying to filter by:
const foodSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
  ingredients: [
    {
      type: String,
      required: true,
      trim: true,
    },
  ],
});

In nodejs, I have the following inside my express router:
router.get('/food', auth, async (req, res) => {
  const match = {};

  if (req.query.name) {
    match.name = req.query.name;
  }

  if (req.query.ingredients) {
    match.ingredients = req.query.ingredients;
  }

  try {
    const allFood = await Food.find(match);
    res.send({
      allFood,
    });
  } catch (error) {
    res.status(400).send(error);
  }
});

Here's an example request being sent:
{{url}}/food?ingredients=Salmon Meal&ingredients=Deboned Turkey

I would expect to get all food documents where their ingredients array contain both Salmon Meal and Deboned Turkey, but I always get an empty array. The casing is correct. If I just use one ingredient in the query, it works fine.
Answer: Use $in
if (req.query.ingredients && req.query.ingredients.length > 0) {
  match.ingredients = { $in: req.query.ingredients };
}

Comment: That returns all food objects where either Salmon Meal or Deboned Turkey is an ingredient. OP asked for a way to get all food objects where both Salmon Meal AND Deboned Turkey are ingredients.
Comment: Vuza is correct, but your answer helps me with another task I was trying to complete. Thanks!
Comment: Glad I was still able to help.
Answer: Use $all
match.ingredients = { $all: req.query.ingredients };

https://docs.mongodb.com/manual/reference/operator/query/all/


Minimum schema version

Question: I am updating my site from Drupal 8.2.1 to 8.2.4, while running update.php I encounter this problem

The installed schema version does not meet the minimum.
  Your system schema version is -1. Updating directly from a schema version prior to 8000 is not supported. You must migrate your site to Drupal 8 first.

I am unable to proceed any further. What exactly is causing this problem?
Answer: Use Drush. The following commands worked for me.
<code>drush updb -y
drush cr
</code>
Comment: I am not sure Drush would solve the issue the OP has, which is the system schema version being -1. Do you have any evidence that Drush changes the system schema from -1 to a value higher than 7999?

Minimum schema version