How to dynamically populate select options?

Question: I'm trying to build an admin form for a module, using system_settings_form().
I want the users to be able to select sub-options, from a list that is dynamically generated depending on the main option.
For example
$main_options = array('foo','bar');
$sub_options['foo'] = array('foolish','football','foodstuff');
$sub_options['bar'] = array('barley','baroque','barbarian');

$form = array();

$form['main_option'] = array(
    '#type' => 'select',
    '#options' => $main_options,
);

$form['sub_option'] = array(
    '#type'  => 'select',
    '#options' => $sub_options[SOMEHOW USE THE SELECTED VALUE OF main_option AS INDEX],
);

return system_settings_form($form);

So I would expect sub_option to be unpopulated the first time the form is called, and then populated as soon as the user populates main_option.
Is this possible?
Update
Thanks for the advice re Ajax. I looked up https://www.drupal.org/node/752056 and this is what I've built: here the values in olt_test need to change based on the value selected for olt_provider.
  $form['olt_provider'] = array(
    '#type' => 'select',
    '#title' => t('Provider'),
    '#options' => variable_get('providers'),
    '#ajax' => array(
      'callback' => 'olt_provider_select_callback',
      'wrapper' => 'tests-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  $form['olt_test'] = array(
    '#type' => 'select',
    '#title' => t('Test'),
    '#prefix' => '
',
    '#options' => array(''),
  );

and in olt_provider_select_callback() I have
  function olt_provider_select_callback($form, $form_state) {

  $new_options_value = [new value calculation snipped]

  $form['olt_test'] = array(
    '#type' => 'select',
    '#title' => t('Test'),
    '#prefix' => '
',
    '#options' => $new_options_value,
  );

  return $form['olt_test'];
}

The problem I'm now seeing is that the Ajax only fires on the first time the olt_provider select box is clicked - subsequent clicks don't fire. Any thoughts?
The problem I'm now seeing is that although the olt_test dropdown is correctly updated via Ajax, this replacement value is not saved on form submission. Any thoughts?
Final Update - My form is working correctly now. The data was being saved on form submission, but I needed to add some more code to retrieve the saved data and display the default values when the form was loaded.
Comment: It is possible, but with Drupal AJAX. See #ajax in the form API.
Answer: As said before you could make use of Form APIs #states to display one element only after a certain input to another form element has been made. In your case you'd maybe go with two additional select lists, both initially hidden. Check form_examples_states_form() for more information.
$form['main'] = array(
  '#type' => 'select',
  // ...
);
$form['sub_a'] = array(
  '#type' => 'select',
  // ...
  '#states' => array(
    'visible' => array(
      ':input[name="main"]' => array('value' => 'foo'),
    ),
  ),
);
$form['sub_b'] = array(
  '#type' => 'select',
  // ...
  '#states' => array(
    'visible' => array(
      ':input[name="main"]' => array('value' => 'bar'),
    ),
  ),
);

Answer: Ajax would be the better way to get precisely what you are asking.  One important part of using the form ajax is if you dont tell it which part to rewrite, and which to return, it will rewrite the whole form.  It is easy to cause an Inception style recursion problem.  This is a pretty good explanation of the ajax.
An alternate, because I always like to provide them, is using form #states.  Most straightforward use of states would be if you have one sub_option select element for each of the main_options, or perhaps whole fieldsets.
Answer: There is an example of dependent drop-down in the developer examples.
function ajax_example_dependent_dropdown($form, &$form_state) {
  // Get the list of options to populate the first dropdown.
  $options_first = _ajax_example_get_first_dropdown_options();
  // If we have a value for the first dropdown from $form_state['values'] we use
  // this both as the default value for the first dropdown and also as a
  // parameter to pass to the function that retrieves the options for the
  // second dropdown.
  $selected = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : key($options_first);

  $form['dropdown_first'] = array(
    '#type' => 'select',
    '#title' => 'Instrument Type',
    '#options' => $options_first,
    '#default_value' => $selected,

    // Bind an ajax callback to the change event (which is the default for the
    // select form type) of the first dropdown. It will replace the second
    // dropdown when rebuilt.
    '#ajax' => array(

      // When 'event' occurs, Drupal will perform an ajax request in the
      // background. Usually the default value is sufficient (eg. change for
      // select elements), but valid values include any jQuery event,
      // most notably 'mousedown', 'blur', and 'submit'.
      // 'event' => 'change',
      'callback' => 'ajax_example_dependent_dropdown_callback',
      'wrapper' => 'dropdown-second-replace',
    ),
  );

  $form['dropdown_second'] = array(
    '#type' => 'select',
    '#title' => $options_first[$selected] . ' ' . t('Instruments'),

    // The entire enclosing div created here gets replaced when dropdown_first
    // is changed.
    '#prefix' => '
',
    '#suffix' => '
',

    // When the form is rebuilt during ajax processing, the $selected variable
    // will now have the new value and so the options will change.
    '#options' => _ajax_example_get_second_dropdown_options($selected),
    '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function ajax_example_dependent_dropdown_callback($form, $form_state) {
  return $form['dropdown_second'];
}

The purpose of the code is clear: The second drop-down element is populated of values that depend from the value the user selects from the first drop-down, using the following function.
function _ajax_example_get_second_dropdown_options($key = '') {
  $options = array(
    t('String') => drupal_map_assoc(array(
      t('Violin'),
      t('Viola'),
      t('Cello'),
      t('Double Bass'),
    )),
    t('Woodwind') => drupal_map_assoc(array(
      t('Flute'),
      t('Clarinet'),
      t('Oboe'),
      t('Bassoon'),
    )),
    t('Brass') => drupal_map_assoc(array(
      t('Trumpet'),
      t('Trombone'),
      t('French Horn'),
      t('Euphonium'),
    )),
    t('Percussion') => drupal_map_assoc(array(
      t('Bass Drum'),
      t('Timpani'),
      t('Snare Drum'),
      t('Tambourine'),
    )),
  );
  if (isset($options[$key])) {
    return $options[$key];
  }
  else {
    return array();
  }
}

The main difference with your code is that the AJAX callback just returns the form element that is dynamically changed; it's the form builder that changes the drop-down options. The most common error is changing a form element in the AJAX callback, which is not what Drupal expects it to do.
A note about using #states: For more simple cases, like hidding one or more elements basing on the value of another element, that is the perfect use case. In your case, supposing that the first drop-down element has N different values, using #states would mean having N+1 drop-downs, with just two being visible.
Considering also that each drop-down should have a different element id, the submission handler would be a little complicated to write. Differently, the submission handler for the example I show would just check $form_state['values']['dropdown_first'] and $form_state['values']['dropdown_second']. With the example given by leymannx, you should check the value of $form_state['values']['main'] to understand which of the other drop-down elements would contain the selected value.


CGI script runs when called directly, but not when it's the index

Question: Having never worked with CGI before (I'm a PHP person, really), I'm confused as to why my installation of Bugzilla won't display the index page correctly.
Before you ask:

libapache2-mod-fastcgi is installed on the machine
I have ExecCGI enabled for the directory in question
I added .cgi as a handler as a cgi-script

When I access the script directly (by going to index.cgi), the script parses and renders correctly. When accessing the web root, the contents of index.cgi are displayed in plain text.
Am I missing something?
Answer: You need to add index.cgi to the DirectoryIndex list:
<code>DirectoryIndex index.cgi
</code>
If you have some sort of redirect from / to index.cgi, remove it with this statement in effect.  I have not tested this, but this is how I used to handle index.php on my system, back when I used php.
Comment: Thanks! That did the trick. I used to have that problem with PHP, but I solved it so long ago, that I didn't even think it was the same problem! Heh.


When building app for visionOS only, code inside os(iOS) directive is used

Question: I have app which supports two destinations: iPhone and Apple Vision, both using their native SDKs (iOS, visionOS). When I need to wrap iOS-only code inside #if os(iOS) compiler directive and I try to build visionOS app, the code inside #if os(iOS) block is used as well.

The only way how I can tell compiler that this code is for iOS is by saying it is not for visionOS.

Why is that? Is visionOS some kind of sub-platform of iOS? I didn't find any documentation for it. I'm using Xcode 15.0 beta 5 and you can simulate it simply by creating new visionOS-only app.
Comment: Probably, similar to `macCatalyst`, I think Apple is trying to make it all work with little adapting.
Answer: Okay, it was probably just bug on Xcode 15.0 beta 5, on Xcode 15.0 beta 8 directives work as expected.


How do I get the days between the today's day and the last day of the month using Moment.js?

Question: Here's the code that I have right now:
  const moment = require('moment')
    const m = moment

    const currDay = m().format('D')
    const dayOfWeek = m().format('dddd')
    const daysInMonth = m().daysInMonth()

    const startOfMonth = moment().startOf('month').format('YYYY-MM-DD hh:mm');
    const endOfMonth   = moment().endOf('month').format('YYYY-MM-DD hh:mm');

I need to create a calendar row where the first item would be the todays date, and the rest of the calendar items would be the whatever amount of days are left depending on the current month so I could render each day in between in my HTML with Vue.
Example:  Wed 8, Thu 9, Fri 10 ... Fri 31.
Answer: I think the OP is tripped up on the common mistake of formatting prematurely. format is good to see an intermediate result, but doing so produces a string that's no good for additional calculation.
Try to handle date objects only. Convert to strings only when you must: (a) presenting to a human reader, or (b) serializing for storage or transmission.
Working without formatting...

const daysRemainingThisMonth = moment().endOf('month').diff(moment(), 'days');
console.log(`There are ${daysRemainingThisMonth} days remaining this month`)

Answer: Just as a POJS equivalent, if you have a function to return the last day of the month, you can use that and just get the difference between the two dates, e.g.

function getMonthEnd(date = new Date()) {
  return new Date(date.getFullYear(), date.getMonth() + 1, 0);
}

function getMonthDaysLeft(date = new Date()) {
  return getMonthEnd(date).getDate() - date.getDate();
}

let d = new Date();
console.log(`There are ${getMonthDaysLeft(d)} days left in ${d.toLocaleString('en',{month:'long'})}.`);

To get a list/array of the days remaining, just loop over a date, adding 1 day at a time, and write the dates in the required format into the list:

function getMonthDaysLeftAsList(date = new Date()) {
  let d = new Date(+date);
  // Formatter
  let f = new Intl.DateTimeFormat('en',{
    day: 'numeric',
    month: 'short'
  });
  let m = d.getMonth();
  let dayList = [];
  while (d.getMonth() == m) {
    dayList.push(f.format(d));
    d.setDate(d.getDate() + 1);
  }
  return dayList;
}

console.log(getMonthDaysLeftAsList());


Joining rows from two 2d arrays where a common column value is found

Question: I have two arrays that I would like to join into one.  Both arrays have a common key=>value and I would like to insert the values of one array to the other so that I to create one array.
$array1 = [
    ['ID' => 123456, 'Key' => 1000, 'value' => 123.45],
    ['ID' => 789012, 'Key' => 1001, 'value' => 56748.17],
];

$array2 = [
    ['Key' => 1000, 'description' => 'desc1'],
    ['Key' => 1001, 'description' => 'desc2'],
];

I would like to join Array2 with Array1 so that the resulting Array is as follows:
array (
  0 =>
  array (
    'ID' => 123456,
    'Key' => 1000,
    'value' => 123.45,
    'description' => 'desc1',
  ),
  1 =>
  array (
    'ID' => 789012,
    'Key' => 1001,
    'value' => 56748.17,
    'description' => 'desc2',
  ),
)

So the arrays have been joined using the [Key] value as the, well, key.  I've looked at array_merge and other function but I can't seem to get these two arrays to "merge" properly.
Comment: are these database search result? if yes, did you try joining on `Key` column?
Comment: A better [mcve] would provide array data that didn't also align by first level indexes and indicated what the desired result is when one of the arrays doesn't have a specific `Key`.
Answer: You would have to do something like
$result = array();

foreach ($a1 as $v1)
{
    foreach ($a2 as $k2 => $v2)
    {
        if ($v1['Key'] === $v2['Key'])
        {
            $result[] = array_merge($v1, $v2);
            unset($a2[$k2]);
            break;
        }
    }
}

Version with for loops
$result = array();

$c_a1 = count($a1);
$c_a2 = count($a2);

for ($i = 0; $i < $c_a1; $i++)
{
    for ($j = 0; $j < $c_a2; $j++)
    {
        if ($a1[$i]['Key'] === $a2[$j]['Key'])
        {
            $result[] = array_merge($a1[$i], $a2[$j]);
            unset($a2[$j]);
            $c_a2--;
            break;
        }
    }
}

Comment: @shiplu.mokadd.im I've added an unset to remove the ones who are uneeded after that.
Comment: `foreach` uses a copy of array. You should use `for` if you want to unset it.
Comment: @shiplu.mokadd.im The unset still works in this case, although `for` might be more interesting in this case indeed. I'll do something.
Comment: While there is less lines, I find this code less clearer. I guess that it's mostly about each-other's tastes!
Answer: try this, its linear
$keyval = array();

foreach($array1 as $item)$keyval[$item['Key']] = $item['value'];
foreach($array2 as $key=>$item)$array2[$key]['description'] = isset($keyval[$item['Key']]) ? $keyval[$item['Key']] : '';

Answer: @radashk's solution will work if you can always guarantee that $array1[$i] corresponds to $array2[$i].  From my reading of the question, that's not guaranteed, but instead you want to make sure that $array1[$i]['Key'] == $array2[$j]['Key'], and combine elements where those Keys match.
There may be a more elegant solution, but I would do it like this:
    // builds up new $tmpArray, using the Key as the index
$tmpArray = array();
foreach($array1 as $innerArray1){
            $tmpArray[$innerArray1['Key']] = $innerArray1;
}

    //Merges the values from $array2 into $tmpArray
foreach($array2 as $innerArray2) {
            if (isset($tmpArray[$innerArray2['Key']])) {
                $tmpArray[$innerArray2['Key']] = array_merge($tmpArray[$innerArray2['Key']], $innerArray2);
            }else{
                $tmpArray[$innerArray2['Key']] = $innerArray2;
            }

}

Comment: I get this error when I use the above code

PHP Parse error:  syntax error, unexpected ',', expecting ']'
Comment: @user1639319 - fixed it; had a missing bracket - also added some extra error checks
Answer: This is my approach:
$temp_ array = array_fill_keys (array_map(create_function('$a', 'return $a["Key"];'), $array_1) , $array_1);
$result = array();
foreach ($array_2 as $item) {
    if (isset($temp_array[$item['Key']])) {
        $result[] = array_merge($item, $temp_array[$item['Key']]);
    }
}

I have elaborated more in the code above, and reached this improved version:
function array_merge_items_by_common_key_value($key, $array_1, $array_2)
{
    $result = array();
    $temp_ array = array_fill_keys(array_map(create_function('$a', 'return $a["' . $key . '"];'), $array_1) , $array_1);
    foreach ($array_2 as $item)
    {
        $result[$item[$key]] = isset($temp_array[$item[$key]]) ? array_merge($item, $temp_array[$item[$key]]) : $item;
    }
    return array_values(array_merge($result, array_diff_key($array_1, $result)));
}

$merged_arrays = array_merge_items_by_common_key_value('Key', $temp_array, $array_2);

First, a temporary array is created: it is equal to $array_1, but its keys are the values to be matched.
Then, $array_2 is looped. When a match is found, the merge is done. If there is no match, then the $array_2 value is maintained, untouched.
Finally, those values in the $array_1 which were not matched, are also appended to the resulting array.
So, no item of both $array_1 or $array_2 is lost, while the matched items are merged.
Answer: Use temporary first level keys to swiftly identify matching Key values between the two arrays.  When an array2 row qualifies for merger with the first, use the union-assignment operator (+=).  Call array_value() after looping if you don't want to preserve the temporary keys.
Code: (Demo)
$result = array_column($array1, null, 'Key');
foreach ($array2 as $row) {
    if (isset($result[$row['Key']])) {
        $result[$row['Key']] += $row;
    }
}
var_export(array_values($result));


How to know which lines were selected from a DataTable

Question: I have a page with a "rich:DataTable". For each table row, added a checkbox to allow the user to select more than one line before excute an operation. How to retrieve the rows that were selected?
Answer: Just add a boolean  , maybe called selected , to the POJO that represents a row for the rich:DataTable . And bind this boolean to the <h:selectBooleanCheckbox> in the <rich:column> inside the <rich:dataTable>
For example , your beans , POJO and the view may look likes this:
<rich:dataTable value="#{myBean.customerList}" var="customer">
  <rich:column>
   <h:selectBooleanCheckbox value="#{customer.selected}" />
  </rich:column>
  <rich:column>
    <h:outputText value="#{customer.name}" />
  </rich:column>
  <rich:column>
    <h:outputText value="#{customer.address}" />
  </rich:column>
</rich:dataTable>

public class MyBean {

    private List<Customer> customerList;

    //getter and setter for the customerList
}

public class Customer{

    private boolean selected;
    private String name;
    private String address;

    //getter and setter for the properties
}

To retrieve the rows that were selected , just iterate the MyBean.customerList and check if the selected property of the Customer is true.
Answer: [SOLVED] I decided otherwise. Added a "Map " and a column with "CheckBox" this way: "". By submitting the form, the lines of "Map" that are selected will get the Boolean property equal "true".
My Bean:
public class Bean<T extends Object> {
    private Map<T, Boolean> selectedRowsMap = new HashMap<T, Boolean>(0);
    ...
    public Set<T> getSelectedRows() {
        selectedRows.clear();
        for (T key : getSelectedRowsMap().keySet()) {
            if (getSelectedRowsMap().get(key) == true){
                selectedRows.add(key);
            }
        }

        return selectedRows;
    }
}

My XHTML:
<rich:dataTable>
    <rich:column>
        <h:selectBooleanCheckbox value="#{bean.selectedRowsMap[row]}" />
    </rich:column>
    <rich:column>
        <h:outputText value="${row.age}" />
    </rich:column>
    ...
<rich:dataTable>


How to get a more major sound without going directly to major?

Question: So I am composing a piece for piano trio to represent the transition from winter to spring. I have finished the first part where it is all in minor, D minor to be more specific, to represent winter. It starts off with the piano representing snow with the staccato high notes and the violin and cello both representing the wind. Then the violin continues to represent the wind and the cello plays a somber melody to represent the person experiencing the wind and snow. Now, I want to have the music get a more major quality to it but I don't want to go directly to major. I want it to be gradual to represent the rise in temperature with a few bouts of minor to represent cold snaps.
How can I get this gradual move from minor to major in quality? Would I use modes like Dorian and Mixolydian, each of which is 1 step closer to the major scale? Would I simply introduce F# and C# while Bb is still being played or what? I want to keep the tonic of the piece as D while this minor to major transition is occurring.
EDIT:
Here is the progression that occurs in the winter theme:
Dm -> Gm -> Dm -> F -> Dm -> Gm -> Dm -> F -> Bb -> Gm -> Dm -> F -> Gm -> Dm
As you can see, it starts with the same 4 chords twice. Then the Bb chord is the place where it diverges from the original 4 chord progression.
Answer: I'll assume that "going to major" means shifting the key to full-blown D major, crucially making the D major chord the tonic chord.
Thus, one nice way to get a more major quality or sound without "going directly to major" is to make sure you use the (♯)6 scale degree instead of the (♭)6 scale degree, make sure you use only the leading tone (instead of the flattened subtonic) at that point, and to essentially borrow chords from the tonic major that use those scale degrees (e.g. IV, ii). Since V is such a common chord in minor-key passages, using it is NOT interpreted as getting a more major sound (and neither is using other leading tone-using chords), but using the flattened subtonic ((♭)7) without using the (♯)6 scale degree will ruin your chances of being interpreted as getting a more major sound because the flattened subtonic is not found in major keys. I still prefer avoiding the ♯3 scale degree at that point because that is THE scale degree hallmark of going to a major key. (This means that I'd avoid using the Mixolydian mode.)
With one manifestation of this (the use of the (♯)6 scale degree), you can argue that you'd be using the Dorian mode; you'd be correct.
Answer: Use modes! I'd recommend the Mixolydian mode or the Lydian mode, two modes which get rather close to Major without being Major.
The Lydian scale starts on the Fourth degree of the major scale and the 6th degree of the minor scale.
The mixolydian scale starts on the V of major and the VII of minor.
Overall, I'd recommend Mixolydian.
Answer: You could change some of your minor chords to m7 chords, e.g. Dm -> Dm7. Because the 7th of a minor chord is the 5th of its parallel major chord (F in this example) it sounds more majory.
Another option is to use maj7 chords. The Dm could be substituted by a Bbmaj7 which just adds an Bb to the Dm chord. Like in the example above the resulting tetrachord "includes" a minor chord and a major chord. Also Fmaj7 is possible which sounds less majory than a pure F because it includes also an Am.
Answer: I agree with @Alcathous...

First point I would make is to not overvalue the label 'major' and 'minor'.

But some things to consider:

modes: Dorian shifts closer to major mode, but I would be careful about thinking that a few accidentals closer to a major key will give you the effect you want, Dorian has a serious feel to me, Mixolydian a little forlorn, etc.
some kind of emphasis on the major triads: III, VI, & VII
you could try some chord planing around the major triad regions. These diatonic chords are the basic set III iv v VI VII or F gm am Bb C but you could use the raised forms of iv and v as F G A Bb C some parallel harmony in that region mixed in with the normal minor mode might provide some possibilities
first inversion minor triads seem a bit 'softer' to me, sort of less strongly minor, that might be exploited, 'v6/5' (minor dominant - a minor seventh chord in first inversion) would seem to be a good example of major/minor ambiguity in first inversion
incomplete chords could be a good strategy: what is Bb D or F A in D minor? typically they will probably sound as root position VI or III but could ambiguously be iv or i that could be exploited and of course the simple thirds are major.

Minor = cold, major = warm. That's a bit Mickey Mousing.
Why not rather motionless = cold, motion = warmth? What rhythmic devices can be used? What effect could be had with long rests after unresolved or ambiguous harmony to represent endless winter? You could explore similar things with range extremes, timbre, tempo, relative motion types, multi-voice texture, etc. Expression too. Bartok indicated sans vibrato in some of his quartets to create a desolate effect.
Answer: I have no idea what your music sounds like. First point I would make is to not overvalue the label 'major' and 'minor'. Major sounds as much like winter as it sounds like spring.
It can make a lot of sense to have a piece that stats in D minor and then ends in D major. You can repeat the same thematic material, but now with a major third, and it will sound different.
I wouldn't really explore modal music because modal music is modal and not functional. You state that you have music in D minor right now. So I assume you have harmonic movement. There are many keys you can modulate to leaving D minor before returning to the main theme ending in D major. The most obvious key to modulate to is A major (or A minor). And you can 'simply' return to D major after you are 'done'. How do you modulate? You play some chords that have only notes both keys share, then do a V-I cadence in the new key. You would need to change Bb to B, C to C#, F to F# and G to G#. Which is quite a lot, so you want to do it in a gentle way, or else the music will sound disconnected. If your music is now repeating a simple chord progression several times, and then goes meandering while the key of D minor is undermined and it is not clear what key it is, it will sound meandering. And if you don't just go Dm - G - F#m - E - A, but more gradual, it will not sound like there is a big disconnect.
Taking your current chord progression and repeating it while you change all Fs to F#s and/or Cs to C#s is likely to sound odd. And you will also have to ask if after doing so, D is still tonic and you aren't in G major. And your melody will sound out of whack if your tonic is suddenly different because the degrees of your melody also change. You ended your melody on a fifth, but now your fifth became a second. And ending a phrase on a second doesn't have same effect as ending on a fifth. And it will be even more obvious for a melody ending on the tonic.


How to make sshfs + VPN + git a tolerable working environment?

Question: Currently the code base for the project I am working on is remotely on a company server. and it has to stay like that. also the remote git repository cannot be made public.
My current setup is:

Connect to the VPN
run sshfs to mount a copy of the code
start working on the code
when I am done: ssh to the remote server and run git commands there

The problem with this, is that the VPN falls from time to time, so My sshfs mounth breaks, and my IDE freezes. what I do is to manually reconnect the VPN, then run sshfs again, and get back to work.
But it gets annoying as the VPN falls more often.
So I wonder if there are any settings for sshfs for some sort of cache, that would allow me to work, and only sync the changes when the VPN gets back.
That may make no sense, since if the remote driver is not available there is nothing to write to. So what about a different setup that uses some watch kind of thing and uses rsync to move changes in a bidirectional way (either when I save a file, or when I do git pull )
I can't just git clone, because I can't reproduce the entire environment to work 'locally' (DB and stuff)
the code has to be in their servers, in order for me to test/see my work I have to access a URL, that is my sandbox. I can't git push each time I want to see my changes.
Comment: Why don't you use `git` the sane way? Clone the repo, and work remotely.
Comment: Cripes, that's pretty broken.
Comment: I can't just git clone, because I can't reproduce the entire environment to work 'locally' the code has to be in their servers, in order for me to test/see my work. I have access a URL that is my sandbox. I can't git push each time I want to see my changes
Comment: How is it a bad question? its not like I can change their infrastructure, or take decisions over it, I just need a way to work with them remotely.
Answer: I am using this sshfs options to minimize latency:
sshfs -o Ciphers=arcfour,compression=no,nonempty,auto_cache,reconnect,workaround=all firstname.lastname@example.com:/usr/local/gitdev/ ~/dev/code

It has the reconnect flag, all sshfs workarounds, using auto cache and arcfour chiper.
You can read about those options on sshfs manual, I found those the fastest sshfs options at least to my setup.
ETA: More on sshfs performance read here: sshfs performance
Comment: unknown workaround: 'all'
Answer: zecrazytux is right -- Why don't you use git the way you're supposed to: by cloning the repository, working on it remotely, and pushing the changes back to the master?
I see no reason you "can't" git push your work each time you want to see your changes (ideally pushing to a development branch that then gets merged when it's tested and proven working) -- lots of people do this. You can even use a post-receive hook to deploy your changes into the environment if you want to automate that part of things.
(You obviously don't WANT to do this, but you haven't given any reason why so I reject the premise of your problem.)

Frankly there's nothing you can do to make an unreliable network connection "tolerable" (ESPECIALLY if you're trying to mount network filesystems) -- you can either work remotely as outlined above, SSH into the system and work directly on it (screen is your friend here), or investigate and fix the underlying network instability.
Trying to do something else to "make it tolerable" is an exercise in futility (think "cocktail umbrella in a hurricane").
Comment: The reason is, we have redmine and each commit should have a specific format. so a bunch of commits is not acceptable for a single task. Also having to do git commit + push, before going to the browser and do a refresh (F5), would make it less tolerable than it is now.

Imagine having to commit + push, just because I missed a semicolon (I'm exagerating, but you get the idea)
Comment: `we have redmine and each commit should have a specific format` <-- So when you merge the development branch format the commit for the merge the way redmine expects it. `git` is flexible like that :-)
Comment: The missing semicolon thing is simple: Don't make mistakes (I'm exaggerating, but you get the idea - you can run static syntax checks against your stuff before you push to eliminate little things like that, and since Redmine is only going to see the merge-down commit nobody needs to know the horrors that happened in your dev branch anyway) -- otherwise we're back to "work remotely, use `screen` for when the connection dies"
Comment: that could be true, but I'm still left with having to commit+push to see the changes, off course I use syntax checkers, you didn't get the idea. but you know that when working in web apps, you need to do a lot of page refresh when working on something, again commit+puhs would make it less tolerable than it is now.
Comment: You should be able to have this setup: origin → remote clone → local clone.  A push from the local clone will be done to the remote clone (and is not restricted by any redmine stuff).  When you are in a state which seems proper for redmine, you can push the remote clone to origin.
Answer: I have phpstorm IDE over vpn + sshfs from home and it's git which is slow, scanning lots of files.
I use https://github.com/ericpruitt/sshfsexec with my ide or my terminal and all local commands are executed as ssh remote commands automatically and it's faster.
After install it, on PHPSTORM : settings>Git > path to git executable => /home/username/bin/sshfsexec/git
Answer: I recently use mutagen instead of sshfs it's much better when working on unstable connection.
https://github.com/mutagen-io/mutagen
mutagen sync create --name=test --default-owner-beta="USER_HERE" --default-group-beta="GROUP_HERE" --mode=two-way-resolved /localhost/path/to/code firstname.lastname@example.com:/remote/path/to/code

Make sure you install the agent on the remote dev server.
Cheers


Gradient from non-trainable weights function

Question: I'm trying to implement a self-written loss function. My pipeline is as follows
x -> {constant computation} = x_feature -> machine learning training -> y_feature -> {constant computation} = y_produced
These "constant computations" are necessary to bring out the differences between the desired o/p and produced o/p.
So if I take the L2 norm of the y_produced and y_original, how should I incorporate this loss in the original loss.
Please Note that y_produced has a different dimension than y_feature.
Comment: what is your original loss? which language you are using? if you have two loss variable, you can simple add them.
Comment: My original loss functions deal with the y_feature and x_feature, but I'm not getting the desired training by using those loss values so I'm amplifying their effect using constant computations, which changes the dimension as well. These dimension changes are not an option. Language is Python and whole setup is in tensorflow.  @WasiAhmad
Comment: To be more specific these constant computations involve Fourier transforms and a little more @WasiAhmad
Answer: As long as you are using differentiable operations there is no difference between "constant transformations" and "learnable ones". There is no such distinction, look even at the linear layer of a neural net
f(x) = sigmoid( W * x + b )

is it constant or learnable? W and b are trained, but "sigmoid" is not, yet gradient flows the same way, no matter if something is a variable or not. In particular gradient wrt. to x is the same for
g(x) = sigmoid( A * x + c )

where A and c are constants.
The only problem you will encounter is using non-differentiable operations, such as: argmax, sorting, indexing, sampling etc. these operations do not have a well defined gradient thus you cannot directly use first order optimisers with them. As long as you stick with the differentiable ones - the problem described does not really exist - there is no difference between "constant transromations" and any other transformations - no matter change of the size etc.
Comment: I'm writing the whole computation in tensorflow right now, will ask for more help if that code involves something not differentiable.
If that function involves something non-differentiable, we won't introduce those gradient right?
Comment: Gradient should become None, however there might be also implemented to constantly return 0 which might be more tricky. In either way you end up with *improper* optimisation then. It is not 'just a missing bit', it would actually lead to no convergence guarantees (if you have some non-differentiable path in your model, gradient descent can fail to learn anything, it can cycle, blow up etc.)


Como fazer um sistema de pesquisa com Urls Amigaveis

Question: Olá, eu gostaria de fazer um sistema de pesquisa com Urls amigáveis, pesquisei bastante e tentei muitas coisas, não ainda não consegui.
Gostaria que a url ficasse desta form site.com/home/categoria/pesquisa.
home.php
<form method="POST" class="floatLeft formSearch" action="home/go">

        <input type="text" name="searchInput" class="searchInput floatLeft">
        <select name="categorySearch" maxlength="255" class="categorySearch floatLeft">
                <option value="Todos" selected="selected">Todos</option>
                <option value="Serie">Serie</option>
                <option value="Filme">Filme</option>
                <option value="Anime">Anime</option>
                <option value="Filme Adulto">Filme Adulto</option>
                <option value="Desenho">Desenho</option>
                <option value="Software">Software</option>
                <option value="Jogos">Jogos</option>
        </select>
        <input type="image" name="submitSearch" src="<?=DIR_IMAGES ?>lupa.png" class="submitSearch floatLeft">

</form>
require DIR_FUNCS.'/funcSQL.php';
$sql = new SQL();

if(isset($_POST['submitSearch']))
{
    if(isset($_GET['go']))
    {
        if(preg_match("^/[A-Za-z]+/", $_POST['searchInput']))
        {
            $search = $_POST['searchInput'];
            echo $search;
            $sql->listTorrentSearch($search, "Todos");
        }
    }
}

FuncSQL.php
public function listTorrentSearch($search, $category)
{
    $conn = $this->openSQL();
    $cont = 0;

    if($category == "Todos")
    {
        $result = mysqli_query($conn, "SELECT * FROM torrents WHERE Nome LIKE '".$search."%'");
    }
    else
    {
        $result = mysqli_query($conn, "SELECT * FROM torrents WHERE Nome LIKE '".$search."%' AND Categoria='".$category."'");
    }

    while($row = mysqli_fetch_array($result))
    {

        if($cont < 25)
        {
        $name = $row['Nome'];
        $category = $row['Categoria'];
        $size = $row['Size'];
        $magnet = $row['Magnet'];

        $createTorrentClass = new CreateTorrent();

        $createTorrentClass->createTorrentDiv($name, $category, $size, $magnet);

        $cont++;
        }
    }

    mysqli_close($conn);
}

.htacess
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1

tratarUrl.php
$pUrl = strip_tags(trim(filter_input(INPUT_GET, 'url', FILTER_DEFAULT)));
$sUrl = (empty($pUrl) ? "index" : $pUrl);
$url = array_filter(explode('/', $sUrl));

if (count($url) > 1) {
$cont = 1;
foreach ($url as $arg) {
    define("PARAM" . $cont, $arg);
    $cont++;
}
} else if (count($url) == 1) {
if (file_exists(DIR_PAGES . $url[0] . '.php')) {
    $pag = DIR_PAGES . $url[0] . '.php';
} else {
    if($url[0] != 'index')
    {
        $pag = DIR_PAGES . '404.php';
    }
    else
    {
        $pag = DIR_PAGES . 'home.php';
    }
}
} else {
$pag = DIR_PAGES . '404.php';
}

Answer: Lucas,
Nesse blog tem uma explicação bem completa, mas resumindo você deverá fazer o seguinte:
Você precisa marcar os endereços atuais do seu site e como você quer que eles fiquem. Siga um padrão para manter as mesmas informações organizadas. Exemplos:

http://meusite.com/produtos.php?id=8 (URL atual)
http://meusite.com/produtos/tenis/8/ (Nova URL)

Vamos começar com o exemplo da página de contato que atualmente você acessa pelo endereço http://www.meusite.com.br/contato.php.
Vá até a raiz do seu site e edite ou crie um arquivo chamado .htaccess.
Coloque as seguintes linhas:
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^contato/?$ /contato.php [NC,L]
</IfModule>

O IfModule é como um bloco de condição que verifica se um certo módulo existe e está habilitado.
A regra é escrita pelo RewriteRule:
RewriteRule ^contato/?$/contato.php [NC,L]

A validação da URL é feita via expressão regular, o circunflexo ^ significa "inicio", o cifrão $ significa "fim" e a parte /? significa uma barra opcional, ou seja: A reescrita acontecerá para as URLs meusite.com.br/contato e meusite.com.br/contato/.
Na parte /contato.php informamos para o servidor qual arquivo atenderá pela requisição. Preste atenção que é nessa parte que dizemos ao servidor qual o formato da nossa antiga URL.
Na parte [NC,L] há  flags, o NC de "no case" (ignora a diferença entre maiúsculas e minúsculas) e L de "last" faz com que se essa regra for utilizada, nenhuma outra regra seja usada.
Se você quiser aprender mais sobre flags, recomendo a leitura da documentação do Apache.
Se quiser trabalahar com URLs mais complexas, que contenham valores variáveis como o exemplo meusite.com/produtos/tenis/ verifique aqui:

http://blog.thiagobelem.net/aprendendo-urls-amigaveis-com-regras-complexas
Comment: Olá, dei uma olhada no tutorial, quando eu uso a regra `RewriteRule ^(.*)$ index.php?s=3&c=5` e acesso `site.com/?s=3&c=2` ele retorna `3 e 5`, porem quando eu uso a regra `RewriteRule ^(.*)$ index.php?s=$1&c=$2` e acesso o mesmo site, ele retorna `index.php e vazio`.
Comment: @LucasCarezia você quer redirecionar site.com/?s=3&c=2 para o que? Para site.com/index/ ou site.com/3/2 ou outro destino?
Comment: RewriteRule ^index/([0-9-]+)/([0-9]+)/?$ /index.php?s=$1&c=$2 [NC]
Comment: O exemplo acima deverá transformar sua URL em index/1/2/


AWS - Using CloudWatch to trigger script on ec2 instance

Question: I've found a lot of similar questions but none that seem to be specific to my question here: I have a python script that deletes old log files. I have Cloudwatch to monitor available storage, is it possible to trigger that script (IE, run this command: python mypythonscript.py) when alarm is triggered.
From all my research this does not appear to be possible unless we developed a system that interpreted the emails sent by CloudWatch and SNS and then run a script based on that interpretation.
The goal is self-healing this issue when it alarms, but from what we've gathered it doesn't appear to be possible that CloudWatch itself can trigger anything to happen on the EC2 instance. If this is true, I'm just looking for confirmation from people smarter than I!
Thanks!
Answer: CloudWatch, by itself, cannot run a command on your EC2 instance. You could however combine CloudWatch with some other AWS services to accomplish your goal. The way I would recommend accomplishing this is the following:

Create an AWS EC2 Run Command that executes your Python script.
Create an AWS Lambda function that invokes the Run Command when called.
Configure the Lambda function to use the CloudWatch alerts SNS topic as a trigger.
Comment: Thanks for this Mark! This helps clarify what we can do to create a self-healing monitoring system for our platform. I appreciate the assistance!
Answer: Or you can use
CloudWatch Events for execute Run Command:
https://docs.aws.amazon.com/systems-manager/latest/userguide/rc-cwe.html
Answer: To expand on @Viviane's answer: Create an EventBridge event. Have it trigger off a custom event pattern to match your CloudWatch events of interest (these events are auto-pub'd to EventBridge). These links helped me:

https://docs.aws.amazon.com/eventbridge/latest/userguide/filtering-examples-structure.html
https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-and-eventbridge.html


How do inversions of extended chords work?

Question: I am trying to understand what is the main difference between inversions and voicings, The way I see it is that the inversion will establish the lowest note on a chord, while the voicing is the specific arrangement of harmonics used when playing that chord.
But this becomes blurry in my mind when using extended chords. Can someone please explain how inversions work with extended chords?
Comment: Inversions can also have different voicings, not just chords with the root as the lowest note. https://www.musictheory.net/lessons/51
Comment: Voicings maintain the root as the lowest note of the chord, and inversions do not (the notes are inverted.)
Comment: [Identifying "Drop chords" from a given voicing](https://music.stackexchange.com/questions/84162/identifying-drop-chords-from-a-given-voicing) has nice answers on drop voicing you might find useful.
Comment: @wabisabied - are you sure that's correct?
Comment: @Tim it's what I'd come to understand, but delving further into it, including reading your answer, seems to indicate I've over-simplified, at best. Thanks for the call-out.
Answer: One just gets more inversions. With  7th chords, there are 4 inversions; any note can be in the bass. Inversion of chords does not specify the disposition of upper voices (in general.) There is an exception in that 9th chords almost always have the 9th above the root. For chords with more than 5 tones, it's not always the case that the object is a chord; it could be a simpler chord with non-chord tones added (not uncommon).
Answer: In theory, inverting an extended chord works the same as inverting a simple triad, except that more inversions are possible.  In practice, however, notes are usually omitted from extended chords to avoid jarring dissonances, so not all of the inversions are seen in the wild.
13th chords are usually in root position because their inversions are academic.
Because all 7 notes of the scale are present in a 13th chord (at least in theory), inverting it has the effect of turning it into a different 13th chord.
To touch on the distinction between inversion and voicing:  A chord's inversion will only tell you which note is in the bass.  It doesn't say anything else about it.  A chord's voicing is a more complete picture that would include the inversion as well as other characteristics.  The term voicing is often used in the context of a particular instrument, e.g. piano voicings or guitar voicings, and therefore include a consideration of what is idiomatic for that instrument.
Other characteristics which factor into the voicing are (not necessarily exhaustive):

which order (top to bottom) do the notes appear in?
what is the spacing between the notes?
which notes (if any) have been omitted?
which notes (if any) have been doubled?
in ensemble settings, which instruments are playing which notes in which registers? (i.e. orchestration)
Answer:
The way I see it is that the inversion will establish the lowest note on a chord, while the voicing is the specific arangement of harmonics used when playing that chord.

That right.

But this becomes blurry in my mind when using extended chords.

Let's first point out that seventh chords can put any chord tone into the bass including the seventh. Ex. C: V4/2 would be F G B D with the seventh in the bass, typically resolving down to the third of the tonic chord in I6. Without question that is totally conventional harmony.
Now let's consider extensions to be the intervals high than the seventh: ninths, elevenths, and thirteenths. The seventh should be present with those extensions so they aren't mixed up with simple intervals add2, sus4, add6, etc.
The conventional treatment would be to place the extensions above the chord root. (Walter Piston's Harmony is my source for that point. His text is concern with roughly Bach to Brahms with later Romantics like Grieg and Dvorak, so fairly conservative.) I think the rationale is that putting the extensions in the bass can give the impression of other chords with some added non-chord tones or their own extensions!
Consider a basic G7 and the extensions above. Put the ninth in the bass and it sounds like an Am9 on the bottom with two appoggiaturas, put the eleventh in the bass and it sounds like a Cmaj9, put the thirteenth in the bass and it sounds like an Em7 with a b9 or a non-chord tone of some kind.
So for all practical purposes, conventional handling sets the inversion "limit" at third inversion. And for clarity's sake put the extensions above the root, but you probably have a lot of freedom with the specifics of the voices above the root.
Answer: Exactly the same way as with simple chords, just more possible inversions.
Having said that, anything beyond the 7th in a 'pile-of-thirds' type extended chord is almost always going to be in the upper structure, not as the bass note.  C, C/E, C/G, C/B♭ (call it C7/B♭ if you like) are commonplace.   C9/D, C7(#11)/F# and C13/A are less likely.
If you're thinking in guitar terms, and there's a bass player, there may be little point it thinking of 'inversions' in what YOU play, just 'voicings'. It doesn't matter so much whether you're playing C E G, E G C, G C E or an open voicing if the bass is hitting (say) an E.   Whatever YOU do, musically it's a first inversion.
Answer: There is some crossover. Inversions (and root position) will tell what note is at the bottom - in C major triad, C as bass will be root, E as bass will be 1st inversion, and G as bass will be 2nd inversion. It matters not which order the other two are, above the lowest note.
The more notes added to that triad (7ths, 9ths, 11ths, 13ths, and their ♭/♯ alterations), the more inversions there can be. Obviously, with a 5 note chord, there are 5 different choices for which note is at the bottom. Again, order of other notes (or even lack of them) won't affect the naming of that inversion. Some may not sound good - but that's a different kettle of fish!
Voicings - open or closed? Closed voicings occur when each and every note is as close to the next (up and down) that it can be. Open voicings use whatever notes are appropriate, but will not use every consecutive note from that chord. All voicings are subject to root or inversions. They can have any of the approriate notes, in any order. They can double or treble certain notes. On guitar, it's common on chords such as open E to play three root notes.
So, whilst being closely related, they're not the same, although they do both contribute to information about a chord, they are not synonymous. Every voicing will also have a label for its inversion, but an inversion tells us little about the voicing.
Check out slash chords, drop voicing. And be aware that in certain circumstances, 3rd, 4th, 5th inversions won't necessarily sound good. In others, they work really well...


Custom ckeditor fileUpload in java with apache fileUpload parseRequest returns empty list

Question: I have a seam 2.2.2 application and I'm trying to customize ckeditor fileUpload plugin to it.
The solution I've come up is:
1) init the editor for all elements with 'editor' style class:
var elements = CKEDITOR.document.find('.editor');
for(var i = 0; i< elements["$"].length; i++){
        CKEDITOR.replace(elements["$"][i], {
            filebrowserUploadUrl: rootPath + "/cops/filebrowserUploadUrl.seam"
        });
    }

2) Set filebrowserUploadUrl.seam, to do nothing but to execute:
#{attachmentController.sendImageToServer()}

3) implement the back-end with apache commons fileUpload:
public void sendImageToServer()
{
    HttpServletRequest request = ServletContexts.instance().getRequest();
    DiskFileItemFactory factory = new DiskFileItemFactory();

    File repository = (File) request.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);
    ServletFileUpload upload = new ServletFileUpload(factory);

    try
    {
        List<FileItem> items = upload.parseRequest(request);
        processItems(items); //set the file data to specific att
        saveOpenAttachment(); //save the file to disk
    }

This method is called all right. I can debbug an upload parameter (with some binary data) inside the request but upload.parseRequest(request) returns an empty list. I have searched this problem and I did everything I could do but I am not able to tell if the application custom FaceletViewHandler is causing this.
Although if I could find the solution to this problem I would be very satisfied, I'm feeling this is not a good solution. Maybe the integration of Seam with facelets could give me a better solution. I really don't know.
Any suggestion?
Comment: I get the suggestion working by doing List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request) at the bean and setting   in my components.xml. But still a doubt: any other url-pattern crashes it. Does anyone know why?
Answer: Final solution was like Seam multipart filter handle requests:
ServletRequest request = (ServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
try
{
  if (!(request instanceof MultipartRequest))
  {
     request = unwrapMultipartRequest(request);
  }

  if (request instanceof MultipartRequest)
  {
     MultipartRequest multipartRequest = (MultipartRequest) request;

     String clientId = "upload";
     setFileData(multipartRequest.getFileBytes(clientId));
     setFileContentType(multipartRequest.getFileContentType(clientId));
     setFileName(multipartRequest.getFileName(clientId));
     saveOpenAttachment();
  }
}

Now I handle the request like Seam does, and do not need the web:multipart-filter config that was breaking other types of request.


When is a function one-to-one?

Question: I am going crazy over a statement that is supposed to be false.
"A function T: R^n -> R^m is one-to-one if the only vector v in R^n whose image is 0 is v = 0"
I thought this was true since otherwise if there was another vector u that did not equal the zero vector but whose image was the zero vector then f(u) and f(v) would not be distinct and hence the function not one-to-one. This also explains why the null space consisting of only the zero vector makes the function one-to-one. For if in the RREF there were free variable(s) then the generating set for the null space would not only be the zero vector. Multiple vectors of R^n would equal the zero vector of R^m and hence the function would not be one-to-one.
Where does my logic break?
Comment: Do you talk about arbitrary functions or *linear* functions?
Comment: It doesnt specify, it states only what i wrote. I was actually wondering if it was a trick question and the book left it ambiguous on purpose. However in terms of the section and chapter that i am on, it is about linear functions/linear transformations.
Answer: The definition of being one to one is: if $f(x)=f(y)$ then $x=y$.
This definition is for functions. The statement you are posting don't work for functions in general, it's works for a special kind of functions called linear (maybe linear transformation in your case). Then
If $T$ is just a function: this is false. Take $T:\Bbb{R}\to\Bbb{R}$ such that $T(0)=0$ and $T(x)=1$ if $x\neq 0$.
If $T$ is linear: this is true. Suppose that the unique vector $\mathbf{v}$ such that $T(\mathbf{v})=0$ is $\mathbf{v}=0$. If $T(\mathbf{v})=T(\mathbf{w})$ then $T(\mathbf{v})-T(\mathbf{w})=0$, so $T(\mathbf{v-w})=0$ which implies $\mathbf{v}=\mathbf{w}$ and $T$ is one to one. The other direction is clear.
Comment: How does your explanation of T not being linear function with T(0)=0 and T(x)=1 where x!=0 explains why T is not one-to-one. Shouldnt you try to show something along the lines of a none linear function T where T(0)=0 and T(x)=0 where x!=0? Also it would help to give an example of such a function T.
Comment: @Bubbletea He's trying to point out that for non-linear functions, the condition "$T(x)=0$ has only the solution $x =0$" is not enough to prove one-to-one-ness. So he needs a function that _fulfills that condition_, but still isn't one-to-one. Therefore, for $T$ to be a true example of what he wants to show, $T(x)$ has to be something other than $0$ (say, for instance $1$) when $x \neq 0$.
Answer: Now it depends on the definition of one-to-one. For me one-to-one means that
the mapping is injective and surjective. So $T: R \to R^2, x\mapsto (x,0)$ would not be one-to-one in this definition.
Since it is said in a comment that this does not answer the question: The question is why a -- I guess linear -- mapping from $R^m$ to $R^n$ can be not one-to-one if only the zero vector is mapped into the zero vector. If an one-to-one correspondence is meant as I suppose here, it gives an example and answers the question.
Comment: According to [wikipedia](http://en.wikipedia.org/wiki/One-to-one), a one-to-one _function_ is injective, while a one-to-one _correspondence_ is bijective. Not that wikipedia decides the standard in any way, but I think that's the common interpretation.
Comment: @Arthur, ok,  but then the statement the OP asks about, would be true, or? I would say, here it depends on the *exact wording* and the used definitions.
Comment: And you're right that knowing the exact definitions is important to answering this question, but that would make this answer more suited as a comment (it does not answer the question, it asks for clarification).

When is a function one-to-one?


Is there an idempotent element in a finite semigroup?

Question: Let $(G,\cdot)$ be a non-empty finite semigroup. Is there any $a\in G$ such that:
$$a^2=a$$
It seems to be true in view of theorem 2.2.1 page 97 of this book (I'm not sure).  But is there an elementary proof?

Theorem 2.2.1. [R. Ellis] Let $S$ be a compact right topological semigroup. Then there exists an idempotent in it.

This theorem is also known as Ellis–Numakura lemma.
Comment: "Pages 77 to 99 are not shown in this preview". Do you have another link?
Comment: See also [this post on MO](http://mathoverflow.net/questions/42512/awfully-sophisticated-proof-for-simple-facts/45372#45372) and the comments there.
Answer: Note first that it suffices to prove that $a^k = a$ for some $k \geq 2$. If $k = 2$ we are done. Otherwise $k > 2$ and multiplying both sides by $a^{k-2}$ gives $(a^{k-1})^2 = a^{k-1}$.
Fix $x \in G$ and consider the sequence
$$x, x^2, x^4, x^8, x^{16}, \ldots$$
Since $G$ is finite, there is repetition in this sequence. That is, $x^{2^t} = x^{2^s}$ for some integers $t > s \geq 1$. Thus $x^{2^t} = (x^{2^s})^{2^{t-s}} = x^{2^s}$, so choosing $a = x^{2^{s}}$ and $k = 2^{t-s}$ gives $a^k = a$. Note that $k \geq 2$ since $t > s$.
Comment: Excellent answer +1
Answer: Pick an arbitrary element and start iterating $x\mapsto x^2$. Since the semigroup is finite you will eventually hit a cycle. This gives you a $b$ such that $b^k=b$ for some $k\ge 2$. Now set $a=b^{k-1}$.
Answer: You can find a proof $^1$ of the following theorem, from which your assertion follows, at Proof Wiki
Finite Semigroup: Exists Idempotent Power

Theorem
Let $(S,\circ)$ be a finite semigroup.
For every element in $(S,\circ),$ there is a power of that element which is idempotent.
That is: $$\forall x \in S:\exists i \in \mathbb N:x^i=x^i\circ x^i$$

Essentially, then, for your purposes: you can simply set $a = x^i$, and you have the existence of an idempotent element $a \in S$ such that $\;a^2 = a$.
$1.$ Source of proof: Thomas A. Whitelaw: An Introduction to Abstract Algebra (1978).
Comment: assume we know every finite element in a semigroup $S$ has an idempotent. Then for each $a$ in $S$ , $\{a^n \mid n\in \Bbb N \}$ is a semigroup. So it has an idempotent, say $a^k$. $a^ka^k=a^k$ for some $k$.
Comment: You asked about whether there exists an element in each semigroup...such that it is idempotent. We don't know that for each x $x \circ x = x$, we only know (from the theorem) that for each $x$, exists a ***power*** $i$ of $x$ such that $x^i\circ x^i = x^i$...that's what the theorem above states. From that we know that exists $y = x^i$ such that $y\circ y = y$, we don't know that for all $a$ in the semigroup, $a\circ a = a$. The assumption that "every finite element in a semigroup has [**a power that is**] an idempotent" is NOT to say ever finite element in a semigroup *is* idempotent.
Comment: N.B. [Proof Wiki](http://www.proofwiki.org/wiki/Main_Page) is a great resource when looking for a proof, or an alternative proof, to mathematical proofs. (Link is to "main page").
Comment: I do not agree with "stronger, and more general". Because it's a simple consequence of the question.
Comment: @CutieKrait: Actually, no, this theorem talks about every element of a finite semigroup, not just the existence of some element such that... Your question and its answer follow from the theorem above. Besides, the point of my post was not to argue the merits of the theorem or your question, the point of my post was to simply offer help.
Comment: Actually, CutieKrait, I think we're splitting hairs. Your observation (in your post) was astute, and the answer you accepted provides the essentials of the proof (which happens to be the proof to which I linked you), with the added observation that we can obtain an idempotent element in any finite semigroup by equating it with the idempotent power of another element.
Comment: thanks. my point was what you edited out! in fact I wanted to check if the theorem in your post is a corollary of the theorem in the book.
Answer: When I first saw the question, I remembered there was a proof on MO using Ramsey theory, but couldn't remember how the argument went, so I came up with the following, that I first posted as a comment:

A cute proof using Schur's theorem: Fix $a$ in your semigroup $S$, and color $n$ and $m$ with the same color whenever $a^n=a^m$. By Schur's theorem (and the fact that the semigroup is finite) there are $n\le m$ such that $n$, $m$, and $n+m$ have the same color. That is, $a^n=a^m=a^{n+m}=(a^n)^2$.

(Today I finally found the thread on MO with the Ramsey theory proof, using Ramsey's theorem directly rather than Schur's theorem.)
Answer: This is a very good point proved by E.H.Moore that says:

Some power of every element of a finite semigroup is idempotent.

Trans. Amer. Math. Soc. 3 1902
Answer: Let $x$ be an element of $S$. Since $S$ is finite, there exist integers $i, p >0$ such that $x^i = x^{i+p}$. It follows that, for all $k \geqslant i$, $x^k = x^{k+p}$. In particular, if $k$ is a multiple of $p$, say $k = qp$, one has
$(x^k)^2 = x^{2k} = x^{k+qp} = x^k$ and thus $x^k$ is idempotent.
Answer: This is essentially the J.-E. Pin's argument. Let $x$ be in your semigroup. There are positive integers $i,j$ such that $x^{i+j}=x^i$. We have $x^{i+jk}=x^i$ for all positive integer $k$ (induction on $k$). Choosing $k$ so that $jk>i$ we get
$$
(x^{jk})^2=x^{jk-i}\,x^{i+jk}=x^{jk-i}\,x^i=x^{jk}.
$$


Is it common to play several strings of a cello simultaneously?

Question: I am toying around with some cello Vst having basically no experience with playing any string instrument and realized that the sound of my generated sounds is quite artificial which underlines the fact that I have no clue about how a cello is played.
Now while watching some tutorial about cellos I am wondering how many strings are typically played during a piece?
The bridge is curved so you either won't or even can't play 3 or 4 strings at the same time, but do you play two of them? Or is this effect purely created by playing one string and letting it swing while playing the next string?
Bonus: Does a straight bow mean that only one string is played? :)
Answer: It is common to play double-stops, certainly in solo pieces; and indeed also quite common to play 3- or 4-voice chords (these need to be "broken", i.e. you quickly excite the low strings and let them ring, then pull the bow up and sustain the high strings).
Indeed the multi-stringedness might have something to do with what you call "synthetic" sound you're suffering from: most of the time, even if only one string is actively played, the other are free to vibrate and cause sympathetic resonance. But this influences the sound only subtly anyway, so it probably isn't your main problem.
This part of the answer doesn't apply to your question, I thought you were talking about an actual cello when I wrote it, not a VST one.

"straight bow" is more to the point. This is orthogonal to how many strings you're playing... literally: a straight bow is when the angle between the bow and string is 90°. This is normally the best angle to get a good solid sound1.
  Angle is just one of many bow parameters:
  - Default position for the bow on the string is between the bridge and the beginning of the fingerboard, a bit closer to the fingerboard but by no means above it2.
  - The bow itself can be angled axially, i.e. you can either have all bow hairs flat on the string or you use mainly the upmost hairs. Again, straight is a good thing to practise first, though it's generally ok to have an angle here (it gives a bit of a sweeter sound).
  - Pressure is of great relevance. You'll often hear the advice "use your arm's weight", i.e. you should be relaxed yet excert a firm and steady pressure on the bow against the string.
  - Same goes for speed. You can move the bow fast or slow, but you need to be deliberate about it, and consistent.

  Controlling all these parameters in realtime is, obviously, not easy. Apart from the inevitable practising effort, you should make sure you're holding the bow the correct way. You'll find many pictures on the internet, but really – asking a teacher to show it to you is much more effective. There are many bad habits you can develop in the right hand.

  So that was only the bowing aspect. Of course, when playing proper cello pieces you also need to be very accurate about the left hand fingering. But before you blame it on the left hand ("more vibrato" is definitely not the solution to your problem, though it might initially seem to help), make sure you get the bowing right.

Now, the above block hints at what's the real problem with VST strings: there's a darn lot of parameters a good string player controls simultaneously, to get the right sound at every moment in a performance. If a note is repeated, even if it's nominally the same length and dynamic level, it'll sound different because the bow is moving the other direction. If a passage is played quickly / staccato, the player will put in more pressure on the beginning of the tones so the notes develop fast enough, whereas in slow / legato it's more of a soft fade-in. For some intervals you might need to perform a particular position change that gives a barely noticable, but characteristic sound (in particular on the cello, position changes can make quite an audible portamento even when the player hides it).
Today's top-notch plugins, e.g. the Embertone Blakus Cello, will generally offer ways to emulate all such effects. But it'll only sound natural if you actually know how to correctly place the effects.
There's one particular thing I consider paramountly important but is largely neglected by vendors of such plugins: intonation. Though players of guitar or piano will regularly claim otherwise, string instruments do not play in 12-edo tuning. Every single note is actually fine-tuned to some pitch that can depend on lots of factors; it's normally said that string players switch between Pythagorean tuning and just (5-limit) intonation, depending on the context.

1Good players will often deliberately angle the bow in various ways, but (unless you want to provoke e.g. a particular screech sound) this must be combined with controlled moving of the bow point. Before you try any of this, make sure you know how to bow straight.
2You'll sometimes find an indication "sul tasto", this means you should bow right at the edge of the fingerboard. Again, this is something to use as an effect.
Comment: Thanks for the reply and valuable insight, I've checked whether my Vst provided some of those abilities and it doesn't. Some elaborated packages for Orchestra provide additional degrees of freedom to express bow movement etc. but without actually knowing how to play a cello this might be a waste of money for me :)
Comment: You are absolutely right about intonation on string instruments... It is amazing to me (keyboard player) that the interaction of hand and ear can hit the right spots on the string... and, which I did not realize for a long time, no one is playing "equal temperament"! :)
Answer: Yes it is quite common. The technical term for this is double stop. Note, that independent of form of the bow the hairs are just fixed at the tip and the frog. So the hairs have really no choice but to form a straight line (but are deformed by contact with the strings). Even since the string arrangement is curved, it is easy to find an angle, where the bow has contact to two strings, with more force even three.
String instruments are quite hard to synthesize due to the complicated waveforms and even more complicated attack behavior, i. e. the sound phase at the beginning of the tone. This frequently sounds more artificial than the sustained tone later, so it is likely, that it is not your fault.
Comment: But strings are still easier to synthesize than wind instruments. Someone did a study about ten years ago which showed that people could distinguish synth strings from real strings 75% of the time, but they could distinguish synth brass from real brass 95% of the time. Of course the technology has improved since then, but I venture to guess he'd get pretty much the same results if he tried it again now.
Comment: @RobertSoupe: interesting (do you have a reference?); but I'd strongly suspect this was for _ensemble sounds_. In a string ensemble, so many instruments play unisono that the instruments' nuances are "smeared out" to something you can basically model as noise. In a wind section, there's less duplication.
Comment: @leftaroundabout Sorry, I can't remember. I think it was an undergrad research project at the University of Chicago, and I think you're right, it was ensemble sounds. As I remember, the guy recorded a string quartet, a wind quintet and a brass quintet, then he had the musicians who recorded listen to their own recordings and to synth versions, then he had medical students, engineering students, random people off the street, etc., listen.
Comment: @RobertSoupe: well, for string quartet, my point wouldn't apply. Surprising! Although, it doesn't really tell very much without knowing about the particular synths that were used.
Answer: Basic background
A cello has four strings, tuned in fifths: C, G, D, A (just below middle C).
Double Stops
It is possible to simultaneously play any two strings that are next to each other.  The bowing is generally not difficult.
To be realistic, though, you also have to consider the fingering.  Some limitations to consider are:

The left hand can only spread so far.
It's more difficult to change fingering for both strings at exactly the same time, especially if playing legato on the same bow stroke.
Vibrato is limited when the left hand is pressing on two strings at once.

Those limitations are simplified when one of the notes is played using an open string.
Triple Stops
It is also possible to play three strings simultaneously, since there is some elasticity in the bow .  However, such triple stops are limited in duration, since a long stroke will prevent the middle string from vibrating freely, and the tone quality will be poor.  Triple stops would commonly be used for, say, the final chords of a symphony.  They would all be down-bow strokes.
The caveats of double-stops also apply, of course.
Three- and Four-string Rolled Chords
Four-note chords can be played as well, by quickly rolling the bow.  For example, C-G-E-C can be played by a C+G double stop (easy, since they are both open strings), followed immediately by an E+C double stop on the D and A strings.

A good illustration of double stops and rolled chords is the Sarabande from Bach's Cello Suite No. 1.  The score (I use "the" loosely, as there are many editions, some of which differ significantly) calls for double, triple, and even quadruple stops.  However, since it is very much a legato piece, these ideal chords can only be approximated by rolling.  In actual execution, no more than two strings are being played at any given instant.
I've excerpted Dörffel's edition below.  I recommend that you watch Mischa Maisky's performance, especially the close-up shots towards the end.
Answer: I don't play cello, but I'll answer this based on what I do on double bass.
Simple answer: You can play two strings together. It is common to play several strings together.

how many strings are typically played during a piece?

All of them. I think you wanted to ask

how many strings are typically played simultaneously during a piece?

Αnd the answer to this depends on the song.
There is no rule that tells you you have to play only one or two strings at a time. If a cello plays with a piano, you might not need to play chords. If a cello plays alone, it might need to play some chords; thus playing two strings together.
From my experience, the most 'typical' songs have mostly single strings being played, but it is not uncommon to see chords on a cello. I have seen it many, many times.
My personal answer to this would be: Play as many strings simultaneously as you want.

Does a straight bow mean that only one string is played?

No. With a straight bow (I've never seen a curved one -- normal bows are straight) you can play up to 2 strings together, since the instrument is curved.
Comment: When somebody talks about a straight bow I'd normally take it that they mean the _angle_ between bow and string, i.e. it's straight vs. angled. [Curved bows](http://en.wikipedia.org/wiki/Curved_bow), though extant, are sure rather exotic.
Answer: Samuel,
There are many great answers above, here's a bit more. I play the cello, and as mentioned above, you can play 2 strings at a time. This is known as a double stop. It is quite common and I think it sounds great.
If you're utilizing sampled cello sounds, you'll definitely meet a challenge in trying to make it sound convincing or realistic. However if you require more than 2 notes at a time with the string sound, you can write the remaining notes for the viola or violin, or you can write the piece for multiple cellists.
Comment: Thank you for the answer. The amount of voices or Vst quality is not a problem here as Steinberg and Halion Sonic (SE) are quite advanced tools for that task. Simply the missing insight of how a specific instrument is played just makes the synth experience a little shallow. While I've found access to piano or bagpipes manageable, violins and cellos are not :/ as I tend to teach them by myself.
Answer: Cellist Frances-Marie Uitti pioneered a style of playing with one bow over and one under the strings. So she can -- and regularly does -- get 4 notes simultaneously.

Alternatively, you could use a bow with very slack hairs and hit 3 or 4 strings with one bow.


How do I handle the click event of a v-menu in Vuetify?

Question: How can I check and handle the click event of a v-menu in Vuetify?
Answer: The best way is to use v-model on v-menu & watch to variable change.
HTML
  <v-menu
    v-model="isOpened">
  </v-menu>

SCRIPT
export default({
   watch:{
    isOpened: function(){
      // do whatever you want
    }
  }
})

Answer: Here is an example:
<template v-slot:activator="{ on: { click } }">
  <v-btn @click="(click) (exit=!exit)" icon>
    <v-icon v-if="!exit">mdi-dots-vertical</v-icon>
    <v-icon v-else>mdi-close</v-icon>
  </v-btn>
</template>

As you can see, if the menu is clicked the exit var is set to its opposite value and therefore the mdi-close icon is shown on the button. If the menu is clicked again, the event changing the exit variable will trigger again and the vertical dots will be shown.
I only posted this question to save the exact syntax for myself for later because I have been digging Vuetify docs for hours and finally figured out how to do it.
Comment: ok, but let's say exit= false, & when user clicks on button then exit will be true but when user will click outside of the v-menu (not on button) then menu will be hidden & exit is still true which means its not syncing. In this case this logic will fail here. Mark me if i am wrong.
Comment: but where is exit variable declared ?
Comment: In this particular example it's simply declared in the script tag with the default value 'false'.


Como Popular um TreeView com os Diretórios e Arquivos do Sistema em C#

Question: Em minha aplicação (Windows Forms) tenho que fazer uma arvore de diretórios para o usuário buscar por um(ou mais) arquivo(s) dentro do sistema dele.
Vi na Web como fazer essa arvore em um tutorial da Microsoft, mas no exemplo deles a TreeView apenas exibe os diretórios, não os arquivos propriamente ditos (os arquivos são exibidos em uma ListView que não é prático).
A Arvore funciona, mas eu preciso ver os arquivos do Diretório e se possível já seleciona-los (recuperar os FileName deles) para minha aplicação.
Segue o Código.
private void PopulateTreeView()
 {
     TreeNode rootNode;

     DirectoryInfo info = new DirectoryInfo(@"../..");
     if (info.Exists)
     {
         rootNode = new TreeNode(info.Name);
         rootNode.Tag = info;
         GetDirectories(info.GetDirectories(), rootNode);
         treeView1.Nodes.Add(rootNode);
     }
 }

 private void GetDirectories(DirectoryInfo[] subDirs,TreeNode nodeToAddTo)
 {
     TreeNode aNode;
     DirectoryInfo[] subSubDirs;
     foreach (DirectoryInfo subDir in subDirs)
     {
         aNode = new TreeNode(subDir.Name, 0, 0);
         aNode.Tag = subDir;
         aNode.ImageKey = "folder";
         subSubDirs = subDir.GetDirectories();
         if (subSubDirs.Length != 0)
         {
             GetDirectories(subSubDirs, aNode);
         }
         nodeToAddTo.Nodes.Add(aNode);
     }
 }

Vi nesse tutorial que eu posso aplicar um foreach para cada arquivo encontrado no node e exibi-lo no ListView, mas como adiciona-lo a TreeView ?
Obrigado.
Comment: Você pode dar uma olhada em neste vídeo : https://www.youtube.com/watch?v=55PCdfvlyYk , ele mostra como você pode exibir os itens no controle do Tree View no diretório especificado .  Assim que estiver com tempo vou tentar postar a postar a resposta.
Comment: Obrigado amigo, não posso assistir vídeo no trabalho, mas vou dar uma olhada nesse link quando chegar em casa, muito obrigado pela ajuda
Answer: Acredito que este exemplo vai te ajudar.
Diretório dos arquivos

Código
 DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Users\mmurta\Desktop\PastaMeuSistema\Arquivos_Meu_Sistema");

        private void Form1_Load(object sender, EventArgs e)
        {
            if (Directory.Exists(@"C:\Users\mmurta\Desktop\PastaMeuSistema"))
            {
                try
                {
                    DirectoryInfo[] directories = directoryInfo.GetDirectories();

                    foreach (FileInfo file in directoryInfo.get())
                    {
                        if (file.Exists)
                        {
                            TreeNode nodes = treeView.Nodes[0].Nodes.Add(file.Name);
                        }
                    }

                    if (directories.Length > 0)
                    {
                        foreach (DirectoryInfo directory in directories)
                        {
                            TreeNode node = treeView.Nodes[0].Nodes.Add(directory.Name);
                            foreach (FileInfo file in directory.GetFiles())
                            {
                                if (file.Exists)
                                {
                                    TreeNode nodes = treeView.Nodes[0].Nodes[node.Index].Nodes.Add(file.Name);
                                }
                            }
                        }
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

Resultado :

Depois se preferir você pode realizar o download do o código fonte aqui , foi disponibilizado pelo autor do Vídeo .
Comment: Opa amigo, no mesmo momento que eu ia postar a resposta você mandou a sua HAHA, obrigado pela ajuda cara.
Comment: Ok , Tente buscar os termos em inglês no google sobre o que você deseja implementar , se mesmo assim a dúvida  bater nos estamos aqui =D. Se você achou adequado meu exemplo por favor marque como resposta*-*.
Answer: Consegui resolver o problema, fiz uma lógica para que dentro de cada nó onde tenha arquivos seja criado mais um nó para exibi-los.
segue codigo:
    private void PopularTreeView()
    {
        TreeNode rootNode;

        DirectoryInfo info = new DirectoryInfo(@"D:\codigos");
        if (info.Exists)
        {
            rootNode = new TreeNode(info.Name);
            rootNode.Tag = info;
            GetDirectories(info.GetDirectories(), rootNode);
            treeView1.Nodes.Add(rootNode);
        }
    }

    private void GetDirectories(DirectoryInfo[] subDirs, TreeNode nodeToAddTo)
    {
        TreeNode aNode;
        DirectoryInfo[] subSubDirs;
        foreach (DirectoryInfo subDir in subDirs)
        {
            aNode = new TreeNode(subDir.Name, 0, 0);
            aNode.Tag = subDir;
            aNode.ImageKey = "icone-pasta";
            subSubDirs = subDir.GetDirectories();
            if (subSubDirs.Length != 0)
            {
                GetDirectories(subSubDirs, aNode);
            }
            nodeToAddTo.Nodes.Add(aNode);
            foreach (FileInfo file in subDir.GetFiles())
            {
                TreeNode node = new TreeNode();
                node.Text = file.Name;
                node.ImageIndex = 1;
                node.SelectedImageIndex = 1;
                nodeToAddTo.Nodes.Add(node);
            }
        }
    }


is java.util.logging.Logger class info() method a I/O operation?

Question: I saw in the stack overflow when it comes to server side industrial level applications using a logger framework over System.out.println() is an efficient way to deal with Logging.And I also red that System.out.println() is an I/O operation,because of that it needs more CPU usage.So I need to know is logger.info() [which is a builtin class comes with java] is an I/O operation or not and a explanation why if it is not.
Comment: Ultimately, there will be IO, but IO in logging frameworks are usually more optimized for throughput (and a broad range of targets, eg logging into a remote logging platform, etc) compared to `System.out.println`.
Answer: It depends on the registered handler(s).
By default, JUL outputs to console via a ConsoleHandler, that is an IO operation. If logging is configured with a handler that logs to file (FileHandler) or via Network (SocketHandler), that would also be an IO operation.
There is also a MemoryHandler, which wouldn't make logging an IO operation. But it has a very, very limited usefulness.
Using another log framework like SLF4J doesn't change that. Logging is inherently an IO operation, since you want the log to be accessible outside of the application and even after the termination of the process. It is still advantageous to use a framework like SLF4J, though, for various reasons (cf. Why not use java.util.logging?).


SignalR Multiple Hub Connection .NET Core

Question: I have 2 Hub classes,
SystemNotificationHub.cs
public class SystemNotificationHub : Hub { }

QuotationChatHub.cs
public class QuotationChatHub: Hub { }

SystemNotificationHub is defined in _Layout.cshtml so user is connected to hub continously,
and when user enters to QuotationChat.cshtml page, I want also same user to connect the QuotationChatHub, so in a simple manner I'd like the user to connect multiple hubs at the same time.
I cannot let user to connect more than 1 hub at the same time. How can I achive this?
StartUp endPoint Configurations
endpoints.MapHub<SystemNotificationHub>("/systemNotificationHub");
endpoints.MapHub<QuotationHub>("/quotationHub");
quotationChat.js
$(function () {
    if (connection === null) {
        connection = new signalR.HubConnectionBuilder()
            .withUrl("/quotationHub")
            .build();

        connection.start().then(function () {
            document.getElementById('sendButton').onclick = function () {
                connection.invoke("BroadcastFromClient")
                    .catch(function (err) {
                        return console.error(err.toString());
                    });
            };
        });
    }
});

notification.js

$(function () {
    if (connection === null) {
        connection = new signalR.HubConnectionBuilder()
            .withUrl("/systemNotificationHub")
            .build();

        connection.on("Notify", function (response) {

        });

        connection.on("HubError", function (response) {
            alert(response.error);
        });

        connection.start().then(function () {
            connection.invoke("NotificationMethod")
                .catch(function (err) {
                    return console.error(err.toString());
                });
        });
    }
});

Comment: Okay - so whats you're quesiton exactly? - try and make it a singular question with an actual quesiton mark so we clearly understand what you need
Comment: you only described your situation here. please add an actual question
Comment: I've edited the question, simply I cannot let user to connect more than 1 Hub at the same time. Only 1 Hub which is the first one that user connects is working, quotationHub is not working when user enters that specific page.
Comment: Actually as I see, before the edit, he just forgot a question mark, and the other hand statements are okay where he says that he cannot connects users to 2 hubs at the same time.
Comment: so basically if i understand you correctly you want the ability to drop a connection when one is made on a different hub?
if so just fire an event to a hub manager that will disconnect the client from other hubs...
Comment: No, I want to connect both of the hubs, now, because of the SystemNotificationHub connection, it seems I cannot open another connection to QuotationChatHub @Liran
Answer: As far as I know, this issue is related with your if condition in your codes.
You have checked connection is null or not before creating the connection builder. But all two js use the same connection model.
To solve this issue, I suggest you could try to create a new connection for systemNotificationHub for example connection1 and then your code will work well.
More details, you could refer to below codes:
quotationChat.js not changed.
notification.js:
//Define a new connection1 as the new js object as connection
$(function () {
    if (connection1 === null) {
        connection1 = new signalR.HubConnectionBuilder()
            .withUrl("/systemNotificationHub")
            .build();

        connection1.on("Notify", function (response) {

        });

        connection1.on("HubError", function (response) {
            alert(response.error);
        });

        connection1.start().then(function () {
            connection.invoke("NotificationMethod")
                .catch(function (err) {
                    return console.error(err.toString());
                });
        });
    }
});


onClick={} com retorno de div com conteúdo da API

Question: fala rapaziada. estou com um problema de iniciante... sou novo no reactjs e queria saber como faço para que: assim que eu clicar no button ele me retornar os dados da api dentro de uma DIV
ex: (article, section e etc...)
import React, { Component } from 'react';
import Api from '../API/index';

import './main.css'

class Main extends Component {

    constructor(props){
        super(props);
        this.state = {
            planets : [],
        }
    }

    componentDidMount(){
        this.loadItens();
    }

        loadItens = async () => {
            const response = await Api.get('/planets');
            this.setState({ planets: response.data.results });
        }

render() {
    return(

              {this.state.planets.map(planetz => (

 Nome: {planetz.name}

 Clima: {planetz.climate}

 Terreno: {planetz.terrain}

 População:  {planetz.population}

 Participação em filmes: {planetz.films.length}

                      <button type="submit" onClick={this.loadItens}> Procurar Planetas </button>

              ))}

    );
};
}
export default Main;

Comment: João, poderia [editar](https://pt.stackoverflow.com/posts/406616/edit) sua pergunta e esclarecer seu **problema / dificuldade** ?
Comment: sim, com certeza! já foi editado... obrigado.
Comment: Mas você já não está fazendo isso? No seu `onClick` você invoca a função `loadItens`. `loadItens` busca dados no seu servidor, e então invoca o `setState` para alterar o `state` e re-renderizar o componente. Está tudo correto. O único problema é que você colocou o seu `button` dentro do loop que monta o HTML dos planetas, então se você não tiver nenhum planeta no seu `state`, você não irá entrar no loop e nenhum botão será renderizado.
Comment: @user140628 Não. eu chamei o parametro do map() dentro do article que me retornou os itens da api. eu queria saber como faço para que assim que clicar nesse botão ele me retornasse esses parametros sem precisar ter que chama-los no html. vlw!
Comment: Então ainda não entendi exatamente o que você está tentando fazer. Eu entendo que você é iniciante, mas os termos que você está utilizando para descrever esse problema não fazem sentido e isso está dificultando a comunicação. `parâmetro` é uma valor passado para uma função "chamar o parâmetro do map" é uma frase que não faz sentido. Outra coisa é que eu não estou entendendo é o que você quer dizer com "retornar esses parâmetros sem precisar chama-los no html"
Comment: ex: eu retornei dentro do article  Nome: {planetz.name}  eu queria que assim que eu clicasse no button ele me retornasse isso sem eu precisar ter que usar esse  Nome: {planetz.name}  manualmente.
Comment: O que você quer dizer por "usar  Nome: {planetz.name}  manualmente"? Desculpe, mas parece que estamos falando línguas diferentes.
Comment: precisa se desculpar não.. tudo certo!  "manualmente" não precisar chama-lo dentro article.
Comment: ao clickar no button queria que me retornasse esse map() com os itens contidos na api que no caso seriam, nome do planeta, clima,terreno,população do planeta. isso tudo apenas ao clicar no button.
Answer: Fala João, tudo bem?
Veja, você quer carregar os dados só ao clicar no botão, você colocou componentDidMount chamando a API e ai ele vai trazer os dados desse jeito. tenho uma sugestão pra vc:
class Main extends Component {

    constructor(props){
        super(props);
        this.state = {
            planets : [],
        }
    }
    // Não vai ter isso aqui!
    // componentDidMount(){
    //     this.loadItens();
    // }

        loadItens = async () => {
            const response = await Api.get('/planets');
            this.setState({ planets: response.data.results });
        }

render() {
    return(

         <button
            type="submit"
            onClick={this.loadItens}
         >
           Procurar Planetas
         </button>
              {this.state.planets.length
                && this.state.planets.map(planetz => (

 Nome: {planetz.name}

 Clima: {planetz.climate}

 Terreno: {planetz.terrain}

 População:  {planetz.population}

 Participação em filmes: {planetz.films.length}

              ))}

    );
};
}
export default Main;

O que fiz ali foi comentar seu componentDidMount, mudar o botão de procurar planetas para logo abaixo da
 para sair do loop e ficar disponível.
Coloquei também uma verificação pra rodar o map só se o planets estiver populado. (eita deu quase duplo sentido. hehehe).
Acho que assim resolve.
Comment: Para consumir uma API não é necessário sempre ter um método de ciclo de vida ? Obrigado!
Comment: Não necessariamente, João. Se ao abrir a página precisar por exemplo carregar apenas o nome dos planetas para uma listagem, aí você pode usar o componentDidMout() ou o useEffect(() => {}, []) que faz parte da nova api de Hooks do React. Esses métodos faram uma leitura inicial na API logo após a página estar carregada.
No seu caso não era necessário, já que a comunicação com a API só ocorre após uma interação do usuário com a aplicação. No seu caso, é necessário clicar no botão primeiro. Caso não tiver ficado claro, me fala que te explico melhor.
Comment: Entendi completamente. Só tenho uma dúvida quanto ao componentDidMount... com a chamada da API com o async loadItens que eu fiz ela já está sendo consumida, certo? esse componentDidMount é apenas para renderizar o conteúdo da API em tela ? obrigado!
Comment: Esse método do ciclo de vida do React só é executado quando a página foi renderizada, ou seja, quando ela já passou pelo método render(). Eu não lembro mais de cabeça quais são todos os métodos do ciclo de vida, mas cada um executa num certo momento, tipo antes de carregar a tela (componentWillMount), antes de destruir um componente (componentWillUnMount).
Comment: Para ser mais claro, e respondendo sua pergunta, ele não serve para renderizar nada na tela. o método que renderiza é o render().
Comment: Ok. obrigado pela ajuda!


Can one specify the default region for the EC2 command line tools using a variable?

Question: Is there an EC2_* environment variable to specify the default region of the EC2 command line tools in order to avoid specifying the --region eu-west-1 option for each command?
Answer: for Latest AWS CLI:
export AWS_DEFAULT_REGION=eu-west-1

reference:
http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
for older EC2 CLI:
export EC2_URL=https://ec2.eu-west-1.amazonaws.com

reference:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/SettingUp_CommandLine.html
http://docs.aws.amazon.com/general/latest/gr/rande.html
Comment: Yes, RTFM. Thanks for the link to the latest version (AWS_DEFAULT_REGION). Exactly what I was looking for!
Comment: Of course this changes it for anything so if you only want it temporarily, you should change it back as soon as possible and serialize access.
Some sort of PUSH and POP would be nice, AWS people.


Como fazer Request de dados JSON

Question: Preciso coletar alguns dados de um programa que possui API:
PipeDrive API Reference
Se entendi bem, para cada tarefa, sera gerado uma URL para fazer o Requeste desdes dados, exemplo:
https://api.pipedrive.com/v1/deals?stage_id=45&status=all_not_deleted&start=0&api_token=8***76c******9740**78223a2c

Mas como faço para retornar esses dados em minha aplicação?
O metodo é GET.
Comment: Você quer saber o quê, especificamente? Como fazer uma requisição para esta API usando C#?
Comment: @LINQ exatamente isso.. obrigado
Comment: Thomas, ainda fica um pouco ampla. Você quer fazer com tudo "na mão"? Usar alguma biblioteca de terceiros?
Comment: @LINQ, então, hoje estou utilizando `Entity Framework`, `Jquery` mas não sei qual seria a melhor abordagem.. Vi o pessoal utilizando `Ajax` para consumir os dados, os dados vindo dessa API, serão atualizados com frequência.. praticamente a cada atualização de pagina, irei precisar ir buscar os dados novamente..
Answer: Olá, tem algumas abordagens, vou citar à que acho mais apropriada, que é a utilizando o HttpClient.
Caso não encontre ele no seu projeto, instale o seguinte pacote.: System.Net.Http
public class MinhaController : Controller
{
    // o HttpClient deve ter uma instancia estatica, para evitar ficar abrindo muitas portas.
    private static HttpClient httpClient;

    static MinhaController()
    {
        httpClient = new HttpClient();
        httpClient.BaseAddress = new Uri("https://api.pipedrive.com/v1/deals");
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //Se precisar adicionar alguma autenticação, faça o aqui.
    }

    public async Task<ActionResult> Index()
    {
        var stageId = GetStageFromSomewhere();
        var token = GetTokenFromSomewhere();
        var queryString = $"?stage_id={stageId}&status=all_not_deleted&start=0&api_token={token}";
        var response = await httpClient.GetAsync(queryString);
        if (response.IsSuccessStatusCode)
        {
            var json = await response.Content.ReadAsStringAsync();
            var model = Newtonsoft.Json.JsonConvert.DeserializeObject<MeuModelo>(json)
            return Json(model);
        }
        return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "Erro ao acessar a API.");
    }
}

EDIT
O AP pediu para enumerar algumas demais abordagens, então vamos lá.:

HttpWebRequest - Bastante complexo, porem permite controlar cada aspecto da requisição.
WebClient - Abstração do HttpWebRequest, bastante simples, sem muitos controles.
HttpClient - Disponível no .NET 4.5, permite operação async/await e combina o melhor do HttpWebRequest e WebClient.
RestSharp - Similar ao HttpClient, porem sem o async/await e com melhor compatibilidade.

Então, no seu caso, o HttpClient é o mais indicado.
Comment: Amigo, obrigado pela resposta.. poderia descrever quais as outras abordagens? somente o nome para que eu pesquise? obrigado
Comment: @ThomasErichPimentel feito.

Como fazer Request de dados JSON


How to convert .PNG image to tiles for Bing or Google Maps with ASP.NET?

Question: I'm looking for a way to convert .PNGs (like this one: http://1drv.ms/1O9lrG5) to tiles that I can use with Google or Bing Maps. I'm thinking of a server side script that does this every 10 minutes (as the content of the .PNGs might change).
I know of tools like MapCruncher, but this is not what I'm looking for: I want a fully automated way that gets the relevant .PNGs, generates tiles (with the lat/long from all 4 corners) and let those be accessed by my client app.
Any ideas?
Answer: If what you want is this: MapTilerLayer (or overlay-simple), you can use a dynamic url to render the image and set it as the source image for the overlay.
Example from Google Maps Javascript API:
<code>function initialize() {
  var mapOptions = {
    zoom: 11,
    center: new google.maps.LatLng(62.323907, -150.109291),
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var swBound = new google.maps.LatLng(62.281819, -150.287132);
  var neBound = new google.maps.LatLng(62.400471, -150.005608);
  var bounds = new google.maps.LatLngBounds(swBound, neBound);

  // THE DYNAMIC IMAGE URL
  var srcImage = 'http://your.url/image.ashx';

  // The custom USGSOverlay object contains the USGS image,
  // the bounds of the image, and a reference to the map.
  overlay = new USGSOverlay(bounds, srcImage, map);
}
</code>
Comment: Yes, I know if this functionality - but I want to actually create tiles from a .PNG
Answer: Unless you want to write the slicing code yourself, a possibility would be to use the older DeepZoomTools.dll.
You can get the .dll by downloading deep zoom composer and pulling it from it's bin.
Here's a link to a blog showing how to programmatically create the tiles.
I used it a few years ago for a project to good effect. If needed, I could try and find the code out.